diff --git a/.gitignore b/.gitignore index d16b0398e7..97d78540bd 100644 --- a/.gitignore +++ b/.gitignore @@ -60,7 +60,6 @@ build_*_vc10/ *.mode*v* *.pbxuser *.xcbkptlist -*.xcscheme *.xcworkspacedata *.xcuserstate *.xccheckout diff --git a/.gitmodules b/.gitmodules index 91585f7b9a..24fc5625d3 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,12 +4,12 @@ [submodule "cocos/scripting/auto-generated"] path = cocos/scripting/auto-generated url = git://github.com/cocos2d-x/bindings-auto-generated.git -[submodule "samples/Javascript/Shared"] - path = samples/Javascript/Shared - url = git://github.com/cocos2d/cocos2d-js-tests.git [submodule "tools/cocos2d-console"] path = tools/cocos2d-console url = git://github.com/cocos2d/cocos2d-console.git [submodule "plugin"] path = plugin url = https://github.com/cocos2d-x/plugin-x.git +[submodule "tests/test-javascript/tests"] + path = tests/test-javascript/tests + url = git://github.com/cocos2d/cocos2d-js-tests.git diff --git a/AUTHORS b/AUTHORS index fd5cf6a651..095386f830 100644 --- a/AUTHORS +++ b/AUTHORS @@ -95,6 +95,7 @@ Developers: Added Mingw-crt Support without breaking VS SDK CMake support for windows. Added support for x64 target of windows. + Added Dutch Language support. mchinen fix emulator issue for OpenGL ES 2.0 on Android @@ -510,6 +511,8 @@ Developers: Lee, Jae-Hong (pyrasis) Maintainer of tizen port. + localStorageGetItem crashes when column text is NULL. + fix image bug on Android lumendes Updating spine-runtime to EsotericSoftware/spine-runtimes@5f90386. @@ -718,6 +721,19 @@ Developers: Pisces000221 Corrected a few mistakes in the README file of project-creator. + Corrected a mistake in README. + + hbbalfred + Fixed a bug that crash if file doesn't exist when using FileUtils::getStringFromFile. + + liang8305 + Use multiple processes according the number of cores to build android project + + pandamicro + Exposed SAXParser to JS, it is used for parsing XML in JS. + + hanjukim + Fixed a bug that color and opacity settings were not applied when invoking Label::alignText. Retired Core Developers: WenSheng Yang diff --git a/CHANGELOG b/CHANGELOG index 68acb827a9..3da3c6d302 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,17 +1,85 @@ -cocos2d-x-3.0final ?.? ? +cocos2d-x-3.0rc0 Feb.?? 2014 [All] - [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands + [NEW] Adds Dutch Language support. + + [FIX] EGLView improvements: renamed to GLView, no longer a singleton, easier to customize + [FIX] Removes samples except testcpp|testjavascript|testlua. Moves sample games to `cocos2d/samples` repo. + +cocos2d-x-3.0beta2 Jan.24 2014 +[All] + [NEW] Full screen support for desktop platforms. + [NEW] Adds performance test for EventDispatcher. + [NEW] Adds performance test for Containers(Vector<>, Array, Map, Dictionary). [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. + [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands + [NEW] GLCache: glActiveTexture() is cached with GL::activeTexture(). All code MUST call the cached version in order to work correctly + [NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use. + [NEW] Label: Integrates LabelAtlas into new Label. + [NEW] Node: Added `setGlobalZOrder()`. Useful to change the Node's render order. Node::setZOrder() -> Node::setLocalZOrder() + [NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10% + + [FIX] event->stopPropagation can't work for EventListenerTouchAllAtOnce. + [FIX] Uses unified `desktop/CCEGLView.h/cpp` for desktop platforms (windows, mac, linux). + [FIX] Bindings-generator supports Windows again and remove dependency of LLVM since we only need binary(libclang.so/dll). + [FIX] Removes unused files for MAC platform after using glfw3 to create opengl context. + [FIX] Wrong arithmetic of child's position in ParallaxNode::addChild() + [FIX] CocoStudio: TestColliderDetector in ArmatureTest can't work. + [FIX] CocoStudio: The order of transform calculation in Skin::getNodeToWorldTransform() is incorrect. + [FIX] Crash if file doesn't exist when using FileUtils::getStringFromFile. + [FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong. + [FIX] Label: Memory leak in FontFreeType::createFontAtlas(). + [FIX] Label: Crash when using unknown characters. + [FIX] Label: Missing line breaks and wrong alignment. + [FIX] Label: Corrupt looking characters and incorrect spacing between characters + [FIX] Label: Label:color and opacity settings are invalid afeter these these properties changed: 1)text content changed 2)align style changed 3)max line width limited + [FIX] Label: Crash when using unknown characters + [FIX] Console: log(format, va_args) is private to prevent possible resolution errors [FIX] Configuration: dumpInfo() -> getInfo() [FIX] ControlSlider doesn't support to set selected thumb sprite. [FIX] ControlButton doesn't support to set scale ratio of touchdown state. [FIX] Particles: Crash was triggered if there is not `textureFileName`section in particle plist file. - [FIX] Tests: TestCpp works with CMake on Windows. - [FIX] Tests: Sprites Performance Test has 3 new tests + [FIX] Renderer: Uses a float as key with only the depth. Viewport, opaque are not needed now + [FIX] Renderer Performance Fix: QuadCommand::init() does not copy the Quads, it only store a reference making the code faster + [FIX] Renderer Performance Fix: Sprite and SpriteBatchNode (and subclasses) has much better performance + [FIX] Renderer Performance Fix: When note using VAO, call glBufferData() instead of glBufferSubData(). + [FIX] Renderer Performance Fix: Doesn't sort z=0 elements. It also uses sort() instead of stable_sort() for z!=0. + [FIX] Sprite: removed _hasChildren optimization. It uses !_children.empty() now which is super fast as well + [FIX] Tests: Sprites Performance Test has 4 new tests [FIX] TextureCache: getTextureForKey and removeTextureForKey work as expected [FIX] TextureCache: dumpCachedTextureInfo() -> getCachedTextureInfo() [FIX] Websocket doesn't support send/receive data which larger than 4096 bytes. - [FIX] Windows: There will be some compilation errors when using x64 target on Windows. + [FIX] Object: Remove _retainCount + [FIX] ParallaxNode: Coordinate of Sprite may be wrong after being added into ParallaxNode + [FIX] Crash if there is not `textureFileName`section in particle plist file + [FIX] Websocket cannot send/receive more than 4096 bytes data + [FIX] TextureCache::addImageAsync can't load first image + [FIX] ControlSlider: Can not set "selected thumb sprite" + [FIX] ControlSlider: Can not set "scale ratio" + [FIX] Crash when loading tga format image + [FIX] Keyboard pressed events are being repeatedly fired before keyboard is released +[Android] + [FIX] Background music can't be resumed when back from foreground + [FIX] ANR (Application Not Responding) appears on android 2.3 when pressing hardware button. +[lua binding] + [NEW] Can bind classes that have the same class names but different namesapces + [FIX] Use EventDispatcher to update some test cases + [FIX] sp.SkeletonAnimation:registerScriptHandler should not override cc.Node:registerScriptHandler +[javascript binding] + [NEW] Bind SAXParser + [FIX] Pure JS class that wants to inherite from cc.Class will trigger an irrelevant log + [FIX] Mac and iOS Simulator should also use SpiderMonkey which was built in RELEASE mode + [FIX] Crash when running JSB projects on iOS device in DEBUG mode + [FIX] Crash when Firefox connects to JSB application on Mac platform. +[Desktop] + [NEW] Support fullscreen +[Linux] + [FIX] "Testing empty labels" in LabelTest crashes. +[Mac] + [FIX] Removes unused files after using glfw3 to create opengl context +[Win32] + [FIX] Compiling error when using x64 target + [FIX] Tests: TestCpp works with CMake + [FIX] Bindings-generator supports Windows again and remove dependency of LLVM since it only needs binary of libclang cocos2d-x-3.0beta Jan.7 2014 [All] @@ -758,7 +826,7 @@ cocos2d-2.0-x-2.0.2 @Aug.30 2012 Refactor #1399: adjust directory structure Refactor #1402: improve static creator function names to avoid confusion Refactor #1413: improve CCTouch::getLocation(), getDelta() which returns OpenGL coordinates directly - Refactor #1437: change the return type of CCApplication::sharedApplication() and CCEGLView::sharedOpenGLView() to a pointer + Refactor #1437: change the return type of CCApplication::sharedApplication() and CCGLView::sharedOpenGLView() to a pointer Refactor #1441: put hd and iPad resources of TestCpp into separate directories Refactor #1442: use CREATE_FUNC to replace LAYER_CREATE_FUNC and SCENE_CREATE_FUNC [iOS] @@ -792,7 +860,7 @@ cocos2d-2.0-rc2-x-2.0.1 @Jun.28 2012 Bug #1293: fix a bug that CCDirector::getFrames() returns wrong value Bug #1296: fix a logical error in CCTMXTiledMap::tilesetForLayer() Bug #1300: fix a typo of CC_ENABLE_CACHE_TEXTTURE_DATA - Bug #1301: apply scissor with points in CCEGLView::sharedOpenGLView().setScissorInPoints() + Bug #1301: apply scissor with points in CCGLView::sharedOpenGLView().setScissorInPoints() Bug #1302: change the parameter type of CCMenu::setHandlerPriority to signed int Bug #1308: fix a logical bug in CCTouchDispatcher Bug #1326: fix a bug that the compilation of HelloLua and testjs project was broken after synchronizing to rc2 diff --git a/CMakeLists.txt b/CMakeLists.txt index a5486c2b41..6bf32542eb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -45,9 +45,7 @@ option(BUILD_EDITOR_SPINE "Build editor support for spine" ON) option(BUILD_EDITOR_COCOSTUDIO "Build editor support for cocostudio" ON) option(BUILD_EDITOR_COCOSBUILDER "Build editor support for cocosbuilder" ON) -option(BUILD_HelloCpp "Only build HelloCpp sample" ON) option(BUILD_TestCpp "Only build TestCpp sample" ON) -option(BUILD_HelloLua "Only build HelloLua sample" OFF) option(BUILD_TestLua "Only build TestLua sample" OFF) else()#temp @@ -63,10 +61,7 @@ option(BUILD_EDITOR_SPINE "Build editor support for spine" ON) option(BUILD_EDITOR_COCOSTUDIO "Build editor support for cocostudio" ON) option(BUILD_EDITOR_COCOSBUILDER "Build editor support for cocosbuilder" ON) - -option(BUILD_HelloCpp "Only build HelloCpp sample" ON) option(BUILD_TestCpp "Only build TestCpp sample" ON) -option(BUILD_HelloLua "Only build HelloLua sample" ON) option(BUILD_TestLua "Only build TestLua sample" ON) endif()#temp @@ -155,6 +150,7 @@ include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/external/unzip ${CMAKE_CURRENT_SOURCE_DIR}/external/edtaa3func ${CMAKE_CURRENT_SOURCE_DIR}/external/chipmunk/include/chipmunk + ${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/platform/desktop ${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/platform/${PLATFORM_FOLDER} ${CMAKE_CURRENT_SOURCE_DIR}/external/jpeg/include/${PLATFORM_FOLDER} ${CMAKE_CURRENT_SOURCE_DIR}/external/png/include/${PLATFORM_FOLDER} @@ -169,7 +165,7 @@ if(WIN32) ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/gles/include/OGLES ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/icon/include ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/zlib/include - external/curl/include/${PLATFORM_FOLDER} + external/curl/include/${PLATFORM_FOLDER} ) elseif(APPLE) include_directories( @@ -177,8 +173,9 @@ elseif(APPLE) ) else() include_directories( + /usr/include + /usr/local/include/GLFW ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/fmod/include/${ARCH_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/external/curl/include/${PLATFORM_FOLDER}/${ARCH_DIR} ) endif() @@ -192,8 +189,8 @@ if(WIN32) ${CMAKE_CURRENT_SOURCE_DIR}/external/png/prebuilt/${PLATFORM_FOLDER} ${CMAKE_CURRENT_SOURCE_DIR}/external/freetype2/prebuilt/${PLATFORM_FOLDER} ${CMAKE_CURRENT_SOURCE_DIR}/external/curl/prebuilt/${PLATFORM_FOLDER} - ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/icon/prebuilt - ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/zlib/prebuilt + ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/icon/prebuilt + ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/zlib/prebuilt ) endif() @@ -208,7 +205,6 @@ else() ${CMAKE_CURRENT_SOURCE_DIR}/external/webp/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/external/png/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/external/freetype2/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/external/curl/prebuilt/${PLATFORM_FOLDER}/${ARCH_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/external/${PLATFORM_FOLDER}-specific/fmod/prebuilt/${ARCH_DIR} ) @@ -283,20 +279,13 @@ add_subdirectory(external/lua/tolua) add_subdirectory(cocos/scripting) endif(BUILD_LIBS_LUA) -# build samples -if(BUILD_HelloCpp) -add_subdirectory(samples/Cpp/HelloCpp) -endif(BUILD_HelloCpp) +# build tests if(BUILD_TestCpp) -add_subdirectory(samples/Cpp/TestCpp) +add_subdirectory(tests/test-cpp) endif(BUILD_TestCpp) -if(BUILD_HelloLua) -add_subdirectory(samples/Lua/HelloLua) -endif(BUILD_HelloLua) - if(BUILD_TestLua) -add_subdirectory(samples/Lua/TestLua) +add_subdirectory(tests/test-lua) endif(BUILD_TestLua) diff --git a/README.md b/README.md index ea9fa791ca..7036f82ffb 100644 --- a/README.md +++ b/README.md @@ -24,12 +24,12 @@ How to start a new game 1. Download the code from [cocos2d download site][4] 2. Enter `tools/project-creator` -3. Run the `create-projects.py` script +3. Run the `create_project.py` script Example: $ cd cocos2d-x/tools/project-creator - $ ./project-creator.py -n mygame -k com.your_company.mygame -l cpp -p /home/mygame + $ ./create_project.py -n mygame -k com.your_company.mygame -l cpp -p /home/mygame $ cd /home/mygame ### Build new project for android ### diff --git a/build/android-build.py b/build/android-build.py index 3285c690e9..b3b035799a 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -1,17 +1,34 @@ #!/usr/bin/python # android-build.py -# Build android samples +# Build android import sys import os, os.path import shutil from optparse import OptionParser -CPP_SAMPLES = ['hellocpp', 'testcpp', 'simplegame', 'assetsmanager'] -LUA_SAMPLES = ['hellolua', 'testlua'] -JSB_SAMPLES = ['cocosdragon', 'crystalcraze', 'moonwarriors', 'testjavascript', 'watermelonwithme'] +CPP_SAMPLES = ['testcpp'] +LUA_SAMPLES = ['testlua'] +JSB_SAMPLES = ['testjavascript'] ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES +def get_num_of_cpu(): + ''' The build process can be accelerated by running multiple concurrent job processes using the -j-option. + ''' + try: + platform = sys.platform + if platform == 'win32': + if 'NUMBER_OF_PROCESSORS' in os.environ: + return int(os.environ['NUMBER_OF_PROCESSORS']) + else: + return 1 + else: + from numpy.distutils import cpuinfo + return cpuinfo.cpu._getNCPUs() + except Exception: + print "Can't know cpuinfo, use default 1 cpu" + return 1 + def check_environment_variables(): ''' Checking the environment NDK_ROOT, which will be used for building ''' @@ -57,9 +74,9 @@ def select_toolchain_version(): def caculate_built_samples(args): ''' Compute the sampels to be built - 'cpp' for short of all cpp samples - 'lua' for short of all lua smpleas - 'jsb' for short of all javascript samples + 'cpp' for short of all cpp tests + 'lua' for short of all lua tests + 'jsb' for short of all javascript tests ''' if 'all' in args: @@ -94,10 +111,12 @@ def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param,sdk_root,an else: ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + num_of_cpu = get_num_of_cpu() if ndk_build_param == None: - command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + command = '%s -j%d -C %s %s' % (ndk_path, num_of_cpu, app_android_root, ndk_module_path) else: - command = '%s -C %s %s %s' % (ndk_path, app_android_root, ndk_build_param, ndk_module_path) + command = '%s -j%d -C %s %s %s' % (ndk_path, num_of_cpu, app_android_root, ndk_build_param, ndk_module_path) + print command if os.system(command) != 0: raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!") elif android_platform is not None: @@ -140,47 +159,23 @@ def copy_resources(target, app_android_root): # jsb samples should copy javascript files and resources(shared with cocos2d-html5) if target in JSB_SAMPLES: - resources_dir = os.path.join(app_android_root, "../../../../cocos/scripting/javascript/script") + resources_dir = os.path.join(app_android_root, "../../../cocos/scripting/javascript/script") copy_files(resources_dir, assets_dir) - if target == "cocosdragon": - resources_dir = os.path.join(app_android_root, "../../Shared/games/CocosDragonJS/Published files Android") - if target == "crystalcraze": - resources_dir = os.path.join(app_android_root, "../../Shared/games/CrystalCraze/Published-Android") if target == "testjavascript": - resources_dir = os.path.join(app_android_root, "../../Shared/tests/") - if target == "watermelonwithme": - resources_dir = os.path.join(app_android_root, "../../Shared/games/WatermelonWithMe") - if target != "moonwarriors": - copy_files(resources_dir, assets_dir) - else: - resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors/res") - dst_dir = os.path.join(assets_dir, "res") - os.mkdir(dst_dir) - copy_files(resources_dir, dst_dir) - resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors/src") - dst_dir = os.path.join(assets_dir, "src") - os.mkdir(dst_dir) - copy_files(resources_dir, dst_dir) - resources_dir = os.path.join(app_android_root, "../../Shared/games/MoonWarriors") - for item in os.listdir(resources_dir): - path = os.path.join(resources_dir, item) - if item.endswith('.js') and os.path.isfile(path): - shutil.copy(path, assets_dir) + resources_dir = os.path.join(app_android_root, "../tests/") - # AssetsManager test should also copy javascript files - if target == "assetsmanager": - resources_dir = os.path.join(app_android_root, "../../../../cocos/scripting/javascript/script") copy_files(resources_dir, assets_dir) + # lua samples should copy lua script if target in LUA_SAMPLES: - resources_dir = os.path.join(app_android_root, "../../../../cocos/scripting/lua/script") + resources_dir = os.path.join(app_android_root, "../../../cocos/scripting/lua/script") copy_files(resources_dir, assets_dir) # TestLua shared resources with TestCpp if target == "testlua": - resources_dir = os.path.join(app_android_root, "../../../Cpp/TestCpp/Resources") + resources_dir = os.path.join(app_android_root, "../../test-cpp/Resources") copy_files(resources_dir, assets_dir) def build_samples(target,ndk_build_param,android_platform,build_mode): @@ -194,12 +189,12 @@ def build_samples(target,ndk_build_param,android_platform,build_mode): cocos_root = os.path.join(current_dir, "..") if android_platform is not None: - sdk_root = check_environment_variables_sdk() - if android_platform.isdigit(): - android_platform = 'android-'+android_platform - else: - print 'please use vaild android platform' - exit(1) + sdk_root = check_environment_variables_sdk() + if android_platform.isdigit(): + android_platform = 'android-'+android_platform + else: + print 'please use vaild android platform' + exit(1) if build_mode is None: build_mode = 'debug' @@ -208,28 +203,12 @@ def build_samples(target,ndk_build_param,android_platform,build_mode): app_android_root = '' for target in build_targets: - if target == 'hellocpp': - app_android_root = os.path.join(cocos_root, 'samples/Cpp/HelloCpp/proj.android') - elif target == 'testcpp': - app_android_root = os.path.join(cocos_root, 'samples/Cpp/TestCpp/proj.android') - elif target == 'simplegame': - app_android_root = os.path.join(cocos_root, 'samples/Cpp/SimpleGame/proj.android') - elif target == 'assetsmanager': - app_android_root = os.path.join(cocos_root, 'samples/Cpp/AssetsManagerTest/proj.android') - elif target == 'hellolua': - app_android_root = os.path.join(cocos_root, 'samples/Lua/HelloLua/proj.android') + if target == 'testcpp': + app_android_root = os.path.join(cocos_root, 'tests/test-cpp/proj.android') elif target == 'testlua': - app_android_root = os.path.join(cocos_root, 'samples/Lua/TestLua/proj.android') - elif target == 'cocosdragon': - app_android_root = os.path.join(cocos_root, 'samples/Javascript/CocosDragonJS/proj.android') - elif target == 'crystalcraze': - app_android_root = os.path.join(cocos_root, 'samples/Javascript/CrystalCraze/proj.android') - elif target == 'moonwarriors': - app_android_root = os.path.join(cocos_root, 'samples/Javascript/MoonWarriors/proj.android') + app_android_root = os.path.join(cocos_root, 'tests/test-lua/proj.android') elif target == 'testjavascript': - app_android_root = os.path.join(cocos_root, 'samples/Javascript/TestJavascript/proj.android') - elif target == 'watermelonwithme': - app_android_root = os.path.join(cocos_root, 'samples/Javascript/WatermelonWithMe/proj.android') + app_android_root = os.path.join(cocos_root, 'tests/test-javascript/proj.android') else: print 'unknown target: %s' % target continue @@ -241,19 +220,40 @@ def build_samples(target,ndk_build_param,android_platform,build_mode): if __name__ == '__main__': #parse the params - usage = """usage: %prog [options] target + usage = """ + This script is mainy used for building tests built-in with cocos2d-x. - Valid targets are: [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon|crystalcraze|moonwarriors|testjavascript|watermelonwithme] + Usage: %prog [options] target - You can use [all|cpp|lua|jsb], to build all, or all the C++, or all the Lua, or all the JavaScript samples respectevely.""" + Valid targets are: [testcpp|testlua|testjavascript]. You can combine them arbitrarily with a whitespace among two valid targets. + + You can use [all|cpp|lua|jsb], to build all the tests, or all the c++ tests, or all the Lua tests, or all the JavaScript tests respectevely. + + cpp = ['testcpp'] + lua = ['testlua'] + jsb = ['testjavascript'] + all = cpp + lua + jsb // be careful with the all target, it may took a very long time to compile all the projects, do it under your own risk. + + If you are new to cocos2d-x, I recommend you start with testcpp, testlua or testjavascript. + + You can combine these targets like this: + + //1. to build simplegame and assetsmanager + python android-build.py -p 10 testcpp testlua + + //2. to build testlua and all the jsb tests + python android-build.py -p 19 testlua jsb + + Note: You should install ant to generate apk while building the andriod tests. But it is optional. You can generate apk with eclipse. + """ parser = OptionParser(usage=usage) parser.add_option("-n", "--ndk", dest="ndk_build_param", - help='parameter for ndk-build') + help='Parameter for ndk-build') parser.add_option("-p", "--platform", dest="android_platform", - help='parameter for android-update.Without the parameter,the script just build dynamic library for project. Valid android-platform are:[10|11|12|13|14|15|16|17|18|19]') + help='Parameter for android-update. Without the parameter,the script just build dynamic library for the projects. Valid android-platform are:[10|11|12|13|14|15|16|17|18|19]') parser.add_option("-b", "--build", dest="build_mode", - help='the build mode for java project,debug[default] or release.Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html') + help='The build mode for java project,debug[default] or release. Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html') (opts, args) = parser.parse_args() if len(args) == 0: diff --git a/build/cocos2d-win32.vc2012.sln b/build/cocos2d-win32.vc2012.sln index 3593a117d8..37798a321a 100644 --- a/build/cocos2d-win32.vc2012.sln +++ b/build/cocos2d-win32.vc2012.sln @@ -5,15 +5,13 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libAudio", "..\cocos\audio\ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libcocos2d", "..\cocos\2d\cocos2d.vcxproj", "{98A51BA8-FC3A-415B-AC8F-8C7BD464E93E}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloCpp", "..\samples\Cpp\HelloCpp\proj.win32\HelloCpp.vcxproj", "{B8BF9E81-35FD-4582-BA1C-B85FA365BABB}" -EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libBox2D", "..\external\Box2D\proj.win32\Box2D.vcxproj", "{929480E7-23C0-4DF6-8456-096D71547116}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libchipmunk", "..\external\chipmunk\proj.win32\chipmunk.vcxproj", "{207BC7A9-CCF1-4F2F-A04D-45F72242AE25}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libExtensions", "..\extensions\proj.win32\libExtensions.vcxproj", "{21B2C324-891F-48EA-AD1A-5AE13DE12E28}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestCpp", "..\samples\Cpp\TestCpp\proj.win32\TestCpp.vcxproj", "{76A39BB2-9B84-4C65-98A5-654D86B86F2A}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestCpp", "..\tests\test-cpp\proj.win32\TestCpp.vcxproj", "{76A39BB2-9B84-4C65-98A5-654D86B86F2A}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libCocosBuilder", "..\cocos\editor-support\cocosbuilder\proj.win32\libCocosBuilder.vcxproj", "{811C0DAB-7B96-4BD3-A154-B7572B58E4AB}" EndProject @@ -25,29 +23,15 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libNetwork", "..\cocos\netw EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libSpine", "..\cocos\editor-support\spine\proj.win32\libSpine.vcxproj", "{B7C2A162-DEC9-4418-972E-240AB3CBFCAE}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AssetsManagerTest", "..\samples\Cpp\AssetsManagerTest\proj.win32\AssetsManagerTest.vcxproj", "{6D37505F-A890-441D-BD3F-A61E2C0469CE}" -EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBinding", "..\cocos\scripting\javascript\bindings\proj.win32\libJSBinding.vcxproj", "{39379840-825A-45A0-B363-C09FFEF864BD}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestJavascript", "..\samples\Javascript\TestJavascript\proj.win32\TestJavascript.vcxproj", "{D0F06A44-A245-4D13-A498-0120C203B539}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestJavascript", "..\tests\test-javascript\proj.win32\TestJavascript.vcxproj", "{D0F06A44-A245-4D13-A498-0120C203B539}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libLocalStorage", "..\cocos\storage\local-storage\proj.win32\libLocalStorage.vcxproj", "{632A8F38-D0F0-4D22-86B3-D69F5E6BF63A}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CocosDragonJS", "..\samples\Javascript\CocosDragonJS\proj.win32\CocosDragonJS.vcxproj", "{68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CrystalCraze", "..\samples\Javascript\CrystalCraze\proj.win32\CrystalCraze.vcxproj", "{9A17D9A4-4B11-4E32-94F6-895FF4909EC5}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MoonWarriors", "..\samples\Javascript\MoonWarriors\proj.win32\MoonWarriors.vcxproj", "{1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WatermelonWithMe", "..\samples\Javascript\WatermelonWithMe\proj.win32\WatermelonWithMe.vcxproj", "{BE092D9E-95AE-4F86-84CE-F4519E4F3F15}" -EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblua", "..\cocos\scripting\lua\bindings\liblua.vcxproj", "{DDC3E27F-004D-4DD4-9DD3-931A013D2159}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloLua", "..\samples\Lua\HelloLua\proj.win32\HelloLua.vcxproj", "{13E55395-94A2-4CD9-BFC2-1A051F80C17D}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLua", "..\samples\Lua\TestLua\proj.win32\TestLua.win32.vcxproj", "{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SimpleGame", "..\samples\Cpp\SimpleGame\proj.win32\SimpleGame.vcxproj", "{E0E282F4-8487-452C-BFAB-CB960EB4D22F}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestLua", "..\tests\test-lua\proj.win32\TestLua.win32.vcxproj", "{4E6A7A0E-DDD8-4BAA-8B22-C964069364ED}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libJSBindingForBuilder", "..\cocos\scripting\javascript\bindings\cocosbuilder\libJSBindingForBuilder.vcxproj", "{F9DA0FC1-651B-457B-962E-A4D61CEBF5FD}" EndProject diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index faa1e4571d..9d609edff2 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -3d6ada05d55194dd8e4c10ed8316add7c0d8705c \ No newline at end of file +caae58ff83f2655d5ea4c19e00a2be17259f8559 \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id deleted file mode 100644 index 0f53b948c7..0000000000 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -2efefc01ff97bda1498d1d4a850ea1881f751f7c \ No newline at end of file diff --git a/build/cocos2d_tests.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_tests.xcodeproj/project.pbxproj.REMOVED.git-id new file mode 100644 index 0000000000..93894bc133 --- /dev/null +++ b/build/cocos2d_tests.xcodeproj/project.pbxproj.REMOVED.git-id @@ -0,0 +1 @@ +88d35147fd70ffbc353388aa9424bd2f0645ac95 \ No newline at end of file diff --git a/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test JavaScript Mac.xcscheme b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test JavaScript Mac.xcscheme new file mode 100644 index 0000000000..28f898622e --- /dev/null +++ b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test JavaScript Mac.xcscheme @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test JavaScript iOS.xcscheme b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test JavaScript iOS.xcscheme new file mode 100644 index 0000000000..133414e7f6 --- /dev/null +++ b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test JavaScript iOS.xcscheme @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test cpp Mac.xcscheme b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test cpp Mac.xcscheme new file mode 100644 index 0000000000..67958d0d29 --- /dev/null +++ b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test cpp Mac.xcscheme @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test cpp iOS.xcscheme b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test cpp iOS.xcscheme new file mode 100644 index 0000000000..49d3995c5f --- /dev/null +++ b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test cpp iOS.xcscheme @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test lua Mac.xcscheme b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test lua Mac.xcscheme new file mode 100644 index 0000000000..be135ee298 --- /dev/null +++ b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test lua Mac.xcscheme @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test lua iOS.xcscheme b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test lua iOS.xcscheme new file mode 100644 index 0000000000..5491ffde08 --- /dev/null +++ b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/Test lua iOS.xcscheme @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/build-all-tests Mac.xcscheme b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/build-all-tests Mac.xcscheme new file mode 100644 index 0000000000..7e6100542d --- /dev/null +++ b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/build-all-tests Mac.xcscheme @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/build-all-tests iOS.xcscheme b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/build-all-tests iOS.xcscheme new file mode 100644 index 0000000000..7791124b23 --- /dev/null +++ b/build/cocos2d_tests.xcodeproj/xcshareddata/xcschemes/build-all-tests iOS.xcscheme @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/build/win32-msvc-2010-x86.cmd b/build/win32-msvc-2010-x86.cmd deleted file mode 100644 index cf3d9e893f..0000000000 --- a/build/win32-msvc-2010-x86.cmd +++ /dev/null @@ -1,8 +0,0 @@ -@echo off -SETLOCAL - -:start -mkdir win32-msvc-vs2010-x86 -cd win32-msvc-vs2010-x86 -cmake -G "Visual Studio 10" ../.. -pause diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 303a1da40f..06baeeef45 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -47,10 +47,9 @@ CCEventListenerTouch.cpp \ CCEventMouse.cpp \ CCEventTouch.cpp \ CCFont.cpp \ +CCFontCharMap.cpp \ CCFontAtlas.cpp \ CCFontAtlasCache.cpp \ -CCFontAtlasFactory.cpp \ -CCFontDefinition.cpp \ CCFontFNT.cpp \ CCFontFreeType.cpp \ ccFPSImages.c \ @@ -90,7 +89,6 @@ CCSpriteBatchNode.cpp \ CCSpriteFrame.cpp \ CCSpriteFrameCache.cpp \ CCTextFieldTTF.cpp \ -CCTextImage.cpp \ CCTexture2D.cpp \ CCTextureAtlas.cpp \ CCTextureCache.cpp \ @@ -113,7 +111,7 @@ cocos2d.cpp \ TGAlib.cpp \ TransformUtils.cpp \ ZipUtils.cpp \ -platform/CCEGLViewProtocol.cpp \ +platform/CCGLViewProtocol.cpp \ platform/CCFileUtils.cpp \ platform/CCSAXParser.cpp \ platform/CCThread.cpp \ @@ -122,6 +120,7 @@ renderer/CCFrustum.cpp \ renderer/CCGroupCommand.cpp \ renderer/CCMaterialManager.cpp \ renderer/CCQuadCommand.cpp \ +renderer/CCBatchCommand.cpp \ renderer/CCRenderCommand.cpp \ renderer/CCRenderer.cpp \ renderer/CCRenderMaterial.cpp \ diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 5e88b70832..15492a651f 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -34,7 +34,7 @@ THE SOFTWARE. #include "ccGLStateCache.h" #include "CCDirector.h" #include "TransformUtils.h" -#include "CCRenderer.h" +#include "renderer/CCRenderer.h" #include "renderer/CCQuadCommand.h" // external @@ -152,13 +152,13 @@ void AtlasNode::draw(void) auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); - _quadCommand.init(0, - _vertexZ, + _quadCommand.init( + _globalZOrder, _textureAtlas->getTexture()->getName(), shader, _blendFunc, _textureAtlas->getQuads(), - _textureAtlas->getTotalQuads(), + _quadsToDraw, _modelViewTransform); Director::getInstance()->getRenderer()->addCommand(&_quadCommand); diff --git a/cocos/2d/CCClippingNode.cpp b/cocos/2d/CCClippingNode.cpp index cdaf6a3df5..47cd72a881 100644 --- a/cocos/2d/CCClippingNode.cpp +++ b/cocos/2d/CCClippingNode.cpp @@ -31,9 +31,10 @@ #include "CCShaderCache.h" #include "CCDirector.h" #include "CCDrawingPrimitives.h" -#include "CCRenderer.h" -#include "CCGroupCommand.h" -#include "CCCustomCommand.h" + +#include "renderer/CCRenderer.h" +#include "renderer/CCGroupCommand.h" +#include "renderer/CCCustomCommand.h" NS_CC_BEGIN @@ -209,12 +210,12 @@ void ClippingNode::visit() Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand.init(0,_vertexZ); + _groupCommand.init(_globalZOrder); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); - _beforeVisitCmd.init(0,_vertexZ); + _beforeVisitCmd.init(_globalZOrder); _beforeVisitCmd.func = CC_CALLBACK_0(ClippingNode::onBeforeVisit, this); renderer->addCommand(&_beforeVisitCmd); if (_alphaThreshold < 1) @@ -237,7 +238,7 @@ void ClippingNode::visit() } _stencil->visit(); - _afterDrawStencilCmd.init(0,_vertexZ); + _afterDrawStencilCmd.init(_globalZOrder); _afterDrawStencilCmd.func = CC_CALLBACK_0(ClippingNode::onAfterDrawStencil, this); renderer->addCommand(&_afterDrawStencilCmd); @@ -251,7 +252,7 @@ void ClippingNode::visit() { auto node = _children.at(i); - if ( node && node->getZOrder() < 0 ) + if ( node && node->getLocalZOrder() < 0 ) node->visit(); else break; @@ -267,7 +268,7 @@ void ClippingNode::visit() this->draw(); } - _afterVisitCmd.init(0,_vertexZ); + _afterVisitCmd.init(_globalZOrder); _afterVisitCmd.func = CC_CALLBACK_0(ClippingNode::onAfterVisit, this); renderer->addCommand(&_afterVisitCmd); diff --git a/cocos/2d/CCConfiguration.cpp b/cocos/2d/CCConfiguration.cpp index a576532ade..940c9fdb9b 100644 --- a/cocos/2d/CCConfiguration.cpp +++ b/cocos/2d/CCConfiguration.cpp @@ -31,13 +31,13 @@ THE SOFTWARE. #include "CCDictionary.h" #include "CCInteger.h" #include "CCBool.h" -#include "cocos2d.h" #include "platform/CCFileUtils.h" using namespace std; NS_CC_BEGIN +extern const char* cocos2dVersion(); Configuration* Configuration::s_sharedConfiguration = nullptr; @@ -75,7 +75,7 @@ bool Configuration::init() _valueDict["cocos2d.x.compiled_with_gl_state_cache"] = Value(true); #endif -#ifdef DEBUG +#if COCOS2D_DEBUG _valueDict["cocos2d.x.build_type"] = Value("DEBUG"); #else _valueDict["cocos2d.x.build_type"] = Value("RELEASE"); @@ -146,7 +146,7 @@ void Configuration::gatherGPUInfo() _supportsShareableVAO = checkForGLExtension("vertex_array_object"); _valueDict["gl.supports_vertex_array_object"] = Value(_supportsShareableVAO); - + CHECK_GL_ERROR_DEBUG(); } diff --git a/cocos/2d/CCDeprecated.h b/cocos/2d/CCDeprecated.h index 05c1d618ee..cf02a8cf6a 100644 --- a/cocos/2d/CCDeprecated.h +++ b/cocos/2d/CCDeprecated.h @@ -764,7 +764,7 @@ CC_DEPRECATED_ATTRIBUTE typedef TMXTiledMap CCTMXTiledMap; CC_DEPRECATED_ATTRIBUTE typedef TileMapAtlas CCTileMapAtlas; CC_DEPRECATED_ATTRIBUTE typedef Timer CCTimer; CC_DEPRECATED_ATTRIBUTE typedef Scheduler CCScheduler; -CC_DEPRECATED_ATTRIBUTE typedef EGLView CCEGLView; +CC_DEPRECATED_ATTRIBUTE typedef GLView CCEGLView; CC_DEPRECATED_ATTRIBUTE typedef Component CCComponent; CC_DEPRECATED_ATTRIBUTE typedef AffineTransform CCAffineTransform; @@ -840,7 +840,7 @@ CC_DEPRECATED_ATTRIBUTE extern const char* kCCAttributeNameColor; CC_DEPRECATED_ATTRIBUTE extern const char* kCCAttributeNamePosition; CC_DEPRECATED_ATTRIBUTE extern const char* kCCAttributeNameTexCoord; -CC_DEPRECATED_ATTRIBUTE const int kCCVertexAttribFlag_None = GL::VERTEX_ATTRIB_FLAT_NONE; +CC_DEPRECATED_ATTRIBUTE const int kCCVertexAttribFlag_None = GL::VERTEX_ATTRIB_FLAG_NONE; CC_DEPRECATED_ATTRIBUTE const int kCCVertexAttribFlag_Position = GL::VERTEX_ATTRIB_FLAG_POSITION; CC_DEPRECATED_ATTRIBUTE const int kCCVertexAttribFlag_Color = GL::VERTEX_ATTRIB_FLAG_COLOR; CC_DEPRECATED_ATTRIBUTE const int kCCVertexAttribFlag_TexCoords = GL::VERTEX_ATTRIB_FLAG_TEX_COORDS; diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 3e06a99c75..b7bee4df39 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -55,14 +55,15 @@ THE SOFTWARE. #include "kazmath/GL/matrix.h" #include "CCProfiling.h" #include "platform/CCImage.h" -#include "CCEGLView.h" +#include "CCGLView.h" #include "CCConfiguration.h" #include "CCEventDispatcher.h" #include "CCEventCustom.h" #include "CCFontFreeType.h" -#include "CCRenderer.h" -#include "CCConsole.h" +#include "renderer/CCRenderer.h" #include "renderer/CCFrustum.h" +#include "CCConsole.h" + /** Position of the FPS @@ -164,9 +165,6 @@ bool Director::init(void) _renderer = new Renderer; _console = new Console; - // create autorelease pool - PoolManager::sharedPoolManager()->push(); - return true; } @@ -192,9 +190,8 @@ Director::~Director(void) delete _renderer; delete _console; - // pop the autorelease pool - PoolManager::sharedPoolManager()->pop(); - PoolManager::purgePoolManager(); + // clean auto release pool + PoolManager::destroyInstance(); // delete _lastUpdate CC_SAFE_DELETE(_lastUpdate); @@ -354,7 +351,7 @@ void Director::calculateDeltaTime() _deltaTime = MAX(0, _deltaTime); } -#ifdef DEBUG +#if COCOS2D_DEBUG // If we are debugging our code, prevent big delta time if (_deltaTime > 0.2f) { @@ -368,7 +365,7 @@ float Director::getDeltaTime() const { return _deltaTime; } -void Director::setOpenGLView(EGLView *openGLView) +void Director::setOpenGLView(GLView *openGLView) { CCASSERT(openGLView, "opengl view should not be null"); @@ -379,9 +376,10 @@ void Director::setOpenGLView(EGLView *openGLView) conf->gatherGPUInfo(); CCLOG("%s\n",conf->getInfo().c_str()); - // EAGLView is not a Object - delete _openGLView; // [openGLView_ release] + if(_openGLView) + _openGLView->release(); _openGLView = openGLView; + _openGLView->retain(); // set size _winSizeInPoints = _openGLView->getDesignResolutionSize(); @@ -944,7 +942,8 @@ void Director::createStatsLabel() Secondly, the size of this image is 480*320, to display the FPS label with correct size, a factor of design resolution ratio of 480x320 is also needed. */ - float factor = EGLView::getInstance()->getDesignResolutionSize().height / 320.0f; + auto glview = Director::getInstance()->getOpenGLView(); + float factor = glview->getDesignResolutionSize().height / 320.0f; _FPSLabel = LabelAtlas::create(); _FPSLabel->retain(); @@ -1048,7 +1047,7 @@ void DisplayLinkDirector::mainLoop() drawScene(); // release the objects - PoolManager::sharedPoolManager()->pop(); + PoolManager::getInstance()->getCurrentPool()->clear(); } } diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index 23bc8cda42..be553ea84a 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -49,7 +49,7 @@ NS_CC_BEGIN /* Forward declarations. */ class LabelAtlas; class Scene; -class EGLView; +class GLView; class DirectorDelegate; class Node; class Scheduler; @@ -143,12 +143,12 @@ public: /** seconds per frame */ inline float getSecondsPerFrame() { return _secondsPerFrame; } - /** Get the EGLView, where everything is rendered + /** Get the GLView, where everything is rendered * @js NA * @lua NA */ - inline EGLView* getOpenGLView() { return _openGLView; } - void setOpenGLView(EGLView *openGLView); + inline GLView* getOpenGLView() { return _openGLView; } + void setOpenGLView(GLView *openGLView); TextureCache* getTextureCache() const; @@ -202,7 +202,7 @@ public: /** returns visible size of the OpenGL view in points. * the value is equal to getWinSize if don't invoke - * EGLView::setDesignResolutionSize() + * GLView::setDesignResolutionSize() */ Size getVisibleSize() const; @@ -422,8 +422,8 @@ protected: /* delta time since last tick to main loop */ float _deltaTime; - /* The EGLView, where everything is rendered */ - EGLView *_openGLView; + /* The GLView, where everything is rendered */ + GLView *_openGLView; //texture cache belongs to this director TextureCache *_textureCache; @@ -492,8 +492,8 @@ protected: /* Console for the director */ Console *_console; - // EGLViewProtocol will recreate stats labels to fit visible rect - friend class EGLViewProtocol; + // GLViewProtocol will recreate stats labels to fit visible rect + friend class GLViewProtocol; }; /** diff --git a/cocos/2d/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp index b920a311c2..003209b6e4 100644 --- a/cocos/2d/CCDrawNode.cpp +++ b/cocos/2d/CCDrawNode.cpp @@ -26,9 +26,9 @@ #include "CCGL.h" #include "CCEventType.h" #include "CCConfiguration.h" -#include "CCCustomCommand.h" +#include "renderer/CCCustomCommand.h" +#include "renderer/CCRenderer.h" #include "CCDirector.h" -#include "CCRenderer.h" #include "CCEventListenerCustom.h" #include "CCEventDispatcher.h" @@ -241,7 +241,7 @@ void DrawNode::render() void DrawNode::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(DrawNode::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 609b67c3cd..9c2603b57c 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -191,7 +191,7 @@ EventDispatcher::~EventDispatcher() removeAllEventListeners(); } -void EventDispatcher::visitTarget(Node* node) +void EventDispatcher::visitTarget(Node* node, bool isRootNode) { int i = 0; auto& children = node->getChildren(); @@ -206,24 +206,55 @@ void EventDispatcher::visitTarget(Node* node) { child = children.at(i); - if ( child && child->getZOrder() < 0 ) - visitTarget(child); + if ( child && child->getLocalZOrder() < 0 ) + visitTarget(child, false); else break; } - _nodePriorityMap.insert(std::make_pair(node, ++_nodePriorityIndex)); + if (_nodeListenersMap.find(node) != _nodeListenersMap.end()) + { + _globalZOrderNodeMap[node->getGlobalZOrder()].push_back(node); + } for( ; i < childrenCount; i++ ) { child = children.at(i); if (child) - visitTarget(child); + visitTarget(child, false); } } else { - _nodePriorityMap.insert(std::make_pair(node, ++_nodePriorityIndex)); + if (_nodeListenersMap.find(node) != _nodeListenersMap.end()) + { + _globalZOrderNodeMap[node->getGlobalZOrder()].push_back(node); + } + } + + if (isRootNode) + { + std::vector globalZOrders; + globalZOrders.reserve(_globalZOrderNodeMap.size()); + + for (const auto& e : _globalZOrderNodeMap) + { + globalZOrders.push_back(e.first); + } + + std::sort(globalZOrders.begin(), globalZOrders.end(), [](const float a, const float b){ + return a < b; + }); + + for (const auto& globalZ : globalZOrders) + { + for (const auto& n : _globalZOrderNodeMap[globalZ]) + { + _nodePriorityMap[n] = ++_nodePriorityIndex; + } + } + + _globalZOrderNodeMap.clear(); } } @@ -354,7 +385,7 @@ void EventDispatcher::forceAddEventListener(EventListener* listener) } else { - setDirty(listenerID, DirtyFlag::FIXED_PRITORY); + setDirty(listenerID, DirtyFlag::FIXED_PRIORITY); } } @@ -496,7 +527,7 @@ void EventDispatcher::setPriority(EventListener* listener, int fixedPriority) if (listener->getFixedPriority() != fixedPriority) { listener->setFixedPriority(fixedPriority); - setDirty(listener->getListenerID(), DirtyFlag::FIXED_PRITORY); + setDirty(listener->getListenerID(), DirtyFlag::FIXED_PRIORITY); } return; } @@ -784,7 +815,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) if (event->isStopped()) { updateListeners(event); - return false; + return true; } return false; @@ -921,7 +952,7 @@ void EventDispatcher::sortEventListeners(const EventListener::ListenerID& listen if (dirtyFlag != DirtyFlag::NONE) { - if ((int)dirtyFlag & (int)DirtyFlag::FIXED_PRITORY) + if ((int)dirtyFlag & (int)DirtyFlag::FIXED_PRIORITY) { sortEventListenersOfFixedPriority(listenerID); } @@ -947,7 +978,7 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener _nodePriorityIndex = 0; _nodePriorityMap.clear(); - visitTarget(rootNode); + visitTarget(rootNode, true); // After sort: priority < 0, > 0 auto sceneGraphlisteners = listeners->getSceneGraphPriorityListeners(); @@ -1135,7 +1166,7 @@ bool EventDispatcher::isEnabled() const void EventDispatcher::setDirtyForNode(Node* node) { - // Mark the node dirty only when there was an eventlistener associates with it. + // Mark the node dirty only when there is an eventlistener associated with it. if (_nodeListenersMap.find(node) != _nodeListenersMap.end()) { _dirtyNodes.insert(node); diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index cb62e4711b..f7c886508b 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -207,16 +207,16 @@ protected: enum class DirtyFlag { NONE = 0, - FIXED_PRITORY = 1 << 0, + FIXED_PRIORITY = 1 << 0, SCENE_GRAPH_PRIORITY = 1 << 1, - ALL = FIXED_PRITORY | SCENE_GRAPH_PRIORITY + ALL = FIXED_PRIORITY | SCENE_GRAPH_PRIORITY }; /** Sets the dirty flag for a specified listener ID */ void setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag); /** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with scene graph priority */ - void visitTarget(Node* node); + void visitTarget(Node* node, bool isRootNode); /** Listeners map */ std::unordered_map _listeners; @@ -230,6 +230,9 @@ protected: /** The map of node and its event priority */ std::unordered_map _nodePriorityMap; + /** key: Global Z Order, value: Sorted Nodes */ + std::unordered_map> _globalZOrderNodeMap; + /** The listeners to be added after dispatching event */ std::vector _toAddedListeners; diff --git a/cocos/2d/CCEventTouch.h b/cocos/2d/CCEventTouch.h index 9a8037d494..508241ca85 100644 --- a/cocos/2d/CCEventTouch.h +++ b/cocos/2d/CCEventTouch.h @@ -60,7 +60,7 @@ private: EventCode _eventCode; std::vector _touches; - friend class EGLViewProtocol; + friend class GLViewProtocol; }; diff --git a/cocos/2d/CCFont.cpp b/cocos/2d/CCFont.cpp index dc363cfe02..1a158af323 100644 --- a/cocos/2d/CCFont.cpp +++ b/cocos/2d/CCFont.cpp @@ -26,14 +26,8 @@ #include "CCFont.h" #include "ccUTF8.h" -#include "CCFontFNT.h" -#include "CCFontFreeType.h" -#include "edtaa3func.h" - NS_CC_BEGIN -const int Font::DistanceMapSpread = 3; - const char * Font::_glyphASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ "; const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ "; @@ -42,7 +36,6 @@ const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLM Font::Font() : _usedGlyphs(GlyphCollection::ASCII) , _customGlyphs(nullptr) -,_distanceFieldEnabled(false) { } @@ -92,6 +85,7 @@ void Font::setCurrentGlyphCollection(GlyphCollection glyphs, const char *customG break; } + _usedGlyphs = glyphs; } const char * Font::getCurrentGlyphCollection() const @@ -106,175 +100,7 @@ const char * Font::getCurrentGlyphCollection() const } } -Font* Font::createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) -{ - return FontFreeType::create(fntName, fontSize, glyphs, customGlyphs); -} - -Font* Font::createWithFNT(const std::string& fntFilePath) -{ - return FontFNT::create(fntFilePath); -} - -unsigned char * Font::makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height) -{ - unsigned int pixelAmount = (width + 2 * DistanceMapSpread) * (height + 2 * DistanceMapSpread); - - short * xdist = (short *) malloc( pixelAmount * sizeof(short) ); - short * ydist = (short *) malloc( pixelAmount * sizeof(short) ); - double * gx = (double *) calloc( pixelAmount, sizeof(double) ); - double * gy = (double *) calloc( pixelAmount, sizeof(double) ); - double * data = (double *) calloc( pixelAmount, sizeof(double) ); - double * outside = (double *) calloc( pixelAmount, sizeof(double) ); - double * inside = (double *) calloc( pixelAmount, sizeof(double) ); - unsigned int i,j; - - // Convert img into double (data) rescale image levels between 0 and 1 - unsigned int outWidth = width + 2 * DistanceMapSpread; - for (i = 0; i < width; ++i) - { - for (j = 0; j < height; ++j) - { - data[j * outWidth + DistanceMapSpread + i] = img[j * width + i] / 255.0; - } - } - - width += 2 * DistanceMapSpread; - height += 2 * DistanceMapSpread; - - // Transform background (outside contour, in areas of 0's) - computegradient( data, width, height, gx, gy); - edtaa3(data, gx, gy, width, height, xdist, ydist, outside); - for( i=0; i< pixelAmount; i++) - if( outside[i] < 0.0 ) - outside[i] = 0.0; - - // Transform foreground (inside contour, in areas of 1's) - for( i=0; i< pixelAmount; i++) - data[i] = 1 - data[i]; - computegradient( data, width, height, gx, gy); - edtaa3(data, gx, gy, width, height, xdist, ydist, inside); - for( i=0; i< pixelAmount; i++) - if( inside[i] < 0.0 ) - inside[i] = 0.0; - - // The bipolar distance field is now outside-inside - double dist; - /* Single channel 8-bit output (bad precision and range, but simple) */ - unsigned char *out = (unsigned char *) malloc( pixelAmount * sizeof(unsigned char) ); - for( i=0; i < pixelAmount; i++) - { - dist = outside[i] - inside[i]; - dist = 128.0 - dist*16; - if( dist < 0 ) dist = 0; - if( dist > 255 ) dist = 255; - out[i] = (unsigned char) dist; - } - /* Dual channel 16-bit output (more complicated, but good precision and range) */ - /*unsigned char *out = (unsigned char *) malloc( pixelAmount * 3 * sizeof(unsigned char) ); - for( i=0; i< pixelAmount; i++) - { - dist = outside[i] - inside[i]; - dist = 128.0 - dist*16; - if( dist < 0.0 ) dist = 0.0; - if( dist >= 256.0 ) dist = 255.999; - // R channel is a copy of the original grayscale image - out[3*i] = img[i]; - // G channel is fraction - out[3*i + 1] = (unsigned char) ( 256 - (dist - floor(dist)* 256.0 )); - // B channel is truncated integer part - out[3*i + 2] = (unsigned char)dist; - }*/ - - free( xdist ); - free( ydist ); - free( gx ); - free( gy ); - free( data ); - free( outside ); - free( inside ); - - return out; -} - -void Font::setDistanceFieldEnabled(bool distanceFieldEnabled) -{ - _distanceFieldEnabled = distanceFieldEnabled; -} - -bool Font::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize) -{ - unsigned char *sourceBitmap = 0; - int sourceWidth = 0; - int sourceHeight = 0; - - sourceBitmap = getGlyphBitmap(charToRender, sourceWidth, sourceHeight); - - if (!sourceBitmap) - return false; - - if (_distanceFieldEnabled) - { - unsigned char * out = makeDistanceMap(sourceBitmap,sourceWidth,sourceHeight); - - int iX = posX; - int iY = posY; - - sourceWidth += 2 * DistanceMapSpread; - sourceHeight += 2 * DistanceMapSpread; - - for (int y = 0; y < sourceHeight; ++y) - { - int bitmap_y = y * sourceWidth; - - for (int x = 0; x < sourceWidth; ++x) - { - /* Dual channel 16-bit output (more complicated, but good precision and range) */ - /*int index = (iX + ( iY * destSize )) * 3; - int index2 = (bitmap_y + x)*3; - destMemory[index] = out[index2]; - destMemory[index + 1] = out[index2 + 1]; - destMemory[index + 2] = out[index2 + 2];*/ - - //Single channel 8-bit output - destMemory[iX + ( iY * destSize )] = out[bitmap_y + x]; - - iX += 1; - } - - iX = posX; - iY += 1; - } - free(out); - return true; - } - - int iX = posX; - int iY = posY; - - for (int y = 0; y < sourceHeight; ++y) - { - int bitmap_y = y * sourceWidth; - - for (int x = 0; x < sourceWidth; ++x) - { - unsigned char cTemp = sourceBitmap[bitmap_y + x]; - - // the final pixel - destMemory[(iX + ( iY * destSize ) )] = cTemp; - - iX += 1; - } - - iX = posX; - iY += 1; - } - - //everything good - return true; -} - -unsigned short int * Font::getUTF16Text(const char *text, int &outNumLetters) const +unsigned short* Font::getUTF16Text(const char *text, int &outNumLetters) const { unsigned short* utf16String = cc_utf8_to_utf16(text); @@ -290,7 +116,7 @@ int Font::getUTF16TextLenght(unsigned short int *text) const return cc_wcslen(text); } -unsigned short int * Font::trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const +unsigned short * Font::trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const { if ( newBegin < 0 || newEnd <= 0 ) return 0; @@ -316,11 +142,6 @@ unsigned short int * Font::trimUTF16Text(unsigned short int *text, int newBegin return trimmedString; } -Rect Font::getRectForChar(unsigned short theChar) const -{ - return Rect::ZERO; -} - NS_CC_END diff --git a/cocos/2d/CCFont.h b/cocos/2d/CCFont.h index 440da0808b..719d424a49 100644 --- a/cocos/2d/CCFont.h +++ b/cocos/2d/CCFont.h @@ -28,43 +28,29 @@ #include -#include "cocos2d.h" #include "CCLabel.h" NS_CC_BEGIN // fwd -class GlyphDef; class FontAtlas; class CC_DLL Font : public Object { public: - static const int DistanceMapSpread; - // create the font - static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); - static Font* createWithFNT(const std::string& fntFilePath); - - static unsigned char * makeDistanceMap(unsigned char *img, unsigned int width, unsigned int height); - void setDistanceFieldEnabled(bool distanceFieldEnabled); - bool isDistanceFieldEnabled() const { return _distanceFieldEnabled;} - bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); - virtual FontAtlas *createFontAtlas() = 0; - virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; + virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; virtual const char* getCurrentGlyphCollection() const; - virtual int getLetterPadding() const { return 0; } virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const { return 0; } - virtual GlyphDef* getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const { return 0; } + virtual int getFontMaxHeight() const { return 0; } - virtual Rect getRectForChar(unsigned short theChar) const; virtual int getUTF16TextLenght(unsigned short int *text) const; - virtual unsigned short int * getUTF16Text(const char *text, int &outNumLetters) const; - virtual unsigned short int * trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const; + virtual unsigned short * getUTF16Text(const char *text, int &outNumLetters) const; + virtual unsigned short * trimUTF16Text(unsigned short int *text, int newBegin, int newEnd) const; protected: @@ -82,7 +68,6 @@ protected: char * _customGlyphs; static const char * _glyphASCII; static const char * _glyphNEHE; - bool _distanceFieldEnabled; }; diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 4d35ce980d..9010956c3d 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -22,10 +22,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "cocos2d.h" + #include "CCFontAtlas.h" -#include "CCFont.h" #include "CCFontFreeType.h" +#include "ccUTF8.h" +#include "CCDirector.h" #define PAGE_WIDTH 1024 #define PAGE_HEIGHT 1024 @@ -37,10 +38,9 @@ _font(&theFont), _currentPageData(nullptr) { _font->retain(); - _makeDistanceMap = _font->isDistanceFieldEnabled(); FontFreeType* fontTTf = dynamic_cast(_font); - if (fontTTf && fontTTf->isDynamicGlyphCollection()) + if (fontTTf) { _currentPageLineHeight = _font->getFontMaxHeight(); _commonLineHeight = _currentPageLineHeight * 0.8f; @@ -48,24 +48,25 @@ _currentPageData(nullptr) _currentPage = 0; _currentPageOrigX = 0; _currentPageOrigY = 0; - _letterPadding = 5; - + _letterPadding = 0; + + _makeDistanceMap = fontTTf->isDistanceFieldEnabled(); if(_makeDistanceMap) { - _commonLineHeight += 2 * Font::DistanceMapSpread; - _letterPadding += 2 * Font::DistanceMapSpread; - _currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1); - } - else - { - _currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1); + _commonLineHeight += 2 * FontFreeType::DistanceMapSpread; + _letterPadding += 2 * FontFreeType::DistanceMapSpread; } + _currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1); _currentPageData = new unsigned char[_currentPageDataSize]; memset(_currentPageData, 0, _currentPageDataSize); addTexture(*tex,0); tex->release(); } + else + { + _makeDistanceMap = false; + } } FontAtlas::~FontAtlas() @@ -100,6 +101,7 @@ bool FontAtlas::getLetterDefinitionForChar(unsigned short letteCharUTF16, FontL } else { + outDefinition.validDefinition = false; return false; } } @@ -114,6 +116,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) std::unordered_map fontDefs; int length = cc_wcslen(utf16String); + float offsetAdjust = _letterPadding / 2; //find out new letter for (int i = 0; i < length; ++i) { @@ -128,31 +131,28 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) Rect tempRect; FontLetterDefinition tempDef; - tempDef.offsetX = 0; - tempDef.anchorX = 0.0f; - tempDef.anchorY = 1.0f; - if (!fontTTf->getBBOXFotChar(utf16String[i], tempRect)) + if (!fontTTf->getBBOXFotChar(utf16String[i], tempRect,tempDef.xAdvance)) { tempDef.validDefinition = false; tempDef.letteCharUTF16 = utf16String[i]; - tempDef.commonLineHeight = 0; tempDef.width = 0; tempDef.height = 0; tempDef.U = 0; - tempDef.V = 0; + tempDef.V = 0; + tempDef.offsetX = 0; tempDef.offsetY = 0; tempDef.textureID = 0; + tempDef.xAdvance = 0; } else { tempDef.validDefinition = true; tempDef.letteCharUTF16 = utf16String[i]; - tempDef.width = tempRect.size.width + _letterPadding; - tempDef.height = _currentPageLineHeight - 1; - tempDef.offsetY = tempRect.origin.y; - tempDef.commonLineHeight = _currentPageLineHeight; - + tempDef.width = tempRect.size.width + _letterPadding; + tempDef.height = tempRect.size.height + _letterPadding; + tempDef.offsetX = tempRect.origin.x + offsetAdjust; + tempDef.offsetY = _commonLineHeight + tempRect.origin.y - offsetAdjust; } fontDefs[utf16String[i]] = tempDef; } @@ -161,14 +161,14 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) Size _pageContentSize = Size(PAGE_WIDTH,PAGE_HEIGHT); float scaleFactor = CC_CONTENT_SCALE_FACTOR(); float glyphWidth; - Texture2D::PixelFormat pixelFormat = _makeDistanceMap ? Texture2D::PixelFormat::A8 : Texture2D::PixelFormat::A8; + Texture2D::PixelFormat pixelFormat = Texture2D::PixelFormat::A8; + for(auto it = fontDefs.begin(); it != fontDefs.end(); it++) { if(it->second.validDefinition) { - _currentPageOrigX += _letterPadding; - glyphWidth = it->second.width - _letterPadding; + glyphWidth = it->second.width; if (_currentPageOrigX + glyphWidth > PAGE_WIDTH) { @@ -190,9 +190,9 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) tex->release(); } } - _font->renderCharAt(it->second.letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,PAGE_WIDTH); + fontTTf->renderCharAt(it->second.letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,PAGE_WIDTH); - it->second.U = _currentPageOrigX - 1; + it->second.U = _currentPageOrigX; it->second.V = _currentPageOrigY; it->second.textureID = _currentPage; // take from pixels to points @@ -205,7 +205,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) glyphWidth = 0; _fontLetterDefinitions[it->second.letteCharUTF16] = it->second; - _currentPageOrigX += glyphWidth; + _currentPageOrigX += glyphWidth + 1; } if(fontDefs.size() > 0) _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, pixelFormat, PAGE_WIDTH, PAGE_HEIGHT, _pageContentSize ); @@ -230,8 +230,6 @@ float FontAtlas::getCommonLineHeight() const void FontAtlas::setCommonLineHeight(float newHeight) { - if(_makeDistanceMap) - newHeight += 2 * Font::DistanceMapSpread; _commonLineHeight = newHeight; } @@ -240,4 +238,4 @@ const Font * FontAtlas::getFont() const return _font; } -NS_CC_END \ No newline at end of file +NS_CC_END diff --git a/cocos/2d/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h index 0a2d6f215b..babec604e5 100644 --- a/cocos/2d/CCFontAtlas.h +++ b/cocos/2d/CCFontAtlas.h @@ -26,11 +26,14 @@ #define _CCFontAtlas_h_ #include +#include "CCPlatformMacros.h" +#include "CCObject.h" NS_CC_BEGIN //fwd class Font; +class Texture2D; struct FontLetterDefinition { @@ -42,10 +45,8 @@ struct FontLetterDefinition float offsetX; float offsetY; int textureID; - float commonLineHeight; - float anchorX; - float anchorY; bool validDefinition; + int xAdvance; }; class CC_DLL FontAtlas : public Object diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index ccea76b254..8c5021b636 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -23,9 +23,13 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCFontAtlasCache.h" -#include "CCFontAtlasFactory.h" +#include +#include "CCFontAtlasCache.h" + +#include "CCFontFNT.h" +#include "CCFontFreeType.h" +#include "CCFontCharMap.h" NS_CC_BEGIN @@ -38,15 +42,24 @@ FontAtlas * FontAtlasCache::getFontAtlasTTF(const std::string& fontFileName, int if ( !tempAtlas ) { - tempAtlas = FontAtlasFactory::createAtlasFromTTF(fontFileName, size, glyphs, customGlyphs, useDistanceField); - if (tempAtlas) - _atlasMap[atlasName] = tempAtlas; + FontFreeType *font = FontFreeType::create(fontFileName, size, glyphs, customGlyphs); + if (font) + { + font->setDistanceFieldEnabled(useDistanceField); + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } } else { tempAtlas->retain(); } - + return tempAtlas; } @@ -57,9 +70,18 @@ FontAtlas * FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName) if ( !tempAtlas ) { - tempAtlas = FontAtlasFactory::createAtlasFromFNT(fontFileName); - if (tempAtlas) - _atlasMap[atlasName] = tempAtlas; + Font *font = FontFNT::create(fontFileName); + + if(font) + { + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } } else { @@ -69,6 +91,92 @@ FontAtlas * FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName) return tempAtlas; } +FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile) +{ + std::string atlasName = generateFontName(plistFile, 0, GlyphCollection::CUSTOM,false); + FontAtlas *tempAtlas = _atlasMap[atlasName]; + + if ( !tempAtlas ) + { + Font *font = FontCharMap::create(plistFile); + + if(font) + { + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } + } + else + { + tempAtlas->retain(); + } + + return tempAtlas; +} + +FontAtlas * FontAtlasCache::getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) +{ + char tmp[30]; + sprintf(tmp,"name:%u_%d_%d_%d",texture->getName(),itemWidth,itemHeight,startCharMap); + std::string atlasName = generateFontName(tmp, 0, GlyphCollection::CUSTOM,false); + FontAtlas *tempAtlas = _atlasMap[atlasName]; + + if ( !tempAtlas ) + { + Font *font = FontCharMap::create(texture,itemWidth,itemHeight,startCharMap); + + if(font) + { + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } + } + else + { + tempAtlas->retain(); + } + + return tempAtlas; +} + +FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +{ + std::string atlasName = generateFontName(charMapFile, 0, GlyphCollection::CUSTOM,false); + FontAtlas *tempAtlas = _atlasMap[atlasName]; + + if ( !tempAtlas ) + { + Font *font = FontCharMap::create(charMapFile,itemWidth,itemHeight,startCharMap); + + if(font) + { + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } + } + else + { + tempAtlas->retain(); + } + + return tempAtlas; +} + std::string FontAtlasCache::generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField) { std::string tempName(fontFileName); @@ -110,7 +218,7 @@ bool FontAtlasCache::releaseFontAtlas(FontAtlas *atlas) { if ( item.second == atlas ) { - if( atlas->isSingleReference() ) + if (atlas->getReferenceCount() == 1) { _atlasMap.erase(item.first); } diff --git a/cocos/2d/CCFontAtlasCache.h b/cocos/2d/CCFontAtlasCache.h index bdc7dd24d1..82353e7949 100644 --- a/cocos/2d/CCFontAtlasCache.h +++ b/cocos/2d/CCFontAtlasCache.h @@ -29,23 +29,24 @@ #include #include -#include "cocos2d.h" #include "CCFontAtlas.h" +#include "CCLabel.h" NS_CC_BEGIN class CC_DLL FontAtlasCache -{ - +{ public: - static FontAtlas * getFontAtlasTTF(const std::string& fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false); static FontAtlas * getFontAtlasFNT(const std::string& fontFileName); + + static FontAtlas * getFontAtlasCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + static FontAtlas * getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); + static FontAtlas * getFontAtlasCharMap(const std::string& plistFile); static bool releaseFontAtlas(FontAtlas *atlas); -private: - +private: static std::string generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField); static std::unordered_map _atlasMap; }; diff --git a/cocos/2d/CCFontCharMap.cpp b/cocos/2d/CCFontCharMap.cpp new file mode 100644 index 0000000000..29098acde3 --- /dev/null +++ b/cocos/2d/CCFontCharMap.cpp @@ -0,0 +1,166 @@ +/**************************************************************************** + Copyright (c) 2013 Zynga Inc. + Copyright (c) 2013-2014 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. + ****************************************************************************/ + +#include "CCFontCharMap.h" +#include "CCFontAtlas.h" +#include "platform/CCFileUtils.h" +#include "CCDirector.h" +#include "CCTextureCache.h" +#include "ccUTF8.h" + +NS_CC_BEGIN + +FontCharMap * FontCharMap::create(const std::string& plistFile) +{ + std::string pathStr = FileUtils::getInstance()->fullPathForFilename(plistFile); + std::string relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/"; + + ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(pathStr.c_str()); + + CCASSERT(dict["version"].asInt() == 1, "Unsupported version. Upgrade cocos2d version"); + + std::string textureFilename = relPathStr + dict["textureFilename"].asString(); + + unsigned int width = dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR(); + unsigned int height = dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR(); + unsigned int startChar = dict["firstChar"].asInt(); + + Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(textureFilename); + if (!tempTexture) + { + return nullptr; + } + + FontCharMap *tempFont = new FontCharMap(tempTexture,width,height,startChar); + + if (!tempFont) + { + return nullptr; + } + tempFont->autorelease(); + return tempFont; +} + +FontCharMap* FontCharMap::create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +{ + Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(charMapFile); + + if (!tempTexture) + { + return nullptr; + } + + FontCharMap *tempFont = new FontCharMap(tempTexture,itemWidth,itemHeight,startCharMap); + + if (!tempFont) + { + return nullptr; + } + tempFont->autorelease(); + return tempFont; +} + +FontCharMap* FontCharMap::create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) +{ + FontCharMap *tempFont = new FontCharMap(texture,itemWidth,itemHeight,startCharMap); + + if (!tempFont) + { + return nullptr; + } + tempFont->autorelease(); + return tempFont; +} + +FontCharMap::~FontCharMap() +{ + +} + +int * FontCharMap::getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const +{ + if (!text) + return 0; + + outNumLetters = cc_wcslen(text); + + if (!outNumLetters) + return 0; + + int *sizes = new int[outNumLetters]; + if (!sizes) + return 0; + + for (int c = 0; c < outNumLetters; ++c) + { + sizes[c] = 0; + } + + return sizes; +} + +FontAtlas * FontCharMap::createFontAtlas() +{ + FontAtlas *tempAtlas = new FontAtlas(*this); + if (!tempAtlas) + return nullptr; + + Size s = _texture->getContentSize(); + + int itemsPerColumn = (int)(s.height / _itemHeight); + int itemsPerRow = (int)(s.width / _itemWidth); + + tempAtlas->setCommonLineHeight(_itemHeight); + + FontLetterDefinition tempDefinition; + tempDefinition.textureID = 0; + tempDefinition.offsetX = 0.0f; + tempDefinition.offsetY = 0.0f; + tempDefinition.validDefinition = true; + tempDefinition.width = _itemWidth; + tempDefinition.height = _itemHeight; + tempDefinition.xAdvance = _itemWidth * CC_CONTENT_SCALE_FACTOR(); + + int charId = _mapStartChar; + for (int row = 0; row < itemsPerColumn; ++row) + { + for (int col = 0; col < itemsPerRow; ++col) + { + tempDefinition.letteCharUTF16 = charId; + + tempDefinition.U = _itemWidth * col; + tempDefinition.V = _itemHeight * row; + + tempAtlas->addLetterDefinition(tempDefinition); + charId++; + } + } + + tempAtlas->addTexture(*_texture,0); + + return tempAtlas; +} + +NS_CC_END \ No newline at end of file diff --git a/cocos/2d/CCFontDefinition.h b/cocos/2d/CCFontCharMap.h similarity index 58% rename from cocos/2d/CCFontDefinition.h rename to cocos/2d/CCFontCharMap.h index 5bec2bb098..d91d12e2bc 100644 --- a/cocos/2d/CCFontDefinition.h +++ b/cocos/2d/CCFontCharMap.h @@ -1,6 +1,6 @@ /**************************************************************************** Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -23,48 +23,44 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef _FontDefinition_h_ -#define _FontDefinition_h_ +#ifndef _CCFontCharMap_h_ +#define _CCFontCharMap_h_ -#include - -#include "CCTextImage.h" #include "CCFont.h" -#include "CCFontAtlas.h" NS_CC_BEGIN -/** - */ -class CC_DLL FontDefinitionTTF : public Object -{ +class FontCharMap : public Font +{ public: + static FontCharMap * create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + static FontCharMap * create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); + static FontCharMap * create(const std::string& plistFile); - static FontDefinitionTTF* create(Font *font, int textureSize = 0); - FontAtlas * createFontAtlas(); + virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override; + virtual FontAtlas *createFontAtlas() override; -private: - /** - * @js ctor - */ - FontDefinitionTTF(); +protected: + FontCharMap(Texture2D* texture,int itemWidth, int itemHeight, int startCharMap) + :_texture(texture) + ,_mapStartChar(startCharMap) + ,_itemWidth(itemWidth) + ,_itemHeight(itemHeight) + {} /** * @js NA * @lua NA */ - ~FontDefinitionTTF(); + virtual ~FontCharMap(); - bool initDefinition(Font *font, const char *letters, int textureSize); - bool prepareLetterDefinitions(TextFontPagesDef *pageDefs); - void addLetterDefinition(const FontLetterDefinition &defToAdd); - - TextImage * _textImages; - std::unordered_map _fontLettersDefinitionUTF16; - float _commonLineHeight; +private: + Texture2D* _texture; + int _mapStartChar; + int _itemWidth; + int _itemHeight; - static const int DEFAUL_ATLAS_TEXTURE_SIZE; }; NS_CC_END -#endif +#endif /* defined(_CCFontCharMap_h_) */ diff --git a/cocos/2d/CCFontDefinition.cpp b/cocos/2d/CCFontDefinition.cpp deleted file mode 100644 index c0d8af5051..0000000000 --- a/cocos/2d/CCFontDefinition.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 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. - ****************************************************************************/ - -#include "cocos2d.h" -#include "CCFontDefinition.h" - -NS_CC_BEGIN - -const int FontDefinitionTTF::DEFAUL_ATLAS_TEXTURE_SIZE = 1024; - -FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0) -{ -} - -FontDefinitionTTF* FontDefinitionTTF::create(Font *font, int textureSize) -{ - if (textureSize == 0) - textureSize = DEFAUL_ATLAS_TEXTURE_SIZE; - - FontDefinitionTTF *ret = new FontDefinitionTTF; - - if (!ret) - return 0; - - const char *glyph = font->getCurrentGlyphCollection(); - if (!glyph) - return nullptr; - - if (ret->initDefinition(font, glyph, textureSize)) - { - ret->autorelease(); - return ret; - } - else - { - delete ret; - return 0; - } -} - -FontDefinitionTTF::~FontDefinitionTTF() -{ - if (_textImages) - { - delete _textImages; - } -} - -bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs) -{ - // get all the pages - TextFontPagesDef *pages = pageDefs; - if (!pages) - return (false); - - float maxLineHeight = -1; - - // loops all the pages - for (int cPages = 0; cPages < pages->getNumPages(); ++cPages) - { - // loops all the lines in this page - for (int cLines = 0; cLinesgetPageAt(cPages)->getNumLines(); ++cLines) - { - float posXUV = 0.0; - float posYUV = pages->getPageAt(cPages)->getLineAt(cLines)->getY(); - - int charsCounter = 0; - - for (int c = 0; c < pages->getPageAt(cPages)->getLineAt(cLines)->getNumGlyph(); ++c) - { - // the current glyph - GlyphDef currentGlyph = pages->getPageAt(cPages)->getLineAt(cLines)->getGlyphAt(c); - - // letter width - float letterWidth = currentGlyph.getRect().size.width; - - // letter height - float letterHeight = pages->getPageAt(cPages)->getLineAt(cLines)->getHeight(); - - // add this letter definition - FontLetterDefinition tempDef; - - - // carloX little hack (this should be done outside the loop) - if (posXUV == 0.0) - posXUV = currentGlyph.getPadding(); - - tempDef.validDefinition = currentGlyph.isValid(); - - if (tempDef.validDefinition) - { - tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter(); - tempDef.width = letterWidth + currentGlyph.getPadding(); - tempDef.height = (letterHeight - 1); - tempDef.U = (posXUV - 1); - tempDef.V = posYUV; - tempDef.offsetX = currentGlyph.getRect().origin.x; - tempDef.offsetY = currentGlyph.getRect().origin.y; - tempDef.textureID = cPages; - tempDef.commonLineHeight = currentGlyph.getCommonHeight(); - - // take from pixels to points - tempDef.width = tempDef.width / CC_CONTENT_SCALE_FACTOR(); - tempDef.height = tempDef.height / CC_CONTENT_SCALE_FACTOR(); - tempDef.U = tempDef.U / CC_CONTENT_SCALE_FACTOR(); - tempDef.V = tempDef.V / CC_CONTENT_SCALE_FACTOR(); - - if (tempDef.commonLineHeight>maxLineHeight) - maxLineHeight = tempDef.commonLineHeight; - } - else - { - tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter(); - tempDef.commonLineHeight = 0; - tempDef.width = 0; - tempDef.height = 0; - tempDef.U = 0; - tempDef.V = 0; - tempDef.offsetX = 0; - tempDef.offsetY = 0; - tempDef.textureID = 0; - } - - - // add this definition - addLetterDefinition(tempDef); - - // move bounding box to the next letter - posXUV += letterWidth + currentGlyph.getPadding(); - - // next char in the string - ++charsCounter; - } - } - } - - // store the common line height - _commonLineHeight = maxLineHeight; - - // - return true; -} - -bool FontDefinitionTTF::initDefinition(cocos2d::Font *font, const char *letters, int textureSize) -{ - // preare texture/image stuff - _textImages = new TextImage(); - if (!_textImages) - return false; - - if (!_textImages->initWithString(letters, textureSize, textureSize, font, true)) - { - delete _textImages; - _textImages = 0; - return false; - } - - // prepare the new letter definition - return prepareLetterDefinitions(_textImages->getPages()); -} - -void FontDefinitionTTF::addLetterDefinition(const FontLetterDefinition &defToAdd) -{ - if (_fontLettersDefinitionUTF16.find(defToAdd.letteCharUTF16) == _fontLettersDefinitionUTF16.end()) - { - _fontLettersDefinitionUTF16[defToAdd.letteCharUTF16] = defToAdd; - } -} - -FontAtlas * FontDefinitionTTF::createFontAtlas() -{ - int numTextures = 0; - TextFontPagesDef *pages = _textImages->getPages(); - - if (pages) - numTextures = pages->getNumPages(); - else - return nullptr; - - if (!numTextures) - return nullptr; - - FontAtlas *retAtlas = new FontAtlas(*_textImages->getFont()); - - if (!retAtlas) - return 0; - - for (int c = 0; c < numTextures; ++c) - { - TextFontPagesDef *pPages = _textImages->getPages(); - retAtlas->addTexture(*(pPages->getPageAt(c)->getPageTexture()), c); - } - - // set the common line height - retAtlas->setCommonLineHeight(_commonLineHeight * 0.8); - - for( auto &item: _fontLettersDefinitionUTF16 ) - { - if ( item.second.validDefinition ) - { - FontLetterDefinition tempDefinition = item.second; - tempDefinition.offsetX = 0; - tempDefinition.anchorX = 0.0f; - tempDefinition.anchorY = 1.0f; - retAtlas->addLetterDefinition(tempDefinition); - } - } - - // done here - return retAtlas; -} - -NS_CC_END diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index 93fd5c2410..fc043535f2 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -25,6 +25,10 @@ #include "CCFontFNT.h" #include "CCFontAtlas.h" +#include "CCLabelBMFont.h" +#include "CCDirector.h" +#include "CCTextureCache.h" +#include "ccUTF8.h" NS_CC_BEGIN @@ -58,7 +62,7 @@ FontFNT::~FontFNT() } -Size * FontFNT::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const +int * FontFNT::getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const { if (!text) return 0; @@ -68,39 +72,21 @@ Size * FontFNT::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters if (!outNumLetters) return 0; - Size *sizes = new Size[outNumLetters]; + int *sizes = new int[outNumLetters]; if (!sizes) return 0; for (int c = 0; c < outNumLetters; ++c) { - int advance = 0; - int kerning = 0; - - advance = getAdvanceForChar(text[c]); - if (c < (outNumLetters-1)) - kerning = getHorizontalKerningForChars(text[c], text[c+1]); - - sizes[c].width = (advance + kerning); + sizes[c] = getHorizontalKerningForChars(text[c], text[c+1]); + else + sizes[c] = 0; } return sizes; } -int FontFNT::getAdvanceForChar(unsigned short theChar) const -{ - tFontDefHashElement *element = nullptr; - - // unichar is a short, and an int is needed on HASH_FIND_INT - unsigned int key = theChar; - HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element); - if (! element) - return -1; - - return element->fontDef.xAdvance; -} - int FontFNT::getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const { int ret = 0; @@ -118,28 +104,6 @@ int FontFNT::getHorizontalKerningForChars(unsigned short firstChar, unsigned sh return ret; } -Rect FontFNT::getRectForCharInternal(unsigned short theChar) const -{ - Rect retRect; - ccBMFontDef fontDef; - tFontDefHashElement *element = nullptr; - unsigned int key = theChar; - - HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element); - - if (element) - { - retRect = element->fontDef.rect; - } - - return retRect; -} - -Rect FontFNT::getRectForChar(unsigned short theChar) const -{ - return getRectForCharInternal(theChar); -} - FontAtlas * FontFNT::createFontAtlas() { FontAtlas *tempAtlas = new FontAtlas(*this); @@ -190,9 +154,8 @@ FontAtlas * FontFNT::createFontAtlas() //carloX: only one texture supported FOR NOW tempDefinition.textureID = 0; - tempDefinition.anchorX = 0.5f; - tempDefinition.anchorY = 0.5f; tempDefinition.validDefinition = true; + tempDefinition.xAdvance = fontDef.xAdvance; // add the new definition tempAtlas->addLetterDefinition(tempDefinition); } diff --git a/cocos/2d/CCFontFNT.h b/cocos/2d/CCFontFNT.h index eec0bd761c..f0955b5849 100644 --- a/cocos/2d/CCFontFNT.h +++ b/cocos/2d/CCFontFNT.h @@ -26,11 +26,12 @@ #ifndef _CCFontFNT_h_ #define _CCFontFNT_h_ -#include "cocos2d.h" #include "CCFont.h" NS_CC_BEGIN +class CCBMFontConfiguration; + class FontFNT : public Font { @@ -38,8 +39,7 @@ public: static FontFNT * create(const std::string& fntFilePath); - virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; - virtual Rect getRectForChar(unsigned short theChar) const override; + virtual int* getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override; virtual FontAtlas *createFontAtlas() override; protected: @@ -54,9 +54,7 @@ protected: private: - int getAdvanceForChar(unsigned short theChar) const; int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const; - Rect getRectForCharInternal(unsigned short theChar) const; CCBMFontConfiguration * _configuration; diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 60b5a11954..dbfdffbb8f 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -28,23 +28,19 @@ THE SOFTWARE. #include "ccUTF8.h" #include "CCFontFreeType.h" -#include "CCTextImage.h" -#include "CCFont.h" -#include "CCFontDefinition.h" +#include "platform/CCFileUtils.h" +#include "edtaa3func.h" NS_CC_BEGIN FT_Library FontFreeType::_FTlibrary; bool FontFreeType::_FTInitialized = false; +const int FontFreeType::DistanceMapSpread = 3; FontFreeType * FontFreeType::create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) { - bool dynamicGlyphCollection = false; - if(glyphs == GlyphCollection::DYNAMIC) - dynamicGlyphCollection = true; - - FontFreeType *tempFont = new FontFreeType(dynamicGlyphCollection); + FontFreeType *tempFont = new FontFreeType(); if (!tempFont) return nullptr; @@ -88,13 +84,10 @@ FT_Library FontFreeType::getFTLibrary() return _FTlibrary; } -FontFreeType::FontFreeType(bool dynamicGlyphCollection) -: _fontRef(nullptr), -_letterPadding(5), -_dynamicGlyphCollection(dynamicGlyphCollection) +FontFreeType::FontFreeType() +: _fontRef(nullptr) +,_distanceFieldEnabled(false) { - if(_distanceFieldEnabled) - _letterPadding += 2 * DistanceMapSpread; } bool FontFreeType::createFontObject(const std::string &fontName, int fontSize) @@ -140,26 +133,18 @@ FontFreeType::~FontFreeType() FontAtlas * FontFreeType::createFontAtlas() { - if (_dynamicGlyphCollection) + FontAtlas *atlas = new FontAtlas(*this); + if (_usedGlyphs != GlyphCollection::DYNAMIC) { - FontAtlas *atlas = new FontAtlas(*this); - this->release(); - return atlas; - } - else - { - FontDefinitionTTF *def = FontDefinitionTTF::create(this); - - if (!def) - return nullptr; - - FontAtlas *atlas = def->createFontAtlas(); - - return atlas; - } + unsigned short* utf16 = cc_utf8_to_utf16(getCurrentGlyphCollection()); + atlas->prepareLetterDefinitions(utf16); + CC_SAFE_DELETE_ARRAY(utf16); + } + this->release(); + return atlas; } -bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const +bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect, int &xAdvance) const { if (!_fontRef) return false; @@ -175,80 +160,17 @@ bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const return false; // store result in the passed rectangle - outRect.origin.x = 0; + outRect.origin.x = _fontRef->glyph->metrics.horiBearingX >> 6; outRect.origin.y = - (_fontRef->glyph->metrics.horiBearingY >> 6); outRect.size.width = (_fontRef->glyph->metrics.width >> 6); outRect.size.height = (_fontRef->glyph->metrics.height >> 6); + xAdvance = (static_cast(_fontRef->glyph->metrics.horiAdvance >> 6)); + return true; } -GlyphDef * FontFreeType::getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text) const -{ - unsigned short* utf16String = 0; - - if (UTF16text) - { - utf16String = (unsigned short*) text; - } - else - { - utf16String = cc_utf8_to_utf16(text); - } - - // - if (!utf16String) - return 0; - - int numChar = cc_wcslen(utf16String); - if (!numChar) - return 0; - - // allocate the needed Glyphs - GlyphDef *glyphs = new GlyphDef[numChar]; - assert(glyphs != nullptr); - if (!glyphs) - return 0; - - // sore result as CCRect - for (int c = 0; c < numChar; ++c) - { - Rect tempRect; - - if (!getBBOXFotChar(utf16String[c], tempRect)) - { - log("Warning: Cannot find definition for glyph: %c in font:%s", utf16String[c], _fontName.c_str()); - - tempRect.origin.x = 0; - tempRect.origin.y = 0; - tempRect.size.width = 0; - tempRect.size.height = 0; - - glyphs[c].setRect(tempRect); - glyphs[c].setUTF16Letter(utf16String[c]); - glyphs[c].setValid(false); - glyphs[c].setPadding(_letterPadding); - } - else - { - glyphs[c].setRect(tempRect); - glyphs[c].setUTF16Letter(utf16String[c]); - glyphs[c].setPadding(_letterPadding); - glyphs[c].setValid(true); - } - } - - outNumGlyphs = numChar; - - // free memory - if (!UTF16text) - delete [] utf16String; - - // done - return glyphs; -} - -Size * FontFreeType::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const +int * FontFreeType::getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const { if (!text) return 0; @@ -258,64 +180,21 @@ Size * FontFreeType::getAdvancesForTextUTF16(unsigned short *text, int &outNumLe if (!outNumLetters) return 0; - Size *sizes = new Size[outNumLetters]; + int *sizes = new int[outNumLetters]; if (!sizes) return 0; for (int c = 0; c < outNumLetters; ++c) { - int advance = 0; - int kerning = 0; - - advance = getAdvanceForChar(text[c]) - getBearingXForChar(text[c]); - if (c < (outNumLetters-1)) - kerning = getHorizontalKerningForChars(text[c], text[c+1]); - - sizes[c].width = (advance + kerning); + sizes[c] = getHorizontalKerningForChars(text[c], text[c+1]); + else + sizes[c] = 0; } return sizes; } -int FontFreeType::getAdvanceForChar(unsigned short theChar) const -{ - if (!_fontRef) - return 0; - - // get the ID to the char we need - int glyph_index = FT_Get_Char_Index(_fontRef, theChar); - - if (!glyph_index) - return 0; - - // load glyph infos - if (FT_Load_Glyph(_fontRef, glyph_index, FT_LOAD_DEFAULT)) - return 0; - - // get to the advance for this glyph - return (static_cast(_fontRef->glyph->advance.x >> 6)); -} - -int FontFreeType::getBearingXForChar(unsigned short theChar) const -{ - - if (!_fontRef) - return 0; - - // get the ID to the char we need - int glyphIndex = FT_Get_Char_Index(_fontRef, theChar); - - if (!glyphIndex) - return 0; - - // load glyph infos - if (FT_Load_Glyph(_fontRef, glyphIndex, FT_LOAD_DEFAULT)) - return 0; - - return (static_cast(_fontRef->glyph->metrics.horiBearingX >>6)); -} - int FontFreeType::getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const { if (!_fontRef) @@ -374,9 +253,162 @@ unsigned char * FontFreeType::getGlyphBitmap(unsigned short theChar, int &outWid return _fontRef->glyph->bitmap.buffer; } -int FontFreeType::getLetterPadding() const +unsigned char * makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height) { - return _letterPadding; + unsigned int pixelAmount = (width + 2 * FontFreeType::DistanceMapSpread) * (height + 2 * FontFreeType::DistanceMapSpread); + + short * xdist = (short *) malloc( pixelAmount * sizeof(short) ); + short * ydist = (short *) malloc( pixelAmount * sizeof(short) ); + double * gx = (double *) calloc( pixelAmount, sizeof(double) ); + double * gy = (double *) calloc( pixelAmount, sizeof(double) ); + double * data = (double *) calloc( pixelAmount, sizeof(double) ); + double * outside = (double *) calloc( pixelAmount, sizeof(double) ); + double * inside = (double *) calloc( pixelAmount, sizeof(double) ); + unsigned int i,j; + + // Convert img into double (data) rescale image levels between 0 and 1 + unsigned int outWidth = width + 2 * FontFreeType::DistanceMapSpread; + for (i = 0; i < width; ++i) + { + for (j = 0; j < height; ++j) + { + data[j * outWidth + FontFreeType::DistanceMapSpread + i] = img[j * width + i] / 255.0; + } + } + + width += 2 * FontFreeType::DistanceMapSpread; + height += 2 * FontFreeType::DistanceMapSpread; + + // Transform background (outside contour, in areas of 0's) + computegradient( data, width, height, gx, gy); + edtaa3(data, gx, gy, width, height, xdist, ydist, outside); + for( i=0; i< pixelAmount; i++) + if( outside[i] < 0.0 ) + outside[i] = 0.0; + + // Transform foreground (inside contour, in areas of 1's) + for( i=0; i< pixelAmount; i++) + data[i] = 1 - data[i]; + computegradient( data, width, height, gx, gy); + edtaa3(data, gx, gy, width, height, xdist, ydist, inside); + for( i=0; i< pixelAmount; i++) + if( inside[i] < 0.0 ) + inside[i] = 0.0; + + // The bipolar distance field is now outside-inside + double dist; + /* Single channel 8-bit output (bad precision and range, but simple) */ + unsigned char *out = (unsigned char *) malloc( pixelAmount * sizeof(unsigned char) ); + for( i=0; i < pixelAmount; i++) + { + dist = outside[i] - inside[i]; + dist = 128.0 - dist*16; + if( dist < 0 ) dist = 0; + if( dist > 255 ) dist = 255; + out[i] = (unsigned char) dist; + } + /* Dual channel 16-bit output (more complicated, but good precision and range) */ + /*unsigned char *out = (unsigned char *) malloc( pixelAmount * 3 * sizeof(unsigned char) ); + for( i=0; i< pixelAmount; i++) + { + dist = outside[i] - inside[i]; + dist = 128.0 - dist*16; + if( dist < 0.0 ) dist = 0.0; + if( dist >= 256.0 ) dist = 255.999; + // R channel is a copy of the original grayscale image + out[3*i] = img[i]; + // G channel is fraction + out[3*i + 1] = (unsigned char) ( 256 - (dist - floor(dist)* 256.0 )); + // B channel is truncated integer part + out[3*i + 2] = (unsigned char)dist; + }*/ + + free( xdist ); + free( ydist ); + free( gx ); + free( gy ); + free( data ); + free( outside ); + free( inside ); + + return out; +} + +void FontFreeType::setDistanceFieldEnabled(bool distanceFieldEnabled) +{ + _distanceFieldEnabled = distanceFieldEnabled; +} + +bool FontFreeType::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize) +{ + unsigned char *sourceBitmap = 0; + int sourceWidth = 0; + int sourceHeight = 0; + + sourceBitmap = getGlyphBitmap(charToRender, sourceWidth, sourceHeight); + + if (!sourceBitmap) + return false; + + if (_distanceFieldEnabled) + { + unsigned char * out = makeDistanceMap(sourceBitmap,sourceWidth,sourceHeight); + + int iX = posX; + int iY = posY; + + sourceWidth += 2 * DistanceMapSpread; + sourceHeight += 2 * DistanceMapSpread; + + for (int y = 0; y < sourceHeight; ++y) + { + int bitmap_y = y * sourceWidth; + + for (int x = 0; x < sourceWidth; ++x) + { + /* Dual channel 16-bit output (more complicated, but good precision and range) */ + /*int index = (iX + ( iY * destSize )) * 3; + int index2 = (bitmap_y + x)*3; + destMemory[index] = out[index2]; + destMemory[index + 1] = out[index2 + 1]; + destMemory[index + 2] = out[index2 + 2];*/ + + //Single channel 8-bit output + destMemory[iX + ( iY * destSize )] = out[bitmap_y + x]; + + iX += 1; + } + + iX = posX; + iY += 1; + } + free(out); + return true; + } + + int iX = posX; + int iY = posY; + + for (int y = 0; y < sourceHeight; ++y) + { + int bitmap_y = y * sourceWidth; + + for (int x = 0; x < sourceWidth; ++x) + { + unsigned char cTemp = sourceBitmap[bitmap_y + x]; + + // the final pixel + destMemory[(iX + ( iY * destSize ) )] = cTemp; + + iX += 1; + } + + iX = posX; + iY += 1; + } + + //everything good + return true; } NS_CC_END \ No newline at end of file diff --git a/cocos/2d/CCFontFreeType.h b/cocos/2d/CCFontFreeType.h index bd86c5effc..98b182428e 100644 --- a/cocos/2d/CCFontFreeType.h +++ b/cocos/2d/CCFontFreeType.h @@ -39,25 +39,27 @@ NS_CC_BEGIN class CC_DLL FontFreeType : public Font { public: - + static const int DistanceMapSpread; + static FontFreeType * create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); static void shutdownFreeType(); + void setDistanceFieldEnabled(bool distanceFieldEnabled); + bool isDistanceFieldEnabled() const { return _distanceFieldEnabled;} + bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); + virtual FontAtlas * createFontAtlas() override; - virtual Size * getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; - virtual GlyphDef * getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const override; + virtual int * getHorizontalKerningForTextUTF16(unsigned short *text, int &outNumLetters) const override; + unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const override; virtual int getFontMaxHeight() const override; - virtual int getLetterPadding() const override; - bool getBBOXFotChar(unsigned short theChar, Rect &outRect) const; - - inline bool isDynamicGlyphCollection() { return _dynamicGlyphCollection;} + bool getBBOXFotChar(unsigned short theChar, Rect &outRect,int &xAdvance) const; protected: - FontFreeType(bool dynamicGlyphCollection = false); + FontFreeType(); virtual ~FontFreeType(); bool createFontObject(const std::string &fontName, int fontSize); @@ -66,17 +68,14 @@ private: bool initFreeType(); FT_Library getFTLibrary(); - int getAdvanceForChar(unsigned short theChar) const; - int getBearingXForChar(unsigned short theChar) const; int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar) const; static FT_Library _FTlibrary; static bool _FTInitialized; FT_Face _fontRef; - int _letterPadding; std::string _fontName; Data _ttfData; - bool _dynamicGlyphCollection; + bool _distanceFieldEnabled; }; NS_CC_END diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index d7125bcd30..5c7c1de844 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -24,70 +24,90 @@ ****************************************************************************/ #include "CCLabel.h" -#include "CCFontDefinition.h" #include "CCFontAtlasCache.h" #include "CCLabelTextFormatter.h" +#include "CCSprite.h" +#include "CCShaderCache.h" +#include "ccUTF8.h" +#include "CCSpriteFrame.h" +#include "CCDirector.h" +#include "renderer/CCRenderer.h" +#include "CCFont.h" #define DISTANCEFIELD_ATLAS_FONTSIZE 50 NS_CC_BEGIN -Label* Label::createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs, bool useDistanceField) +Label* Label::create() { - FontAtlas *tmpAtlas = nullptr; - if(useDistanceField) - tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), DISTANCEFIELD_ATLAS_FONTSIZE, glyphs, customGlyphs,true); - else - tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), fontSize, glyphs, customGlyphs,false); + Label *ret = new Label(); - if (!tmpAtlas) - return nullptr; - - // create the actual label - Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize, useDistanceField,true); - - if (templabel) - { - if(useDistanceField) - templabel->setFontSize(fontSize); - templabel->setText(label, lineSize, alignment, false); - return templabel; - } - - return nullptr; -} - -Label* Label::createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment, int lineSize) -{ - - FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath.c_str()); - - if (!tmpAtlas) - return 0; - - Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize); - - if (templabel) - { - templabel->setText(label, lineSize, alignment, false); - return templabel; - } - else - { - return 0; - } - - return 0; -} - -Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int lineSize, bool useDistanceField,bool useA8Shader) -{ - Label *ret = new Label(atlas, alignment, useDistanceField,useA8Shader); - if (!ret) - return 0; - - if( ret->init() ) + return nullptr; + + ret->autorelease(); + + return ret; +} + +Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment /* = TextHAlignment::CENTER */, int lineSize /* = 0 */) +{ + Label *ret = new Label(nullptr,alignment); + + if (!ret) + return nullptr; + + if (ret->setTTFConfig(ttfConfig)) + { + if(ttfConfig.distanceFieldEnabled) + ret->setFontSize(ttfConfig.fontSize); + ret->setWidth(lineSize); + ret->setString(text); + ret->autorelease(); + return ret; + } + else + { + delete ret; + return nullptr; + } +} + +Label* Label::createWithTTF(const std::string& text, const std::string& fontFilePath, int fontSize, int lineSize /* = 0 */, TextHAlignment alignment /* = TextHAlignment::CENTER */, GlyphCollection glyphs /* = GlyphCollection::NEHE */, const char *customGlyphs /* = 0 */, bool useDistanceField /* = false */) +{ + TTFConfig ttfConfig(fontFilePath.c_str(),fontSize,glyphs,customGlyphs,useDistanceField); + return createWithTTF(ttfConfig,text,alignment,lineSize); +} + +Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment /* = TextHAlignment::CENTER */, int lineSize /* = 0 */) +{ + Label *ret = new Label(nullptr,alignment); + + if (!ret) + return nullptr; + + if (ret->setBMFontFilePath(bmfontFilePath)) + { + ret->setWidth(lineSize); + ret->setString(text); + ret->autorelease(); + return ret; + } + else + { + delete ret; + return nullptr; + } +} + +Label* Label::createWithCharMap(const std::string& plistFile) +{ + Label *ret = new Label(); + + if (!ret) + return nullptr; + + if (ret->setCharMap(plistFile)) { ret->autorelease(); return ret; @@ -95,36 +115,102 @@ Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int li else { delete ret; - return 0; + return nullptr; } - - return ret; +} + +Label* Label::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) +{ + Label *ret = new Label(); + + if (!ret) + return nullptr; + + if (ret->setCharMap(texture,itemWidth,itemHeight,startCharMap)) + { + ret->autorelease(); + return ret; + } + else + { + delete ret; + return nullptr; + } +} + +Label* Label::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +{ + Label *ret = new Label(); + + if (!ret) + return nullptr; + + if (ret->setCharMap(charMapFile,itemWidth,itemHeight,startCharMap)) + { + ret->autorelease(); + return ret; + } + else + { + delete ret; + return nullptr; + } +} + +bool Label::setCharMap(const std::string& plistFile) +{ + FontAtlas *newAtlas = FontAtlasCache::getFontAtlasCharMap(plistFile); + + if (!newAtlas) + return false; + + return initWithFontAtlas(newAtlas); +} + +bool Label::setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) +{ + FontAtlas *newAtlas = FontAtlasCache::getFontAtlasCharMap(texture,itemWidth,itemHeight,startCharMap); + + if (!newAtlas) + return false; + + return initWithFontAtlas(newAtlas); +} + +bool Label::setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +{ + FontAtlas *newAtlas = FontAtlasCache::getFontAtlasCharMap(charMapFile,itemWidth,itemHeight,startCharMap); + + if (!newAtlas) + return false; + + return initWithFontAtlas(newAtlas); } Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,bool useA8Shader) : _reusedLetter(nullptr) -, _multilineEnable(true) , _commonLineHeight(0.0f) , _lineBreakWithoutSpaces(false) , _width(0.0f) , _alignment(alignment) -, _currentUTF16String(0) -, _originalUTF16String(0) -, _advances(nullptr) +, _currentUTF16String(nullptr) +, _originalUTF16String(nullptr) +, _horizontalKernings(nullptr) , _fontAtlas(atlas) -, _isOpacityModifyRGB(true) +, _isOpacityModifyRGB(false) , _useDistanceField(useDistanceField) , _useA8Shader(useA8Shader) , _fontSize(0) , _uniformEffectColor(0) { + _cascadeColorEnabled = true; } Label::~Label() { delete [] _currentUTF16String; delete [] _originalUTF16String; - delete [] _advances; + delete [] _horizontalKernings; if (_fontAtlas) FontAtlasCache::releaseFontAtlas(_fontAtlas); @@ -137,10 +223,14 @@ bool Label::init() bool ret = true; if(_fontAtlas) { - _reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0)); - _reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB); - ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30); - _reusedLetter->retain(); + if (_reusedLetter == nullptr) + { + _reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0)); + _reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB); + _reusedLetter->retain(); + _reusedLetter->setAnchorPoint(Point::ANCHOR_TOP_LEFT); + } + ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30); } if (_useDistanceField) setLabelEffect(LabelEffect::NORMAL,Color3B::BLACK); @@ -148,54 +238,89 @@ bool Label::init() setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR)); else setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); + return ret; } -void Label::setString(const std::string &stringToRender) +bool Label::initWithFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled /* = false */, bool useA8Shader /* = false */) { - _multilineEnable = true; - setText(stringToRender, _width, TextHAlignment::CENTER, false); + FontAtlas *oldAtlas = _fontAtlas; + bool oldDistanceFieldEnable = _useDistanceField; + bool oldA8ShaderEnabel = _useA8Shader; + + _fontAtlas = atlas; + _useDistanceField = distanceFieldEnabled; + _useA8Shader = useA8Shader; + + bool ret = Label::init(); + if (oldAtlas) + { + if (ret) + { + FontAtlasCache::releaseFontAtlas(oldAtlas); + } + else + { + _fontAtlas = oldAtlas; + _useDistanceField = oldDistanceFieldEnable; + _useA8Shader = oldA8ShaderEnabel; + Label::init(); + + FontAtlasCache::releaseFontAtlas(atlas); + } + } + + if (_fontAtlas) + { + _commonLineHeight = _fontAtlas->getCommonLineHeight(); + if(_currentUTF16String) + { + resetCurrentString(); + alignText(); + } + } + + return ret; } -void Label::setString(const std::string &stringToRender,bool multilineEnable) +bool Label::setTTFConfig(const TTFConfig& ttfConfig) { - _multilineEnable = multilineEnable; - setText(stringToRender, _width, TextHAlignment::CENTER, false); + FontAtlas *newAtlas = nullptr; + if(ttfConfig.distanceFieldEnabled) + newAtlas = FontAtlasCache::getFontAtlasTTF(ttfConfig.fontFilePath, DISTANCEFIELD_ATLAS_FONTSIZE, ttfConfig.glyphs, ttfConfig.customGlyphs,true); + else + newAtlas = FontAtlasCache::getFontAtlasTTF(ttfConfig.fontFilePath, ttfConfig.fontSize, ttfConfig.glyphs, ttfConfig.customGlyphs,false); + + if (!newAtlas) + return false; + + return initWithFontAtlas(newAtlas,ttfConfig.distanceFieldEnabled,true); } -bool Label::setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces) +bool Label::setBMFontFilePath(const std::string& bmfontFilePath) { - if (!_fontAtlas) + FontAtlas *newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath); + + if (!newAtlas) return false; + + return initWithFontAtlas(newAtlas); +} + +void Label::setString(const std::string& text) +{ + if (!_fontAtlas || _commonLineHeight <= 0) + return ; - // carloX - // reset the string - resetCurrentString(); - - _width = lineWidth; - _alignment = alignment; - _lineBreakWithoutSpaces = lineBreakWithoutSpaces; - - // store locally common line height - _commonLineHeight = _fontAtlas->getCommonLineHeight(); - if (_commonLineHeight <= 0) - return false; - -// int numLetter = 0; - unsigned short* utf16String = cc_utf8_to_utf16(stringToRender.c_str()); + unsigned short* utf16String = cc_utf8_to_utf16(text.c_str()); if(!utf16String) - return false; - - _cascadeColorEnabled = true; - + return ; + _originalUTF8String = text; setCurrentString(utf16String); setOriginalString(utf16String); // align text alignText(); - - // done here - return true; } void Label::setAlignment(TextHAlignment alignment) @@ -206,11 +331,14 @@ void Label::setAlignment(TextHAlignment alignment) // store _alignment = alignment; - // reset the string - resetCurrentString(); - - // need to align text again - alignText(); + if (_currentUTF16String) + { + // reset the string + resetCurrentString(); + + // need to align text again + alignText(); + } } } @@ -221,12 +349,14 @@ void Label::setWidth(float width) // store _width = width; - - // reset the string - resetCurrentString(); - - // need to align text again - alignText(); + if (_currentUTF16String) + { + // reset the string + resetCurrentString(); + + // need to align text again + alignText(); + } } } @@ -238,7 +368,11 @@ void Label::setLineBreakWithoutSpace(bool breakWithoutSpace) _lineBreakWithoutSpaces = breakWithoutSpace; // need to align text again - alignText(); + if(_currentUTF16String) + { + resetCurrentString(); + alignText(); + } } } @@ -294,12 +428,12 @@ float Label::getScaleX() const } void Label::alignText() -{ +{ if(_textureAtlas) _textureAtlas->removeAllQuads(); _fontAtlas->prepareLetterDefinitions(_currentUTF16String); LabelTextFormatter::createStringSprites(this); - if(_multilineEnable && LabelTextFormatter::multilineText(this) ) + if(_width > 0 && LabelTextFormatter::multilineText(this) ) LabelTextFormatter::createStringSprites(this); LabelTextFormatter::alignText(this); @@ -337,20 +471,22 @@ void Label::alignText() insertQuadFromSprite(_reusedLetter,vaildIndex++); } } + + updateColor(); } -bool Label::computeAdvancesForString(unsigned short int *stringToRender) +bool Label::computeHorizontalKernings(unsigned short int *stringToRender) { - if (_advances) + if (_horizontalKernings) { - delete [] _advances; - _advances = 0; + delete [] _horizontalKernings; + _horizontalKernings = 0; } int letterCount = 0; - _advances = _fontAtlas->getFont()->getAdvancesForTextUTF16(stringToRender, letterCount); + _horizontalKernings = _fontAtlas->getFont()->getHorizontalKerningForTextUTF16(stringToRender, letterCount); - if(!_advances) + if(!_horizontalKernings) return false; else return true; @@ -384,7 +520,7 @@ bool Label::setCurrentString(unsigned short *stringToSet) // _currentUTF16String = stringToSet; // compute the advances - return computeAdvancesForString(stringToSet); + return computeHorizontalKernings(stringToSet); } void Label::resetCurrentString() @@ -423,10 +559,8 @@ Sprite * Label::updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, const F SpriteFrame *frame = SpriteFrame::createWithTexture(theTexture, uvRect); if (frame) { - spriteToUpdate->setBatchNode(this); - spriteToUpdate->setTexture(theTexture); - spriteToUpdate->setSpriteFrame(frame); - spriteToUpdate->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY)); + spriteToUpdate->setBatchNode(this); + spriteToUpdate->setSpriteFrame(frame); } return spriteToUpdate; @@ -531,7 +665,7 @@ void Label::onDraw() void Label::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Label::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -557,8 +691,8 @@ Sprite * Label::getLetter(int ID) sp = Sprite::createWithTexture(&_fontAtlas->getTexture(_lettersInfo[ID].def.textureID),uvRect); sp->setBatchNode(this); - sp->setAnchorPoint(Point(_lettersInfo[ID].def.anchorX, _lettersInfo[ID].def.anchorY)); - sp->setPosition(_lettersInfo[ID].position); + sp->setAnchorPoint(Point::ANCHOR_MIDDLE); + sp->setPosition(Point(_lettersInfo[ID].position.x+uvRect.size.width/2,_lettersInfo[ID].position.y-uvRect.size.height/2)); sp->setOpacity(_realOpacity); this->addSpriteWithoutQuad(sp, ID, ID); @@ -569,75 +703,19 @@ Sprite * Label::getLetter(int ID) return nullptr; } -float Label::getLetterPosXLeft( int index ) const -{ - return _lettersInfo[index].position.x * _scaleX - (_lettersInfo[index].contentSize.width * _scaleX * _lettersInfo[index].def.anchorX); -} - -float Label::getLetterPosXRight( int index ) const -{ - return _lettersInfo[index].position.x * _scaleX + (_lettersInfo[index].contentSize.width * _scaleX * _lettersInfo[index].def.anchorX); -} - int Label::getCommonLineHeight() const { return _commonLineHeight; } -int Label::getKerningForCharsPair(unsigned short first, unsigned short second) const -{ - return 0; -} - -int Label::getXOffsetForChar(unsigned short c) const -{ - FontLetterDefinition tempDefinition; - bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition); - if (!validDefinition) - return -1; - - return (tempDefinition.offsetX); -} - -int Label::getYOffsetForChar(unsigned short c) const -{ - FontLetterDefinition tempDefinition; - bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition); - if (!validDefinition) - return -1; - - return (tempDefinition.offsetY); -} - -int Label::getAdvanceForChar(unsigned short c, int hintPositionInString) const -{ - if (_advances) - { - // not that advance contains the X offset already - FontLetterDefinition tempDefinition; - bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition); - if (!validDefinition) - return -1; - - return (_advances[hintPositionInString].width); - } - else - { - return -1; - } -} - -Rect Label::getRectForChar(unsigned short c) const -{ - return _fontAtlas->getFont()->getRectForChar(c); -} - // string related stuff int Label::getStringNumLines() const { int quantityOfLines = 1; - unsigned int stringLen = _currentUTF16String ? cc_wcslen(_currentUTF16String) : 0; + unsigned int stringLen = _currentUTF16String ? cc_wcslen(_currentUTF16String) : -1; + if (stringLen < 1) + return stringLen; if (stringLen == 0) return (-1); @@ -659,17 +737,12 @@ int Label::getStringLenght() const return _currentUTF16String ? cc_wcslen(_currentUTF16String) : 0; } -unsigned short Label::getCharAtStringPosition(int position) const -{ - return _currentUTF16String[position]; -} - -unsigned short * Label::getUTF8String() const +unsigned short * Label::getUTF16String() const { return _currentUTF16String; } -void Label::assignNewUTF8String(unsigned short *newString) +void Label::assignNewUTF16String(unsigned short *newString) { setCurrentString(newString); } @@ -690,17 +763,6 @@ bool Label::breakLineWithoutSpace() const return _lineBreakWithoutSpaces; } -Size Label::getLabelContentSize() const -{ - return getContentSize(); -} - -void Label::setLabelContentSize(const Size &newSize) -{ - setContentSize(newSize); -} - - // RGBA protocol diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index ea7462ab50..2f6565da51 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -28,9 +28,9 @@ #define _COCOS2D_CCLABEL_H_ #include "CCSpriteBatchNode.h" -#include "CCLabelTextFormatProtocol.h" #include "ccTypes.h" #include "renderer/CCCustomCommand.h" +#include "CCFontAtlas.h" NS_CC_BEGIN @@ -50,27 +50,59 @@ enum class LabelEffect { GLOW }; -//fwd -struct FontLetterDefinition; -class FontAtlas; +struct LetterInfo +{ + FontLetterDefinition def; + Point position; + Size contentSize; +}; +typedef struct _ttfConfig +{ + std::string fontFilePath; + int fontSize; + GlyphCollection glyphs; + const char *customGlyphs; + bool distanceFieldEnabled; -class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public LabelTextFormatProtocol + _ttfConfig(const char* filePath,int size = 36, const GlyphCollection& glyphCollection = GlyphCollection::NEHE, + const char *customGlyphCollection = nullptr,bool useDistanceField = false) + :fontFilePath(filePath) + ,fontSize(size) + ,glyphs(glyphCollection) + ,customGlyphs(customGlyphCollection) + ,distanceFieldEnabled(useDistanceField) + {} +}TTFConfig; + +class CC_DLL Label : public SpriteBatchNode, public LabelProtocol { public: - - // static create - static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0, bool useDistanceField = false); - - static Label* createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0); - - bool setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false); + static Label* create(); + CC_DEPRECATED_ATTRIBUTE static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::LEFT, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0, bool useDistanceField = false); + static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment = TextHAlignment::LEFT, int lineWidth = 0); + + static Label* createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment = TextHAlignment::LEFT, int lineWidth = 0); + + static Label * createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + static Label * createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); + static Label * createWithCharMap(const std::string& plistFile); + + bool setTTFConfig(const TTFConfig& ttfConfig); + + bool setBMFontFilePath(const std::string& bmfontFilePath); + + bool setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + bool setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); + bool setCharMap(const std::string& plistFile); + + virtual void setString(const std::string& text) override; + + //only support for TTF void setLabelEffect(LabelEffect effect,const Color3B& effectColor); - virtual void setString(const std::string &stringToRender) override; - void setString(const std::string &stringToRender,bool multilineEnable); virtual void setAlignment(TextHAlignment alignment); virtual void setWidth(float width); virtual void setLineBreakWithoutSpace(bool breakWithoutSpace); @@ -85,56 +117,49 @@ public: virtual void setColor(const Color3B& color) override; // CCLabelTextFormat protocol implementation - virtual std::vector *getLettersInfo() override { return &_lettersInfo; }; - virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) override; - virtual bool recordPlaceholderInfo(int spriteIndex) override; - virtual float getLetterPosXLeft( int index ) const override; - virtual float getLetterPosXRight( int index ) const override; + virtual std::vector *getLettersInfo() { return &_lettersInfo; }; + virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex); + virtual bool recordPlaceholderInfo(int spriteIndex); - virtual Sprite * getLetter(int ID) override; + virtual Sprite * getLetter(int ID); // font related stuff - virtual int getCommonLineHeight() const override; - virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const override; - virtual int getXOffsetForChar(unsigned short c) const override; - virtual int getYOffsetForChar(unsigned short c) const override; - virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const override; - virtual Rect getRectForChar(unsigned short c) const override; + virtual int getCommonLineHeight() const; + virtual int* getKernings() const { return _horizontalKernings;} // string related stuff - virtual int getStringNumLines() const override; - virtual int getStringLenght() const override; - virtual unsigned short getCharAtStringPosition(int position) const override; - virtual unsigned short * getUTF8String() const override; - virtual void assignNewUTF8String(unsigned short *newString) override; - virtual TextHAlignment getTextAlignment() const override; + virtual int getStringNumLines() const; + virtual int getStringLenght() const; + virtual unsigned short * getUTF16String() const; + virtual void assignNewUTF16String(unsigned short *newString); + virtual TextHAlignment getTextAlignment() const; // label related stuff - virtual float getMaxLineWidth() const override; - virtual bool breakLineWithoutSpace() const override; - virtual Size getLabelContentSize() const override; - virtual void setLabelContentSize(const Size &newSize) override; + virtual float getMaxLineWidth() const; + virtual bool breakLineWithoutSpace() const; // carloX - virtual const std::string& getString() const override { static std::string _ret("not implemented"); return _ret; } + virtual const std::string& getString() const override { return _originalUTF8String; } void addChild(Node * child, int zOrder=0, int tag=0) override; virtual std::string getDescription() const override; virtual void draw(void) override; virtual void onDraw(); + virtual FontAtlas* getFontAtlas() const {return _fontAtlas;} + private: /** * @js NA */ - Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField = false,bool useA8Shader = false); + Label(FontAtlas *atlas = nullptr, TextHAlignment alignment = TextHAlignment::LEFT, bool useDistanceField = false,bool useA8Shader = false); /** * @js NA * @lua NA */ ~Label(); - static Label* createWithAtlas(FontAtlas *atlas, TextHAlignment alignment = TextHAlignment::LEFT, int lineSize = 0, bool useDistanceField = false,bool useA8Shader = false); + bool initWithFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled = false, bool useA8Shader = false); void setFontSize(int fontSize); @@ -142,7 +167,7 @@ private: void alignText(); - bool computeAdvancesForString(unsigned short int *stringToRender); + bool computeHorizontalKernings(unsigned short int *stringToRender); bool setCurrentString(unsigned short *stringToSet); bool setOriginalString(unsigned short *stringToSet); void resetCurrentString(); @@ -151,32 +176,31 @@ private: virtual void updateColor() override; - //! used for optimization - Sprite *_reusedLetter; - std::vector _lettersInfo; - - bool _multilineEnable; - float _commonLineHeight; - bool _lineBreakWithoutSpaces; - float _width; - TextHAlignment _alignment; - unsigned short int * _currentUTF16String; - unsigned short int * _originalUTF16String; - Size * _advances; - FontAtlas * _fontAtlas; - bool _isOpacityModifyRGB; + Sprite *_reusedLetter; + std::vector _lettersInfo; - bool _useDistanceField; - bool _useA8Shader; - int _fontSize; + float _commonLineHeight; + bool _lineBreakWithoutSpaces; + float _width; + TextHAlignment _alignment; + unsigned short int * _currentUTF16String; + unsigned short int * _originalUTF16String; + std::string _originalUTF8String; + int * _horizontalKernings; + FontAtlas * _fontAtlas; + bool _isOpacityModifyRGB; - LabelEffect _currLabelEffect; - Color3B _effectColor; + bool _useDistanceField; + bool _useA8Shader; + int _fontSize; - GLuint _uniformEffectColor; + LabelEffect _currLabelEffect; + Color3B _effectColor; - CustomCommand _customCommand; + GLuint _uniformEffectColor; + + CustomCommand _customCommand; }; diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 539c5dab6a..1b856664fd 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -275,8 +275,7 @@ std::set* CCBMFontConfiguration::parseBinaryConfigFile(unsigned ch unsigned long remains = size; - unsigned char version = pData[3]; - CCASSERT(version == 3, "Only version 3 is supported"); + CCASSERT(pData[3] == 3, "Only version 3 is supported"); pData += 4; remains -= 4; @@ -343,8 +342,7 @@ std::set* CCBMFontConfiguration::parseBinaryConfigFile(unsigned ch */ const char *value = (const char *)pData; - size_t len = strlen(value); - CCASSERT(len < blockSize, "Block size should be less then string"); + CCASSERT(strlen(value) < blockSize, "Block size should be less then string"); _atlasName = FileUtils::getInstance()->fullPathFromRelativeFile(value, controlFile); } diff --git a/cocos/2d/CCLabelTextFormatProtocol.h b/cocos/2d/CCLabelTextFormatProtocol.h deleted file mode 100644 index bf72775a51..0000000000 --- a/cocos/2d/CCLabelTextFormatProtocol.h +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 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. - ****************************************************************************/ - -#ifndef _CCLabelTextFormatProtocol_h_ -#define _CCLabelTextFormatProtocol_h_ -#include "CCFontAtlas.h" -#include - -NS_CC_BEGIN - - -struct LetterInfo -{ - FontLetterDefinition def; - - Point position; - Size contentSize; - bool visible; -}; - -class CC_DLL LabelTextFormatProtocol -{ -public: - - virtual ~LabelTextFormatProtocol() {} - - virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) = 0; - virtual bool recordPlaceholderInfo(int spriteIndex) = 0; - virtual std::vector *getLettersInfo() = 0; - virtual float getLetterPosXLeft(int index) const = 0; - virtual float getLetterPosXRight(int index) const = 0; - // sprite related stuff - virtual cocos2d::Sprite *getLetter(int ID) = 0; - - // font related stuff - virtual int getCommonLineHeight() const = 0; - virtual int getKerningForCharsPair(unsigned short first, unsigned short second) const = 0; - virtual int getXOffsetForChar(unsigned short c) const = 0; - virtual int getYOffsetForChar(unsigned short c) const = 0; - virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const = 0; - virtual cocos2d::Rect getRectForChar(unsigned short c) const = 0; - - // string related stuff - virtual int getStringNumLines() const = 0; - virtual int getStringLenght() const = 0; - virtual unsigned short getCharAtStringPosition(int position) const = 0; - virtual unsigned short * getUTF8String() const = 0; - virtual void assignNewUTF8String(unsigned short *newString) = 0; - virtual TextHAlignment getTextAlignment() const = 0; - - // label related stuff - virtual float getMaxLineWidth() const = 0; - virtual bool breakLineWithoutSpace() const = 0; - virtual cocos2d::Size getLabelContentSize() const = 0; - virtual void setLabelContentSize(const Size &newSize) = 0; -}; - -NS_CC_END - -#endif diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 956c5c3bb1..0ed58fbce2 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -25,76 +25,53 @@ #include -#include "cocos2d.h" #include "ccUTF8.h" #include "CCLabelTextFormatter.h" +#include "CCDirector.h" +#include "CCLabel.h" using namespace std; NS_CC_BEGIN -bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) +bool LabelTextFormatter::multilineText(Label *theLabel) { - // to do if (m_fWidth > 0) - if (theLabel->getMaxLineWidth()) - { - // Step 1: Make multiline - vector strWhole = cc_utf16_vec_from_utf16_str(theLabel->getUTF8String()); - size_t stringLength = strWhole.size(); - - vector multiline_string; - multiline_string.reserve( stringLength ); - - vector last_word; - last_word.reserve( stringLength ); - - unsigned int line = 1, i = 0; - - bool isStartOfLine = false, isStartOfWord = false; - float startOfLine = -1, startOfWord = -1; - - int skip = 0; - - int strLen = theLabel->getStringLenght(); - std::vector *leterInfo = theLabel->getLettersInfo(); - int tIndex = 0; + int strLen = theLabel->getStringLenght(); + auto strWhole = theLabel->getUTF16String(); - for (int j = 0; j+skip < strLen; j++) - { - LetterInfo* info = &leterInfo->at(j+skip); + vector multiline_string; + multiline_string.reserve( strLen ); - unsigned int justSkipped = 0; - - while (info->def.validDefinition == false) - { - justSkipped++; - info = &leterInfo->at( j+skip+justSkipped ); - } - skip += justSkipped; - tIndex = j + skip; - - if (i >= stringLength) - break; - - unsigned short character = strWhole[i]; - - if (!isStartOfWord) - { - startOfWord = theLabel->getLetterPosXLeft( tIndex ); - isStartOfWord = true; - } - - if (!isStartOfLine) - { - startOfLine = startOfWord; - isStartOfLine = true; - } - - // Newline. - if (character == '\n') + vector last_word; + last_word.reserve( strLen ); + + unsigned int line = 1; + + bool isStartOfLine = false, isStartOfWord = false; + float startOfLine = -1, startOfWord = -1; + + int skip = 0; + + std::vector *leterInfo = theLabel->getLettersInfo(); + int tIndex = 0; + float scalsX = theLabel->getScaleX(); + float lineWidth = theLabel->getMaxLineWidth(); + bool breakLineWithoutSpace = theLabel->breakLineWithoutSpace(); + + for (int j = 0; j+skip < strLen; j++) + { + LetterInfo* info = &leterInfo->at(j+skip); + + unsigned int justSkipped = 0; + + while (info->def.validDefinition == false) + { + justSkipped++; + tIndex = j+skip+justSkipped; + if (strWhole[tIndex-1] == '\n') { cc_utf8_trim_ws(&last_word); - + last_word.push_back('\n'); multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); last_word.clear(); @@ -102,133 +79,119 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) isStartOfLine = false; startOfWord = -1; startOfLine = -1; - i += justSkipped; ++line; - - if (i >= stringLength) - break; - - character = strWhole[i]; - - if (!startOfWord) - { - startOfWord = theLabel->getLetterPosXLeft( tIndex ); - isStartOfWord = true; - } - if (!startOfLine) - { - startOfLine = startOfWord; - isStartOfLine = true; - } } - - // Whitespace. - if (isspace_unicode(character)) + if(tIndex < strLen) + { + info = &leterInfo->at( tIndex ); + } + else + break; + } + skip += justSkipped; + tIndex = j + skip; + + if (tIndex >= strLen) + break; + + unsigned short character = strWhole[tIndex]; + + if (!isStartOfWord) + { + startOfWord = info->position.x * scalsX; + isStartOfWord = true; + } + + if (!isStartOfLine) + { + startOfLine = startOfWord; + isStartOfLine = true; + } + + // Whitespace. + if (isspace_unicode(character)) + { + last_word.push_back(character); + multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); + last_word.clear(); + isStartOfWord = false; + startOfWord = -1; + continue; + } + + float posRight = (info->position.x + info->contentSize.width) * scalsX; + // Out of bounds. + if (posRight - startOfLine > lineWidth) + { + if (!breakLineWithoutSpace) { last_word.push_back(character); - multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); - last_word.clear(); - isStartOfWord = false; - startOfWord = -1; - ++i; - continue; - } - - // Out of bounds. - if (theLabel->getLetterPosXRight( tIndex ) - startOfLine > theLabel->getMaxLineWidth()) - { - if (!theLabel->breakLineWithoutSpace()) - { - last_word.push_back(character); - - int found = cc_utf8_find_last_not_char(multiline_string, ' '); - if (found != -1) - cc_utf8_trim_ws(&multiline_string); - else - multiline_string.clear(); - - if (multiline_string.size() > 0) - multiline_string.push_back('\n'); - - ++line; - isStartOfLine = false; - startOfLine = -1; - ++i; - } + + int found = cc_utf8_find_last_not_char(multiline_string, ' '); + if (found != -1) + cc_utf8_trim_ws(&multiline_string); else - { - cc_utf8_trim_ws(&last_word); - - last_word.push_back('\n'); - multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); - last_word.clear(); - isStartOfWord = false; - isStartOfLine = false; - startOfWord = -1; - startOfLine = -1; - ++line; - - if (i >= stringLength) - break; - - if (!startOfWord) - { - startOfWord = theLabel->getLetterPosXLeft( tIndex ); - isStartOfWord = true; - } - if (!startOfLine) - { - startOfLine = startOfWord; - isStartOfLine = true; - } - - --j; - } - - continue; + multiline_string.clear(); + + if (multiline_string.size() > 0) + multiline_string.push_back('\n'); + + ++line; + isStartOfLine = false; + startOfLine = -1; } else { - // Character is normal. - last_word.push_back(character); - ++i; - continue; + cc_utf8_trim_ws(&last_word); + + last_word.push_back('\n'); + multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); + last_word.clear(); + isStartOfWord = false; + isStartOfLine = false; + startOfWord = -1; + startOfLine = -1; + ++line; + --j; } } - - multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); - - size_t size = multiline_string.size(); - unsigned short* strNew = new unsigned short[size + 1]; - - for (size_t j = 0; j < size; ++j) + else { - strNew[j] = multiline_string[j]; + // Character is normal. + last_word.push_back(character); } - - strNew[size] = 0; - theLabel->assignNewUTF8String(strNew); - - return true; } - else + + multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); + + size_t size = multiline_string.size(); + unsigned short* strNew = new unsigned short[size + 1]; + + for (size_t j = 0; j < size; ++j) { - return false; + strNew[j] = multiline_string[j]; } + + strNew[size] = 0; + theLabel->assignNewUTF16String(strNew); + + return true; } -bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel) +bool LabelTextFormatter::alignText(Label *theLabel) { int i = 0; int lineNumber = 0; - int strLen = cc_wcslen(theLabel->getUTF8String()); + int strLen = cc_wcslen(theLabel->getUTF16String()); vector lastLine; std::vector *leterInfo = theLabel->getLettersInfo(); + auto strWhole = theLabel->getUTF16String(); + for (int ctr = 0; ctr <= strLen; ++ctr) - { - unsigned short int currentChar = theLabel->getCharAtStringPosition(ctr); - + { + unsigned short currentChar = strWhole[ctr]; + if (currentChar == '\n' || currentChar == 0) { float lineWidth = 0.0f; @@ -241,23 +204,21 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel) continue; } int index = static_cast(i + lineLength - 1 + lineNumber); - if(currentChar == 0) - index -= 1; if (index < 0) continue; LetterInfo* info = &leterInfo->at( index ); if(info->def.validDefinition == false) continue; - lineWidth = info->position.x + info->contentSize.width /2.0f; + lineWidth = info->position.x + info->contentSize.width; float shift = 0; switch (theLabel->getTextAlignment()) { case TextHAlignment::CENTER: - shift = theLabel->getLabelContentSize().width/2.0f - lineWidth/2.0f; + shift = theLabel->getContentSize().width/2.0f - lineWidth/2.0f; break; case TextHAlignment::RIGHT: - shift = theLabel->getLabelContentSize().width - lineWidth; + shift = theLabel->getContentSize().width - lineWidth; break; default: break; @@ -273,7 +234,7 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel) info = &leterInfo->at( index ); if(info) { - info->position = info->position + Point(shift, 0.0f); + info->position.x += shift; } } } @@ -291,7 +252,7 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel) return true; } -bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel) +bool LabelTextFormatter::createStringSprites(Label *theLabel) { // check for string unsigned int stringLen = theLabel->getStringLenght(); @@ -305,37 +266,42 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel) unsigned short prev = -1; - Size tmpSize = Size::ZERO; int longestLine = 0; unsigned int totalHeight = 0; - int quantityOfLines = theLabel->getStringNumLines(); int commonLineHeight = theLabel->getCommonLineHeight(); - totalHeight = commonLineHeight * quantityOfLines; - nextFontPositionY = 0 - (commonLineHeight - totalHeight); + totalHeight = commonLineHeight * quantityOfLines; + nextFontPositionY = totalHeight; - Rect rect; - Rect charRect; int charXOffset = 0; int charYOffset = 0; int charAdvance = 0; + + auto strWhole = theLabel->getUTF16String(); + FontAtlas* fontAtlas = theLabel->getFontAtlas(); + FontLetterDefinition tempDefinition; + auto kernings = theLabel->getKernings(); for (unsigned int i = 0; i < stringLen; i++) { - // get the current character - unsigned short c = theLabel->getCharAtStringPosition(i); - - charXOffset = theLabel->getXOffsetForChar(c); - charYOffset = theLabel->getYOffsetForChar(c); - charAdvance = theLabel->getAdvanceForChar(c, i); - charRect = theLabel->getRectForChar(c); - - int kerningAmount = theLabel->getKerningForCharsPair(prev, c); + unsigned short c = strWhole[i]; + if (fontAtlas->getLetterDefinitionForChar(c, tempDefinition)) + { + charXOffset = tempDefinition.offsetX; + charYOffset = tempDefinition.offsetY; + charAdvance = tempDefinition.xAdvance; + } + else + { + charXOffset = -1; + charYOffset = -1; + charAdvance = -1; + } if (c == '\n') { @@ -346,12 +312,8 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel) continue; } - // See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!) - int yOffset = commonLineHeight - charYOffset; - - - Point fontPos = Point((float)nextFontPositionX + charXOffset + charRect.size.width * 0.5f + kerningAmount, - (float)nextFontPositionY + yOffset - charRect.size.height * 0.5f); + Point fontPos = Point((float)nextFontPositionX + charXOffset + kernings[i], + (float)nextFontPositionY - charYOffset); if( theLabel->recordLetterInfo(CC_POINT_PIXELS_TO_POINTS(fontPos),c,i) == false) { @@ -360,7 +322,7 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel) } // update kerning - nextFontPositionX += charAdvance + kerningAmount; + nextFontPositionX += charAdvance + kernings[i]; prev = c; if (longestLine < nextFontPositionX) @@ -369,12 +331,13 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel) } } + float lastCharWidth = tempDefinition.width * CC_CONTENT_SCALE_FACTOR(); // If the last character processed has an xAdvance which is less that the width of the characters image, then we need // to adjust the width of the string to take this into account, or the character will overlap the end of the bounding // box - if (charAdvance < charRect.size.width) + if(charAdvance < lastCharWidth) { - tmpSize.width = longestLine + charRect.size.width - charAdvance; + tmpSize.width = longestLine - charAdvance + lastCharWidth; } else { @@ -382,7 +345,7 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel) } tmpSize.height = totalHeight; - theLabel->setLabelContentSize(CC_SIZE_PIXELS_TO_POINTS(tmpSize)); + theLabel->setContentSize(CC_SIZE_PIXELS_TO_POINTS(tmpSize)); return true; } diff --git a/cocos/2d/CCLabelTextFormatter.h b/cocos/2d/CCLabelTextFormatter.h index f6a7ecdec9..2b15b456a6 100644 --- a/cocos/2d/CCLabelTextFormatter.h +++ b/cocos/2d/CCLabelTextFormatter.h @@ -26,17 +26,17 @@ #ifndef _CCLabelTextFormatter_h_ #define _CCLabelTextFormatter_h_ -#include "CCLabelTextFormatProtocol.h" - NS_CC_BEGIN +class Label; + class CC_DLL LabelTextFormatter { public: - static bool multilineText(LabelTextFormatProtocol *theLabel); - static bool alignText(LabelTextFormatProtocol *theLabel); - static bool createStringSprites(LabelTextFormatProtocol *theLabel); + static bool multilineText(Label *theLabel); + static bool alignText(Label *theLabel); + static bool createStringSprites(Label *theLabel); }; diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index 1bae6e040c..54b9c48cd9 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -44,8 +44,8 @@ THE SOFTWARE. #include "CCEventListenerAcceleration.h" #include "platform/CCDevice.h" #include "CCScene.h" -#include "CCCustomCommand.h" -#include "CCRenderer.h" +#include "renderer/CCCustomCommand.h" +#include "renderer/CCRenderer.h" NS_CC_BEGIN @@ -565,7 +565,7 @@ void LayerColor::updateColor() void LayerColor::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(LayerColor::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/cocos/2d/CCMotionStreak.cpp b/cocos/2d/CCMotionStreak.cpp index 4e248b7ea1..735a8edae2 100644 --- a/cocos/2d/CCMotionStreak.cpp +++ b/cocos/2d/CCMotionStreak.cpp @@ -31,8 +31,8 @@ THE SOFTWARE. #include "ccMacros.h" #include "CCDirector.h" #include "CCVertex.h" -#include "CCCustomCommand.h" -#include "CCRenderer.h" +#include "renderer/CCCustomCommand.h" +#include "renderer/CCRenderer.h" NS_CC_BEGIN @@ -359,7 +359,7 @@ void MotionStreak::draw() if(_nuPoints <= 1) return; kmGLGetMatrix(KM_GL_MODELVIEW,&_cachedMV); - _customCommand.init(0,_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(MotionStreak::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 3b7ce1c47c..d331ca1405 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -64,29 +64,12 @@ THE SOFTWARE. NS_CC_BEGIN -#if CC_USE_ARRAY_VECTOR -bool nodeComparisonLess(const RCPtr& pp1, const RCPtr& pp2) +bool nodeComparisonLess(Node* n1, Node* n2) { - Object *p1 = static_cast(pp1); - Object *p2 = static_cast(pp2); - Node *n1 = static_cast(p1); - Node *n2 = static_cast(p2); - - return( n1->getZOrder() < n2->getZOrder() || - ( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() ) + return( n1->getLocalZOrder() < n2->getLocalZOrder() || + ( n1->getLocalZOrder() == n2->getLocalZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() ) ); } -#else -bool nodeComparisonLess(Object* p1, Object* p2) -{ - Node *n1 = static_cast(p1); - Node *n2 = static_cast(p2); - - return( n1->getZOrder() < n2->getZOrder() || - ( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() ) - ); -} -#endif // XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered. static int s_globalOrderOfArrival = 1; @@ -108,7 +91,8 @@ Node::Node(void) , _inverseDirty(true) // children (lazy allocs) // lazy alloc -, _ZOrder(0) +, _localZOrder(0) +, _globalZOrder(0) , _parent(nullptr) // "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true , _tag(Node::INVALID_TAG) @@ -212,32 +196,34 @@ void Node::setSkewY(float newSkewY) _transformDirty = _inverseDirty = true; } -/// zOrder getter -int Node::getZOrder() const -{ - return _ZOrder; -} /// zOrder setter : private method /// used internally to alter the zOrder variable. DON'T call this method manually -void Node::_setZOrder(int z) +void Node::_setLocalZOrder(int z) { - _ZOrder = z; + _localZOrder = z; } -void Node::setZOrder(int z) +void Node::setLocalZOrder(int z) { + _localZOrder = z; if (_parent) { _parent->reorderChild(this, z); } - // should set "_ZOrder" after reorderChild, because the implementation of reorderChild subclass of Node, such as Sprite, - // will return when _ZOrder value is not changed - _setZOrder(z); - + _eventDispatcher->setDirtyForNode(this); } +void Node::setGlobalZOrder(float globalZOrder) +{ + if (_globalZOrder != globalZOrder) + { + _globalZOrder = globalZOrder; + _eventDispatcher->setDirtyForNode(this); + } +} + /// vertexZ getter float Node::getVertexZ() const { @@ -246,9 +232,10 @@ float Node::getVertexZ() const /// vertexZ setter -void Node::setVertexZ(float var) +void Node::setVertexZ(float zOrder) { - _vertexZ = var; + _vertexZ = zOrder; + setGlobalZOrder(zOrder); } @@ -650,7 +637,7 @@ void Node::addChild(Node *child, int zOrder) void Node::addChild(Node *child) { CCASSERT( child != nullptr, "Argument must be non-nil"); - this->addChild(child, child->_ZOrder, child->_tag); + this->addChild(child, child->_localZOrder, child->_tag); } void Node::removeFromParent() @@ -767,7 +754,7 @@ void Node::insertChild(Node* child, int z) { _reorderChildDirty = true; _children.pushBack(child); - child->_setZOrder(z); + child->_setLocalZOrder(z); } void Node::reorderChild(Node *child, int zOrder) @@ -775,7 +762,7 @@ void Node::reorderChild(Node *child, int zOrder) CCASSERT( child != nullptr, "Child must be non-nil"); _reorderChildDirty = true; child->setOrderOfArrival(s_globalOrderOfArrival++); - child->_setZOrder(zOrder); + child->_setLocalZOrder(zOrder); } void Node::sortAllChildren() @@ -816,7 +803,7 @@ void Node::visit() { auto node = _children.at(i); - if ( node && node->_ZOrder < 0 ) + if ( node && node->_localZOrder < 0 ) node->visit(); else break; diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 3069fb0a84..92f63c6edc 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -1,9 +1,9 @@ /**************************************************************************** Copyright (c) 2008-2010 Ricardo Quesada -Copyright (c) 2009 Valentin Milea -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2011 Zynga Inc. -Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2009 Valentin Milea + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2011 Zynga Inc. + Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -72,11 +72,7 @@ enum { kNodeOnCleanup }; -#if CC_USE_ARRAY_VECTOR -bool nodeComparisonLess(const RCPtr& pp1, const RCPtr& pp2); -#else -bool nodeComparisonLess(Object* p1, Object* p2); -#endif +bool nodeComparisonLess(Node* n1, Node* n2); class EventListener; @@ -161,43 +157,72 @@ public: /// @name Setters & Getters for Graphic Peroperties /** - * Sets the Z order which stands for the drawing order, and reorder this node in its parent's children array. - * - * The Z order of node is relative to its siblings. - * It is not related to the OpenGL's z property. This one only affects the draw order of itself and its siblings. - * Lower Z order number are drawn before higher numbers. - * Please refer to `setVertexZ(float)` for the difference. - * - * @param zOrder Z order of this node. + LocalZOrder is the 'key' used to sort the node relative to its siblings. + + The Node's parent will sort all its children based ont the LocalZOrder value. + If two nodes have the same LocalZOrder, then the node that was added first to the children's array will be in front of the other node in the array. + + Also, the Scene Graph is traversed using the "In-Order" tree traversal algorithm ( http://en.wikipedia.org/wiki/Tree_traversal#In-order ) + And Nodes that have LocalZOder values < 0 are the "left" subtree + While Nodes with LocalZOder >=0 are the "right" subtree. + + @see `setGlobalZOrder` + @see `setVertexZ` */ - virtual void setZOrder(int zOrder); - /* - * Sets the z order which stands for the drawing order - * - * This is an internal method. Don't call it outside the framework. - * The difference between setZOrder(int) and _setOrder(int) is: - * - _setZOrder(int) is a pure setter for _ZOrder memeber variable - * - setZOrder(int) firstly changes _ZOrder, then recorder this node in its parent's chilren array. + virtual void setLocalZOrder(int localZOrder); + + CC_DEPRECATED_ATTRIBUTE virtual void setZOrder(int localZOrder) { setLocalZOrder(localZOrder); } + /* Helper function used by `setLocalZOrder`. Don't use it unless you know what you are doing. */ - virtual void _setZOrder(int z); + virtual void _setLocalZOrder(int z); /** - * Gets the Z order of this node. + * Gets the local Z order of this node. * - * @see `setZOrder(int)` + * @see `setLocalZOrder(int)` * - * @return The Z order. + * @return The local (relative to its siblings) Z order. */ - virtual int getZOrder() const; + virtual int getLocalZOrder() const { return _localZOrder; } + CC_DEPRECATED_ATTRIBUTE virtual int getZOrder() const { return getLocalZOrder(); } /** - * Sets the real OpenGL Z vertex. + Defines the oder in which the nodes are renderer. + Nodes that have a Global Z Order lower, are renderer first. + + In case two or more nodes have the same Global Z Order, the oder is not guaranteed. + The only exception if the Nodes have a Global Z Order == 0. In that case, the Scene Graph order is used. + + By default, all nodes have a Global Z Order = 0. That means that by default, the Scene Graph order is used to render the nodes. + + Global Z Order is useful when you need to render nodes in an order different than the Scene Graph order. + + Limitations: Global Z Order can't be used used by Nodes that have SpriteBatchNode as one of their acenstors. + And if ClippingNode is one of the ancestors, then "global Z order" will be relative to the ClippingNode. + + @see `setLocalZOrder()` + @see `setVertexZ()` + + @since v3.0 + */ + virtual void setGlobalZOrder(float globalZOrder); + /** + * Returns the Node's Global Z Order. * - * Differences between openGL Z vertex and cocos2d Z order: - * - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children - * - OpenGL Z might require to set 2D projection - * - cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: `vertexZ = 0` + * @see `setGlobalZOrder(int)` * - * @warning Use it at your own risk since it might break the cocos2d parent-children z order + * @return The node's global Z order + */ + virtual float getGlobalZOrder() const { return _globalZOrder; } + + /** + * Sets the 'z' value in the OpenGL Depth Buffer. + * + * The OpenGL depth buffer and depth testing are disabled by default. You need to turn them on + * in order to use this property correctly. + * + * `setVertexZ()` also sets the `setGlobalZValue()` with the vertexZ value. + * + * @see `setGlobalZValue()` * * @param vertexZ OpenGL Z vertex of this node. */ @@ -506,11 +531,11 @@ public: * A node which called addChild subsequently will take a larger arrival order, * If two children have the same Z order, the child with larger arrival order will be drawn later. * - * @warning This method is used internally for zOrder sorting, don't change this manually + * @warning This method is used internally for localZOrder sorting, don't change this manually * * @param orderOfArrival The arrival order. */ - virtual void setOrderOfArrival(int orderOfArrival); + void setOrderOfArrival(int orderOfArrival); /** * Returns the arrival order, indecates which children is added previously. * @@ -518,7 +543,7 @@ public: * * @return The arrival order. */ - virtual int getOrderOfArrival() const; + int getOrderOfArrival() const; /** @deprecated No longer needed @@ -566,24 +591,24 @@ public: */ virtual void addChild(Node * child); /** - * Adds a child to the container with a z-order + * Adds a child to the container with a local z-order * * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to `setLocalZOrder(int)` */ - virtual void addChild(Node * child, int zOrder); + virtual void addChild(Node * child, int localZOrder); /** * Adds a child to the container with z order and tag * * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) * @param tag A interger to identify the node easily. Please refer to setTag(int) */ - virtual void addChild(Node* child, int zOrder, int tag); + virtual void addChild(Node* child, int localZOrder, int tag); /** * Gets a child from the container with its tag * @@ -686,9 +711,9 @@ public: * Reorders a child according to a new z value. * * @param child An already added child node. It MUST be already added. - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param localZOrder Z order for drawing priority. Please refer to setLocalZOrder(int) */ - virtual void reorderChild(Node * child, int zOrder); + virtual void reorderChild(Node * child, int localZOrder); /** * Sorts the children array once before drawing, instead of every time when a child is added or reordered. @@ -1411,7 +1436,6 @@ protected: float _scaleX; ///< scaling factor on x-axis float _scaleY; ///< scaling factor on y-axis - float _vertexZ; ///< OpenGL real Z vertex Point _position; ///< position of the node @@ -1433,8 +1457,12 @@ protected: mutable bool _transformDirty; ///< transform dirty flag mutable bool _inverseDirty; ///< inverse transform dirty flag - int _ZOrder; ///< z-order value that affects the draw order - + + int _localZOrder; ///< Local order (relative to its siblings) used to sort the node + float _globalZOrder; ///< Global order used to sort the node + float _vertexZ; ///< OpenGL real Z vertex + + Vector _children; ///< array of children nodes Node *_parent; ///< weak reference to parent node @@ -1445,7 +1473,7 @@ protected: GLProgram *_shaderProgram; ///< OpenGL shader - int _orderOfArrival; ///< used to preserve sequence while sorting children with the same zOrder + int _orderOfArrival; ///< used to preserve sequence while sorting children with the same localZOrder Scheduler *_scheduler; ///< scheduler used to schedule timers and updates diff --git a/cocos/2d/CCNodeGrid.cpp b/cocos/2d/CCNodeGrid.cpp index 90d5647a57..be7c1d1a8c 100644 --- a/cocos/2d/CCNodeGrid.cpp +++ b/cocos/2d/CCNodeGrid.cpp @@ -25,9 +25,9 @@ #include "CCNodeGrid.h" #include "CCGrid.h" -#include "CCGroupCommand.h" -#include "CCRenderer.h" -#include "CCCustomCommand.h" +#include "renderer/CCGroupCommand.h" +#include "renderer/CCRenderer.h" +#include "renderer/CCCustomCommand.h" NS_CC_BEGIN @@ -92,7 +92,7 @@ void NodeGrid::visit() Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand.init(0,_vertexZ); + _groupCommand.init(_globalZOrder); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); @@ -104,7 +104,7 @@ void NodeGrid::visit() _nodeGrid->set2DProjection(); } - _gridBeginCommand.init(0,_vertexZ); + _gridBeginCommand.init(_globalZOrder); _gridBeginCommand.func = CC_CALLBACK_0(NodeGrid::onGridBeginDraw, this); renderer->addCommand(&_gridBeginCommand); @@ -125,7 +125,7 @@ void NodeGrid::visit() { auto node = _children.at(i); - if ( node && node->getZOrder() < 0 ) + if ( node && node->getLocalZOrder() < 0 ) node->visit(); else break; @@ -152,7 +152,7 @@ void NodeGrid::visit() director->setProjection(beforeProjectionType); } - _gridEndCommand.init(0,_vertexZ); + _gridEndCommand.init(_globalZOrder); _gridEndCommand.func = CC_CALLBACK_0(NodeGrid::onGridEndDraw, this); renderer->addCommand(&_gridEndCommand); diff --git a/cocos/2d/CCParallaxNode.cpp b/cocos/2d/CCParallaxNode.cpp index a2e165ce85..b8c7f1a52f 100644 --- a/cocos/2d/CCParallaxNode.cpp +++ b/cocos/2d/CCParallaxNode.cpp @@ -100,9 +100,9 @@ void ParallaxNode::addChild(Node *child, int z, const Point& ratio, const Point& obj->setChild(child); ccArrayAppendObjectWithResize(_parallaxArray, (Object*)obj); - Point pos = _position; - pos.x = pos.x * ratio.x + offset.x; - pos.y = pos.y * ratio.y + offset.y; + Point pos = this->absolutePosition(); + pos.x = -pos.x + pos.x * ratio.x + offset.x; + pos.y = -pos.y + pos.y * ratio.y + offset.y; child->setPosition(pos); Node::addChild(child, z, child->getTag()); diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index 5b78d1256f..40a7bc471b 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -44,7 +44,7 @@ #include "kazmath/GL/matrix.h" #include "CCProfiling.h" #include "renderer/CCQuadCommand.h" -#include "CCRenderer.h" +#include "renderer/CCRenderer.h" NS_CC_BEGIN @@ -197,7 +197,7 @@ int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag) _children.insert(pos, child); child->setTag(aTag); - child->_setZOrder(z); + child->_setLocalZOrder(z); child->setParent(this); @@ -218,7 +218,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder) ParticleSystem* child = static_cast(aChild); - if( zOrder == child->getZOrder() ) + if( zOrder == child->getLocalZOrder() ) { return; } @@ -264,7 +264,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder) } } - child->_setZOrder(zOrder); + child->_setLocalZOrder(zOrder); } void ParticleBatchNode::getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z) @@ -280,7 +280,7 @@ void ParticleBatchNode::getCurrentIndex(int* oldIndex, int* newIndex, Node* chil Node* pNode = _children.at(i); // new index - if( pNode->getZOrder() > z && ! foundNewIdx ) + if( pNode->getLocalZOrder() > z && ! foundNewIdx ) { *newIndex = i; foundNewIdx = true; @@ -325,7 +325,7 @@ int ParticleBatchNode::searchNewPositionInChildrenForZ(int z) for( int i=0; i < count; i++ ) { Node *child = _children.at(i); - if (child->getZOrder() > z) + if (child->getLocalZOrder() > z) { return i; } @@ -382,26 +382,13 @@ void ParticleBatchNode::draw(void) return; } -// CC_NODE_DRAW_SETUP(); -// -// GL::blendFunc( _blendFunc.src, _blendFunc.dst ); -// -// _textureAtlas->drawQuads(); - - auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); - - kmMat4 mv; - kmGLGetMatrix(KM_GL_MODELVIEW, &mv); - - _quadCommand.init(0, - _vertexZ, - _textureAtlas->getTexture()->getName(), - shader, - _blendFunc, - _textureAtlas->getQuads(), - _textureAtlas->getTotalQuads(), - mv); - Director::getInstance()->getRenderer()->addCommand(&_quadCommand); + _batchCommand.init( + _globalZOrder, + _shaderProgram, + _blendFunc, + _textureAtlas, + _modelViewTransform); + Director::getInstance()->getRenderer()->addCommand(&_batchCommand); CC_PROFILER_STOP("CCParticleBatchNode - draw"); } diff --git a/cocos/2d/CCParticleBatchNode.h b/cocos/2d/CCParticleBatchNode.h index d4fd276603..bb092e96d2 100644 --- a/cocos/2d/CCParticleBatchNode.h +++ b/cocos/2d/CCParticleBatchNode.h @@ -32,7 +32,7 @@ #include "CCNode.h" #include "CCProtocols.h" -#include "renderer/CCQuadCommand.h" +#include "renderer/CCBatchCommand.h" NS_CC_BEGIN @@ -146,7 +146,7 @@ private: /** the blend function used for drawing the quads */ BlendFunc _blendFunc; // quad command - QuadCommand _quadCommand; + BatchCommand _batchCommand; }; // end of particle_nodes group diff --git a/cocos/2d/CCParticleSystemQuad.cpp b/cocos/2d/CCParticleSystemQuad.cpp index 579db6c024..bd4bef3599 100644 --- a/cocos/2d/CCParticleSystemQuad.cpp +++ b/cocos/2d/CCParticleSystemQuad.cpp @@ -38,9 +38,9 @@ THE SOFTWARE. #include "TransformUtils.h" #include "CCEventType.h" #include "CCConfiguration.h" -#include "CCRenderer.h" +#include "renderer/CCRenderer.h" #include "renderer/CCQuadCommand.h" -#include "CCCustomCommand.h" +#include "renderer/CCCustomCommand.h" // extern #include "kazmath/GL/matrix.h" @@ -439,7 +439,7 @@ void ParticleSystemQuad::draw() auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); - _quadCommand.init(0, _vertexZ, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform); + _quadCommand.init(_globalZOrder, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform); Director::getInstance()->getRenderer()->addCommand(&_quadCommand); } diff --git a/cocos/2d/CCProgressTimer.cpp b/cocos/2d/CCProgressTimer.cpp index 7d135a9016..112b34d85b 100644 --- a/cocos/2d/CCProgressTimer.cpp +++ b/cocos/2d/CCProgressTimer.cpp @@ -33,8 +33,8 @@ THE SOFTWARE. #include "CCDirector.h" #include "TransformUtils.h" #include "CCDrawingPrimitives.h" -#include "CCRenderer.h" -#include "CCCustomCommand.h" +#include "renderer/CCRenderer.h" +#include "renderer/CCCustomCommand.h" // extern #include "kazmath/GL/matrix.h" @@ -555,7 +555,7 @@ void ProgressTimer::draw() if( ! _vertexData || ! _sprite) return; - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ProgressTimer::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index efaad582ef..57b6a00d24 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -38,9 +38,9 @@ THE SOFTWARE. #include "CCEventType.h" #include "CCGrid.h" -#include "CCRenderer.h" -#include "CCGroupCommand.h" -#include "CCCustomCommand.h" +#include "renderer/CCRenderer.h" +#include "renderer/CCGroupCommand.h" +#include "renderer/CCCustomCommand.h" // extern #include "kazmath/GL/matrix.h" @@ -322,7 +322,7 @@ void RenderTexture::beginWithClear(float r, float g, float b, float a, float dep this->begin(); //clear screen - _beginWithClearCommand.init(0, _vertexZ); + _beginWithClearCommand.init(_globalZOrder); _beginWithClearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this); Director::getInstance()->getRenderer()->addCommand(&_beginWithClearCommand); } @@ -340,7 +340,7 @@ void RenderTexture::clearDepth(float depthValue) this->begin(); - _clearDepthCommand.init(0, _vertexZ); + _clearDepthCommand.init(_globalZOrder); _clearDepthCommand.func = CC_CALLBACK_0(RenderTexture::onClearDepth, this); Director::getInstance()->getRenderer()->addCommand(&_clearDepthCommand); @@ -605,7 +605,7 @@ void RenderTexture::draw() begin(); //clear screen - _clearCommand.init(0, _vertexZ); + _clearCommand.init(_globalZOrder); _clearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this); Director::getInstance()->getRenderer()->addCommand(&_clearCommand); @@ -648,13 +648,13 @@ void RenderTexture::begin() (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1,1 ); kmGLMultMatrix(&orthoMatrix); - _groupCommand.init(0, _vertexZ); + _groupCommand.init(_globalZOrder); Renderer *renderer = Director::getInstance()->getRenderer(); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); - _beginCommand.init(0, _vertexZ); + _beginCommand.init(_globalZOrder); _beginCommand.func = CC_CALLBACK_0(RenderTexture::onBegin, this); Director::getInstance()->getRenderer()->addCommand(&_beginCommand); @@ -662,7 +662,7 @@ void RenderTexture::begin() void RenderTexture::end() { - _endCommand.init(0, _vertexZ); + _endCommand.init(_globalZOrder); _endCommand.func = CC_CALLBACK_0(RenderTexture::onEnd, this); Renderer *renderer = Director::getInstance()->getRenderer(); diff --git a/cocos/2d/CCShaderCache.cpp b/cocos/2d/CCShaderCache.cpp index fc06d2d985..aeca686f3a 100644 --- a/cocos/2d/CCShaderCache.cpp +++ b/cocos/2d/CCShaderCache.cpp @@ -290,7 +290,7 @@ void ShaderCache::loadDefaultShader(GLProgram *p, int type) break; case kShaderType_PositionTextureColorAlphaTest: - p->initWithVertexShaderByteArray(ccPositionTextureColor_noMVP_vert, ccPositionTextureColorAlphaTest_frag); + p->initWithVertexShaderByteArray(ccPositionTextureColor_vert, ccPositionTextureColorAlphaTest_frag); p->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION); p->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR); diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 271f1e8db9..264e29c693 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -45,9 +45,9 @@ THE SOFTWARE. #include "CCAffineTransform.h" #include "TransformUtils.h" #include "CCProfiling.h" -#include "CCRenderer.h" +#include "renderer/CCRenderer.h" #include "renderer/CCQuadCommand.h" -#include "CCFrustum.h" +#include "renderer/CCFrustum.h" // external #include "kazmath/GL/matrix.h" @@ -242,9 +242,7 @@ bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated) // zwoptex default values _offsetPosition = Point::ZERO; - - _hasChildren = false; - + // clean the Quad memset(&_quad, 0, sizeof(_quad)); @@ -672,7 +670,7 @@ void Sprite::updateTransform(void) void Sprite::draw(void) { //TODO implement z order - _quadCommand.init(0, _vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform); + _quadCommand.init(_globalZOrder, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform); // if(culling()) { @@ -767,18 +765,12 @@ void Sprite::addChild(Node *child, int zOrder, int tag) } //CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check Node::addChild(child, zOrder, tag); - _hasChildren = true; } void Sprite::reorderChild(Node *child, int zOrder) { - CCASSERT(child != nullptr, ""); - CCASSERT(_children.contains(child), ""); - - if (zOrder == child->getZOrder()) - { - return; - } + CCASSERT(child != nullptr, "child must be non null"); + CCASSERT(_children.contains(child), "child does not belong to this"); if( _batchNode && ! _reorderChildDirty) { @@ -813,8 +805,6 @@ void Sprite::removeAllChildrenWithCleanup(bool cleanup) } Node::removeAllChildrenWithCleanup(cleanup); - - _hasChildren = false; } void Sprite::sortAllChildren() @@ -832,8 +822,8 @@ void Sprite::sortAllChildren() auto tempJ = static_cast( _children->getObjectAtIndex(j) ); //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller - while(j>=0 && ( tempI->getZOrder() < tempJ->getZOrder() || - ( tempI->getZOrder() == tempJ->getZOrder() && + while(j>=0 && ( tempI->getLocalZOrder() < tempJ->getLocalZOrder() || + ( tempI->getLocalZOrder() == tempJ->getLocalZOrder() && tempI->getOrderOfArrival() < tempJ->getOrderOfArrival() ) ) ) { _children->fastSetObject( tempJ, j+1 ); @@ -882,27 +872,24 @@ void Sprite::setDirtyRecursively(bool bValue) { _recursiveDirty = bValue; setDirty(bValue); - // recursively set dirty - if (_hasChildren) - { - for(const auto &child: _children) { - Sprite* sp = dynamic_cast(child); - if (sp) - { - sp->setDirtyRecursively(true); - } + + for(const auto &child: _children) { + Sprite* sp = dynamic_cast(child); + if (sp) + { + sp->setDirtyRecursively(true); } } } // XXX HACK: optimization -#define SET_DIRTY_RECURSIVELY() { \ - if (! _recursiveDirty) { \ - _recursiveDirty = true; \ - setDirty(true); \ - if ( _hasChildren) \ - setDirtyRecursively(true); \ - } \ +#define SET_DIRTY_RECURSIVELY() { \ + if (! _recursiveDirty) { \ + _recursiveDirty = true; \ + setDirty(true); \ + if (!_children.empty()) \ + setDirtyRecursively(true); \ + } \ } void Sprite::setPosition(const Point& pos) diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index 0a937a64e1..2081ef8336 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -538,7 +538,6 @@ protected: bool _dirty; /// Whether the sprite needs to be updated bool _recursiveDirty; /// Whether all of the sprite's children needs to be updated - bool _hasChildren; /// Whether the sprite contains children bool _shouldBeHidden; /// should not be drawn because one of the ancestors is not visible kmMat4 _transformToBatch; diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 3ef2e183e9..e93b462d68 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -43,7 +43,7 @@ THE SOFTWARE. #include "CCProfiling.h" #include "CCLayer.h" #include "CCScene.h" -#include "CCRenderer.h" +#include "renderer/CCRenderer.h" #include "renderer/CCQuadCommand.h" // external #include "kazmath/GL/matrix.h" @@ -99,7 +99,7 @@ bool SpriteBatchNode::initWithTexture(Texture2D *tex, ssize_t capacity) _descendants.reserve(capacity); - setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP)); + setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); return true; } @@ -179,7 +179,7 @@ void SpriteBatchNode::reorderChild(Node *child, int zOrder) CCASSERT(child != nullptr, "the child should not be null"); CCASSERT(_children.contains(child), "Child doesn't belong to Sprite"); - if (zOrder == child->getZOrder()) + if (zOrder == child->getLocalZOrder()) { return; } @@ -277,7 +277,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, ssize_t* curIndex) { bool needNewIndex=true; - if (array.at(0)->getZOrder() >= 0) + if (array.at(0)->getLocalZOrder() >= 0) { //all children are in front of the parent oldIndex = sprite->getAtlasIndex(); @@ -294,7 +294,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, ssize_t* curIndex) for(const auto &child: array) { Sprite* sp = static_cast(child); - if (needNewIndex && sp->getZOrder() >= 0) + if (needNewIndex && sp->getLocalZOrder() >= 0) { oldIndex = sprite->getAtlasIndex(); sprite->setAtlasIndex(*curIndex); @@ -356,18 +356,13 @@ void SpriteBatchNode::draw() for(const auto &child: _children) child->updateTransform(); - kmMat4 mv; - kmGLGetMatrix(KM_GL_MODELVIEW, &mv); - - _quadCommand.init(0, - _vertexZ, - _textureAtlas->getTexture()->getName(), - _shaderProgram, - _blendFunc, - _textureAtlas->getQuads(), - _textureAtlas->getTotalQuads(), - mv); - Director::getInstance()->getRenderer()->addCommand(&_quadCommand); + _batchCommand.init( + _globalZOrder, + _shaderProgram, + _blendFunc, + _textureAtlas, + _modelViewTransform); + Director::getInstance()->getRenderer()->addCommand(&_batchCommand); } void SpriteBatchNode::increaseAtlasCapacity(void) @@ -396,7 +391,7 @@ ssize_t SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, ssize_t index) auto& children = parent->getChildren(); for(const auto &child: children) { Sprite* sp = static_cast(child); - if (sp && (sp->getZOrder() < 0)) + if (sp && (sp->getLocalZOrder() < 0)) { index = rebuildIndexInOrder(sp, index); } @@ -411,7 +406,7 @@ ssize_t SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, ssize_t index) for(const auto &child: children) { Sprite* sp = static_cast(child); - if (sp && (sp->getZOrder() >= 0)) + if (sp && (sp->getLocalZOrder() >= 0)) { index = rebuildIndexInOrder(sp, index); } @@ -492,7 +487,7 @@ ssize_t SpriteBatchNode::atlasIndexForChild(Sprite *sprite, int nZ) else { // previous & sprite belong to the same branch - if ((prev->getZOrder() < 0 && nZ < 0) || (prev->getZOrder() >= 0 && nZ >= 0)) + if ((prev->getLocalZOrder() < 0 && nZ < 0) || (prev->getLocalZOrder() >= 0 && nZ >= 0)) { return highestAtlasIndexInChild(prev) + 1; } diff --git a/cocos/2d/CCSpriteBatchNode.h b/cocos/2d/CCSpriteBatchNode.h index fc140aa391..bbb6294e6d 100644 --- a/cocos/2d/CCSpriteBatchNode.h +++ b/cocos/2d/CCSpriteBatchNode.h @@ -35,7 +35,7 @@ THE SOFTWARE. #include "CCProtocols.h" #include "CCTextureAtlas.h" #include "ccMacros.h" -#include "renderer/CCQuadCommand.h" +#include "renderer/CCBatchCommand.h" NS_CC_BEGIN @@ -189,7 +189,7 @@ protected: TextureAtlas *_textureAtlas; BlendFunc _blendFunc; - QuadCommand _quadCommand; // quad command + BatchCommand _batchCommand; // render command // all descendants: children, grand children, etc... // There is not need to retain/release these objects, since they are already retained by _children diff --git a/cocos/2d/CCSpriteFrameCache.cpp b/cocos/2d/CCSpriteFrameCache.cpp index a2b289ced6..bc89ef1b69 100644 --- a/cocos/2d/CCSpriteFrameCache.cpp +++ b/cocos/2d/CCSpriteFrameCache.cpp @@ -293,7 +293,7 @@ void SpriteFrameCache::removeUnusedSpriteFrames() for (auto iter = _spriteFrames.begin(); iter != _spriteFrames.end(); ++iter) { SpriteFrame* spriteFrame = iter->second; - if( spriteFrame->retainCount() == 1 ) + if( spriteFrame->getReferenceCount() == 1 ) { toRemoveFrames.push_back(iter->first); CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", iter->first.c_str()); diff --git a/cocos/2d/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index 33a4b77519..54fecd658b 100644 --- a/cocos/2d/CCTMXTiledMap.cpp +++ b/cocos/2d/CCTMXTiledMap.cpp @@ -174,7 +174,7 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) if (layerInfo->_visible) { TMXLayer *child = parseLayer(layerInfo, mapInfo); - addChild((Node*)child, idx, idx); + addChild(child, idx, idx); // update content size with the max size const Size& childSize = child->getContentSize(); diff --git a/cocos/2d/CCTMXXMLParser.h b/cocos/2d/CCTMXXMLParser.h index 621a197734..6d980b2c36 100644 --- a/cocos/2d/CCTMXXMLParser.h +++ b/cocos/2d/CCTMXXMLParser.h @@ -250,8 +250,9 @@ public: inline void setStoringCharacters(bool storingCharacters) { _storingCharacters = storingCharacters; }; /// properties - inline ValueMap getProperties() const { return _properties; }; - inline void setProperties(ValueMap properties) { + inline const ValueMap& getProperties() const { return _properties; } + inline ValueMap& getProperties() { return _properties; } + inline void setProperties(const ValueMap& properties) { _properties = properties; }; diff --git a/cocos/2d/CCTextFieldTTF.cpp b/cocos/2d/CCTextFieldTTF.cpp index b00a69bbdb..cb82c88be6 100644 --- a/cocos/2d/CCTextFieldTTF.cpp +++ b/cocos/2d/CCTextFieldTTF.cpp @@ -26,7 +26,7 @@ THE SOFTWARE. #include "CCTextFieldTTF.h" #include "CCDirector.h" -#include "CCEGLView.h" +#include "CCGLView.h" NS_CC_BEGIN @@ -126,7 +126,7 @@ bool TextFieldTTF::attachWithIME() if (ret) { // open keyboard - EGLView * pGlView = Director::getInstance()->getOpenGLView(); + GLView * pGlView = Director::getInstance()->getOpenGLView(); if (pGlView) { pGlView->setIMEKeyboardState(true); @@ -141,7 +141,7 @@ bool TextFieldTTF::detachWithIME() if (ret) { // close keyboard - EGLView * glView = Director::getInstance()->getOpenGLView(); + GLView * glView = Director::getInstance()->getOpenGLView(); if (glView) { glView->setIMEKeyboardState(false); diff --git a/cocos/2d/CCTextImage.cpp b/cocos/2d/CCTextImage.cpp deleted file mode 100644 index d47ab768d0..0000000000 --- a/cocos/2d/CCTextImage.cpp +++ /dev/null @@ -1,478 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 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. - ****************************************************************************/ - -#include -#include -#include -#include - -#include "cocos2d.h" -#include "CCTextImage.h" -#include "CCFontFreeType.h" -#include "CCFont.h" - -NS_CC_BEGIN - - -TextLineDef::TextLineDef(float x, float y, float width, float height) :_x(x), _y(y), _width(width), _height(height) -{ -} - -TextPageDef::TextPageDef(int pageNum, int width, int height): _pageNum(pageNum), - _width(width), - _height(height), - _pageData(0), - _pageTexture(0) -{ -} - -TextPageDef::~TextPageDef() -{ - size_t numLines = _lines.size(); - - for( size_t c = 0; crelease(); - } -} - -bool TextPageDef::generatePageTexture(bool releasePageData) -{ - if (!_pageData) - return false; - - if (_pageTexture) - { - _pageTexture->release(); - _pageTexture = 0; - } - - Size imageSize = Size((float)(_width), (float)(_height)); - if((imageSize.width <= 0) || (imageSize.height <= 0)) - return false; - - _pageTexture = new Texture2D(); - if (!_pageTexture) - return false; - - int dataLenght = (_width * _height * 1); - bool textureCreated = _pageTexture->initWithData(_pageData, dataLenght, Texture2D::PixelFormat::A8, _width, _height, imageSize); - - // release the page data if requested - if (releasePageData && textureCreated) - { - delete [] _pageData; - _pageData = 0; - } - - return textureCreated; -} - -void TextPageDef::preparePageTexture(bool releaseRAWData) -{ - generatePageTexture(releaseRAWData); -} - -Texture2D *TextPageDef::getPageTexture() -{ - if (!_pageTexture) - { - generatePageTexture(); - } - - return _pageTexture; -} - -TextFontPagesDef::TextFontPagesDef() -{ -} - -TextFontPagesDef::~TextFontPagesDef() -{ - size_t numPages = _pages.size(); - for( size_t c = 0; c < numPages; ++c ) - { - if (_pages[c]) - delete _pages[c]; - } -} - -TextImage::TextImage(): _fontPages(0), _font(0) -{ -} - -TextImage::~TextImage() -{ - if (_fontPages) - delete _fontPages; - - if (_font) - _font->release(); -} - -bool TextImage::initWithString(const char *text, int width, int height, cocos2d::Font* font, bool releaseRAWData) -{ - bool textIsUTF16 = false; - - if (_font) - { - _font->release(); - _font = 0; - } - - // carloX - _font = font; - - // generate the glyphs for the requested text (glyphs are latter's bounding boxes) - if (!generateTextGlyphs(text)) - return false; - - Size constrainSize; - unsigned short int *strUTF16 = 0; - - int stringNumChars; - if (textIsUTF16) - { - strUTF16 = (unsigned short int *)text; - stringNumChars = cc_wcslen(strUTF16); - } - else - { - // string needs to go to unicode - strUTF16 = _font->getUTF16Text(text, stringNumChars); - } - - if (!strUTF16 || !stringNumChars) - return false; - - // create all the needed pages - if (!createPageDefinitions(strUTF16, width, height, _font->getFontMaxHeight())) - return false; - - // release the original string if needed - if (!textIsUTF16) - delete [] strUTF16; - - // actually create the needed images - return createImageDataFromPages(_fontPages, releaseRAWData); - - return true; -} - -bool TextImage::createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight) -{ - bool needToReleaseText = false; - int delta = 0; - int currentPage = 0; - float currentY = 0.0; - - // - unsigned short int *strUTF16 = inText; - - if (_fontPages) - delete _fontPages; - - // create pages for the font - _fontPages = new TextFontPagesDef(); - if (!_fontPages) - return false; - - // create the first page (ther is going to be at least one page) - TextPageDef *currentPageDef = new TextPageDef(currentPage, imageWidth, imageHeight); - if (!currentPageDef) - return false; - - // add the current page - _fontPages->addPage(currentPageDef); - - // work out creating pages - - do { - - // choose texture page - if ((currentY + lineHeight) > imageHeight) - { - currentY = 0; - currentPage += 1; - - // create a new page and add - currentPageDef = new TextPageDef(currentPage, imageWidth, imageHeight); - if (!currentPageDef) - return false; - - _fontPages->addPage(currentPageDef); - } - - // get the new fitting string - Size tempSize; - tempSize.width = imageWidth; - tempSize.height = imageHeight; - - // figure out how many glyphs fit in this line - int newLineSize = 0; - int numFittingChar = getNumGlyphsFittingInSize(_textGlyphs, strUTF16, _font, &tempSize, newLineSize); - - // crete the temporary new string - unsigned short int *pTempString = 0; - pTempString = _font->trimUTF16Text(strUTF16, 0, (numFittingChar - 1)); - - // create the new line and add to the current page - TextLineDef *newLine = new TextLineDef(0.0, currentY, newLineSize, lineHeight); - if (!newLine) - return false; - - // add all the glyphs to this line - addGlyphsToLine(newLine, (const char *)pTempString, true); - - // add the line the to current page - currentPageDef->addLine(newLine); - - // can now release the string - delete [] pTempString; - - // create the new string - int stringLenght = _font->getUTF16TextLenght(strUTF16); - delta = (stringLenght - numFittingChar); - - // there is still some leftover, need to work on it - if (delta) - { - // create the new string - unsigned short int *tempS = _font->trimUTF16Text(strUTF16, numFittingChar, (stringLenght - 1)); - - if (needToReleaseText) - delete [] strUTF16; - - // a copy of the string has been created, so next time I'll need to release it - needToReleaseText = true; - - // assign pointer - strUTF16 = tempS; - } - - // go to next line - currentY += lineHeight; - - } while(delta); - - if (needToReleaseText) - delete [] strUTF16; - - return true; -} - -int TextImage::getNumGlyphsFittingInSize(std::map &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize) -{ - if (!strUTF8) - return 0; - - float widthWithBBX = 0.0f; - float lastWidth = 0.0f; - - // get the string to UTF8 - int numChar = cc_wcslen(strUTF8); - - for (int c = 0; c < numChar; ++c) - { - widthWithBBX += (glyphDefs[strUTF8[c]].getRect().size.width + glyphDefs[strUTF8[c]].getPadding()); - - if (widthWithBBX >= constrainSize->width) - { - outNewSize = lastWidth; - return c; - } - - lastWidth = widthWithBBX; - } - - outNewSize = constrainSize->width; - return numChar; -} - -bool TextImage::addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16) -{ - if (!_font) - return false; - - int numLetters = 0; - unsigned short int *UTF16string = 0; - - if (textIsUTF16) - { - UTF16string = (unsigned short int *)lineText; - numLetters = cc_wcslen(UTF16string); - } - else - { - UTF16string = _font->getUTF16Text(lineText, numLetters); - } - - for (int c = 0; c < numLetters; ++c) - { - _textGlyphs[UTF16string[c]].setCommonHeight(line->getHeight()); - line->addGlyph(_textGlyphs[UTF16string[c]] ); - } - - if(!textIsUTF16) - delete [] UTF16string; - - return true; -} - -bool TextImage::generateTextGlyphs(const char * text) -{ - if (!_font) - return false; - - int numGlyphs = 0; - GlyphDef *newGlyphs = _font->getGlyphDefintionsForText(text, numGlyphs); - - if (!newGlyphs) - return false; - - if (!_textGlyphs.empty()) - _textGlyphs.clear(); - - for (int c = 0; c < numGlyphs; ++c) - _textGlyphs[newGlyphs[c].getUTF8Letter()] = newGlyphs[c]; - - delete [] newGlyphs; - return true; -} - -bool TextImage::createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData) -{ - int numPages = thePages->getNumPages(); - if (!numPages) - return false; - - for (int c = 0; c < numPages; ++c) - { - unsigned char *pageData = 0; - pageData = preparePageGlyphData(thePages->getPageAt(c)); - - if (pageData) - { - // set the page data - thePages->getPageAt(c)->setPageData(pageData); - - // crete page texture and relase RAW data - thePages->getPageAt(c)->preparePageTexture(releaseRAWData); - } - else - { - return false; - } - } - - return true; -} - -unsigned char * TextImage::preparePageGlyphData(TextPageDef *thePage) -{ - return renderGlyphData(thePage); -} - -unsigned char * TextImage::renderGlyphData(TextPageDef *thePage) -{ - if (!thePage) - return 0; - - if (!_font) - return 0; - - if (thePage->getNumLines() == 0) - return nullptr; - - int pageWidth = thePage->getWidth(); - int pageHeight = thePage->getHeight(); - - // prepare memory and clean to 0 - int sizeInBytes = (pageWidth * pageHeight * 1); - unsigned char* data = new unsigned char[sizeInBytes]; - - if (!data) - return 0; - - memset(data, 0, sizeInBytes); - - int numLines = thePage->getNumLines(); - - for (int c = 0; c < numLines; ++c) - { - TextLineDef *currentLine = thePage->getLineAt(c); - - float origX = _font->getLetterPadding(); - float origY = currentLine->getY(); - - int numGlyphToRender = currentLine->getNumGlyph(); - - for (int cglyph = 0; cglyph < numGlyphToRender; ++cglyph) - { - GlyphDef currGlyph = currentLine->getGlyphAt(cglyph); - _font->renderCharAt(currGlyph.getUTF8Letter(), origX, origY, data, pageWidth); - origX += (currGlyph.getRect().size.width + _font->getLetterPadding()); - } - } - -#ifdef _DEBUG_FONTS_ - static int counter = 0; - char outFilename[512]; - sprintf(outFilename,"testIMG%d", counter); - ++counter; - Image *image = new Image; - image->initWithRawData(data, (pageWidth * pageWidth * 4), 1024, 1024, 8, false); - image->saveToFile(outFilename); -#endif - - // we are done here - return data; -} - -NS_CC_END - - - - - - - - - - - - diff --git a/cocos/2d/CCTextImage.h b/cocos/2d/CCTextImage.h deleted file mode 100644 index 1c0da97201..0000000000 --- a/cocos/2d/CCTextImage.h +++ /dev/null @@ -1,211 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 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. - ****************************************************************************/ - -#ifndef _TextImage_h_ -#define _TextImage_h_ - -//#include "CCFont.h" -#include - -NS_CC_BEGIN - -class Font; - -/** @brief GlyphDef defines one single glyph (character) in a text image - * - * it defines the bounding box for the glyph in the texture page, the character the padding (spacing) between characters - * - */ - -class CC_DLL GlyphDef -{ -public: - - GlyphDef() : _validGlyph(false) { /*do nothing*/ } - GlyphDef(unsigned short int letterUTF8, const Rect &rect) { _gliphRect = rect; _uTF16Letter = letterUTF8; } - - void setUTF16Letter(unsigned short int letterUTF8) { _uTF16Letter = letterUTF8; } - void setRect(const Rect & theRect) { _gliphRect = theRect; } - unsigned short int getUTF8Letter() { return _uTF16Letter; } - const Rect & getRect() const { return _gliphRect; } - void setPadding(float padding) { _padding = padding; } - float getPadding() { return _padding; } - void setCommonHeight(float commonHeight) { _commonHeight = commonHeight; } - float getCommonHeight() { return _commonHeight; } - void setValid(bool isValid) { _validGlyph = isValid; } - bool isValid() { return _validGlyph; } - -private: - - Rect _gliphRect; - unsigned short int _uTF16Letter; - float _padding; - float _commonHeight; - bool _validGlyph; - -}; - -/** @brief TextLineDef define a line of text in a text image texture page - * - * conllects all the GlyphDef for a text line plus line size and line position in text image space - * - */ -class CC_DLL TextLineDef -{ -public: - - TextLineDef(float x, float y, float width, float height); - - float getX() const { return _x; } - float getY() const { return _y; } - float getWidth() const { return _width; } - float getHeight() const { return _height; } - - void addGlyph(GlyphDef theGlyph) { _glyphs.push_back(theGlyph); } - int getNumGlyph() const { return static_cast(_glyphs.size()); } - const GlyphDef & getGlyphAt(int index) const { return _glyphs[index]; } - -private: - - float _x; - float _y; - float _width; - float _height; - std::vector _glyphs; - -}; - -/** @brief TextPageDef defines one text image page (a TextImage can have/use more than one page) - * - * collects all the TextLineDef for one page, the witdh and height of the page and the graphics (texture) for the page - * - */ -class CC_DLL TextPageDef -{ -public: - /** - * @js NA - */ - TextPageDef(int pageNum, int width, int height); - /** - * @js NA - * @lua NA - */ - ~TextPageDef(); - - void addLine(TextLineDef *theLine) { _lines.push_back(theLine); } - int getNumLines() const { return static_cast(_lines.size()); } - TextLineDef * getLineAt(int index) const { return _lines[index]; } - int getWidth() const { return _width; } - int getHeight() const { return _height; } - int getPageNumber() const { return _pageNum; } - void setPageData(unsigned char *data) { _pageData = data; } - const unsigned char * getPageData() const { return _pageData; } - Texture2D *getPageTexture(); - void preparePageTexture(bool releaseRAWData = true); - -private: - - bool generatePageTexture(bool releasePageData = false); - - int _pageNum; - int _width; - int _height; - unsigned char * _pageData; - Texture2D * _pageTexture; - std::vector _lines; - -}; - -/** @brief CCTextFontPages collection of pages (TextPageDef) - * - * A TextImage is composed by one or more text pages. This calss collects all of those pages - */ -class CC_DLL TextFontPagesDef -{ -public: - /** - * @js ctor - */ - TextFontPagesDef(); - /** - * @js NA - * @lua NA - */ - ~TextFontPagesDef(); - - void addPage(TextPageDef *newPage) { _pages.push_back(newPage); } - int getNumPages() const { return static_cast(_pages.size()); } - TextPageDef* getPageAt(int index) const { return _pages[index]; } - -private: - - std::vector _pages; - -}; - -/** @brief TextImage - * - */ -class CC_DLL TextImage -{ -public: - /** - * @js ctor - */ - TextImage(); - /** - * @js NA - * @lua NA - */ - ~TextImage(); - - bool initWithString(const char *text, int width, int height, Font* font, bool releaseRAWData = true); - - TextFontPagesDef * getPages() const { return _fontPages; } - Font * getFont() const { return _font; } - -private: - - bool createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData = true); - bool addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16 = false); - bool generateTextGlyphs(const char * text); - int getNumGlyphsFittingInSize(std::map &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize); - bool createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight); - unsigned char * preparePageGlyphData(TextPageDef *thePage); - - // glyph rendering - unsigned char * renderGlyphData(TextPageDef *thePage); - - std::map _textGlyphs; - TextFontPagesDef * _fontPages; - Font * _font; -}; - - -NS_CC_END - - -#endif diff --git a/cocos/2d/CCTexture2D.cpp b/cocos/2d/CCTexture2D.cpp index 120ffe83d5..17ec6d2e3f 100644 --- a/cocos/2d/CCTexture2D.cpp +++ b/cocos/2d/CCTexture2D.cpp @@ -544,7 +544,6 @@ bool Texture2D::initWithData(const void *data, ssize_t dataLen, Texture2D::Pixel _contentSize = contentSize; _maxS = contentSize.width / (float)(pixelsWide); _maxT = contentSize.height / (float)(pixelsHigh); - } bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, int pixelsWide, int pixelsHigh) diff --git a/cocos/2d/CCTextureAtlas.cpp b/cocos/2d/CCTextureAtlas.cpp index 8a9818d8fc..2d2787a25d 100644 --- a/cocos/2d/CCTextureAtlas.cpp +++ b/cocos/2d/CCTextureAtlas.cpp @@ -624,11 +624,11 @@ void TextureAtlas::drawNumberOfQuads(ssize_t numberOfQuads, ssize_t start) { glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); // option 1: subdata - //glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * n , &_quads[start] ); - +// glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * n , &_quads[start] ); + // option 2: data - // glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * (n-start), &quads_[start], GL_DYNAMIC_DRAW); - +// glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * (n-start), &quads_[start], GL_DYNAMIC_DRAW); + // option 3: orphaning + glMapBuffer glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * (numberOfQuads-start), nullptr, GL_DYNAMIC_DRAW); void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index c6527ba07f..aaa9ccfb4a 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -386,7 +386,7 @@ void TextureCache::removeUnusedTextures() { for( auto it=_textures.cbegin(); it!=_textures.cend(); /* nothing */) { Texture2D *tex = it->second; - if( tex->retainCount() == 1 ) { + if( tex->getReferenceCount() == 1 ) { CCLOG("cocos2d: TextureCache: removing unused texture: %s", it->first.c_str()); tex->release(); @@ -485,7 +485,7 @@ std::string TextureCache::getCachedTextureInfo() const count++; snprintf(buftmp,sizeof(buftmp)-1,"\"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB\n", it->first.c_str(), - (long)tex->retainCount(), + (long)tex->getReferenceCount(), (long)tex->getName(), (long)tex->getPixelsWide(), (long)tex->getPixelsHigh(), diff --git a/cocos/2d/CCTransitionPageTurn.cpp b/cocos/2d/CCTransitionPageTurn.cpp index 7ade9878a4..7e4102b009 100644 --- a/cocos/2d/CCTransitionPageTurn.cpp +++ b/cocos/2d/CCTransitionPageTurn.cpp @@ -98,23 +98,23 @@ void TransitionPageTurn::draw() if( _isInSceneOnTop ) { _outSceneProxy->visit(); - _enableOffsetCmd.init(0, _vertexZ); + _enableOffsetCmd.init(_globalZOrder); _enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd); _inSceneProxy->visit(); - _disableOffsetCmd.init(0, _vertexZ); + _disableOffsetCmd.init(_globalZOrder); _disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd); } else { _inSceneProxy->visit(); - _enableOffsetCmd.init(0, _vertexZ); + _enableOffsetCmd.init(_globalZOrder); _enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd); _outSceneProxy->visit(); - _disableOffsetCmd.init(0, _vertexZ); + _disableOffsetCmd.init(_globalZOrder); _disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd); } diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt index 88090ec7c5..18133edc9d 100644 --- a/cocos/2d/CMakeLists.txt +++ b/cocos/2d/CMakeLists.txt @@ -7,7 +7,7 @@ set(PLATFORM_SRC platform/win32/CCFileUtilsWin32.cpp platform/win32/CCCommon.cpp platform/win32/CCApplication.cpp - platform/win32/CCEGLView.cpp + platform/win32/CCGLView.cpp platform/win32/CCImage.cpp platform/win32/CCDevice.cpp ) @@ -21,7 +21,7 @@ set(PLATFORM_SRC platform/linux/CCFileUtilsLinux.cpp platform/linux/CCCommon.cpp platform/linux/CCApplication.cpp - platform/linux/CCEGLView.cpp + platform/desktop/CCGLView.cpp platform/linux/CCImage.cpp platform/linux/CCDevice.cpp ) @@ -67,16 +67,14 @@ set(COCOS2D_SRC CCFont.cpp CCFontAtlas.cpp CCFontAtlasCache.cpp - CCFontAtlasFactory.cpp - CCFontDefinition.cpp CCFontFNT.cpp CCFontFreeType.cpp + CCFontCharMap.cpp CCLabel.cpp CCLabelAtlas.cpp CCLabelBMFont.cpp CCLabelTTF.cpp CCLabelTextFormatter.cpp - CCTextImage.cpp CCLayer.cpp CCScene.cpp CCTransition.cpp @@ -136,7 +134,7 @@ set(COCOS2D_SRC CCDeprecated.cpp platform/CCSAXParser.cpp platform/CCThread.cpp - platform/CCEGLViewProtocol.cpp + platform/CCGLViewProtocol.cpp platform/CCFileUtils.cpp ../../external/edtaa3func/edtaa3func.cpp renderer/CCCustomCommand.cpp @@ -144,6 +142,7 @@ set(COCOS2D_SRC renderer/CCGroupCommand.cpp renderer/CCMaterialManager.cpp renderer/CCQuadCommand.cpp + renderer/CCBatchCommand.cpp renderer/CCRenderCommand.cpp renderer/CCRenderer.cpp renderer/CCRenderMaterial.cpp diff --git a/cocos/2d/ccCArray.cpp b/cocos/2d/ccCArray.cpp index 9c43756ffd..b0827eed5c 100644 --- a/cocos/2d/ccCArray.cpp +++ b/cocos/2d/ccCArray.cpp @@ -73,7 +73,7 @@ void ccArrayEnsureExtraCapacity(ccArray *arr, ssize_t extra) { while (arr->max < arr->num + extra) { - CCLOG("cocos2d: ccCArray: resizing ccArray capacity from [%d] to [%d].", + CCLOGINFO("cocos2d: ccCArray: resizing ccArray capacity from [%d] to [%d].", static_cast(arr->max), static_cast(arr->max*2)); diff --git a/cocos/2d/ccGLStateCache.cpp b/cocos/2d/ccGLStateCache.cpp index 97599289d1..d8a620f463 100644 --- a/cocos/2d/ccGLStateCache.cpp +++ b/cocos/2d/ccGLStateCache.cpp @@ -44,7 +44,6 @@ namespace static bool s_vertexAttribColor = false; static bool s_vertexAttribTexCoords = false; - #if CC_ENABLE_GL_STATE_CACHE #define kMaxActiveTexture 16 @@ -55,6 +54,8 @@ namespace static GLenum s_blendingDest = -1; static int s_GLServerState = 0; static GLuint s_VAO = 0; + static GLenum s_activeTexture = -1; + #endif // CC_ENABLE_GL_STATE_CACHE } @@ -159,7 +160,7 @@ void bindTexture2DN(GLuint textureUnit, GLuint textureId) if (s_currentBoundTexture[textureUnit] != textureId) { s_currentBoundTexture[textureUnit] = textureId; - glActiveTexture(GL_TEXTURE0 + textureUnit); + activeTexture(GL_TEXTURE0 + textureUnit); glBindTexture(GL_TEXTURE_2D, textureId); } #else @@ -186,6 +187,18 @@ void deleteTextureN(GLuint textureUnit, GLuint textureId) glDeleteTextures(1, &textureId); } +void activeTexture(GLenum texture) +{ +#if CC_ENABLE_GL_STATE_CACHE + if(s_activeTexture != texture) { + s_activeTexture = texture; + glActiveTexture(s_activeTexture); + } +#else + glActiveTexture(texture); +#endif +} + void bindVAO(GLuint vaoId) { if (Configuration::getInstance()->supportsShareableVAO()) diff --git a/cocos/2d/ccGLStateCache.h b/cocos/2d/ccGLStateCache.h index a33f8ba59d..5b8b30c254 100644 --- a/cocos/2d/ccGLStateCache.h +++ b/cocos/2d/ccGLStateCache.h @@ -44,7 +44,7 @@ namespace GL { /** vertex attrib flags */ enum { - VERTEX_ATTRIB_FLAT_NONE = 0, + VERTEX_ATTRIB_FLAG_NONE = 0, VERTEX_ATTRIB_FLAG_POSITION = 1 << 0, VERTEX_ATTRIB_FLAG_COLOR = 1 << 1, @@ -129,6 +129,12 @@ void CC_DLL deleteTexture(GLuint textureId); */ void CC_DLL deleteTextureN(GLuint textureUnit, GLuint textureId); +/** Select active texture unit. + If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glActiveTexture() directly. + @since v3.0 + */ +void CC_DLL activeTexture(GLenum texture); + /** If the vertex array is not already bound, it binds it. If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly. @since v2.0.0 diff --git a/cocos/2d/ccShader_PositionTextureColor_noMVP_vert.h b/cocos/2d/ccShader_PositionTextureColor_noMVP_vert.h index bae95bcfea..f2d39c3c10 100644 --- a/cocos/2d/ccShader_PositionTextureColor_noMVP_vert.h +++ b/cocos/2d/ccShader_PositionTextureColor_noMVP_vert.h @@ -38,7 +38,7 @@ varying vec2 v_texCoord; \n\ \n\ void main() \n\ { \n\ - gl_Position = CC_PMatrix * a_position; \n\ + gl_Position = CC_PMatrix * a_position; \n\ v_fragmentColor = a_color; \n\ v_texCoord = a_texCoord; \n\ } \n\ diff --git a/cocos/2d/ccTypes.cpp b/cocos/2d/ccTypes.cpp index b0bfefc710..11b995efd5 100644 --- a/cocos/2d/ccTypes.cpp +++ b/cocos/2d/ccTypes.cpp @@ -107,9 +107,9 @@ Color4B::Color4B(GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a) {} Color4B::Color4B(const Color3B& color) -: r(color.r * 255) -, g(color.g * 255) -, b(color.b * 255) +: r(color.r) +, g(color.g) +, b(color.b) , a(255) {} diff --git a/cocos/2d/ccUTF8.cpp b/cocos/2d/ccUTF8.cpp index 6e70a313d5..7ebf8a0e31 100644 --- a/cocos/2d/ccUTF8.cpp +++ b/cocos/2d/ccUTF8.cpp @@ -279,9 +279,9 @@ cc_utf8_get_char (const char * p) unsigned short* cc_utf8_to_utf16(const char* str_old, int length/* = -1 */, int* rUtf16Size/* = nullptr */) { - unsigned short len = cc_utf8_strlen(str_old, length); + long len = cc_utf8_strlen(str_old, length); if (rUtf16Size != nullptr) { - *rUtf16Size = len; + *rUtf16Size = static_cast(len); } unsigned short* str_new = new unsigned short[len + 1]; diff --git a/cocos/2d/cocos2d.cpp b/cocos/2d/cocos2d.cpp index 99adc6518c..648f459d6a 100644 --- a/cocos/2d/cocos2d.cpp +++ b/cocos/2d/cocos2d.cpp @@ -25,13 +25,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "cocos2d.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN const char* cocos2dVersion() { - return "3.0-beta"; + return "3.0-beta2"; } NS_CC_END diff --git a/cocos/2d/cocos2d.h b/cocos/2d/cocos2d.h index 3476f536a5..61db6419a1 100644 --- a/cocos/2d/cocos2d.h +++ b/cocos/2d/cocos2d.h @@ -154,44 +154,44 @@ THE SOFTWARE. #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) #include "platform/ios/CCApplication.h" - #include "platform/ios/CCEGLView.h" + #include "platform/ios/CCGLView.h" #include "platform/ios/CCGL.h" #include "platform/ios/CCStdC.h" #endif // CC_TARGET_PLATFORM == CC_PLATFORM_IOS #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "platform/android/CCApplication.h" - #include "platform/android/CCEGLView.h" + #include "platform/android/CCGLView.h" #include "platform/android/CCGL.h" #include "platform/android/CCStdC.h" #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID #if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) #include "platform/blackberry/CCApplication.h" - #include "platform/blackberry/CCEGLView.h" + #include "platform/blackberry/CCGLView.h" #include "platform/blackberry/CCGL.h" #include "platform/blackberry/CCStdC.h" #endif // CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) - #include "platform/win32/CCApplication.h" - #include "platform/win32/CCEGLView.h" - #include "platform/win32/CCGL.h" - #include "platform/win32/CCStdC.h" + #include "platform/win32/CCApplication.h" + #include "platform/desktop/CCGLView.h" + #include "platform/win32/CCGL.h" + #include "platform/win32/CCStdC.h" #endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) - #include "platform/mac/CCApplication.h" - #include "platform/mac/CCEGLView.h" - #include "platform/mac/CCGL.h" - #include "platform/mac/CCStdC.h" + #include "platform/mac/CCApplication.h" + #include "platform/desktop/CCGLView.h" + #include "platform/mac/CCGL.h" + #include "platform/mac/CCStdC.h" #endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC #if (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) - #include "platform/linux/CCApplication.h" - #include "platform/linux/CCEGLView.h" - #include "platform/linux/CCGL.h" - #include "platform/linux/CCStdC.h" + #include "platform/linux/CCApplication.h" + #include "platform/desktop/CCGLView.h" + #include "platform/linux/CCGL.h" + #include "platform/linux/CCStdC.h" #endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX // script_support diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index 90be6eac6d..8a158e44f0 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -247,8 +247,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - + @@ -287,7 +286,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - @@ -306,17 +304,18 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - + + - + @@ -427,8 +426,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - + @@ -442,7 +440,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - @@ -487,7 +484,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - @@ -509,18 +505,19 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - + + - + @@ -539,4 +536,4 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - \ No newline at end of file + diff --git a/cocos/2d/cocos2d.vcxproj.filters b/cocos/2d/cocos2d.vcxproj.filters index b57af69e45..29491e4794 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -112,6 +112,9 @@ {cba0f362-878c-438b-ad0f-43d287516357} + + {32373f63-2c2d-4eab-bc4a-21745ba0b3fb} + @@ -318,12 +321,6 @@ label_nodes - - label_nodes - - - label_nodes - label_nodes @@ -345,9 +342,6 @@ label_nodes - - label_nodes - platform\etc @@ -360,9 +354,6 @@ platform\win32 - - platform\win32 - platform\win32 @@ -372,7 +363,7 @@ platform\win32 - + platform @@ -598,6 +589,15 @@ renderer + + renderer + + + label_nodes + + + platform\desktop + @@ -828,12 +828,6 @@ label_nodes - - label_nodes - - - label_nodes - label_nodes @@ -849,27 +843,18 @@ label_nodes - - label_nodes - label_nodes label_nodes - - label_nodes - platform\etc platform\win32 - - platform\win32 - platform\win32 @@ -891,7 +876,7 @@ platform - + platform @@ -1207,5 +1192,14 @@ renderer + + renderer + + + label_nodes + + + platform\desktop + - \ No newline at end of file + diff --git a/cocos/2d/cocos2d_headers.props b/cocos/2d/cocos2d_headers.props index 766558aa4b..7691b6685b 100644 --- a/cocos/2d/cocos2d_headers.props +++ b/cocos/2d/cocos2d_headers.props @@ -7,7 +7,7 @@ - $(EngineRoot)cocos\2d;$(EngineRoot)cocos\2d\renderer;$(EngineRoot)cocos\gui;$(EngineRoot)cocos\base;$(EngineRoot)cocos\physics;$(EngineRoot)cocos\math\kazmath\include;$(EngineRoot)cocos\2d\platform\win32;$(EngineRoot)external\glfw3\include\win32;$(EngineRoot)external\win32-specific\gles\include\OGLES + $(EngineRoot)cocos\2d;$(EngineRoot)cocos\2d\renderer;$(EngineRoot)cocos\gui;$(EngineRoot)cocos\base;$(EngineRoot)cocos\physics;$(EngineRoot)cocos\math\kazmath\include;$(EngineRoot)cocos\2d\platform\win32;$(EngineRoot)cocos\2d\platform\desktop;$(EngineRoot)external\glfw3\include\win32;$(EngineRoot)external\win32-specific\gles\include\OGLES _VARIADIC_MAX=10;%(PreprocessorDefinitions) diff --git a/cocos/2d/cocos2dx.mk b/cocos/2d/cocos2dx.mk deleted file mode 100644 index 41ef87b631..0000000000 --- a/cocos/2d/cocos2dx.mk +++ /dev/null @@ -1,149 +0,0 @@ -################################################################################ -# -# LINUX MAKEFILE -# -# Available options are: -# - CLANG=1 : Compiles with clang instead of gcc. Clang must be in your PATH. -# - V=1 : Enables the verbose mode. -# - DEBUG=1 : Enables the debug mode, disable compiler optimizations. -# - OPENAL=1 : Uses OpenAL instead of FMOD as sound engine. -# -################################################################################ - -all: - -# Remove -Wall, because it enables -Wunused-function, and this warning exists in webp.h -# when enable c++11. I don't know why. -# GCC 4.6 is primary platform for cocos2d v.3, because it's default compiler for Android, -# Blackberry, some Linux distributions.It supports all important features of c++11, but have -# no flag "-std=c++11" (which was turned on in version 4.7). -CCFLAGS += -MMD -Wno-deprecated-declarations -fPIC -CXXFLAGS += -MMD -Wno-deprecated-declarations -fPIC -std=gnu++0x - -ifeq ($(CLANG), 1) -CC := clang -CXX := clang++ -DEFINES += -D__STRICT_ANSI__ # Allows clang 3.3 to use __float128 -else -CC = gcc -CXX = g++ -CCFLAGS += -Werror -CXXFLAGS += -Werror -endif - -ARFLAGS = cr - -DEFINES += -DLINUX -DCC_KEYBOARD_SUPPORT - -ifdef USE_BOX2D -DEFINES += -DCC_ENABLE_BOX2D_INTEGRATION=1 -else -DEFINES += -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -endif - -THIS_MAKEFILE := $(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) -ifndef COCOS_ROOT -COCOS_ROOT := $(realpath $(dir $(THIS_MAKEFILE))/../..) -endif -COCOS_SRC = $(COCOS_ROOT)/cocos/2d -OBJ_DIR ?= obj - -LIB_DIR = $(COCOS_ROOT)/lib/linux -BIN_DIR = bin - -INCLUDES += \ - -I$(COCOS_SRC)/ \ - -I$(COCOS_SRC)/../math/kazmath/include \ - -I$(COCOS_SRC)/platform/linux \ - -I$(COCOS_SRC)/../../external/jpeg/include/linux \ - -I$(COCOS_SRC)/../../external/tiff/include/linux \ - -I$(COCOS_SRC)/../../external/webp/include/linux \ - -I$(COCOS_SRC)/../../external/tinyxml2 \ - -I$(COCOS_SRC)/../../external/unzip \ - -I$(COCOS_SRC)/../../external/glfw3/include/linux \ - -I$(COCOS_SRC)/../physics \ - -I$(COCOS_SRC)/../base \ - -I$(COCOS_SRC)/../../external/chipmunk/include/chipmunk \ - -I$(COCOS_SRC)/../../external/freetype2/include/linux \ - -I$(COCOS_SRC)/../.. \ - -I$(COCOS_SRC)/../audio/include - -LBITS := $(shell getconf LONG_BIT) - -ifeq ($(DEBUG), 1) -CCFLAGS += -g3 -O0 -CXXFLAGS += -g3 -O0 -DEFINES += -D_DEBUG -DCOCOS2D_DEBUG=1 -OBJ_DIR := $(OBJ_DIR)/debug -LIB_DIR := $(LIB_DIR)/debug -BIN_DIR := $(BIN_DIR)/debug -else -CCFLAGS += -O3 -CXXFLAGS += -O3 -DEFINES += -DNDEBUG -OBJ_DIR := $(OBJ_DIR)/release -LIB_DIR := $(LIB_DIR)/release -BIN_DIR := $(BIN_DIR)/release -endif - -ifndef V -LOG_CC = @echo " CC $@"; -LOG_CXX = @echo " CXX $@"; -LOG_AR = @echo " AR $@"; -LOG_LINK = @echo " LINK $@"; -endif - -OBJECTS := $(SOURCES:.cpp=.o) -OBJECTS := $(OBJECTS:.c=.o) -OBJECTS := $(subst ../,,$(OBJECTS)) -OBJECTS := $(subst $(COCOS_ROOT)/,,$(OBJECTS)) -OBJECTS := $(addprefix $(OBJ_DIR)/, $(OBJECTS)) -DEPS = $(OBJECTS:.o=.d) -CORE_MAKEFILE_LIST := $(MAKEFILE_LIST) --include $(DEPS) - -STATICLIBS_DIR = $(COCOS_ROOT)/external -ifeq ($(LBITS),64) -POSTFIX = 64-bit -else -POSTFIX = 32-bit -endif -STATICLIBS = $(STATICLIBS_DIR)/freetype2/prebuilt/linux/$(POSTFIX)/libfreetype.a \ - $(STATICLIBS_DIR)/jpeg/prebuilt/linux/$(POSTFIX)/libjpeg.a \ - $(STATICLIBS_DIR)/tiff/prebuilt/linux/$(POSTFIX)/libtiff.a \ - $(STATICLIBS_DIR)/webp/prebuilt/linux/$(POSTFIX)/libwebp.a - -ifneq ($(OPENAL),1) -ifeq ($(LBITS),64) -FMOD_LIBDIR = $(COCOS_ROOT)/cocos/audio/third-party/fmod/lib64/api/lib -SHAREDLIBS += -lfmodex64 -else -FMOD_LIBDIR = $(COCOS_ROOT)/cocos/audio/third-party/fmod/api/lib -SHAREDLIBS += -lfmodex -endif -endif - -SHAREDLIBS += -lGLEW -lfontconfig -lpthread -lGL -lpng `pkg-config --libs glfw3` -SHAREDLIBS += -L$(FMOD_LIBDIR) -Wl,-rpath,$(abspath $(FMOD_LIBDIR)) -SHAREDLIBS += -L$(LIB_DIR) -Wl,-rpath,$(abspath $(LIB_DIR)) - -LIBS = -lrt -lz -lX11 - -clean: - rm -rf $(OBJ_DIR) - rm -f $(TARGET) core - -.PHONY: all clean - -# If the parent Makefile defines $(EXECUTABLE) then define this as the target -# and create a 'make run' rule to run the app. -ifdef EXECUTABLE -TARGET := $(BIN_DIR)/$(EXECUTABLE) - -all: $(TARGET) - -run: $(TARGET) - cd $(dir $^) && ./$(notdir $^) - -.PHONY: run -endif diff --git a/cocos/2d/platform/CCApplicationProtocol.h b/cocos/2d/platform/CCApplicationProtocol.h index 9042c649d0..016fb4b988 100644 --- a/cocos/2d/platform/CCApplicationProtocol.h +++ b/cocos/2d/platform/CCApplicationProtocol.h @@ -33,6 +33,8 @@ NS_CC_BEGIN * @{ */ +class EAGLView; + class CC_DLL ApplicationProtocol { public: diff --git a/cocos/2d/platform/CCCommon.h b/cocos/2d/platform/CCCommon.h index fa300cd4fe..fcd28b4997 100644 --- a/cocos/2d/platform/CCCommon.h +++ b/cocos/2d/platform/CCCommon.h @@ -56,6 +56,7 @@ enum class LanguageType ITALIAN, GERMAN, SPANISH, + DUTCH, RUSSIAN, KOREAN, JAPANESE, diff --git a/cocos/2d/platform/CCEGLViewProtocol.cpp b/cocos/2d/platform/CCGLViewProtocol.cpp similarity index 83% rename from cocos/2d/platform/CCEGLViewProtocol.cpp rename to cocos/2d/platform/CCGLViewProtocol.cpp index f494ddf44d..0c0a6277e6 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.cpp +++ b/cocos/2d/platform/CCGLViewProtocol.cpp @@ -23,7 +23,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCEGLViewProtocol.h" +#include "CCGLViewProtocol.h" #include "CCTouch.h" #include "CCDirector.h" #include "CCSet.h" @@ -71,24 +71,23 @@ namespace { } -EGLViewProtocol::EGLViewProtocol() -: _delegate(nullptr) -, _scaleX(1.0f) +GLViewProtocol::GLViewProtocol() +: _scaleX(1.0f) , _scaleY(1.0f) , _resolutionPolicy(ResolutionPolicy::UNKNOWN) { } -EGLViewProtocol::~EGLViewProtocol() +GLViewProtocol::~GLViewProtocol() { } -void EGLViewProtocol::pollInputEvents() +void GLViewProtocol::pollInputEvents() { } -void EGLViewProtocol::setDesignResolutionSize(float width, float height, ResolutionPolicy resolutionPolicy) +void GLViewProtocol::setDesignResolutionSize(float width, float height, ResolutionPolicy resolutionPolicy) { CCASSERT(resolutionPolicy != ResolutionPolicy::UNKNOWN, "should set resolutionPolicy"); @@ -107,17 +106,17 @@ void EGLViewProtocol::setDesignResolutionSize(float width, float height, Resolut _scaleX = _scaleY = MAX(_scaleX, _scaleY); } - if (resolutionPolicy == ResolutionPolicy::SHOW_ALL) + else if (resolutionPolicy == ResolutionPolicy::SHOW_ALL) { _scaleX = _scaleY = MIN(_scaleX, _scaleY); } - if ( resolutionPolicy == ResolutionPolicy::FIXED_HEIGHT) { + else if ( resolutionPolicy == ResolutionPolicy::FIXED_HEIGHT) { _scaleX = _scaleY; _designResolutionSize.width = ceilf(_screenSize.width/_scaleX); } - if ( resolutionPolicy == ResolutionPolicy::FIXED_WIDTH) { + else if ( resolutionPolicy == ResolutionPolicy::FIXED_WIDTH) { _scaleY = _scaleX; _designResolutionSize.height = ceilf(_screenSize.height/_scaleY); } @@ -131,27 +130,28 @@ void EGLViewProtocol::setDesignResolutionSize(float width, float height, Resolut _resolutionPolicy = resolutionPolicy; // reset director's member variables to fit visible rect - Director::getInstance()->_winSizeInPoints = getDesignResolutionSize(); - Director::getInstance()->createStatsLabel(); - Director::getInstance()->setGLDefaultValues(); + auto director = Director::getInstance(); + director->_winSizeInPoints = getDesignResolutionSize(); + director->createStatsLabel(); + director->setGLDefaultValues(); } -const Size& EGLViewProtocol::getDesignResolutionSize() const +const Size& GLViewProtocol::getDesignResolutionSize() const { return _designResolutionSize; } -const Size& EGLViewProtocol::getFrameSize() const +const Size& GLViewProtocol::getFrameSize() const { return _screenSize; } -void EGLViewProtocol::setFrameSize(float width, float height) +void GLViewProtocol::setFrameSize(float width, float height) { _designResolutionSize = _screenSize = Size(width, height); } -Size EGLViewProtocol::getVisibleSize() const +Size GLViewProtocol::getVisibleSize() const { if (_resolutionPolicy == ResolutionPolicy::NO_BORDER) { @@ -163,7 +163,7 @@ Size EGLViewProtocol::getVisibleSize() const } } -Point EGLViewProtocol::getVisibleOrigin() const +Point GLViewProtocol::getVisibleOrigin() const { if (_resolutionPolicy == ResolutionPolicy::NO_BORDER) { @@ -176,12 +176,7 @@ Point EGLViewProtocol::getVisibleOrigin() const } } -void EGLViewProtocol::setTouchDelegate(EGLTouchDelegate * delegate) -{ - _delegate = delegate; -} - -void EGLViewProtocol::setViewPortInPoints(float x , float y , float w , float h) +void GLViewProtocol::setViewPortInPoints(float x , float y , float w , float h) { glViewport((GLint)(x * _scaleX + _viewPortRect.origin.x), (GLint)(y * _scaleY + _viewPortRect.origin.y), @@ -189,7 +184,7 @@ void EGLViewProtocol::setViewPortInPoints(float x , float y , float w , float h) (GLsizei)(h * _scaleY)); } -void EGLViewProtocol::setScissorInPoints(float x , float y , float w , float h) +void GLViewProtocol::setScissorInPoints(float x , float y , float w , float h) { glScissor((GLint)(x * _scaleX + _viewPortRect.origin.x), (GLint)(y * _scaleY + _viewPortRect.origin.y), @@ -197,12 +192,12 @@ void EGLViewProtocol::setScissorInPoints(float x , float y , float w , float h) (GLsizei)(h * _scaleY)); } -bool EGLViewProtocol::isScissorEnabled() +bool GLViewProtocol::isScissorEnabled() { return (GL_FALSE == glIsEnabled(GL_SCISSOR_TEST)) ? false : true; } -Rect EGLViewProtocol::getScissorRect() const +Rect GLViewProtocol::getScissorRect() const { GLfloat params[4]; glGetFloatv(GL_SCISSOR_BOX, params); @@ -213,17 +208,17 @@ Rect EGLViewProtocol::getScissorRect() const return Rect(x, y, w, h); } -void EGLViewProtocol::setViewName(const std::string& viewname ) +void GLViewProtocol::setViewName(const std::string& viewname ) { _viewName = viewname; } -const std::string& EGLViewProtocol::getViewName() const +const std::string& GLViewProtocol::getViewName() const { return _viewName; } -void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float ys[]) +void GLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float ys[]) { int id = 0; float x = 0.0f; @@ -273,7 +268,7 @@ void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float y dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[]) +void GLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[]) { int id = 0; float x = 0.0f; @@ -321,7 +316,7 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys dispatcher->dispatchEvent(&touchEvent); } -void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]) +void GLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]) { int id = 0; float x = 0.0f; @@ -381,27 +376,27 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode } } -void EGLViewProtocol::handleTouchesEnd(int num, int ids[], float xs[], float ys[]) +void GLViewProtocol::handleTouchesEnd(int num, int ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::ENDED, num, ids, xs, ys); } -void EGLViewProtocol::handleTouchesCancel(int num, int ids[], float xs[], float ys[]) +void GLViewProtocol::handleTouchesCancel(int num, int ids[], float xs[], float ys[]) { handleTouchesOfEndOrCancel(EventTouch::EventCode::CANCELLED, num, ids, xs, ys); } -const Rect& EGLViewProtocol::getViewPortRect() const +const Rect& GLViewProtocol::getViewPortRect() const { return _viewPortRect; } -float EGLViewProtocol::getScaleX() const +float GLViewProtocol::getScaleX() const { return _scaleX; } -float EGLViewProtocol::getScaleY() const +float GLViewProtocol::getScaleY() const { return _scaleY; } diff --git a/cocos/2d/platform/CCEGLViewProtocol.h b/cocos/2d/platform/CCGLViewProtocol.h similarity index 92% rename from cocos/2d/platform/CCEGLViewProtocol.h rename to cocos/2d/platform/CCGLViewProtocol.h index 45bea52eed..63ab1fa27a 100644 --- a/cocos/2d/platform/CCEGLViewProtocol.h +++ b/cocos/2d/platform/CCGLViewProtocol.h @@ -23,8 +23,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#ifndef __CCEGLVIEWPROTOCOL_H__ -#define __CCEGLVIEWPROTOCOL_H__ +#ifndef __CCGLVIEWPROTOCOL_H__ +#define __CCGLVIEWPROTOCOL_H__ #include "ccTypes.h" #include "CCEventTouch.h" @@ -65,30 +65,30 @@ class EGLTouchDelegate; * @{ */ -class CC_DLL EGLViewProtocol +class CC_DLL GLViewProtocol { public: /** * @js ctor */ - EGLViewProtocol(); + GLViewProtocol(); /** * @js NA * @lua NA */ - virtual ~EGLViewProtocol(); + virtual ~GLViewProtocol(); /** Force destroying EGL view, subclass must implement this method. */ - virtual void end() = 0; + virtual void end() = 0; /** Get whether opengl render system is ready, subclass must implement this method. */ - virtual bool isOpenGLReady() = 0; + virtual bool isOpenGLReady() = 0; /** Exchanges the front and back buffers, subclass must implement this method. */ - virtual void swapBuffers() = 0; + virtual void swapBuffers() = 0; /** Open or close IME keyboard , subclass must implement this method. */ - virtual void setIMEKeyboardState(bool open) = 0; + virtual void setIMEKeyboardState(bool open) = 0; /** * Polls input events. Subclass must implement methods if platform @@ -133,9 +133,6 @@ public: */ virtual const Size& getDesignResolutionSize() const; - /** Set touch delegate */ - virtual void setTouchDelegate(EGLTouchDelegate * delegate); - /** * Set opengl view port rectangle with points. */ @@ -184,8 +181,6 @@ public: protected: void handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]); - EGLTouchDelegate* _delegate; - // real screen size Size _screenSize; // resolution size, it is the size appropriate for the app resources. @@ -195,8 +190,8 @@ protected: // the view name std::string _viewName; - float _scaleX; - float _scaleY; + float _scaleX; + float _scaleY; ResolutionPolicy _resolutionPolicy; }; @@ -205,4 +200,4 @@ protected: NS_CC_END -#endif /* __CCEGLVIEWPROTOCOL_H__ */ +#endif /* __CCGLVIEWPROTOCOL_H__ */ diff --git a/cocos/2d/platform/android/Android.mk b/cocos/2d/platform/android/Android.mk index db9bec71b9..3d27ede872 100644 --- a/cocos/2d/platform/android/Android.mk +++ b/cocos/2d/platform/android/Android.mk @@ -10,7 +10,7 @@ LOCAL_SRC_FILES := \ CCApplication.cpp \ CCCommon.cpp \ CCDevice.cpp \ -CCEGLView.cpp \ +CCGLView.cpp \ CCFileUtilsAndroid.cpp \ CCImage.cpp \ nativeactivity.cpp \ diff --git a/cocos/2d/platform/android/CCApplication.cpp b/cocos/2d/platform/android/CCApplication.cpp index 3c5b3191b3..65990b7c08 100644 --- a/cocos/2d/platform/android/CCApplication.cpp +++ b/cocos/2d/platform/android/CCApplication.cpp @@ -22,11 +22,15 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #include "jni/JniHelper.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" #include "CCApplication.h" #include "CCDirector.h" -#include "CCEGLView.h" +#include "CCGLView.h" #include #include #include @@ -116,6 +120,10 @@ LanguageType Application::getCurrentLanguage() { ret = LanguageType::RUSSIAN; } + else if (0 == strcmp("nl", pLanguageName)) + { + ret = LanguageType::DUTCH; + } else if (0 == strcmp("ko", pLanguageName)) { ret = LanguageType::KOREAN; @@ -157,3 +165,6 @@ void Application::applicationScreenSizeChanged(int newWidth, int newHeight) { } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + diff --git a/cocos/2d/platform/android/CCApplication.h b/cocos/2d/platform/android/CCApplication.h index d3054c29d8..c3d3ce1a5d 100644 --- a/cocos/2d/platform/android/CCApplication.h +++ b/cocos/2d/platform/android/CCApplication.h @@ -22,9 +22,13 @@ 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 __CC_APPLICATION_ANDROID_H__ #define __CC_APPLICATION_ANDROID_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #include "platform/CCCommon.h" #include "platform/CCApplicationProtocol.h" @@ -87,4 +91,6 @@ protected: NS_CC_END -#endif // __CC_APPLICATION_ANDROID_H__ +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + +#endif // __CC_APPLICATION_ANDROID_H__ diff --git a/cocos/2d/platform/android/CCCommon.cpp b/cocos/2d/platform/android/CCCommon.cpp index b48aff2e5c..5a0b77605a 100644 --- a/cocos/2d/platform/android/CCCommon.cpp +++ b/cocos/2d/platform/android/CCCommon.cpp @@ -23,6 +23,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #include "platform/CCCommon.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" #include @@ -44,3 +47,6 @@ void LuaLog(const char * pszFormat) } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + diff --git a/cocos/2d/platform/android/CCDevice.cpp b/cocos/2d/platform/android/CCDevice.cpp index 41c4aa1e9d..74ea1cd858 100644 --- a/cocos/2d/platform/android/CCDevice.cpp +++ b/cocos/2d/platform/android/CCDevice.cpp @@ -22,6 +22,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #include "platform/CCDevice.h" #include "jni/DPIJni.h" #include "nativeactivity.h" @@ -56,3 +60,6 @@ void Device::setAccelerometerInterval(float interval) } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + diff --git a/cocos/2d/platform/android/CCFileUtilsAndroid.cpp b/cocos/2d/platform/android/CCFileUtilsAndroid.cpp index 45f4876323..fe08de5e89 100644 --- a/cocos/2d/platform/android/CCFileUtilsAndroid.cpp +++ b/cocos/2d/platform/android/CCFileUtilsAndroid.cpp @@ -22,6 +22,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #include "CCFileUtilsAndroid.h" #include "platform/CCCommon.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" @@ -353,3 +357,5 @@ string FileUtilsAndroid::getWritablePath() const } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID diff --git a/cocos/2d/platform/android/CCFileUtilsAndroid.h b/cocos/2d/platform/android/CCFileUtilsAndroid.h index 2def6e2566..a5c990f47e 100644 --- a/cocos/2d/platform/android/CCFileUtilsAndroid.h +++ b/cocos/2d/platform/android/CCFileUtilsAndroid.h @@ -25,6 +25,9 @@ Copyright (c) 2013-2014 Chukong Technologies Inc. #ifndef __CC_FILEUTILS_ANDROID_H__ #define __CC_FILEUTILS_ANDROID_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #include "platform/CCFileUtils.h" #include "CCPlatformMacros.h" #include "ccTypes.h" @@ -86,4 +89,6 @@ private: NS_CC_END -#endif // __CC_FILEUTILS_ANDROID_H__ +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + +#endif // __CC_FILEUTILS_ANDROID_H__ diff --git a/cocos/2d/platform/android/CCGL.h b/cocos/2d/platform/android/CCGL.h index 6c9a2468e0..c1c0f0a6d7 100644 --- a/cocos/2d/platform/android/CCGL.h +++ b/cocos/2d/platform/android/CCGL.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef __CCGL_H__ #define __CCGL_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #define glClearDepth glClearDepthf #define glDeleteVertexArrays glDeleteVertexArraysOES #define glGenVertexArrays glGenVertexArraysOES @@ -63,4 +66,6 @@ extern PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArraysOESEXT; #define glDeleteVertexArraysOES glDeleteVertexArraysOESEXT +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #endif // __CCGL_H__ diff --git a/cocos/2d/platform/android/CCEGLView.cpp b/cocos/2d/platform/android/CCGLView.cpp similarity index 65% rename from cocos/2d/platform/android/CCEGLView.cpp rename to cocos/2d/platform/android/CCGLView.cpp index e7da477e4e..2f826d6782 100644 --- a/cocos/2d/platform/android/CCEGLView.cpp +++ b/cocos/2d/platform/android/CCGLView.cpp @@ -22,7 +22,11 @@ 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 "CCEGLView.h" + +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + +#include "CCGLView.h" #include "CCSet.h" #include "CCDirector.h" #include "ccMacros.h" @@ -48,46 +52,79 @@ void initExtensions() { NS_CC_BEGIN -EGLView::EGLView() +GLView* GLView::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor) +{ + auto ret = new GLView; + if(ret && ret->initWithRect(viewName, rect, frameZoomFactor)) { + ret->autorelease(); + return ret; + } + + return nullptr; +} + +GLView* GLView::create(const std::string& viewName) +{ + auto ret = new GLView; + if(ret && ret->initWithFullScreen(viewName)) { + ret->autorelease(); + return ret; + } + + return nullptr; +} + +GLView* GLView::createWithFullScreen(const std::string& viewName) +{ + auto ret = new GLView(); + if(ret && ret->initWithFullScreen(viewName)) { + ret->autorelease(); + return ret; + } + + return nullptr; +} + +GLView::GLView() { initExtensions(); } -EGLView::~EGLView() +GLView::~GLView() { } -bool EGLView::isOpenGLReady() +bool GLView::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor) +{ + return true; +} + +bool GLView::initWithFullScreen(const std::string& viewName) +{ + return true; +} + + +bool GLView::isOpenGLReady() { return (_screenSize.width != 0 && _screenSize.height != 0); } -void EGLView::end() +void GLView::end() { terminateProcessJNI(); } -void EGLView::swapBuffers() +void GLView::swapBuffers() { } -EGLView* EGLView::getInstance() -{ - static EGLView instance; - return &instance; -} - -// XXX: deprecated -EGLView* EGLView::sharedOpenGLView() -{ - return EGLView::getInstance(); -} - -void EGLView::setIMEKeyboardState(bool bOpen) +void GLView::setIMEKeyboardState(bool bOpen) { setKeyboardStateJNI((int)bOpen); } NS_CC_END +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID diff --git a/cocos/2d/platform/android/CCEGLView.h b/cocos/2d/platform/android/CCGLView.h similarity index 64% rename from cocos/2d/platform/android/CCEGLView.h rename to cocos/2d/platform/android/CCGLView.h index dabb0a968d..ec83059d0d 100644 --- a/cocos/2d/platform/android/CCEGLView.h +++ b/cocos/2d/platform/android/CCGLView.h @@ -26,41 +26,40 @@ THE SOFTWARE. #ifndef __CC_EGLVIEW_ANDROID_H__ #define __CC_EGLVIEW_ANDROID_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + +#include "CCObject.h" #include "CCGeometry.h" -#include "platform/CCEGLViewProtocol.h" +#include "platform/CCGLViewProtocol.h" NS_CC_BEGIN -class CC_DLL EGLView : public EGLViewProtocol +class CC_DLL GLView : public Object, public GLViewProtocol { public: - /** - * @js ctor - */ - EGLView(); - /** - * @js NA - * @lua NA - */ - virtual ~EGLView(); - bool isOpenGLReady(); - - // keep compatible - void end(); - void swapBuffers(); - void setIMEKeyboardState(bool bOpen); - // static function - /** - @brief get the shared main open gl window - */ - static EGLView* getInstance(); + static GLView* create(const std::string &viewname); + static GLView* createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor = 1.0f); + static GLView* createWithFullScreen(const std::string& viewName); - /** @deprecated Use getInstance() instead */ - CC_DEPRECATED_ATTRIBUTE static EGLView* sharedOpenGLView(); + bool isOpenGLReady() override; + void end() override; + void swapBuffers() override; + void setIMEKeyboardState(bool bOpen) override; + +protected: + GLView(); + virtual ~GLView(); + + bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor); + bool initWithFullScreen(const std::string& viewName); }; NS_CC_END +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #endif // end of __CC_EGLVIEW_ANDROID_H__ + diff --git a/cocos/2d/platform/android/CCImage.cpp b/cocos/2d/platform/android/CCImage.cpp index 60ce678cd4..213ed4d6ee 100644 --- a/cocos/2d/platform/android/CCImage.cpp +++ b/cocos/2d/platform/android/CCImage.cpp @@ -23,7 +23,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -//#define COCOS2D_DEBUG 1 +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID #define __CC_PLATFORM_IMAGE_CPP__ #include "platform/CCImageCommon_cpp.h" @@ -246,3 +247,5 @@ extern "C" env->GetByteArrayRegion(pixels, 0, size, (jbyte*)bitmapDC._data); } }; + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID diff --git a/cocos/2d/platform/android/CCPlatformDefine.h b/cocos/2d/platform/android/CCPlatformDefine.h index 8d146ebc14..dccf9c758f 100644 --- a/cocos/2d/platform/android/CCPlatformDefine.h +++ b/cocos/2d/platform/android/CCPlatformDefine.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef __CCPLATFORMDEFINE_H__ #define __CCPLATFORMDEFINE_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #include "android/log.h" #define CC_DLL @@ -59,4 +62,6 @@ THE SOFTWARE. #endif #endif +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #endif /* __CCPLATFORMDEFINE_H__*/ diff --git a/cocos/2d/platform/android/CCStdC.h b/cocos/2d/platform/android/CCStdC.h index 804abebceb..464249852a 100644 --- a/cocos/2d/platform/android/CCStdC.h +++ b/cocos/2d/platform/android/CCStdC.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef __CC_STD_C_H__ #define __CC_STD_C_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #include "CCPlatformMacros.h" #include #include @@ -45,4 +48,6 @@ THE SOFTWARE. #define MAX(x,y) (((x) < (y)) ? (y) : (x)) #endif // MAX +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #endif // __CC_STD_C_H__ diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java index e1566df16d..f1e7afb0ed 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java @@ -89,38 +89,43 @@ public class Cocos2dxHelper { jobs.add(r); } + private static boolean sInited = false; public static void init(final Activity activity) { - final ApplicationInfo applicationInfo = activity.getApplicationInfo(); - - initListener(); - - try { - // Get the lib_name from AndroidManifest.xml metadata - ActivityInfo ai = - activity.getPackageManager().getActivityInfo(activity.getIntent().getComponent(), PackageManager.GET_META_DATA); - if (null != ai.metaData) { - String lib_name = ai.metaData.getString(META_DATA_LIB_NAME); - if (null != lib_name) { - System.loadLibrary(lib_name); - } else { - System.loadLibrary(DEFAULT_LIB_NAME); + if (!sInited) { + final ApplicationInfo applicationInfo = activity.getApplicationInfo(); + + initListener(); + + try { + // Get the lib_name from AndroidManifest.xml metadata + ActivityInfo ai = + activity.getPackageManager().getActivityInfo(activity.getIntent().getComponent(), PackageManager.GET_META_DATA); + if (null != ai.metaData) { + String lib_name = ai.metaData.getString(META_DATA_LIB_NAME); + if (null != lib_name) { + System.loadLibrary(lib_name); + } else { + System.loadLibrary(DEFAULT_LIB_NAME); + } } + } catch (PackageManager.NameNotFoundException e) { + throw new RuntimeException("Error getting activity info", e); } - } catch (PackageManager.NameNotFoundException e) { - throw new RuntimeException("Error getting activity info", e); - } + + Cocos2dxHelper.sPackageName = applicationInfo.packageName; + Cocos2dxHelper.sFileDirectory = activity.getFilesDir().getAbsolutePath(); + //Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir); + + Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(activity); + Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(activity); + Cocos2dxHelper.sAssetManager = activity.getAssets(); + + //Cocos2dxHelper.nativeSetAssetManager(sAssetManager); + Cocos2dxBitmap.setContext(activity); + sActivity = activity; - Cocos2dxHelper.sPackageName = applicationInfo.packageName; - Cocos2dxHelper.sFileDirectory = activity.getFilesDir().getAbsolutePath(); - //Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir); - - Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(activity); - Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(activity); - Cocos2dxHelper.sAssetManager = activity.getAssets(); - - //Cocos2dxHelper.nativeSetAssetManager(sAssetManager); - Cocos2dxBitmap.setContext(activity); - sActivity = activity; + sInited = true; + } } public static void initListener() { diff --git a/cocos/2d/platform/android/nativeactivity.cpp b/cocos/2d/platform/android/nativeactivity.cpp index 0e68cf0eb4..9666effc0e 100644 --- a/cocos/2d/platform/android/nativeactivity.cpp +++ b/cocos/2d/platform/android/nativeactivity.cpp @@ -21,6 +21,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #include "nativeactivity.h" #include @@ -43,7 +47,7 @@ THE SOFTWARE. #include "CCFileUtilsAndroid.h" #include "jni/JniHelper.h" -#include "CCEGLView.h" +#include "CCGLView.h" #include "CCDrawingPrimitives.h" #include "CCShaderCache.h" #include "CCTextureCache.h" @@ -111,29 +115,27 @@ extern EditTextCallback s_pfEditTextCallback; extern void* s_ctx; extern "C" { - JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv * env, jobject obj, jbyteArray text) { - jsize size = env->GetArrayLength(text); - pthread_mutex_lock(&(engine.app->mutex)); - if (size > 0) { - + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv * env, jobject obj, jbyteArray text) { + jsize size = env->GetArrayLength(text); + pthread_mutex_lock(&(engine.app->mutex)); + if (size > 0) { + jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0); + char* pBuf = (char*)malloc(size+1); + if (pBuf != NULL) { + memcpy(pBuf, data, size); + pBuf[size] = '\0'; + editboxText = pBuf; + } + env->ReleaseByteArrayElements(text, data, 0); - jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0); - char* pBuf = (char*)malloc(size+1); - if (pBuf != NULL) { - memcpy(pBuf, data, size); - pBuf[size] = '\0'; - editboxText = pBuf; - } - env->ReleaseByteArrayElements(text, data, 0); - - } else { - char* pBuf = (char*)malloc(1); - pBuf[0] = '\0'; - editboxText = pBuf; - } - pthread_cond_broadcast(&engine.app->cond); - pthread_mutex_unlock(&(engine.app->mutex)); - } + } else { + char* pBuf = (char*)malloc(1); + pBuf[0] = '\0'; + editboxText = pBuf; + } + pthread_cond_broadcast(&engine.app->cond); + pthread_mutex_unlock(&(engine.app->mutex)); + } } typedef struct cocos_dimensions { @@ -141,17 +143,21 @@ typedef struct cocos_dimensions { int h; } cocos_dimensions; -static void cocos_init(cocos_dimensions d, struct android_app* app) { +static void cocos_init(cocos_dimensions d, struct android_app* app) +{ LOGI("cocos_init(...)"); pthread_t thisthread = pthread_self(); LOGI("pthread_self() = %X", thisthread); cocos2d::FileUtilsAndroid::setassetmanager(app->activity->assetManager); - if (!cocos2d::Director::getInstance()->getOpenGLView()) + auto director = cocos2d::Director::getInstance(); + auto glview = director->getOpenGLView(); + if (!glview) { - cocos2d::EGLView *view = cocos2d::EGLView::getInstance(); - view->setFrameSize(d.w, d.h); + glview = cocos2d::GLView::create("Android app"); + glview->setFrameSize(d.w, d.h); + director->setOpenGLView(glview); cocos_android_app_init(app); @@ -163,16 +169,18 @@ static void cocos_init(cocos_dimensions d, struct android_app* app) { cocos2d::ShaderCache::getInstance()->reloadDefaultShaders(); cocos2d::DrawPrimitives::init(); cocos2d::VolatileTextureMgr::reloadAllTextures(); + cocos2d::EventCustom foregroundEvent(EVENT_COME_TO_FOREGROUND); - cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&foregroundEvent); - cocos2d::Director::getInstance()->setGLDefaultValues(); + director->getEventDispatcher()->dispatchEvent(&foregroundEvent); + director->setGLDefaultValues(); } } /** * Initialize an EGL context for the current display. */ -static cocos_dimensions engine_init_display(struct engine* engine) { +static cocos_dimensions engine_init_display(struct engine* engine) +{ cocos_dimensions r; r.w = -1; r.h = -1; @@ -245,6 +253,7 @@ static cocos_dimensions engine_init_display(struct engine* engine) { r.w = w; r.h = h; + return r; } @@ -275,7 +284,8 @@ static void dispatch_pending_runnables() { /** * Just the current frame in the display. */ -static void engine_draw_frame(struct engine* engine) { +static void engine_draw_frame(struct engine* engine) +{ LOG_RENDER_DEBUG("engine_draw_frame(...)"); pthread_t thisthread = pthread_self(); LOG_RENDER_DEBUG("pthread_self() = %X", thisthread); @@ -293,14 +303,14 @@ static void engine_draw_frame(struct engine* engine) { /* // Just fill the screen with a color. */ /* glClearColor(((float)engine->state.x)/engine->width, engine->state.angle, */ /* ((float)engine->state.y)/engine->height, 1); */ - /* glClear(GL_COLOR_BUFFER_BIT); */ - - if (s_pfEditTextCallback && editboxText) - { - s_pfEditTextCallback(editboxText, s_ctx); - free(editboxText); - editboxText = NULL; - } + /* glClear(GL_COLOR_BUFFER_BIT); */ + + if (s_pfEditTextCallback && editboxText) + { + s_pfEditTextCallback(editboxText, s_ctx); + free(editboxText); + editboxText = NULL; + } eglSwapBuffers(engine->display, engine->surface); } @@ -308,7 +318,8 @@ static void engine_draw_frame(struct engine* engine) { /** * Tear down the EGL context currently associated with the display. */ -static void engine_term_display(struct engine* engine) { +static void engine_term_display(struct engine* engine) +{ if (engine->display != EGL_NO_DISPLAY) { eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (engine->context != EGL_NO_CONTEXT) { @@ -390,7 +401,7 @@ static int32_t handle_touch_input(AInputEvent *event) { int ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys); return 1; } break; @@ -435,7 +446,7 @@ static int32_t handle_touch_input(AInputEvent *event) { int ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys); + cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys); return 1; } break; @@ -458,7 +469,7 @@ static int32_t handle_key_input(AInputEvent *event) switch (AKeyEvent_getKeyCode(event)) { - case AKEYCODE_BACK: + case AKEYCODE_BACK: { cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE, false); dispatcher->dispatchEvent(&event); @@ -494,8 +505,8 @@ static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) return handle_touch_input(event); } - else - return handle_key_input(event); + else + return handle_key_input(event); return 0; } @@ -533,7 +544,8 @@ void setAccelerometerIntervalJni(float interval) { /** * Process the next main command. */ -static void engine_handle_cmd(struct android_app* app, int32_t cmd) { +static void engine_handle_cmd(struct android_app* app, int32_t cmd) +{ struct engine* engine = (struct engine*)app->userData; switch (cmd) { case APP_CMD_SAVE_STATE: @@ -576,7 +588,7 @@ static void engine_handle_cmd(struct android_app* app, int32_t cmd) { case APP_CMD_GAINED_FOCUS: if (cocos2d::Director::getInstance()->getOpenGLView()) { cocos2d::Application::getInstance()->applicationWillEnterForeground(); - engine->animating = 1; + engine->animating = 1; } break; @@ -594,14 +606,14 @@ static void engine_handle_cmd(struct android_app* app, int32_t cmd) { } static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) { - timeRectChanged = std::chrono::steady_clock::now(); - isContentRectChanged = true; + timeRectChanged = std::chrono::steady_clock::now(); + isContentRectChanged = true; } -static void process_input(struct android_app* app, struct android_poll_source* source) { +static void process_input(struct android_app* app, struct android_poll_source* source) +{ AInputEvent* event = NULL; - int processed = 0; - while (AInputQueue_hasEvents( app->inputQueue ) && AInputQueue_getEvent(app->inputQueue, &event) >= 0) { + while (AInputQueue_getEvent(app->inputQueue, &event) >= 0) { LOGV("New input event: type=%d\n", AInputEvent_getType(event)); if (AInputQueue_preDispatchEvent(app->inputQueue, event)) { continue; @@ -609,10 +621,6 @@ static void process_input(struct android_app* app, struct android_poll_source* s int32_t handled = 0; if (app->onInputEvent != NULL) handled = app->onInputEvent(app, event); AInputQueue_finishEvent(app->inputQueue, event, handled); - processed = 1; - } - if (processed == 0) { - LOGE("Failure reading next input event: %s\n", strerror(errno)); } } /** @@ -644,8 +652,8 @@ void android_main(struct android_app* state) { engine.state = *(struct saved_state*)state->savedState; } - // Screen size change support - state->activity->callbacks->onContentRectChanged = onContentRectChanged; + // Screen size change support + state->activity->callbacks->onContentRectChanged = onContentRectChanged; // loop waiting for stuff to do. @@ -735,19 +743,21 @@ void android_main(struct android_app* state) { LOG_RENDER_DEBUG("android_main : !engine.animating"); } - // Check if screen size changed - if (isContentRectChanged) { - std::chrono::duration duration( - std::chrono::duration_cast>(std::chrono::steady_clock::now() - timeRectChanged)); + // Check if screen size changed + if (isContentRectChanged) { + std::chrono::duration duration( + std::chrono::duration_cast>(std::chrono::steady_clock::now() - timeRectChanged)); - // Wait about 30 ms to get new width and height. Without waiting we can get old values sometime - if (duration.count() > 30) { - isContentRectChanged = false; + // Wait about 30 ms to get new width and height. Without waiting we can get old values sometime + if (duration.count() > 30) { + isContentRectChanged = false; - int32_t newWidth = ANativeWindow_getWidth(engine.app->window); - int32_t newHeight = ANativeWindow_getHeight(engine.app->window); - cocos2d::Application::getInstance()->applicationScreenSizeChanged(newWidth, newHeight); - } - } + int32_t newWidth = ANativeWindow_getWidth(engine.app->window); + int32_t newHeight = ANativeWindow_getHeight(engine.app->window); + cocos2d::Application::getInstance()->applicationScreenSizeChanged(newWidth, newHeight); + } + } } } + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID diff --git a/cocos/2d/platform/android/nativeactivity.h b/cocos/2d/platform/android/nativeactivity.h index bc7517f3cb..ccd03cb149 100644 --- a/cocos/2d/platform/android/nativeactivity.h +++ b/cocos/2d/platform/android/nativeactivity.h @@ -24,6 +24,9 @@ THE SOFTWARE. #ifndef __COCOSNATIVEACTIVITY_H__ #define __COCOSNATIVEACTIVITY_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + /** * This is the interface to the Android native activity */ @@ -32,4 +35,6 @@ void enableAccelerometerJni(void); void disableAccelerometerJni(void); void setAccelerometerIntervalJni(float interval); +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + #endif // __COCOSNATIVEACTIVITY_H__ diff --git a/cocos/2d/platform/win32/CCEGLView.cpp b/cocos/2d/platform/desktop/CCGLView.cpp similarity index 72% rename from cocos/2d/platform/win32/CCEGLView.cpp rename to cocos/2d/platform/desktop/CCGLView.cpp index b6a7c5e62b..5c3370a828 100644 --- a/cocos/2d/platform/win32/CCEGLView.cpp +++ b/cocos/2d/platform/desktop/CCGLView.cpp @@ -23,16 +23,17 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "CCEGLView.h" -#include "CCSet.h" -#include "ccMacros.h" +#include "CCGLView.h" + +#include + #include "CCDirector.h" -#include "CCIMEDispatcher.h" -#include "CCApplication.h" +#include "CCSet.h" #include "CCTouch.h" #include "CCEventDispatcher.h" #include "CCEventKeyboard.h" #include "CCEventMouse.h" +#include "CCIMEDispatcher.h" NS_CC_BEGIN @@ -42,14 +43,13 @@ struct keyCodeItem EventKeyboard::KeyCode keyCode; }; -static std::map g_keyCodeMap; +static std::unordered_map g_keyCodeMap; static keyCodeItem g_keyCodeStructArray[] = { /* The unknown key */ { GLFW_KEY_UNKNOWN , EventKeyboard::KeyCode::KEY_NONE }, /* Printable keys */ - { GLFW_KEY_SPACE , EventKeyboard::KeyCode::KEY_SPACE }, { GLFW_KEY_APOSTROPHE , EventKeyboard::KeyCode::KEY_APOSTROPHE }, { GLFW_KEY_COMMA , EventKeyboard::KeyCode::KEY_COMMA }, @@ -175,37 +175,363 @@ static keyCodeItem g_keyCodeStructArray[] = { { GLFW_KEY_LAST , EventKeyboard::KeyCode::KEY_NONE } }; -#if(_MSC_VER >= 1600) // Visual Studio 2010 or higher version. -// Windows Touch define -#define MOUSEEVENTF_FROMTOUCH 0xFF515700 -// Windows Touch functions -// Workaround to be able tu run app on Windows XP -typedef WINUSERAPI BOOL (WINAPI *RegisterTouchWindowFn)(_In_ HWND hwnd, _In_ ULONG ulFlags); -typedef WINUSERAPI BOOL (WINAPI *UnregisterTouchWindowFn)(_In_ HWND hwnd); -typedef WINUSERAPI LPARAM (WINAPI *GetMessageExtraInfoFn)(VOID); -typedef WINUSERAPI BOOL (WINAPI *GetTouchInputInfoFn)(_In_ HTOUCHINPUT hTouchInput, _In_ UINT cInputs, __out_ecount(cInputs) PTOUCHINPUT pInputs, _In_ int cbSize); -typedef WINUSERAPI BOOL (WINAPI *CloseTouchInputHandleFn)(_In_ HTOUCHINPUT hTouchInput); - -static RegisterTouchWindowFn s_pfRegisterTouchWindowFunction = NULL; -static UnregisterTouchWindowFn s_pfUnregisterTouchWindowFunction = NULL; -static GetMessageExtraInfoFn s_pfGetMessageExtraInfoFunction = NULL; -static GetTouchInputInfoFn s_pfGetTouchInputInfoFunction = NULL; -static CloseTouchInputHandleFn s_pfCloseTouchInputHandleFunction = NULL; - -static bool CheckTouchSupport() +//begin GLViewEventHandler +class GLViewEventHandler { - s_pfRegisterTouchWindowFunction = (RegisterTouchWindowFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "RegisterTouchWindow"); - s_pfUnregisterTouchWindowFunction = (UnregisterTouchWindowFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "UnregisterTouchWindow"); - s_pfGetMessageExtraInfoFunction = (GetMessageExtraInfoFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "GetMessageExtraInfo"); - s_pfGetTouchInputInfoFunction = (GetTouchInputInfoFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "GetTouchInputInfo"); - s_pfCloseTouchInputHandleFunction = (CloseTouchInputHandleFn)GetProcAddress(GetModuleHandle(TEXT("user32.dll")), "CloseTouchInputHandle"); +public: + static bool s_captured; + static float s_mouseX; + static float s_mouseY; + + static void onGLFWError(int errorID, const char* errorDesc); + static void onGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify); + static void onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y); + static void onGLFWMouseScrollCallback(GLFWwindow* window, double x, double y); + static void onGLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); + static void onGLFWCharCallback(GLFWwindow* window, unsigned int character); + static void onGLFWWindowPosCallback(GLFWwindow* windows, int x, int y); + static void onGLFWframebuffersize(GLFWwindow* window, int w, int h); +}; - return (s_pfRegisterTouchWindowFunction && s_pfUnregisterTouchWindowFunction && s_pfGetMessageExtraInfoFunction && s_pfGetTouchInputInfoFunction && s_pfCloseTouchInputHandleFunction); +bool GLViewEventHandler::s_captured = false; +float GLViewEventHandler::s_mouseX = 0; +float GLViewEventHandler::s_mouseY = 0; + +void GLViewEventHandler::onGLFWError(int errorID, const char* errorDesc) +{ + CCLOGERROR("GLFWError #%d Happen, %s\n", errorID, errorDesc); } -#endif /* #if(_MSC_VER >= 1600) */ +void GLViewEventHandler::onGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify) +{ + GLView* eglView = Director::getInstance()->getOpenGLView(); + if(nullptr == eglView) return; + if(GLFW_MOUSE_BUTTON_LEFT == button) + { + if(GLFW_PRESS == action) + { + s_captured = true; + if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) + { + int id = 0; + eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); + } + } + else if(GLFW_RELEASE == action) + { + s_captured = false; + if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) + { + int id = 0; + eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); + } + } + } + + if(GLFW_PRESS == action) + { + EventMouse event(EventMouse::MouseEventType::MOUSE_DOWN); + //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here + event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); + event.setMouseButton(button); + Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); + } + else if(GLFW_RELEASE == action) + { + EventMouse event(EventMouse::MouseEventType::MOUSE_UP); + //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here + event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); + event.setMouseButton(button); + Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); + } +} +void GLViewEventHandler::onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) +{ + GLView* eglView = Director::getInstance()->getOpenGLView(); + if(nullptr == eglView) return; + + if (eglView->isRetina()) { + x *= 2; + y *= 2; + } + + s_mouseX = (float)x; + s_mouseY = (float)y; + + s_mouseX /= eglView->getFrameZoomFactor(); + s_mouseY /= eglView->getFrameZoomFactor(); + + if(s_captured) + { + if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) + { + int id = 0; + eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); + } + } + + EventMouse event(EventMouse::MouseEventType::MOUSE_MOVE); + //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here + event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); + Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); +} + +void GLViewEventHandler::onGLFWMouseScrollCallback(GLFWwindow* window, double x, double y) +{ + GLView* eglView = Director::getInstance()->getOpenGLView(); + if(nullptr == eglView) return; + + EventMouse event(EventMouse::MouseEventType::MOUSE_SCROLL); + //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here + event.setScrollData((float)x, -(float)y); + event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); + Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); +} + +void GLViewEventHandler::onGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) +{ + if (GLFW_REPEAT != action) + { + EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); + auto dispatcher = Director::getInstance()->getEventDispatcher(); + dispatcher->dispatchEvent(&event); + } +} + +void GLViewEventHandler::onGLFWCharCallback(GLFWwindow *window, unsigned int character) +{ + IMEDispatcher::sharedDispatcher()->dispatchInsertText((const char*) &character, 1); +} + +void GLViewEventHandler::onGLFWWindowPosCallback(GLFWwindow *windows, int x, int y) +{ + Director::getInstance()->setViewport(); +} + +void GLViewEventHandler::onGLFWframebuffersize(GLFWwindow* window, int w, int h) +{ + auto view = Director::getInstance()->getOpenGLView(); + + float frameSizeW = view->getFrameSize().width; + float frameSizeH = view->getFrameSize().height; + float factorX = frameSizeW / w * view->getFrameZoomFactor(); + float factorY = frameSizeH / h * view->getFrameZoomFactor();; + + if (fabs(factorX - 0.5f) < FLT_EPSILON && fabs(factorY - 0.5f) < FLT_EPSILON ) + { + view->_isRetina = true; + view->setFrameZoomFactor(2.0f * view->getFrameZoomFactor()); + glfwSetWindowSize(window, static_cast(frameSizeW * 0.5f * view->getFrameZoomFactor()) , static_cast(frameSizeH * 0.5f * view->getFrameZoomFactor())); + } + else if(fabs(factorX - 2.0f) < FLT_EPSILON && fabs(factorY - 2.0f) < FLT_EPSILON) + { + view->_isRetina = false; + view->setFrameZoomFactor(0.5f * view->getFrameZoomFactor()); + glfwSetWindowSize(window, static_cast(frameSizeW * view->getFrameZoomFactor()), static_cast(frameSizeH * view->getFrameZoomFactor())); + } +} + + +//end GLViewEventHandler + + +////////////////////////////////////////////////////////////////////////// +// implement GLView +////////////////////////////////////////////////////////////////////////// + + +GLView* GLView::create(const std::string& viewName) +{ + auto ret = new GLView; + if(ret && ret->initWithRect(viewName, Rect(0, 0, 960, 640), 1)) { + ret->autorelease(); + return ret; + } + + return nullptr; +} + +GLView* GLView::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor) +{ + auto ret = new GLView; + if(ret && ret->initWithRect(viewName, rect, frameZoomFactor)) { + ret->autorelease(); + return ret; + } + + return nullptr; +} + +GLView* GLView::createWithFullScreen(const std::string& viewName) +{ + auto ret = new GLView(); + if(ret && ret->initWithFullScreen(viewName)) { + ret->autorelease(); + return ret; + } + + return nullptr; +} + +GLView::GLView() +: _captured(false) +, _frameZoomFactor(1.0f) +, _supportTouch(false) +, _isRetina(false) +, _mainWindow(nullptr) +, _primaryMonitor(nullptr) +{ + _viewName = "cocos2dx"; + g_keyCodeMap.clear(); + for (auto& item : g_keyCodeStructArray) + { + g_keyCodeMap[item.glfwKeyCode] = item.keyCode; + } + glfwSetErrorCallback(GLViewEventHandler::onGLFWError); + glfwInit(); +} + +GLView::~GLView() +{ + CCLOGINFO("deallocing GLView: %p", this); + glfwTerminate(); +} + +bool GLView::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor) +{ + setViewName(viewName); + setFrameSize(rect.size.width, rect.size.height); + setFrameZoomFactor(frameZoomFactor); + + glfwWindowHint(GLFW_RESIZABLE,GL_FALSE); + + _mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor, + _screenSize.height * _frameZoomFactor, + _viewName.c_str(), + _primaryMonitor, + NULL); + glfwMakeContextCurrent(_mainWindow); + + int w, h; + glfwGetWindowSize(_mainWindow, &w, &h); + int frameBufferW, frameBufferH; + glfwGetFramebufferSize(_mainWindow, &frameBufferW, &frameBufferH); + + if (frameBufferW == 2 * w && frameBufferH == 2 * h) + { + _isRetina = true; + setFrameZoomFactor(frameZoomFactor * 2); + glfwSetWindowSize(_mainWindow, rect.size.width/2 * _frameZoomFactor, rect.size.height/2 * _frameZoomFactor); + } + + glfwSetMouseButtonCallback(_mainWindow, GLViewEventHandler::onGLFWMouseCallBack); + glfwSetCursorPosCallback(_mainWindow, GLViewEventHandler::onGLFWMouseMoveCallBack); + glfwSetScrollCallback(_mainWindow, GLViewEventHandler::onGLFWMouseScrollCallback); + glfwSetCharCallback(_mainWindow, GLViewEventHandler::onGLFWCharCallback); + glfwSetKeyCallback(_mainWindow, GLViewEventHandler::onGLFWKeyCallback); + glfwSetWindowPosCallback(_mainWindow, GLViewEventHandler::onGLFWWindowPosCallback); + glfwSetFramebufferSizeCallback(_mainWindow, GLViewEventHandler::onGLFWframebuffersize); + // check OpenGL version at first + const GLubyte* glVersion = glGetString(GL_VERSION); + + if ( atof((const char*)glVersion) < 1.5 ) + { + char strComplain[256] = {0}; + sprintf(strComplain, + "OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.", + glVersion); + MessageBox(strComplain, "OpenGL version too old"); + return false; + } + + initGlew(); + + // Enable point size by default. + glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); + + return true; +} + +bool GLView::initWithFullScreen(const std::string& viewName) +{ + _primaryMonitor = glfwGetPrimaryMonitor(); + if (nullptr == _primaryMonitor) + return false; + + const GLFWvidmode* videoMode = glfwGetVideoMode(_primaryMonitor); + return initWithRect(viewName, Rect(0, 0, videoMode->width, videoMode->height), 1.0f); +} + +bool GLView::isOpenGLReady() +{ + return nullptr != _mainWindow; +} + +void GLView::end() +{ + if(_mainWindow) + glfwSetWindowShouldClose(_mainWindow,1); +} + +void GLView::swapBuffers() +{ + if(_mainWindow) + glfwSwapBuffers(_mainWindow); +} + +bool GLView::windowShouldClose() +{ + if(_mainWindow) + return glfwWindowShouldClose(_mainWindow); + else + return true; +} + +void GLView::pollEvents() +{ + glfwPollEvents(); +} + +void GLView::setIMEKeyboardState(bool /*bOpen*/) +{ + +} + +void GLView::setFrameZoomFactor(float zoomFactor) +{ + _frameZoomFactor = zoomFactor; + Director::getInstance()->setProjection(Director::getInstance()->getProjection()); +} + +float GLView::getFrameZoomFactor() +{ + return _frameZoomFactor; +} + +void GLView::setFrameSize(float width, float height) +{ + GLViewProtocol::setFrameSize(width, height); +} + +void GLView::setViewPortInPoints(float x , float y , float w , float h) +{ + glViewport((GLint)(x * _scaleX * _frameZoomFactor + _viewPortRect.origin.x * _frameZoomFactor), + (GLint)(y * _scaleY * _frameZoomFactor + _viewPortRect.origin.y * _frameZoomFactor), + (GLsizei)(w * _scaleX * _frameZoomFactor), + (GLsizei)(h * _scaleY * _frameZoomFactor)); +} + +void GLView::setScissorInPoints(float x , float y , float w , float h) +{ + glScissor((GLint)(x * _scaleX * _frameZoomFactor + _viewPortRect.origin.x * _frameZoomFactor), + (GLint)(y * _scaleY * _frameZoomFactor + _viewPortRect.origin.y * _frameZoomFactor), + (GLsizei)(w * _scaleX * _frameZoomFactor), + (GLsizei)(h * _scaleY * _frameZoomFactor)); +} + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) static bool glew_dynamic_binding() { const char *gl_extensions = (const char*)glGetString(GL_EXTENSIONS); @@ -267,201 +593,12 @@ static bool glew_dynamic_binding() } return true; } -//begin EGLViewEventHandler -class EGLViewEventHandler +#endif + +// helper +bool GLView::initGlew() { -public: - static bool s_captured; - static float s_mouseX; - static float s_mouseY; - - static void OnGLFWError(int errorID, const char* errorDesc); - static void OnGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify); - static void OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y); - static void OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y); - static void OnGLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); - static void OnGLFWCharCallback(GLFWwindow* window, unsigned int character); - static void OnGLFWWindowPosCallback(GLFWwindow* windows, int x, int y); -}; - -bool EGLViewEventHandler::s_captured = false; -float EGLViewEventHandler::s_mouseX = 0; -float EGLViewEventHandler::s_mouseY = 0; - -void EGLViewEventHandler::OnGLFWError(int errorID, const char* errorDesc) -{ - CCLOGERROR("GLFWError #%d Happen, %s\n", errorID, errorDesc); -} - -void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify) -{ - EGLView* eglView = EGLView::getInstance(); - if(nullptr == eglView) return; - if(GLFW_MOUSE_BUTTON_LEFT == button) - { - if(GLFW_PRESS == action) - { - s_captured = true; - if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) - { - int id = 0; - eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); - } - } - else if(GLFW_RELEASE == action) - { - s_captured = false; - if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) - { - int id = 0; - eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); - } - } - } - - if(GLFW_PRESS == action) - { - EventMouse event(EventMouse::MouseEventType::MOUSE_DOWN); - event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); - event.setMouseButton(button); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); - } - else if(GLFW_RELEASE == action) - { - EventMouse event(EventMouse::MouseEventType::MOUSE_UP); - event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); - event.setMouseButton(button); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); - } -} - -void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) -{ - s_mouseX = (float)x; - s_mouseY = (float)y; - EGLView* eglView = EGLView::getInstance(); - if(nullptr == eglView) return; - - s_mouseX /= eglView->getFrameZoomFactor(); - s_mouseY /= eglView->getFrameZoomFactor(); - - if(s_captured) - { - if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) - { - int id = 0; - eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); - } - } - - EventMouse event(EventMouse::MouseEventType::MOUSE_MOVE); - //Because OpenGL use upper left as origin point, we need to revert the mouse y coordinate here - event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); -} - -void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y) -{ - EGLView* eglView = EGLView::getInstance(); - if(nullptr == eglView) return; - - EventMouse event(EventMouse::MouseEventType::MOUSE_SCROLL); - //Because OpenGL use upper left as origin point, we need to revert the mouse y coordinate here - event.setScrollData((float)x, -(float)y); - event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); -} - -void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) -{ - if (GLFW_REPEAT != action) - { - EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); - auto dispatcher = Director::getInstance()->getEventDispatcher(); - dispatcher->dispatchEvent(&event); - } -} - -void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character) -{ - IMEDispatcher::sharedDispatcher()->dispatchInsertText((const char*) &character, 1); -} - -void EGLViewEventHandler::OnGLFWWindowPosCallback(GLFWwindow *windows, int x, int y) -{ - if(Director::getInstance()) - { - Director::getInstance()->setViewport(); - } -} - -//end EGLViewEventHandler - -////////////////////////////////////////////////////////////////////////// -// impliment EGLView -////////////////////////////////////////////////////////////////////////// - -EGLView* EGLView::s_pEglView = nullptr; - -EGLView::EGLView() -: _captured(false) -, _lpfnAccelerometerKeyHook(NULL) -, _frameZoomFactor(1.0f) -, _supportTouch(false) -, _mainWindow(nullptr) -{ - CCASSERT(nullptr == s_pEglView, "EGLView is singleton, Should be inited only one time\n"); - s_pEglView = this; - g_keyCodeMap.clear(); - for (auto& item : g_keyCodeStructArray) - { - g_keyCodeMap.insert(std::make_pair(item.glfwKeyCode, item.keyCode)); - } - _viewName = "Cocos2dxWin32"; - glfwSetErrorCallback(EGLViewEventHandler::OnGLFWError); - glfwInit(); -} - -EGLView::~EGLView() -{ - glfwTerminate(); - s_pEglView = nullptr; -} - -bool EGLView::init(const char* viewName, float width, float height, float frameZoomFactor) -{ - if(nullptr != _mainWindow) return true; - - setViewName(viewName); - setFrameSize(width, height); - setFrameZoomFactor(frameZoomFactor); - - glfwWindowHint(GLFW_RESIZABLE,GL_FALSE); - _mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor, _screenSize.height * _frameZoomFactor, _viewName.c_str(), nullptr, nullptr); - glfwMakeContextCurrent(_mainWindow); - - glfwGetFramebufferSize(_mainWindow, &_frameBufferSize[0], &_frameBufferSize[1]); - glfwSetMouseButtonCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseCallBack); - glfwSetCursorPosCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseMoveCallBack); - glfwSetScrollCallback(_mainWindow, EGLViewEventHandler::OnGLFWMouseScrollCallback); - glfwSetCharCallback(_mainWindow, EGLViewEventHandler::OnGLFWCharCallback); - glfwSetKeyCallback(_mainWindow, EGLViewEventHandler::OnGLFWKeyCallback); - glfwSetWindowPosCallback(_mainWindow, EGLViewEventHandler::OnGLFWWindowPosCallback); - - // check OpenGL version at first - const GLubyte* glVersion = glGetString(GL_VERSION); - CCLOG("OpenGL version = %s", glVersion); - - if ( atof((const char*)glVersion) < 1.5 ) - { - char strComplain[256] = {0}; - sprintf(strComplain, - "OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.", - glVersion); - MessageBox(strComplain, "OpenGL version too old"); - return false; - } - +#if (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) GLenum GlewInitResult = glewInit(); if (GLEW_OK != GlewInitResult) { @@ -487,105 +624,17 @@ bool EGLView::init(const char* viewName, float width, float height, float frameZ log("OpenGL 2.0 not supported"); } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) if(glew_dynamic_binding() == false) { MessageBox("No OpenGL framebuffer support. Please upgrade the driver of your video card.", "OpenGL error"); return false; - } + } +#endif - // Enable point size by default on windows. - glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); +#endif // (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) return true; } -void EGLView::setAccelerometerKeyHook( LPFN_ACCELEROMETER_KEYHOOK lpfnAccelerometerKeyHook ) -{ - _lpfnAccelerometerKeyHook=lpfnAccelerometerKeyHook; -} - - -bool EGLView::isOpenGLReady() -{ - return nullptr != _mainWindow; -} - -void EGLView::end() -{ - if(_mainWindow) - glfwSetWindowShouldClose(_mainWindow,1); -} - -void EGLView::swapBuffers() -{ - if(_mainWindow) - glfwSwapBuffers(_mainWindow); -} - -bool EGLView::windowShouldClose() -{ - if(_mainWindow) - return glfwWindowShouldClose(_mainWindow) != 0; - else - return true; -} - -void EGLView::pollEvents() -{ - glfwPollEvents(); -} - -void EGLView::setIMEKeyboardState(bool /*bOpen*/) -{ - -} - -void EGLView::setFrameZoomFactor(float fZoomFactor) -{ - _frameZoomFactor = fZoomFactor; - Director::getInstance()->setProjection(Director::getInstance()->getProjection()); -} - -float EGLView::getFrameZoomFactor() -{ - return _frameZoomFactor; -} - -void EGLView::setFrameSize(float width, float height) -{ - EGLViewProtocol::setFrameSize(width, height); -} - -void EGLView::setViewPortInPoints(float x , float y , float w , float h) -{ - float frameZoomFactorX = _frameBufferSize[0]/_screenSize.width; - float frameZoomFactorY = _frameBufferSize[1]/_screenSize.height; - glViewport((GLint)(x * _scaleX * frameZoomFactorX + _viewPortRect.origin.x * frameZoomFactorX), - (GLint)(y * _scaleY * frameZoomFactorY + _viewPortRect.origin.y * frameZoomFactorY), - (GLsizei)(w * _scaleX * frameZoomFactorX), - (GLsizei)(h * _scaleY * frameZoomFactorY)); -} - -void EGLView::setScissorInPoints(float x , float y , float w , float h) -{ - float frameZoomFactorX = _frameBufferSize[0]/_screenSize.width; - float frameZoomFactorY = _frameBufferSize[1]/_screenSize.height; - glScissor((GLint)(x * _scaleX * frameZoomFactorX + _viewPortRect.origin.x * frameZoomFactorX), - (GLint)(y * _scaleY * frameZoomFactorY + _viewPortRect.origin.y * frameZoomFactorY), - (GLsizei)(w * _scaleX * frameZoomFactorX), - (GLsizei)(h * _scaleY * frameZoomFactorY)); -} - -EGLView* EGLView::getInstance() -{ - CCASSERT(nullptr != s_pEglView, "EGL singleton should not be null"); - return s_pEglView; -} - -// XXX: deprecated -EGLView* EGLView::sharedOpenGLView() -{ - return EGLView::getInstance(); -} - -NS_CC_END +NS_CC_END // end of namespace cocos2d; diff --git a/cocos/2d/platform/mac/CCEGLView.h b/cocos/2d/platform/desktop/CCGLView.h similarity index 68% rename from cocos/2d/platform/mac/CCEGLView.h rename to cocos/2d/platform/desktop/CCGLView.h index 5b72a9b66f..07ee153c1f 100644 --- a/cocos/2d/platform/mac/CCEGLView.h +++ b/cocos/2d/platform/desktop/CCGLView.h @@ -23,82 +23,75 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#ifndef __CC_EGLVIEW_MAC_H__ -#define __CC_EGLVIEW_MAC_H__ +#ifndef __CC_EGLVIEW_DESKTOP_H__ +#define __CC_EGLVIEW_DESKTOP_H__ +#include "CCObject.h" #include "platform/CCCommon.h" -#include "platform/CCEGLViewProtocol.h" +#include "platform/CCGLViewProtocol.h" #include "glfw3.h" NS_CC_BEGIN -class CC_DLL EGLView : public EGLViewProtocol +class CC_DLL GLView : public Object, public GLViewProtocol { public: - /** - * @js ctor - */ - EGLView(); - /** - * @js NA - * @lua NA - */ - virtual ~EGLView(); - - /* override functions */ - virtual bool isOpenGLReady(); - virtual void end(); - virtual void swapBuffers(); - virtual void setFrameSize(float width, float height); - virtual void setIMEKeyboardState(bool bOpen); + static GLView* create(const std::string& viewName); + static GLView* createWithRect(const std::string& viewName, Rect size, float frameZoomFactor = 1.0f); + static GLView* createWithFullScreen(const std::string& viewName); + /* *frameZoomFactor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop. */ - bool init(const std::string& viewName, float width, float height, float frameZoomFactor = 1.0f); -public: - + //void resize(int width, int height); - float getFrameZoomFactor(); + float getFrameZoomFactor(); //void centerWindow(); - virtual void setViewPortInPoints(float x , float y , float w , float h); virtual void setScissorInPoints(float x , float y , float w , float h); - - // static function - /** - @brief get the shared main open gl window - */ - static EGLView* getInstance(); - - /** @deprecated Use getInstance() instead */ - CC_DEPRECATED_ATTRIBUTE static EGLView* sharedOpenGLView(); - - inline bool isRetina() { return _isRetina; }; - + + + bool windowShouldClose(); + void pollEvents(); + GLFWwindow* getWindow() const { return _mainWindow; } + + /* override functions */ + virtual bool isOpenGLReady() override; + virtual void end() override; + virtual void swapBuffers() override; + virtual void setFrameSize(float width, float height) override; + virtual void setIMEKeyboardState(bool bOpen) override; + protected: + GLView(); + virtual ~GLView(); + + bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor); + bool initWithFullScreen(const std::string& viewName); + /* * Set zoom factor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop. */ void setFrameZoomFactor(float zoomFactor); -private: + bool initGlew(); + inline bool isRetina() { return _isRetina; }; + bool _captured; bool _supportTouch; bool _isRetina; float _frameZoomFactor; - static EGLView* s_pEglView; -public: - bool windowShouldClose(); - - void pollEvents(); - GLFWwindow* getWindow() const { return _mainWindow; } -private: + GLFWwindow* _mainWindow; - friend class EGLViewEventHandler; + GLFWmonitor* _primaryMonitor; + friend class GLViewEventHandler; + +private: + CC_DISALLOW_COPY_AND_ASSIGN(GLView); }; NS_CC_END // end of namespace cocos2d -#endif // end of __CC_EGLVIEW_MAC_H__ +#endif // end of __CC_EGLVIEW_DESKTOP_H__ diff --git a/cocos/2d/platform/ios/CCApplication.h b/cocos/2d/platform/ios/CCApplication.h index 843a5d5b99..b2a9ad8d95 100644 --- a/cocos/2d/platform/ios/CCApplication.h +++ b/cocos/2d/platform/ios/CCApplication.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef __CC_APPLICATION_IOS_H__ #define __CC_APPLICATION_IOS_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + #include "platform/CCCommon.h" #include "platform/CCApplicationProtocol.h" @@ -90,4 +93,6 @@ protected: NS_CC_END +#endif // CC_PLATFORM_IOS + #endif // end of __CC_APPLICATION_IOS_H__ diff --git a/cocos/2d/platform/ios/CCApplication.mm b/cocos/2d/platform/ios/CCApplication.mm index 14b07975ca..052cfa0665 100644 --- a/cocos/2d/platform/ios/CCApplication.mm +++ b/cocos/2d/platform/ios/CCApplication.mm @@ -25,6 +25,8 @@ #import "CCApplication.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + #import #import "CCGeometry.h" @@ -108,6 +110,9 @@ LanguageType Application::getCurrentLanguage() else if ([languageCode isEqualToString:@"es"]){ ret = LanguageType::SPANISH; } + else if ([languageCode isEqualToString:@"nl"]){ + ret = LanguageType::DUTCH; + } else if ([languageCode isEqualToString:@"ru"]){ ret = LanguageType::RUSSIAN; } @@ -152,3 +157,5 @@ void Application::applicationScreenSizeChanged(int newWidth, int newHeight) { } NS_CC_END + +#endif // CC_PLATFORM_IOS diff --git a/cocos/2d/platform/ios/CCCommon.mm b/cocos/2d/platform/ios/CCCommon.mm index 28d0dd0e22..83012c3569 100644 --- a/cocos/2d/platform/ios/CCCommon.mm +++ b/cocos/2d/platform/ios/CCCommon.mm @@ -23,6 +23,9 @@ THE SOFTWARE. ****************************************************************************/ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + #include "platform/CCCommon.h" #include @@ -54,3 +57,5 @@ void LuaLog(const char * format) } NS_CC_END + +#endif // CC_PLATFORM_IOS \ No newline at end of file diff --git a/cocos/2d/platform/ios/CCDevice.mm b/cocos/2d/platform/ios/CCDevice.mm index a80efef136..cbf04d092f 100644 --- a/cocos/2d/platform/ios/CCDevice.mm +++ b/cocos/2d/platform/ios/CCDevice.mm @@ -22,6 +22,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ + + +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + #include "CCDevice.h" #include "ccTypes.h" #include "CCEventDispatcher.h" @@ -174,3 +179,5 @@ void Device::setAccelerometerInterval(float interval) NS_CC_END + +#endif // CC_PLATFORM_IOS diff --git a/cocos/2d/platform/ios/EAGLView.h b/cocos/2d/platform/ios/CCEAGLView.h similarity index 98% rename from cocos/2d/platform/ios/EAGLView.h rename to cocos/2d/platform/ios/CCEAGLView.h index 7a8f9c54d8..fe80ab099c 100644 --- a/cocos/2d/platform/ios/EAGLView.h +++ b/cocos/2d/platform/ios/CCEAGLView.h @@ -61,6 +61,9 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. */ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + #import #import #import @@ -119,9 +122,6 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. /** creates an initializes an CCEAGLView with a frame, a color buffer format, a depth buffer format, a sharegroup, and multisamping */ + (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples; -// get the view object -+(id) sharedEGLView; - /** Initializes an CCEAGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer */ - (id) initWithFrame:(CGRect)frame; //These also set the current context /** Initializes an CCEAGLView with a frame, a color buffer format, and 0-bit depth buffer */ @@ -155,3 +155,5 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. -(void) doAnimationWhenKeyboardMoveWithDuration:(float) duration distance:(float) dis; -(void) doAnimationWhenAnotherEditBeClicked; @end + +#endif // CC_PLATFORM_IOS diff --git a/cocos/2d/platform/ios/EAGLView.mm b/cocos/2d/platform/ios/CCEAGLView.mm similarity index 93% rename from cocos/2d/platform/ios/EAGLView.mm rename to cocos/2d/platform/ios/CCEAGLView.mm index e6ab5db271..dcae32d0ea 100644 --- a/cocos/2d/platform/ios/EAGLView.mm +++ b/cocos/2d/platform/ios/CCEAGLView.mm @@ -61,22 +61,23 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. */ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + #import -#import "CCEGLView.h" -#import "EAGLView.h" +#import "CCGLView.h" +#import "CCEAGLView.h" #import "CCES2Renderer.h" #import "CCDirector.h" #import "CCSet.h" #import "CCTouch.h" #import "CCIMEDispatcher.h" #import "OpenGL_Internal.h" -#import "CCEGLView.h" +#import "CCGLView.h" //CLASS IMPLEMENTATIONS: #define IOS_MAX_TOUCHES_COUNT 10 -static CCEAGLView *__view = 0; - @interface CCEAGLView (Private) - (BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup; - (unsigned int) convertPixelFormat:(NSString*) pixelFormat; @@ -115,11 +116,6 @@ static CCEAGLView *__view = 0; return [[[self alloc]initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:retained sharegroup:sharegroup multiSampling:multisampling numberOfSamples:samples] autorelease]; } -+ (id) sharedEGLView -{ - return __view; -} - - (id) initWithFrame:(CGRect)frame { return [self initWithFrame:frame pixelFormat:kEAGLColorFormatRGB565 depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0]; @@ -146,15 +142,13 @@ static CCEAGLView *__view = 0; return nil; } - - __view = self; - + originalRect_ = self.frame; self.keyboardShowNotification = nil; - if ([__view respondsToSelector:@selector(setContentScaleFactor:)]) + if ([self respondsToSelector:@selector(setContentScaleFactor:)]) { - __view.contentScaleFactor = [[UIScreen mainScreen] scale]; + self.contentScaleFactor = [[UIScreen mainScreen] scale]; } } @@ -180,7 +174,6 @@ static CCEAGLView *__view = 0; } } - __view = self; return self; } @@ -409,11 +402,13 @@ static CCEAGLView *__view = 0; int i = 0; for (UITouch *touch in touches) { ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; + xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesBegin(i, (int*)ids, xs, ys); + + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + glview->handleTouchesBegin(i, (int*)ids, xs, ys); } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event @@ -429,11 +424,13 @@ static CCEAGLView *__view = 0; int i = 0; for (UITouch *touch in touches) { ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; + xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesMove(i, (int*)ids, xs, ys); + + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + glview->handleTouchesMove(i, (int*)ids, xs, ys); } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event @@ -450,11 +447,13 @@ static CCEAGLView *__view = 0; int i = 0; for (UITouch *touch in touches) { ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; + xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesEnd(i, (int*)ids, xs, ys); + + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + glview->handleTouchesEnd(i, (int*)ids, xs, ys); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event @@ -471,11 +470,13 @@ static CCEAGLView *__view = 0; int i = 0; for (UITouch *touch in touches) { ids[i] = touch; - xs[i] = [touch locationInView: [touch view]].x * __view.contentScaleFactor;; - ys[i] = [touch locationInView: [touch view]].y * __view.contentScaleFactor;; + xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor;; + ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor;; ++i; } - cocos2d::EGLView::getInstance()->handleTouchesCancel(i, (int*)ids, xs, ys); + + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + glview->handleTouchesCancel(i, (int*)ids, xs, ys); } #pragma mark - UIView - Responder @@ -794,9 +795,10 @@ static CCEAGLView *__view = 0; default: break; } - - float scaleX = cocos2d::EGLView::getInstance()->getScaleX(); - float scaleY = cocos2d::EGLView::getInstance()->getScaleY(); + + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + float scaleX = glview->getScaleX(); + float scaleY = glview->getScaleY(); if (self.contentScaleFactor == 2.0f) @@ -807,7 +809,7 @@ static CCEAGLView *__view = 0; end = CGRectApplyAffineTransform(end, CGAffineTransformScale(CGAffineTransformIdentity, 2.0f, 2.0f)); } - float offestY = cocos2d::EGLView::getInstance()->getViewPortRect().origin.y; + float offestY = glview->getViewPortRect().origin.y; CCLOG("offestY = %f", offestY); if (offestY < 0.0f) { @@ -866,11 +868,12 @@ static CCEAGLView *__view = 0; [UIView setAnimationDuration:duration]; [UIView setAnimationBeginsFromCurrentState:YES]; - //NSLog(@"[animation] dis = %f, scale = %f \n", dis, cocos2d::EGLView::getInstance()->getScaleY()); + //NSLog(@"[animation] dis = %f, scale = %f \n", dis, cocos2d::GLView::getInstance()->getScaleY()); if (dis < 0.0f) dis = 0.0f; - dis *= cocos2d::EGLView::getInstance()->getScaleY(); + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + dis *= glview->getScaleY(); if (self.contentScaleFactor == 2.0f) { @@ -912,3 +915,5 @@ static CCEAGLView *__view = 0; } @end + +#endif // CC_PLATFORM_IOS diff --git a/cocos/2d/platform/ios/CCEGLView.mm b/cocos/2d/platform/ios/CCEGLView.mm deleted file mode 100644 index 399b365e56..0000000000 --- a/cocos/2d/platform/ios/CCEGLView.mm +++ /dev/null @@ -1,98 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2013-2014 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. - ****************************************************************************/ -#include "EAGLView.h" -#include "CCDirectorCaller.h" -#include "CCEGLView.h" -#include "CCSet.h" -#include "CCTouch.h" - -NS_CC_BEGIN - -EGLView::EGLView() -{ - _screenSize.width = _designResolutionSize.width = [[CCEAGLView sharedEGLView] getWidth]; - _screenSize.height = _designResolutionSize.height = [[CCEAGLView sharedEGLView] getHeight]; -} - -EGLView::~EGLView() -{ - -} - -bool EGLView::isOpenGLReady() -{ - return [CCEAGLView sharedEGLView] != nullptr; -} - -bool EGLView::setContentScaleFactor(float contentScaleFactor) -{ - assert(_resolutionPolicy == ResolutionPolicy::UNKNOWN); // cannot enable retina mode - - _scaleX = _scaleY = contentScaleFactor; - [[CCEAGLView sharedEGLView] setNeedsLayout]; - - return true; -} - -void EGLView::end() -{ - [CCDirectorCaller destroy]; - - // destroy EAGLView - [[CCEAGLView sharedEGLView] removeFromSuperview]; -} - - -void EGLView::swapBuffers() -{ - [[CCEAGLView sharedEGLView] swapBuffers]; -} - -void EGLView::setIMEKeyboardState(bool bOpen) -{ - if (bOpen) - { - [[CCEAGLView sharedEGLView] becomeFirstResponder]; - } - else - { - [[CCEAGLView sharedEGLView] resignFirstResponder]; - } -} - -EGLView* EGLView::getInstance() -{ - static EGLView instance; - return &instance; -} - -// XXX: deprecated -EGLView* EGLView::sharedOpenGLView() -{ - return EGLView::getInstance(); -} - -NS_CC_END - diff --git a/cocos/2d/platform/ios/CCES2Renderer.h b/cocos/2d/platform/ios/CCES2Renderer.h index 1c25466fe4..5cd1fe47db 100644 --- a/cocos/2d/platform/ios/CCES2Renderer.h +++ b/cocos/2d/platform/ios/CCES2Renderer.h @@ -27,6 +27,10 @@ // Only compile this code on iOS. These files should NOT be included on your Mac project. // But in case they are included, it won't be compiled. + +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + #import "CCPlatformMacros.h" #import "CCESRenderer.h" #import @@ -76,4 +80,4 @@ @end - +#endif // CC_PLATFORM_IOS diff --git a/cocos/2d/platform/ios/CCES2Renderer.m b/cocos/2d/platform/ios/CCES2Renderer.m index 3f3a226e82..4c687c2d38 100644 --- a/cocos/2d/platform/ios/CCES2Renderer.m +++ b/cocos/2d/platform/ios/CCES2Renderer.m @@ -28,8 +28,11 @@ // Only compile this code on iOS. These files should NOT be included on your Mac project. // But in case they are included, it won't be compiled. -#import "CCPlatformMacros.h" #import "CCES2Renderer.h" + +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + +#import "CCPlatformMacros.h" #import "OpenGL_Internal.h" #if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 @@ -251,3 +254,5 @@ @end +#endif // CC_PLATFORM_IOS + diff --git a/cocos/2d/platform/ios/CCESRenderer.h b/cocos/2d/platform/ios/CCESRenderer.h index e35ea686e1..dd331a49d5 100644 --- a/cocos/2d/platform/ios/CCESRenderer.h +++ b/cocos/2d/platform/ios/CCESRenderer.h @@ -27,6 +27,10 @@ // Only compile this code on iOS. These files should NOT be included on your Mac project. // But in case they are included, it won't be compiled. + +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + #include "CCPlatformMacros.h" #import @@ -48,3 +52,4 @@ - (unsigned int) msaaColorBuffer; @end +#endif // CC_PLATFORM_IOS diff --git a/cocos/2d/platform/ios/CCGL.h b/cocos/2d/platform/ios/CCGL.h index 6104a7fcfd..6b306950c3 100644 --- a/cocos/2d/platform/ios/CCGL.h +++ b/cocos/2d/platform/ios/CCGL.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef __PLATFORM_IOS_CCGL_H__ #define __PLATFORM_IOS_CCGL_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + #define glClearDepth glClearDepthf #define glDeleteVertexArrays glDeleteVertexArraysOES #define glGenVertexArrays glGenVertexArraysOES @@ -39,5 +42,7 @@ THE SOFTWARE. #include #include +#endif // CC_PLATFORM_IOS #endif // __PLATFORM_IOS_CCGL_H__ + diff --git a/cocos/2d/platform/ios/CCGLView.h b/cocos/2d/platform/ios/CCGLView.h new file mode 100644 index 0000000000..0196066d36 --- /dev/null +++ b/cocos/2d/platform/ios/CCGLView.h @@ -0,0 +1,90 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2013-2014 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. + ****************************************************************************/ + +#ifndef __CC_EGLVIEW_IPHONE_H__ +#define __CC_EGLVIEW_IPHONE_H__ + +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + +#include "CCObject.h" +#include "platform/CCCommon.h" +#include "platform/CCGLViewProtocol.h" + +NS_CC_BEGIN + + +/** Class that represent the OpenGL View + */ +class CC_DLL GLView : public Object, public GLViewProtocol +{ +public: + /** creates a GLView with a objective-c CCEAGLView instance */ + static GLView* createWithEAGLView(void* eaglview); + + /** creates a GLView with a title name in fullscreen mode */ + static GLView* create(const std::string& viewName); + + /** creates a GLView with a title name, a rect and the zoom factor */ + static GLView* createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor = 1.0f); + + /** creates a GLView with a name in fullscreen mode */ + static GLView* createWithFullScreen(const std::string& viewName); + + /** sets the content scale factor */ + bool setContentScaleFactor(float contentScaleFactor); + + /** returns the content scale factor */ + float getContentScaleFactor() const; + + /** returns whether or not the view is in Retina Display mode */ + bool isRetinaDisplay() const { return getContentScaleFactor() == 2.0; } + + /** returns the objective-c CCEAGLView instance */ + void* getEAGLView() const { return _eaglview; } + + // overrides + virtual bool isOpenGLReady() override; + virtual void end() override; + virtual void swapBuffers() override; + virtual void setIMEKeyboardState(bool bOpen) override; + +protected: + GLView(); + virtual ~GLView(); + + bool initWithEAGLView(void* eaglview); + bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor); + bool initWithFullScreen(const std::string& viewName); + + // the objective-c CCEAGLView instance + void *_eaglview; +}; + +NS_CC_END + +#endif // CC_PLATFORM_IOS + +#endif // end of __CC_EGLVIEW_IPHONE_H__ diff --git a/cocos/2d/platform/ios/CCGLView.mm b/cocos/2d/platform/ios/CCGLView.mm new file mode 100644 index 0000000000..87062f4f21 --- /dev/null +++ b/cocos/2d/platform/ios/CCGLView.mm @@ -0,0 +1,201 @@ +/**************************************************************************** + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2013-2014 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. + ****************************************************************************/ + +#include "CCPlatformConfig.h" + +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + +#import + +#include "CCEAGLView.h" +#include "CCDirectorCaller.h" +#include "CCGLView.h" +#include "CCSet.h" +#include "CCTouch.h" + +NS_CC_BEGIN + +GLView* GLView::createWithEAGLView(void *eaglview) +{ + auto ret = new GLView; + if(ret && ret->initWithEAGLView(eaglview)) { + ret->autorelease(); + return ret; + } + + return nullptr; +} + +GLView* GLView::create(const std::string& viewName) +{ + auto ret = new GLView; + if(ret && ret->initWithFullScreen(viewName)) { + ret->autorelease(); + return ret; + } + + return nullptr; +} + +GLView* GLView::createWithRect(const std::string& viewName, Rect rect, float frameZoomFactor) +{ + auto ret = new GLView; + if(ret && ret->initWithRect(viewName, rect, frameZoomFactor)) { + ret->autorelease(); + return ret; + } + + return nullptr; +} + +GLView* GLView::createWithFullScreen(const std::string& viewName) +{ + auto ret = new GLView(); + if(ret && ret->initWithFullScreen(viewName)) { + ret->autorelease(); + return ret; + } + + return nullptr; +} + +GLView::GLView() +{ +} + +GLView::~GLView() +{ + CCEAGLView *glview = (CCEAGLView*) _eaglview; + [glview release]; +} + +bool GLView::initWithEAGLView(void *eaglview) +{ + _eaglview = eaglview; + CCEAGLView *glview = (CCEAGLView*) _eaglview; + + _screenSize.width = _designResolutionSize.width = [glview getWidth]; + _screenSize.height = _designResolutionSize.height = [glview getHeight]; +// _scaleX = _scaleY = [glview contentScaleFactor]; + + return true; +} + +bool GLView::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor) +{ + CGRect r = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); + CCEAGLView *eaglview = [CCEAGLView viewWithFrame: r + pixelFormat: kEAGLColorFormatRGB565 + depthFormat: GL_DEPTH24_STENCIL8_OES + preserveBackbuffer: NO + sharegroup: nil + multiSampling: NO + numberOfSamples: 0]; + [eaglview setMultipleTouchEnabled:YES]; + + _screenSize.width = _designResolutionSize.width = [eaglview getWidth]; + _screenSize.height = _designResolutionSize.height = [eaglview getHeight]; +// _scaleX = _scaleY = [eaglview contentScaleFactor]; + + _eaglview = eaglview; + + return true; +} + +bool GLView::initWithFullScreen(const std::string& viewName) +{ + CGRect rect = [[UIScreen mainScreen] bounds]; + Rect r; + r.origin.x = rect.origin.x; + r.origin.y = rect.origin.y; + r.size.width = rect.size.width; + r.size.height = rect.size.height; + + return initWithRect(viewName, r, 1); +} + +bool GLView::isOpenGLReady() +{ + return _eaglview != nullptr; +} + +bool GLView::setContentScaleFactor(float contentScaleFactor) +{ + CC_ASSERT(_resolutionPolicy == ResolutionPolicy::UNKNOWN); // cannot enable retina mode + _scaleX = _scaleY = contentScaleFactor; + + CCEAGLView *eaglview = (CCEAGLView*) _eaglview; + [eaglview setNeedsLayout]; + + return true; +} + +float GLView::getContentScaleFactor() const +{ + CCEAGLView *eaglview = (CCEAGLView*) _eaglview; + + float scaleFactor = [eaglview contentScaleFactor]; + +// CCASSERT(scaleFactor == _scaleX == _scaleY, "Logic error in GLView::getContentScaleFactor"); + + return scaleFactor; +} + +void GLView::end() +{ + [CCDirectorCaller destroy]; + + // destroy EAGLView + CCEAGLView *eaglview = (CCEAGLView*) _eaglview; + + [eaglview removeFromSuperview]; + [eaglview release]; +} + + +void GLView::swapBuffers() +{ + CCEAGLView *eaglview = (CCEAGLView*) _eaglview; + [eaglview swapBuffers]; +} + +void GLView::setIMEKeyboardState(bool open) +{ + CCEAGLView *eaglview = (CCEAGLView*) _eaglview; + + if (open) + { + [eaglview becomeFirstResponder]; + } + else + { + [eaglview resignFirstResponder]; + } +} + +NS_CC_END + +#endif // CC_PLATFOR_IOS + diff --git a/cocos/2d/platform/ios/CCImage.mm b/cocos/2d/platform/ios/CCImage.mm index 5ad55ce594..4d5ba92fe9 100644 --- a/cocos/2d/platform/ios/CCImage.mm +++ b/cocos/2d/platform/ios/CCImage.mm @@ -22,6 +22,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + #include "CCImageCommon_cpp.h" #import "CCImage.h" @@ -468,3 +472,5 @@ bool Image::saveToFile(const std::string& filename, bool isToRGB) NS_CC_END +#endif // CC_PLATFORM_IOS + diff --git a/cocos/2d/platform/ios/CCPlatformDefine.h b/cocos/2d/platform/ios/CCPlatformDefine.h index 02f7c89eba..e6538ef662 100644 --- a/cocos/2d/platform/ios/CCPlatformDefine.h +++ b/cocos/2d/platform/ios/CCPlatformDefine.h @@ -25,6 +25,9 @@ THE SOFTWARE. #ifndef __CCPLATFORMDEFINE_H__ #define __CCPLATFORMDEFINE_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + #include #define CC_DLL @@ -44,5 +47,6 @@ THE SOFTWARE. #endif +#endif // CC_PLATFORM_IOS #endif /* __CCPLATFORMDEFINE_H__*/ diff --git a/cocos/2d/platform/ios/CCStdC.h b/cocos/2d/platform/ios/CCStdC.h index 804abebceb..af440f0e6e 100644 --- a/cocos/2d/platform/ios/CCStdC.h +++ b/cocos/2d/platform/ios/CCStdC.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef __CC_STD_C_H__ #define __CC_STD_C_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + #include "CCPlatformMacros.h" #include #include @@ -45,4 +48,5 @@ THE SOFTWARE. #define MAX(x,y) (((x) < (y)) ? (y) : (x)) #endif // MAX +#endif // CC_PLATFORM_IOS #endif // __CC_STD_C_H__ diff --git a/cocos/2d/platform/ios/OpenGL_Internal.h b/cocos/2d/platform/ios/OpenGL_Internal.h index 9bc7a1860f..a0022582a8 100644 --- a/cocos/2d/platform/ios/OpenGL_Internal.h +++ b/cocos/2d/platform/ios/OpenGL_Internal.h @@ -61,6 +61,9 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. */ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + /* Generic error reporting */ #define REPORT_ERROR(__FORMAT__, ...) printf("%s: %s\n", __FUNCTION__, [[NSString stringWithFormat:__FORMAT__, __VA_ARGS__] UTF8String]) @@ -79,3 +82,5 @@ Copyright (C) 2008 Apple Inc. All Rights Reserved. #endif #define TEST_DELEGATE_METHOD_BIT(__BIT__) (self->__DELEGATE_METHODS_IVAR__ & (1 << __BIT__)) #define SET_DELEGATE_METHOD_BIT(__BIT__, __NAME__) { if([self->__DELEGATE_IVAR__ respondsToSelector:@selector(__NAME__)]) self->__DELEGATE_METHODS_IVAR__ |= (1 << __BIT__); else self->__DELEGATE_METHODS_IVAR__ &= ~(1 << __BIT__); } + +#endif // CC_PLATFORM_IOS diff --git a/cocos/2d/platform/ios/Simulation/AccelerometerSimulation.h b/cocos/2d/platform/ios/Simulation/AccelerometerSimulation.h index 972843302c..49ef7c1276 100644 --- a/cocos/2d/platform/ios/Simulation/AccelerometerSimulation.h +++ b/cocos/2d/platform/ios/Simulation/AccelerometerSimulation.h @@ -23,6 +23,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + #import // when compiling to ARM (iPhone device), hide everything and use system defaults @@ -73,4 +77,6 @@ THE SOFTWARE. @end -#endif +#endif // !TARGET_CPU_ARM + +#endif // CC_PLATFORM_IOS diff --git a/cocos/2d/platform/ios/Simulation/AccelerometerSimulation.m b/cocos/2d/platform/ios/Simulation/AccelerometerSimulation.m index 0a93a263e9..5056ce9522 100644 --- a/cocos/2d/platform/ios/Simulation/AccelerometerSimulation.m +++ b/cocos/2d/platform/ios/Simulation/AccelerometerSimulation.m @@ -26,6 +26,8 @@ THE SOFTWARE. #import "AccelerometerSimulation.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS + // when compiling to ARM (iPhone device), hide everything and use system defaults // if you wish to use simulation mode even on the device, remove the #if/#endif #if !TARGET_CPU_ARM @@ -263,4 +265,6 @@ static CCAccelerometerSimulation *sharedAccelerometer = NULL; } @end -#endif +#endif // !TARGET_CPU_ARM + +#endif // CC_PLATFORM_IOS diff --git a/cocos/2d/platform/linux/CCApplication.cpp b/cocos/2d/platform/linux/CCApplication.cpp index f2efa5b7de..97ae71ba74 100644 --- a/cocos/2d/platform/linux/CCApplication.cpp +++ b/cocos/2d/platform/linux/CCApplication.cpp @@ -23,13 +23,16 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #include "CCApplication.h" #include #include #include #include "CCDirector.h" #include "platform/CCFileUtils.h" -#include "CCEGLView.h" +#include "CCGLView.h" NS_CC_BEGIN @@ -38,61 +41,62 @@ NS_CC_BEGIN Application * Application::sm_pSharedApplication = 0; static long getCurrentMillSecond() { - long lLastTime; - struct timeval stCurrentTime; + long lLastTime; + struct timeval stCurrentTime; - gettimeofday(&stCurrentTime,NULL); - lLastTime = stCurrentTime.tv_sec*1000+stCurrentTime.tv_usec*0.001; //millseconds - return lLastTime; + gettimeofday(&stCurrentTime,NULL); + lLastTime = stCurrentTime.tv_sec*1000+stCurrentTime.tv_usec*0.001; //millseconds + return lLastTime; } Application::Application() { - CC_ASSERT(! sm_pSharedApplication); - sm_pSharedApplication = this; + CC_ASSERT(! sm_pSharedApplication); + sm_pSharedApplication = this; } Application::~Application() { - CC_ASSERT(this == sm_pSharedApplication); - sm_pSharedApplication = NULL; - _animationInterval = 1.0f/60.0f*1000.0f; + CC_ASSERT(this == sm_pSharedApplication); + sm_pSharedApplication = NULL; + _animationInterval = 1.0f/60.0f*1000.0f; } int Application::run() { - // Initialize instance and cocos2d. - if (! applicationDidFinishLaunching()) - { - return 0; - } - - EGLView* pMainWnd = EGLView::getInstance(); - - while (!pMainWnd->windowShouldClose()) + // Initialize instance and cocos2d. + if (! applicationDidFinishLaunching()) { - long iLastTime = getCurrentMillSecond(); - Director::getInstance()->mainLoop(); - pMainWnd->pollEvents(); - long iCurTime = getCurrentMillSecond(); - if (iCurTime-iLastTime<_animationInterval){ - usleep((_animationInterval - iCurTime+iLastTime)*1000); - } + return 0; + } + + auto director = Director::getInstance(); + auto glview = director->getOpenGLView(); + + while (!glview->windowShouldClose()) + { + long iLastTime = getCurrentMillSecond(); + director->mainLoop(); + glview->pollEvents(); + long iCurTime = getCurrentMillSecond(); + if (iCurTime-iLastTime<_animationInterval){ + usleep((_animationInterval - iCurTime+iLastTime)*1000); + } } /* Only work on Desktop * Director::mainLoop is really one frame logic * when we want to close the window, we should call Director::end(); * then call Director::mainLoop to do release of internal resources */ - Director::getInstance()->end(); - Director::getInstance()->mainLoop(); - return -1; + director->end(); + director->mainLoop(); + return -1; } void Application::setAnimationInterval(double interval) { - //TODO do something else - _animationInterval = interval*1000.0f; + //TODO do something else + _animationInterval = interval*1000.0f; } void Application::setResourceRootPath(const std::string& rootResDir) @@ -123,8 +127,8 @@ Application::Platform Application::getTargetPlatform() ////////////////////////////////////////////////////////////////////////// Application* Application::getInstance() { - CC_ASSERT(sm_pSharedApplication); - return sm_pSharedApplication; + CC_ASSERT(sm_pSharedApplication); + return sm_pSharedApplication; } // @deprecated Use getInstance() instead @@ -171,6 +175,10 @@ LanguageType Application::getCurrentLanguage() { ret = LanguageType::SPANISH; } + else if (0 == strcmp("nl", pLanguageName)) + { + ret = LanguageType::DUTCH; + } else if (0 == strcmp("ru", pLanguageName)) { ret = LanguageType::RUSSIAN; @@ -188,23 +196,26 @@ LanguageType Application::getCurrentLanguage() ret = LanguageType::HUNGARIAN; } else if (0 == strcmp("pt", pLanguageName)) - { - ret = LanguageType::PORTUGUESE; - } + { + ret = LanguageType::PORTUGUESE; + } else if (0 == strcmp("ar", pLanguageName)) - { - ret = LanguageType::ARABIC; - } - else if (0 == strcmp("nb", pLanguageName)) - { - ret = LanguageType::NORWEGIAN; - } - else if (0 == strcmp("pl", pLanguageName)) - { - ret = LanguageType::POLISH; - } - - return ret; + { + ret = LanguageType::ARABIC; + } + else if (0 == strcmp("nb", pLanguageName)) + { + ret = LanguageType::NORWEGIAN; + } + else if (0 == strcmp("pl", pLanguageName)) + { + ret = LanguageType::POLISH; + } + + return ret; } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + diff --git a/cocos/2d/platform/linux/CCApplication.h b/cocos/2d/platform/linux/CCApplication.h index 8c5c51ae60..e71e487f2f 100644 --- a/cocos/2d/platform/linux/CCApplication.h +++ b/cocos/2d/platform/linux/CCApplication.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef CCAPLICATION_H_ #define CCAPLICATION_H_ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #include "platform/CCCommon.h" #include "platform/CCApplicationProtocol.h" #include @@ -94,4 +97,6 @@ protected: NS_CC_END +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #endif /* CCAPLICATION_H_ */ diff --git a/cocos/2d/platform/linux/CCCommon.cpp b/cocos/2d/platform/linux/CCCommon.cpp index c48307192b..8ef40e072c 100644 --- a/cocos/2d/platform/linux/CCCommon.cpp +++ b/cocos/2d/platform/linux/CCCommon.cpp @@ -22,6 +22,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #include "platform/CCCommon.h" #include "CCStdC.h" #include "CCConsole.h" @@ -39,3 +43,5 @@ void LuaLog(const char * format) } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX diff --git a/cocos/2d/platform/linux/CCDevice.cpp b/cocos/2d/platform/linux/CCDevice.cpp index 44457cdb6e..683522a337 100644 --- a/cocos/2d/platform/linux/CCDevice.cpp +++ b/cocos/2d/platform/linux/CCDevice.cpp @@ -22,6 +22,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #include "platform/CCDevice.h" #include #include @@ -64,3 +68,5 @@ void Device::setAccelerometerInterval(float interval) } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX diff --git a/cocos/2d/platform/linux/CCEGLView.cpp b/cocos/2d/platform/linux/CCEGLView.cpp deleted file mode 100644 index ac410b2f74..0000000000 --- a/cocos/2d/platform/linux/CCEGLView.cpp +++ /dev/null @@ -1,480 +0,0 @@ -/**************************************************************************** -Copyright (c) 2011 Laschweinski -Copyright (c) 2013-2014 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. -****************************************************************************/ - -#include "CCEGLView.h" -#include "CCGL.h" -#include "ccMacros.h" -#include "CCDirector.h" -#include "CCTouch.h" -#include "CCIMEDispatcher.h" -#include "CCEventDispatcher.h" -#include "CCEventKeyboard.h" -#include "CCEventMouse.h" -#include - -NS_CC_BEGIN - - -static std::map g_keyCodeMap = { - /* The unknown key */ - { GLFW_KEY_UNKNOWN , EventKeyboard::KeyCode::KEY_NONE }, - - /* Printable keys */ - { GLFW_KEY_SPACE , EventKeyboard::KeyCode::KEY_SPACE }, - { GLFW_KEY_APOSTROPHE , EventKeyboard::KeyCode::KEY_APOSTROPHE }, - { GLFW_KEY_COMMA , EventKeyboard::KeyCode::KEY_COMMA }, - { GLFW_KEY_MINUS , EventKeyboard::KeyCode::KEY_MINUS }, - { GLFW_KEY_PERIOD , EventKeyboard::KeyCode::KEY_PERIOD }, - { GLFW_KEY_SLASH , EventKeyboard::KeyCode::KEY_SLASH }, - { GLFW_KEY_0 , EventKeyboard::KeyCode::KEY_0 }, - { GLFW_KEY_1 , EventKeyboard::KeyCode::KEY_1 }, - { GLFW_KEY_2 , EventKeyboard::KeyCode::KEY_2 }, - { GLFW_KEY_3 , EventKeyboard::KeyCode::KEY_3 }, - { GLFW_KEY_4 , EventKeyboard::KeyCode::KEY_4 }, - { GLFW_KEY_5 , EventKeyboard::KeyCode::KEY_5 }, - { GLFW_KEY_6 , EventKeyboard::KeyCode::KEY_6 }, - { GLFW_KEY_7 , EventKeyboard::KeyCode::KEY_7 }, - { GLFW_KEY_8 , EventKeyboard::KeyCode::KEY_8 }, - { GLFW_KEY_9 , EventKeyboard::KeyCode::KEY_9 }, - { GLFW_KEY_SEMICOLON , EventKeyboard::KeyCode::KEY_SEMICOLON }, - { GLFW_KEY_EQUAL , EventKeyboard::KeyCode::KEY_EQUAL }, - { GLFW_KEY_A , EventKeyboard::KeyCode::KEY_A }, - { GLFW_KEY_B , EventKeyboard::KeyCode::KEY_B }, - { GLFW_KEY_C , EventKeyboard::KeyCode::KEY_C }, - { GLFW_KEY_D , EventKeyboard::KeyCode::KEY_D }, - { GLFW_KEY_E , EventKeyboard::KeyCode::KEY_E }, - { GLFW_KEY_F , EventKeyboard::KeyCode::KEY_F }, - { GLFW_KEY_G , EventKeyboard::KeyCode::KEY_G }, - { GLFW_KEY_H , EventKeyboard::KeyCode::KEY_H }, - { GLFW_KEY_I , EventKeyboard::KeyCode::KEY_I }, - { GLFW_KEY_J , EventKeyboard::KeyCode::KEY_J }, - { GLFW_KEY_K , EventKeyboard::KeyCode::KEY_K }, - { GLFW_KEY_L , EventKeyboard::KeyCode::KEY_L }, - { GLFW_KEY_M , EventKeyboard::KeyCode::KEY_M }, - { GLFW_KEY_N , EventKeyboard::KeyCode::KEY_N }, - { GLFW_KEY_O , EventKeyboard::KeyCode::KEY_O }, - { GLFW_KEY_P , EventKeyboard::KeyCode::KEY_P }, - { GLFW_KEY_Q , EventKeyboard::KeyCode::KEY_Q }, - { GLFW_KEY_R , EventKeyboard::KeyCode::KEY_R }, - { GLFW_KEY_S , EventKeyboard::KeyCode::KEY_S }, - { GLFW_KEY_T , EventKeyboard::KeyCode::KEY_T }, - { GLFW_KEY_U , EventKeyboard::KeyCode::KEY_U }, - { GLFW_KEY_V , EventKeyboard::KeyCode::KEY_V }, - { GLFW_KEY_W , EventKeyboard::KeyCode::KEY_W }, - { GLFW_KEY_X , EventKeyboard::KeyCode::KEY_X }, - { GLFW_KEY_Y , EventKeyboard::KeyCode::KEY_Y }, - { GLFW_KEY_Z , EventKeyboard::KeyCode::KEY_Z }, - { GLFW_KEY_LEFT_BRACKET , EventKeyboard::KeyCode::KEY_LEFT_BRACKET }, - { GLFW_KEY_BACKSLASH , EventKeyboard::KeyCode::KEY_BACK_SLASH }, - { GLFW_KEY_RIGHT_BRACKET , EventKeyboard::KeyCode::KEY_RIGHT_BRACKET }, - { GLFW_KEY_GRAVE_ACCENT , EventKeyboard::KeyCode::KEY_GRAVE }, - { GLFW_KEY_WORLD_1 , EventKeyboard::KeyCode::KEY_GRAVE }, - { GLFW_KEY_WORLD_2 , EventKeyboard::KeyCode::KEY_NONE }, - - /* Function keys */ - { GLFW_KEY_ESCAPE , EventKeyboard::KeyCode::KEY_ESCAPE }, - { GLFW_KEY_ENTER , EventKeyboard::KeyCode::KEY_KP_ENTER }, - { GLFW_KEY_TAB , EventKeyboard::KeyCode::KEY_TAB }, - { GLFW_KEY_BACKSPACE , EventKeyboard::KeyCode::KEY_BACKSPACE }, - { GLFW_KEY_INSERT , EventKeyboard::KeyCode::KEY_INSERT }, - { GLFW_KEY_DELETE , EventKeyboard::KeyCode::KEY_DELETE }, - { GLFW_KEY_RIGHT , EventKeyboard::KeyCode::KEY_RIGHT_ARROW }, - { GLFW_KEY_LEFT , EventKeyboard::KeyCode::KEY_LEFT_ARROW }, - { GLFW_KEY_DOWN , EventKeyboard::KeyCode::KEY_DOWN_ARROW }, - { GLFW_KEY_UP , EventKeyboard::KeyCode::KEY_UP_ARROW }, - { GLFW_KEY_PAGE_UP , EventKeyboard::KeyCode::KEY_KP_PG_UP }, - { GLFW_KEY_PAGE_DOWN , EventKeyboard::KeyCode::KEY_KP_PG_DOWN }, - { GLFW_KEY_HOME , EventKeyboard::KeyCode::KEY_KP_HOME }, - { GLFW_KEY_END , EventKeyboard::KeyCode::KEY_END }, - { GLFW_KEY_CAPS_LOCK , EventKeyboard::KeyCode::KEY_CAPS_LOCK }, - { GLFW_KEY_SCROLL_LOCK , EventKeyboard::KeyCode::KEY_SCROLL_LOCK }, - { GLFW_KEY_NUM_LOCK , EventKeyboard::KeyCode::KEY_NUM_LOCK }, - { GLFW_KEY_PRINT_SCREEN , EventKeyboard::KeyCode::KEY_PRINT }, - { GLFW_KEY_PAUSE , EventKeyboard::KeyCode::KEY_PAUSE }, - { GLFW_KEY_F1 , EventKeyboard::KeyCode::KEY_F1 }, - { GLFW_KEY_F2 , EventKeyboard::KeyCode::KEY_F2 }, - { GLFW_KEY_F3 , EventKeyboard::KeyCode::KEY_F3 }, - { GLFW_KEY_F4 , EventKeyboard::KeyCode::KEY_F4 }, - { GLFW_KEY_F5 , EventKeyboard::KeyCode::KEY_F5 }, - { GLFW_KEY_F6 , EventKeyboard::KeyCode::KEY_F6 }, - { GLFW_KEY_F7 , EventKeyboard::KeyCode::KEY_F7 }, - { GLFW_KEY_F8 , EventKeyboard::KeyCode::KEY_F8 }, - { GLFW_KEY_F9 , EventKeyboard::KeyCode::KEY_F9 }, - { GLFW_KEY_F10 , EventKeyboard::KeyCode::KEY_F10 }, - { GLFW_KEY_F11 , EventKeyboard::KeyCode::KEY_F11 }, - { GLFW_KEY_F12 , EventKeyboard::KeyCode::KEY_F12 }, - { GLFW_KEY_F13 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F14 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F15 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F16 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F17 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F18 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F19 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F20 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F21 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F22 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F23 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F24 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F25 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_KP_0 , EventKeyboard::KeyCode::KEY_0 }, - { GLFW_KEY_KP_1 , EventKeyboard::KeyCode::KEY_1 }, - { GLFW_KEY_KP_2 , EventKeyboard::KeyCode::KEY_2 }, - { GLFW_KEY_KP_3 , EventKeyboard::KeyCode::KEY_3 }, - { GLFW_KEY_KP_4 , EventKeyboard::KeyCode::KEY_4 }, - { GLFW_KEY_KP_5 , EventKeyboard::KeyCode::KEY_5 }, - { GLFW_KEY_KP_6 , EventKeyboard::KeyCode::KEY_6 }, - { GLFW_KEY_KP_7 , EventKeyboard::KeyCode::KEY_7 }, - { GLFW_KEY_KP_8 , EventKeyboard::KeyCode::KEY_8 }, - { GLFW_KEY_KP_9 , EventKeyboard::KeyCode::KEY_9 }, - { GLFW_KEY_KP_DECIMAL , EventKeyboard::KeyCode::KEY_PERIOD }, - { GLFW_KEY_KP_DIVIDE , EventKeyboard::KeyCode::KEY_KP_DIVIDE }, - { GLFW_KEY_KP_MULTIPLY , EventKeyboard::KeyCode::KEY_KP_MULTIPLY }, - { GLFW_KEY_KP_SUBTRACT , EventKeyboard::KeyCode::KEY_KP_MINUS }, - { GLFW_KEY_KP_ADD , EventKeyboard::KeyCode::KEY_KP_PLUS }, - { GLFW_KEY_KP_ENTER , EventKeyboard::KeyCode::KEY_KP_ENTER }, - { GLFW_KEY_KP_EQUAL , EventKeyboard::KeyCode::KEY_EQUAL }, - { GLFW_KEY_LEFT_SHIFT , EventKeyboard::KeyCode::KEY_SHIFT }, - { GLFW_KEY_LEFT_CONTROL , EventKeyboard::KeyCode::KEY_CTRL }, - { GLFW_KEY_LEFT_ALT , EventKeyboard::KeyCode::KEY_ALT }, - { GLFW_KEY_LEFT_SUPER , EventKeyboard::KeyCode::KEY_HYPER }, - { GLFW_KEY_RIGHT_SHIFT , EventKeyboard::KeyCode::KEY_SHIFT }, - { GLFW_KEY_RIGHT_CONTROL , EventKeyboard::KeyCode::KEY_CTRL }, - { GLFW_KEY_RIGHT_ALT , EventKeyboard::KeyCode::KEY_ALT }, - { GLFW_KEY_RIGHT_SUPER , EventKeyboard::KeyCode::KEY_HYPER }, - { GLFW_KEY_MENU , EventKeyboard::KeyCode::KEY_MENU }, - { GLFW_KEY_LAST , EventKeyboard::KeyCode::KEY_NONE } -}; - -//begin EGLViewEventHandler -class EGLViewEventHandler -{ -public: - static bool s_captured; - static float s_mouseX; - static float s_mouseY; - - static void OnGLFWError(int errorID, const char* errorDesc); - static void OnGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify); - static void OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y); - static void OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y); - static void OnGLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); - static void OnGLFWCharCallback(GLFWwindow* window, unsigned int character); - static void OnGLFWWindowPosCallback(GLFWwindow* windows, int x, int y); -}; - -bool EGLViewEventHandler::s_captured = false; -float EGLViewEventHandler::s_mouseX = 0; -float EGLViewEventHandler::s_mouseY = 0; - -void EGLViewEventHandler::OnGLFWError(int errorID, const char* errorDesc) -{ - CCLOGERROR("GLFWError #%d Happen, %s\n", errorID, errorDesc); -} - -void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify) -{ - EGLView* eglView = EGLView::getInstance(); - if(nullptr == eglView) return; - if(GLFW_MOUSE_BUTTON_LEFT == button) - { - if(GLFW_PRESS == action) - { - s_captured = true; - if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) - { - int id = 0; - eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); - } - } - else if(GLFW_RELEASE == action) - { - s_captured = false; - if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) - { - int id = 0; - eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); - } - } - } - - if(GLFW_PRESS == action) - { - EventMouse event(EventMouse::MouseEventType::MOUSE_DOWN); - event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); - event.setMouseButton(button); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); - } - else if(GLFW_RELEASE == action) - { - EventMouse event(EventMouse::MouseEventType::MOUSE_UP); - event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); - event.setMouseButton(button); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); - } -} - -void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) -{ - s_mouseX = (float)x; - s_mouseY = (float)y; - EGLView* eglView = EGLView::getInstance(); - if(nullptr == eglView) return; - - s_mouseX /= eglView->getFrameZoomFactor(); - s_mouseY /= eglView->getFrameZoomFactor(); - - if(s_captured) - { - if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) - { - int id = 0; - eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); - } - } - - EventMouse event(EventMouse::MouseEventType::MOUSE_MOVE); - //Because OpenGL use upper left as origin point, we need to revert the mouse y coordinate here - event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); -} - -void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y) -{ - EGLView* eglView = EGLView::getInstance(); - if(nullptr == eglView) return; - - EventMouse event(EventMouse::MouseEventType::MOUSE_SCROLL); - //Because OpenGL use upper left as origin point, we need to revert the mouse y coordinate here - event.setScrollData((float)x, -(float)y); - event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); -} - -void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) -{ - if (GLFW_REPEAT != action) - { - EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); - auto dispatcher = Director::getInstance()->getEventDispatcher(); - dispatcher->dispatchEvent(&event); - } -} - -void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character) -{ - IMEDispatcher::sharedDispatcher()->dispatchInsertText((const char*) &character, 1); -} - -void EGLViewEventHandler::OnGLFWWindowPosCallback(GLFWwindow *windows, int x, int y) -{ - if(Director::getInstance()) - { - Director::getInstance()->setViewport(); - } -} -//end EGLViewEventHandler - - -////////////////////////////////////////////////////////////////////////// -// impliment EGLView -////////////////////////////////////////////////////////////////////////// - -EGLView* EGLView::s_pEglView = nullptr; - -EGLView::EGLView() -: _captured(false) -, _supportTouch(false) -, _frameZoomFactor(1.0f) -, _mainWindow(nullptr) -{ - CCASSERT(nullptr == s_pEglView, "EGLView is singleton, Should be inited only one time\n"); - s_pEglView = this; - _viewName = "Cocos2dxWin32"; - glfwSetErrorCallback(EGLViewEventHandler::OnGLFWError); - glfwInit(); -} - -EGLView::~EGLView() -{ - glfwTerminate(); - s_pEglView = nullptr; -} - -bool EGLView::init(const char* viewName, float width, float height, float frameZoomFactor) -{ - if(nullptr != _mainWindow) return true; - - setViewName(viewName); - setFrameSize(width, height); - setFrameZoomFactor(frameZoomFactor); - - glfwWindowHint(GLFW_RESIZABLE,GL_FALSE); - _mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor, _screenSize.height * _frameZoomFactor, _viewName.c_str(), nullptr, nullptr); - glfwMakeContextCurrent(_mainWindow); - - glfwGetFramebufferSize(_mainWindow, &_frameBufferSize[0], &_frameBufferSize[1]); - - glfwSetMouseButtonCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseCallBack); - glfwSetCursorPosCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseMoveCallBack); - glfwSetScrollCallback(_mainWindow, EGLViewEventHandler::OnGLFWMouseScrollCallback); - glfwSetCharCallback(_mainWindow, EGLViewEventHandler::OnGLFWCharCallback); - glfwSetKeyCallback(_mainWindow, EGLViewEventHandler::OnGLFWKeyCallback); - glfwSetWindowPosCallback(_mainWindow, EGLViewEventHandler::OnGLFWWindowPosCallback); - - // check OpenGL version at first - const GLubyte* glVersion = glGetString(GL_VERSION); - CCLOG("OpenGL version = %s", glVersion); - - if ( atof((const char*)glVersion) < 1.5 ) - { - char strComplain[256] = {0}; - sprintf(strComplain, - "OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.", - glVersion); - MessageBox(strComplain, "OpenGL version too old"); - return false; - } - - GLenum GlewInitResult = glewInit(); - if (GLEW_OK != GlewInitResult) - { - MessageBox((char *)glewGetErrorString(GlewInitResult), "OpenGL error"); - return false; - } - - if (GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader) - { - log("Ready for GLSL"); - } - else - { - log("Not totally ready :("); - } - - if (glewIsSupported("GL_VERSION_2_0")) - { - log("Ready for OpenGL 2.0"); - } - else - { - log("OpenGL 2.0 not supported"); - } - -// if(glew_dynamic_binding() == false) -// { -// MessageBox("No OpenGL framebuffer support. Please upgrade the driver of your video card.", "OpenGL error"); -// return false; -// } -// - // Enable point size by default on windows. - glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); - - return true; -} - -bool EGLView::isOpenGLReady() -{ - return nullptr != _mainWindow; -} - -void EGLView::end() -{ - if(_mainWindow) - glfwSetWindowShouldClose(_mainWindow,1); -} - -void EGLView::swapBuffers() -{ - if(_mainWindow) - glfwSwapBuffers(_mainWindow); -} - -bool EGLView::windowShouldClose() -{ - if(_mainWindow) - return glfwWindowShouldClose(_mainWindow); - else - return true; -} - -void EGLView::pollEvents() -{ - glfwPollEvents(); -} - -void EGLView::setIMEKeyboardState(bool /*bOpen*/) -{ - -} - -void EGLView::setFrameZoomFactor(float fZoomFactor) -{ - _frameZoomFactor = fZoomFactor; - Director::getInstance()->setProjection(Director::getInstance()->getProjection()); -} - -float EGLView::getFrameZoomFactor() -{ - return _frameZoomFactor; -} - -void EGLView::setFrameSize(float width, float height) -{ - EGLViewProtocol::setFrameSize(width, height); -} - -void EGLView::setViewPortInPoints(float x , float y , float w , float h) -{ - float frameZoomFactorX = _frameBufferSize[0]/_screenSize.width; - float frameZoomFactorY = _frameBufferSize[1]/_screenSize.height; - glViewport((GLint)(x * _scaleX * frameZoomFactorX + _viewPortRect.origin.x * frameZoomFactorX), - (GLint)(y * _scaleY * frameZoomFactorY + _viewPortRect.origin.y * frameZoomFactorY), - (GLsizei)(w * _scaleX * frameZoomFactorX), - (GLsizei)(h * _scaleY * frameZoomFactorY)); -} - -void EGLView::setScissorInPoints(float x , float y , float w , float h) -{ - float frameZoomFactorX = _frameBufferSize[0]/_screenSize.width; - float frameZoomFactorY = _frameBufferSize[1]/_screenSize.height; - glScissor((GLint)(x * _scaleX * frameZoomFactorX + _viewPortRect.origin.x * frameZoomFactorX), - (GLint)(y * _scaleY * frameZoomFactorY + _viewPortRect.origin.y * frameZoomFactorY), - (GLsizei)(w * _scaleX * frameZoomFactorX), - (GLsizei)(h * _scaleY * frameZoomFactorY)); -} - -EGLView* EGLView::getInstance() -{ - CCASSERT(nullptr != s_pEglView, "EGL singleton should not be null"); - return s_pEglView; -} - -// XXX: deprecated -EGLView* EGLView::sharedOpenGLView() -{ - return EGLView::getInstance(); -} - -NS_CC_END diff --git a/cocos/2d/platform/linux/CCEGLView.h b/cocos/2d/platform/linux/CCEGLView.h deleted file mode 100644 index ca7949f1fb..0000000000 --- a/cocos/2d/platform/linux/CCEGLView.h +++ /dev/null @@ -1,103 +0,0 @@ -/**************************************************************************** -Copyright (c) 2011 Laschweinski -Copyright (c) 2013-2014 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. -****************************************************************************/ - -#ifndef EGLVIEW_H_ -#define EGLVIEW_H_ - -#include "platform/CCCommon.h" -#include "CCGeometry.h" -#include "platform/CCEGLViewProtocol.h" -#include "glfw3.h" -#include - -bool initExtensions(); - -NS_CC_BEGIN - -class CC_DLL EGLView : public EGLViewProtocol -{ -public: - /** - * @js ctor - */ - EGLView(); - /** - * @js NA - * @lua NA - */ - virtual ~EGLView(); - - /* override functions */ - virtual bool isOpenGLReady(); - virtual void end(); - virtual void swapBuffers(); - virtual void setFrameSize(float width, float height); - virtual void setIMEKeyboardState(bool bOpen); - /* - *frameZoomFactor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop. - */ - bool init(const char* viewName, float width, float height, float frameZoomFactor = 1.0f); -public: - - //void resize(int width, int height); - float getFrameZoomFactor(); - //void centerWindow(); - - - virtual void setViewPortInPoints(float x , float y , float w , float h); - virtual void setScissorInPoints(float x , float y , float w , float h); - - // static function - /** - @brief get the shared main open gl window - */ - static EGLView* getInstance(); - - /** @deprecated Use getInstance() instead */ - CC_DEPRECATED_ATTRIBUTE static EGLView* sharedOpenGLView(); -protected: - /* - * Set zoom factor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop. - */ - void setFrameZoomFactor(float fZoomFactor); -private: - bool _captured; - bool _supportTouch; - - int _frameBufferSize[2]; - float _frameZoomFactor; - static EGLView* s_pEglView; -public: - bool windowShouldClose(); - - void pollEvents(); - GLFWwindow* getWindow() const { return _mainWindow; } -private: - GLFWwindow* _mainWindow; -}; - -NS_CC_END - -#endif /* EGLVIEW_H_ */ diff --git a/cocos/2d/platform/linux/CCFileUtilsLinux.cpp b/cocos/2d/platform/linux/CCFileUtilsLinux.cpp index 2d86c1ec87..7edfad170c 100644 --- a/cocos/2d/platform/linux/CCFileUtilsLinux.cpp +++ b/cocos/2d/platform/linux/CCFileUtilsLinux.cpp @@ -22,6 +22,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #include "CCFileUtilsLinux.h" #include "platform/CCCommon.h" #include "ccMacros.h" @@ -114,3 +118,5 @@ bool FileUtilsLinux::isFileExist(const std::string& strFilePath) const } NS_CC_END + +#endif CC_TARGET_PLATFORM == CC_PLATFORM_LINUX diff --git a/cocos/2d/platform/linux/CCFileUtilsLinux.h b/cocos/2d/platform/linux/CCFileUtilsLinux.h index 20742b02f3..9a574edf6c 100644 --- a/cocos/2d/platform/linux/CCFileUtilsLinux.h +++ b/cocos/2d/platform/linux/CCFileUtilsLinux.h @@ -25,6 +25,9 @@ THE SOFTWARE. #ifndef __CC_FILEUTILS_LINUX_H__ #define __CC_FILEUTILS_LINUX_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #include "platform/CCFileUtils.h" #include "CCPlatformMacros.h" #include "ccTypes.h" @@ -56,5 +59,6 @@ public: NS_CC_END -#endif // __CC_FILEUTILS_LINUX_H__ +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX +#endif // __CC_FILEUTILS_LINUX_H__ diff --git a/cocos/2d/platform/linux/CCGL.h b/cocos/2d/platform/linux/CCGL.h index 63b4b91b4a..f85e7b4640 100644 --- a/cocos/2d/platform/linux/CCGL.h +++ b/cocos/2d/platform/linux/CCGL.h @@ -25,8 +25,13 @@ THE SOFTWARE. #ifndef __CCGL_H__ #define __CCGL_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #include "GL/glew.h" #define CC_GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8 +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #endif // __CCGL_H__ diff --git a/cocos/2d/platform/linux/CCImage.cpp b/cocos/2d/platform/linux/CCImage.cpp index 45602638b5..8add509d35 100644 --- a/cocos/2d/platform/linux/CCImage.cpp +++ b/cocos/2d/platform/linux/CCImage.cpp @@ -22,6 +22,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #include #include @@ -450,23 +454,21 @@ static BitmapDC& sharedBitmapDC() } bool Image::initWithString( - const char * pText, - int nWidth/* = 0*/, - int nHeight/* = 0*/, - TextAlign eAlignMask/* = kAlignCenter*/, - const char * pFontName/* = nil*/, - int nSize/* = 0*/) + const char * text, + int width/* = 0*/, + int height/* = 0*/, + TextAlign alignMask/* = kAlignCenter*/, + const char * fontName/* = nil*/, + int size/* = 0*/) { - bool bRet = false; + bool ret = false; do - { - CC_BREAK_IF(! pText); + { + CC_BREAK_IF(!text || 0 == strlen(text)); BitmapDC &dc = sharedBitmapDC(); - //const char* pFullFontName = FileUtils::getInstance()->fullPathFromRelativePath(pFontName); - - CC_BREAK_IF(! dc.getBitmap(pText, nWidth, nHeight, eAlignMask, pFontName, nSize)); + CC_BREAK_IF(! dc.getBitmap(text, width, height, alignMask, fontName, size)); // assign the dc._data to _data in order to save time _data = dc._data; @@ -478,13 +480,15 @@ bool Image::initWithString( _preMulti = true; _dataLen = _width * _height * 4; - bRet = true; + ret = true; dc.reset(); }while (0); //do nothing - return bRet; + return ret; } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX diff --git a/cocos/2d/platform/linux/CCPlatformDefine.h b/cocos/2d/platform/linux/CCPlatformDefine.h index 5d2a56ff31..77f17916da 100644 --- a/cocos/2d/platform/linux/CCPlatformDefine.h +++ b/cocos/2d/platform/linux/CCPlatformDefine.h @@ -22,9 +22,13 @@ 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 __CCPLATFORMDEFINE_H__ #define __CCPLATFORMDEFINE_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #include #if defined(_USRDLL) @@ -47,5 +51,6 @@ THE SOFTWARE. #endif +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX #endif /* __CCPLATFORMDEFINE_H__*/ diff --git a/cocos/2d/platform/linux/CCStdC.cpp b/cocos/2d/platform/linux/CCStdC.cpp index 9f47e9e17a..b72f1966b0 100644 --- a/cocos/2d/platform/linux/CCStdC.cpp +++ b/cocos/2d/platform/linux/CCStdC.cpp @@ -23,6 +23,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #include "CCStdC.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) @@ -65,5 +68,6 @@ int CC_DLL gettimeofday(struct timeval * val, struct timezone *) return 0; } - #endif // CC_PLATFORM_WIN32 + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX diff --git a/cocos/2d/platform/linux/CCStdC.h b/cocos/2d/platform/linux/CCStdC.h index 5f3e24e8c0..4941bbe66b 100644 --- a/cocos/2d/platform/linux/CCStdC.h +++ b/cocos/2d/platform/linux/CCStdC.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef __CC_STD_C_H__ #define __CC_STD_C_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #include "CCPlatformMacros.h" #include @@ -52,4 +55,6 @@ THE SOFTWARE. #define cosf cos #define sinf sin +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX + #endif // __CC_STD_C_H__ diff --git a/cocos/2d/platform/mac/CCApplication.h b/cocos/2d/platform/mac/CCApplication.h index 5a4c5bd8a5..ed39ee0f35 100644 --- a/cocos/2d/platform/mac/CCApplication.h +++ b/cocos/2d/platform/mac/CCApplication.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef __CC_APPLICATION_MAC_H__ #define __CC_APPLICATION_MAC_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_MAC + #include "platform/CCCommon.h" #include "platform/CCApplicationProtocol.h" #include @@ -52,7 +55,7 @@ public: virtual void setAnimationInterval(double interval); /** - @brief Get status bar rectangle in EGLView window. + @brief Get status bar rectangle in GLView window. */ /** @@ -107,4 +110,6 @@ protected: NS_CC_END +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC + #endif // end of __CC_APPLICATION_MAC_H__; diff --git a/cocos/2d/platform/mac/CCApplication.mm b/cocos/2d/platform/mac/CCApplication.mm index 0ece7367f4..99ac7613a6 100644 --- a/cocos/2d/platform/mac/CCApplication.mm +++ b/cocos/2d/platform/mac/CCApplication.mm @@ -23,6 +23,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_MAC + #import "CCApplication.h" #import #include @@ -30,7 +33,7 @@ THE SOFTWARE. #include "CCGeometry.h" #include "CCDirector.h" #import "CCDirectorCaller.h" -#include "CCEGLView.h" +#include "CCGLView.h" NS_CC_BEGIN @@ -54,12 +57,12 @@ int Application::run() { return 0; } - EGLView* pMainWnd = EGLView::getInstance(); + GLView* glview = Director::getInstance()->getOpenGLView(); - while (!pMainWnd->windowShouldClose()) + while (!glview->windowShouldClose()) { Director::getInstance()->mainLoop(); - pMainWnd->pollEvents(); + glview->pollEvents(); } /* Only work on Desktop @@ -130,6 +133,9 @@ LanguageType Application::getCurrentLanguage() else if ([languageCode isEqualToString:@"es"]){ ret = LanguageType::SPANISH; } + else if ([languageCode isEqualToString:@"nl"]){ + ret = LanguageType::DUTCH; + } else if ([languageCode isEqualToString:@"ru"]){ ret = LanguageType::RUSSIAN; } @@ -189,3 +195,5 @@ const std::string& Application::getStartupScriptFilename(void) } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC diff --git a/cocos/2d/platform/mac/CCCommon.mm b/cocos/2d/platform/mac/CCCommon.mm index 52e4fb7beb..5ff43269cd 100644 --- a/cocos/2d/platform/mac/CCCommon.mm +++ b/cocos/2d/platform/mac/CCCommon.mm @@ -22,14 +22,22 @@ 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 + +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_MAC #include "platform/CCCommon.h" +#include "CCDirector.h" +#include "CCGLView.h" + +#define GLFW_EXPOSE_NATIVE_NSGL +#define GLFW_EXPOSE_NATIVE_COCOA +#include "glfw3native.h" + #include #include -#import "EAGLView.h" - +#include NS_CC_BEGIN @@ -50,7 +58,8 @@ void MessageBox(const char * msg, const char * title) [alert setInformativeText:tmpTitle]; [alert setAlertStyle:NSWarningAlertStyle]; - NSWindow *window = [[CCEAGLView sharedEGLView] window]; + GLView* glview = Director::getInstance()->getOpenGLView(); + id window = glfwGetCocoaWindow(glview->getWindow()); [alert beginSheetModalForWindow:window modalDelegate:[window delegate] didEndSelector:nil @@ -58,3 +67,6 @@ void MessageBox(const char * msg, const char * title) } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC + diff --git a/cocos/2d/platform/mac/CCDevice.mm b/cocos/2d/platform/mac/CCDevice.cpp similarity index 92% rename from cocos/2d/platform/mac/CCDevice.mm rename to cocos/2d/platform/mac/CCDevice.cpp index 4814ee8768..ec90cc36b6 100644 --- a/cocos/2d/platform/mac/CCDevice.mm +++ b/cocos/2d/platform/mac/CCDevice.cpp @@ -22,6 +22,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_MAC + #include "platform/CCDevice.h" NS_CC_BEGIN @@ -43,3 +47,5 @@ void Device::setAccelerometerInterval(float interval) } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC diff --git a/cocos/2d/platform/mac/CCDirectorCaller.h b/cocos/2d/platform/mac/CCDirectorCaller.h index 87117073cb..7e7d9070c3 100644 --- a/cocos/2d/platform/mac/CCDirectorCaller.h +++ b/cocos/2d/platform/mac/CCDirectorCaller.h @@ -22,6 +22,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_MAC + #import #import @@ -38,3 +42,5 @@ THE SOFTWARE. +(id) sharedDirectorCaller; @end + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC diff --git a/cocos/2d/platform/mac/CCDirectorCaller.mm b/cocos/2d/platform/mac/CCDirectorCaller.mm index f371dae133..ea32f5b6b2 100644 --- a/cocos/2d/platform/mac/CCDirectorCaller.mm +++ b/cocos/2d/platform/mac/CCDirectorCaller.mm @@ -22,13 +22,17 @@ 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. ****************************************************************************/ -#import + +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_MAC + #import "CCDirectorCaller.h" -#import "CCDirector.h" -#import "EAGLView.h" -#import "CCEventDispatcherMac.h" +#include "CCDirector.h" #include "CCAutoreleasePool.h" +#import +#import + static id s_sharedDirectorCaller; @interface NSObject(CADisplayLink) @@ -81,8 +85,7 @@ static id s_sharedDirectorCaller; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; cocos2d::Director::getInstance()->drawScene(); - cocos2d::PoolManager::sharedPoolManager()->pop(); - [[CCEventDispatcher sharedDispatcher] dispatchQueuedEvents]; + cocos2d::PoolManager::getInstance()->getCurrentPool()->clear(); [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:nil]; @@ -115,21 +118,9 @@ static CVReturn MyDisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTime // All we do here is tell the display it needs a refresh NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - // get the opengl view - CCEAGLView *openGLView = [CCEAGLView sharedEGLView]; - [openGLView lockOpenGLContext]; - // run the main cocos2d loop cocos2d::Director::getInstance()->mainLoop(); - // flush buffer (this line is very important!) - [[openGLView openGLContext] flushBuffer]; - - [openGLView unlockOpenGLContext]; - - // send any queued events - [[CCEventDispatcher sharedDispatcher] dispatchQueuedEvents]; - [pool release]; } @@ -212,3 +203,5 @@ static CVReturn MyDisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTime } @end + +#endif //s CC_TARGET_PLATFORM == CC_PLATFORM_MAC diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.mm deleted file mode 100644 index a3635be8ed..0000000000 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ /dev/null @@ -1,521 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2014 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. -****************************************************************************/ - -#include "CCEGLView.h" - -#include - -#include "EAGLView.h" -#include "CCDirector.h" -#include "CCSet.h" -#include "CCTouch.h" -#include "CCEventDispatcher.h" -#include "CCEventKeyboard.h" -#include "CCEventMouse.h" -#include "CCIMEDispatcher.h" - -NS_CC_BEGIN - - -static std::unordered_map g_keyCodeMap = { - /* The unknown key */ - { GLFW_KEY_UNKNOWN , EventKeyboard::KeyCode::KEY_NONE }, - - /* Printable keys */ - { GLFW_KEY_SPACE , EventKeyboard::KeyCode::KEY_SPACE }, - { GLFW_KEY_APOSTROPHE , EventKeyboard::KeyCode::KEY_APOSTROPHE }, - { GLFW_KEY_COMMA , EventKeyboard::KeyCode::KEY_COMMA }, - { GLFW_KEY_MINUS , EventKeyboard::KeyCode::KEY_MINUS }, - { GLFW_KEY_PERIOD , EventKeyboard::KeyCode::KEY_PERIOD }, - { GLFW_KEY_SLASH , EventKeyboard::KeyCode::KEY_SLASH }, - { GLFW_KEY_0 , EventKeyboard::KeyCode::KEY_0 }, - { GLFW_KEY_1 , EventKeyboard::KeyCode::KEY_1 }, - { GLFW_KEY_2 , EventKeyboard::KeyCode::KEY_2 }, - { GLFW_KEY_3 , EventKeyboard::KeyCode::KEY_3 }, - { GLFW_KEY_4 , EventKeyboard::KeyCode::KEY_4 }, - { GLFW_KEY_5 , EventKeyboard::KeyCode::KEY_5 }, - { GLFW_KEY_6 , EventKeyboard::KeyCode::KEY_6 }, - { GLFW_KEY_7 , EventKeyboard::KeyCode::KEY_7 }, - { GLFW_KEY_8 , EventKeyboard::KeyCode::KEY_8 }, - { GLFW_KEY_9 , EventKeyboard::KeyCode::KEY_9 }, - { GLFW_KEY_SEMICOLON , EventKeyboard::KeyCode::KEY_SEMICOLON }, - { GLFW_KEY_EQUAL , EventKeyboard::KeyCode::KEY_EQUAL }, - { GLFW_KEY_A , EventKeyboard::KeyCode::KEY_A }, - { GLFW_KEY_B , EventKeyboard::KeyCode::KEY_B }, - { GLFW_KEY_C , EventKeyboard::KeyCode::KEY_C }, - { GLFW_KEY_D , EventKeyboard::KeyCode::KEY_D }, - { GLFW_KEY_E , EventKeyboard::KeyCode::KEY_E }, - { GLFW_KEY_F , EventKeyboard::KeyCode::KEY_F }, - { GLFW_KEY_G , EventKeyboard::KeyCode::KEY_G }, - { GLFW_KEY_H , EventKeyboard::KeyCode::KEY_H }, - { GLFW_KEY_I , EventKeyboard::KeyCode::KEY_I }, - { GLFW_KEY_J , EventKeyboard::KeyCode::KEY_J }, - { GLFW_KEY_K , EventKeyboard::KeyCode::KEY_K }, - { GLFW_KEY_L , EventKeyboard::KeyCode::KEY_L }, - { GLFW_KEY_M , EventKeyboard::KeyCode::KEY_M }, - { GLFW_KEY_N , EventKeyboard::KeyCode::KEY_N }, - { GLFW_KEY_O , EventKeyboard::KeyCode::KEY_O }, - { GLFW_KEY_P , EventKeyboard::KeyCode::KEY_P }, - { GLFW_KEY_Q , EventKeyboard::KeyCode::KEY_Q }, - { GLFW_KEY_R , EventKeyboard::KeyCode::KEY_R }, - { GLFW_KEY_S , EventKeyboard::KeyCode::KEY_S }, - { GLFW_KEY_T , EventKeyboard::KeyCode::KEY_T }, - { GLFW_KEY_U , EventKeyboard::KeyCode::KEY_U }, - { GLFW_KEY_V , EventKeyboard::KeyCode::KEY_V }, - { GLFW_KEY_W , EventKeyboard::KeyCode::KEY_W }, - { GLFW_KEY_X , EventKeyboard::KeyCode::KEY_X }, - { GLFW_KEY_Y , EventKeyboard::KeyCode::KEY_Y }, - { GLFW_KEY_Z , EventKeyboard::KeyCode::KEY_Z }, - { GLFW_KEY_LEFT_BRACKET , EventKeyboard::KeyCode::KEY_LEFT_BRACKET }, - { GLFW_KEY_BACKSLASH , EventKeyboard::KeyCode::KEY_BACK_SLASH }, - { GLFW_KEY_RIGHT_BRACKET , EventKeyboard::KeyCode::KEY_RIGHT_BRACKET }, - { GLFW_KEY_GRAVE_ACCENT , EventKeyboard::KeyCode::KEY_GRAVE }, - { GLFW_KEY_WORLD_1 , EventKeyboard::KeyCode::KEY_GRAVE }, - { GLFW_KEY_WORLD_2 , EventKeyboard::KeyCode::KEY_NONE }, - - /* Function keys */ - { GLFW_KEY_ESCAPE , EventKeyboard::KeyCode::KEY_ESCAPE }, - { GLFW_KEY_ENTER , EventKeyboard::KeyCode::KEY_KP_ENTER }, - { GLFW_KEY_TAB , EventKeyboard::KeyCode::KEY_TAB }, - { GLFW_KEY_BACKSPACE , EventKeyboard::KeyCode::KEY_BACKSPACE }, - { GLFW_KEY_INSERT , EventKeyboard::KeyCode::KEY_INSERT }, - { GLFW_KEY_DELETE , EventKeyboard::KeyCode::KEY_DELETE }, - { GLFW_KEY_RIGHT , EventKeyboard::KeyCode::KEY_RIGHT_ARROW }, - { GLFW_KEY_LEFT , EventKeyboard::KeyCode::KEY_LEFT_ARROW }, - { GLFW_KEY_DOWN , EventKeyboard::KeyCode::KEY_DOWN_ARROW }, - { GLFW_KEY_UP , EventKeyboard::KeyCode::KEY_UP_ARROW }, - { GLFW_KEY_PAGE_UP , EventKeyboard::KeyCode::KEY_KP_PG_UP }, - { GLFW_KEY_PAGE_DOWN , EventKeyboard::KeyCode::KEY_KP_PG_DOWN }, - { GLFW_KEY_HOME , EventKeyboard::KeyCode::KEY_KP_HOME }, - { GLFW_KEY_END , EventKeyboard::KeyCode::KEY_END }, - { GLFW_KEY_CAPS_LOCK , EventKeyboard::KeyCode::KEY_CAPS_LOCK }, - { GLFW_KEY_SCROLL_LOCK , EventKeyboard::KeyCode::KEY_SCROLL_LOCK }, - { GLFW_KEY_NUM_LOCK , EventKeyboard::KeyCode::KEY_NUM_LOCK }, - { GLFW_KEY_PRINT_SCREEN , EventKeyboard::KeyCode::KEY_PRINT }, - { GLFW_KEY_PAUSE , EventKeyboard::KeyCode::KEY_PAUSE }, - { GLFW_KEY_F1 , EventKeyboard::KeyCode::KEY_F1 }, - { GLFW_KEY_F2 , EventKeyboard::KeyCode::KEY_F2 }, - { GLFW_KEY_F3 , EventKeyboard::KeyCode::KEY_F3 }, - { GLFW_KEY_F4 , EventKeyboard::KeyCode::KEY_F4 }, - { GLFW_KEY_F5 , EventKeyboard::KeyCode::KEY_F5 }, - { GLFW_KEY_F6 , EventKeyboard::KeyCode::KEY_F6 }, - { GLFW_KEY_F7 , EventKeyboard::KeyCode::KEY_F7 }, - { GLFW_KEY_F8 , EventKeyboard::KeyCode::KEY_F8 }, - { GLFW_KEY_F9 , EventKeyboard::KeyCode::KEY_F9 }, - { GLFW_KEY_F10 , EventKeyboard::KeyCode::KEY_F10 }, - { GLFW_KEY_F11 , EventKeyboard::KeyCode::KEY_F11 }, - { GLFW_KEY_F12 , EventKeyboard::KeyCode::KEY_F12 }, - { GLFW_KEY_F13 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F14 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F15 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F16 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F17 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F18 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F19 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F20 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F21 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F22 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F23 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F24 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_F25 , EventKeyboard::KeyCode::KEY_NONE }, - { GLFW_KEY_KP_0 , EventKeyboard::KeyCode::KEY_0 }, - { GLFW_KEY_KP_1 , EventKeyboard::KeyCode::KEY_1 }, - { GLFW_KEY_KP_2 , EventKeyboard::KeyCode::KEY_2 }, - { GLFW_KEY_KP_3 , EventKeyboard::KeyCode::KEY_3 }, - { GLFW_KEY_KP_4 , EventKeyboard::KeyCode::KEY_4 }, - { GLFW_KEY_KP_5 , EventKeyboard::KeyCode::KEY_5 }, - { GLFW_KEY_KP_6 , EventKeyboard::KeyCode::KEY_6 }, - { GLFW_KEY_KP_7 , EventKeyboard::KeyCode::KEY_7 }, - { GLFW_KEY_KP_8 , EventKeyboard::KeyCode::KEY_8 }, - { GLFW_KEY_KP_9 , EventKeyboard::KeyCode::KEY_9 }, - { GLFW_KEY_KP_DECIMAL , EventKeyboard::KeyCode::KEY_PERIOD }, - { GLFW_KEY_KP_DIVIDE , EventKeyboard::KeyCode::KEY_KP_DIVIDE }, - { GLFW_KEY_KP_MULTIPLY , EventKeyboard::KeyCode::KEY_KP_MULTIPLY }, - { GLFW_KEY_KP_SUBTRACT , EventKeyboard::KeyCode::KEY_KP_MINUS }, - { GLFW_KEY_KP_ADD , EventKeyboard::KeyCode::KEY_KP_PLUS }, - { GLFW_KEY_KP_ENTER , EventKeyboard::KeyCode::KEY_KP_ENTER }, - { GLFW_KEY_KP_EQUAL , EventKeyboard::KeyCode::KEY_EQUAL }, - { GLFW_KEY_LEFT_SHIFT , EventKeyboard::KeyCode::KEY_SHIFT }, - { GLFW_KEY_LEFT_CONTROL , EventKeyboard::KeyCode::KEY_CTRL }, - { GLFW_KEY_LEFT_ALT , EventKeyboard::KeyCode::KEY_ALT }, - { GLFW_KEY_LEFT_SUPER , EventKeyboard::KeyCode::KEY_HYPER }, - { GLFW_KEY_RIGHT_SHIFT , EventKeyboard::KeyCode::KEY_SHIFT }, - { GLFW_KEY_RIGHT_CONTROL , EventKeyboard::KeyCode::KEY_CTRL }, - { GLFW_KEY_RIGHT_ALT , EventKeyboard::KeyCode::KEY_ALT }, - { GLFW_KEY_RIGHT_SUPER , EventKeyboard::KeyCode::KEY_HYPER }, - { GLFW_KEY_MENU , EventKeyboard::KeyCode::KEY_MENU }, - { GLFW_KEY_LAST , EventKeyboard::KeyCode::KEY_NONE } -}; - - -//begin EGLViewEventHandler -class EGLViewEventHandler -{ -public: - static bool s_captured; - static float s_mouseX; - static float s_mouseY; - - static void onGLFWError(int errorID, const char* errorDesc); - static void onGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify); - static void onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y); - static void onGLFWMouseScrollCallback(GLFWwindow* window, double x, double y); - static void onGLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); - static void onGLFWCharCallback(GLFWwindow* window, unsigned int character); - static void onGLFWWindowPosCallback(GLFWwindow* windows, int x, int y); - static void onGLFWframebuffersize(GLFWwindow* window, int w, int h); -}; - -bool EGLViewEventHandler::s_captured = false; -float EGLViewEventHandler::s_mouseX = 0; -float EGLViewEventHandler::s_mouseY = 0; - -void EGLViewEventHandler::onGLFWError(int errorID, const char* errorDesc) -{ - CCLOGERROR("GLFWError #%d Happen, %s\n", errorID, errorDesc); -} - -void EGLViewEventHandler::onGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify) -{ - EGLView* eglView = EGLView::getInstance(); - if(nullptr == eglView) return; - if(GLFW_MOUSE_BUTTON_LEFT == button) - { - if(GLFW_PRESS == action) - { - s_captured = true; - if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) - { - int id = 0; - eglView->handleTouchesBegin(1, &id, &s_mouseX, &s_mouseY); - } - } - else if(GLFW_RELEASE == action) - { - s_captured = false; - if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,s_mouseY))) - { - int id = 0; - eglView->handleTouchesEnd(1, &id, &s_mouseX, &s_mouseY); - } - } - } - - if(GLFW_PRESS == action) - { - EventMouse event(EventMouse::MouseEventType::MOUSE_DOWN); - //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here - event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); - event.setMouseButton(button); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); - } - else if(GLFW_RELEASE == action) - { - EventMouse event(EventMouse::MouseEventType::MOUSE_UP); - //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here - event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); - event.setMouseButton(button); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); - } -} - -void EGLViewEventHandler::onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) -{ - EGLView* eglView = EGLView::getInstance(); - if(nullptr == eglView) return; - - if (eglView->isRetina()) { - x *= 2; - y *= 2; - } - - s_mouseX = (float)x; - s_mouseY = (float)y; - - s_mouseX /= eglView->getFrameZoomFactor(); - s_mouseY /= eglView->getFrameZoomFactor(); - - if(s_captured) - { - if (eglView->getViewPortRect().equals(Rect::ZERO) || eglView->getViewPortRect().containsPoint(Point(s_mouseX,eglView->getFrameSize().height - s_mouseY))) - { - int id = 0; - eglView->handleTouchesMove(1, &id, &s_mouseX, &s_mouseY); - } - } - - EventMouse event(EventMouse::MouseEventType::MOUSE_MOVE); - //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here - event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); -} - -void EGLViewEventHandler::onGLFWMouseScrollCallback(GLFWwindow* window, double x, double y) -{ - EGLView* eglView = EGLView::getInstance(); - if(nullptr == eglView) return; - - EventMouse event(EventMouse::MouseEventType::MOUSE_SCROLL); - //Because OpenGL and cocos2d-x uses different Y axis, we need to convert the coordinate here - event.setScrollData((float)x, -(float)y); - event.setCursorPosition(s_mouseX, eglView->getViewPortRect().size.height - s_mouseY); - Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); -} - -void EGLViewEventHandler::onGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) -{ - if (GLFW_REPEAT != action) - { - EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); - auto dispatcher = Director::getInstance()->getEventDispatcher(); - dispatcher->dispatchEvent(&event); - } -} - -void EGLViewEventHandler::onGLFWCharCallback(GLFWwindow *window, unsigned int character) -{ - IMEDispatcher::sharedDispatcher()->dispatchInsertText((const char*) &character, 1); -} - -void EGLViewEventHandler::onGLFWWindowPosCallback(GLFWwindow *windows, int x, int y) -{ - Director::getInstance()->setViewport(); -} - -void EGLViewEventHandler::onGLFWframebuffersize(GLFWwindow* window, int w, int h) -{ - auto view = EGLView::getInstance(); - - float frameSizeW = view->getFrameSize().width; - float frameSizeH = view->getFrameSize().height; - float factorX = frameSizeW / w * view->getFrameZoomFactor(); - float factorY = frameSizeH / h * view->getFrameZoomFactor();; - - if (fabs(factorX - 0.5f) < FLT_EPSILON && fabs(factorY - 0.5f) < FLT_EPSILON ) - { - view->_isRetina = true; - view->setFrameZoomFactor(2.0f * view->getFrameZoomFactor()); - glfwSetWindowSize(window, static_cast(frameSizeW * 0.5f * view->getFrameZoomFactor()) , static_cast(frameSizeH * 0.5f * view->getFrameZoomFactor())); - } - else if(fabs(factorX - 2.0f) < FLT_EPSILON && fabs(factorY - 2.0f) < FLT_EPSILON) - { - view->_isRetina = false; - view->setFrameZoomFactor(0.5f * view->getFrameZoomFactor()); - glfwSetWindowSize(window, static_cast(frameSizeW * view->getFrameZoomFactor()), static_cast(frameSizeH * view->getFrameZoomFactor())); - } -} - - -//end EGLViewEventHandler - - -////////////////////////////////////////////////////////////////////////// -// impliment EGLView -////////////////////////////////////////////////////////////////////////// - -EGLView* EGLView::s_pEglView = nullptr; - -EGLView::EGLView() -: _captured(false) -, _frameZoomFactor(1.0f) -, _supportTouch(false) -, _isRetina(false) -, _mainWindow(nullptr) -{ - CCASSERT(nullptr == s_pEglView, "EGLView is singleton, Should be inited only one time\n"); - _viewName = "cocos2dx"; - s_pEglView = this; - glfwSetErrorCallback(EGLViewEventHandler::onGLFWError); - glfwInit(); -} - -EGLView::~EGLView() -{ - CCLOGINFO("deallocing EGLView: %p", this); - glfwTerminate(); - s_pEglView = nullptr; -} - -bool EGLView::init(const std::string& viewName, float width, float height, float frameZoomFactor) -{ - if(nullptr != _mainWindow) return true; - - setViewName(viewName); - setFrameSize(width, height); - setFrameZoomFactor(frameZoomFactor); - - glfwWindowHint(GLFW_RESIZABLE,GL_FALSE); - _mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor, _screenSize.height * _frameZoomFactor, _viewName.c_str(), nullptr, nullptr); - glfwMakeContextCurrent(_mainWindow); - - int w, h; - glfwGetWindowSize(_mainWindow, &w, &h); - int frameBufferW, frameBufferH; - glfwGetFramebufferSize(_mainWindow, &frameBufferW, &frameBufferH); - - if (frameBufferW == 2 * w && frameBufferH == 2 * h) - { - _isRetina = true; - setFrameZoomFactor(frameZoomFactor * 2); - glfwSetWindowSize(_mainWindow, width/2 * _frameZoomFactor, height/2 * _frameZoomFactor); - } - - glfwSetMouseButtonCallback(_mainWindow,EGLViewEventHandler::onGLFWMouseCallBack); - glfwSetCursorPosCallback(_mainWindow,EGLViewEventHandler::onGLFWMouseMoveCallBack); - glfwSetScrollCallback(_mainWindow, EGLViewEventHandler::onGLFWMouseScrollCallback); - glfwSetCharCallback(_mainWindow, EGLViewEventHandler::onGLFWCharCallback); - glfwSetKeyCallback(_mainWindow, EGLViewEventHandler::onGLFWKeyCallback); - glfwSetWindowPosCallback(_mainWindow, EGLViewEventHandler::onGLFWWindowPosCallback); - glfwSetFramebufferSizeCallback(_mainWindow, EGLViewEventHandler::onGLFWframebuffersize); - // check OpenGL version at first - const GLubyte* glVersion = glGetString(GL_VERSION); - - if ( atof((const char*)glVersion) < 1.5 ) - { - char strComplain[256] = {0}; - sprintf(strComplain, - "OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.", - glVersion); - MessageBox(strComplain, "OpenGL version too old"); - return false; - } -// -// GLenum GlewInitResult = glewInit(); -// if (GLEW_OK != GlewInitResult) -// { -// MessageBox((char *)glewGetErrorString(GlewInitResult), "OpenGL error"); -// return false; -// } -// -// if (GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader) -// { -// log("Ready for GLSL"); -// } -// else -// { -// log("Not totally ready :("); -// } -// -// if (glewIsSupported("GL_VERSION_2_0")) -// { -// log("Ready for OpenGL 2.0"); -// } -// else -// { -// log("OpenGL 2.0 not supported"); -// } -// -// if(glew_dynamic_binding() == false) -// { -// MessageBox("No OpenGL framebuffer support. Please upgrade the driver of your video card.", "OpenGL error"); -// return false; -// } -// - // Enable point size by default on windows. - glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); - - return true; -} - -bool EGLView::isOpenGLReady() -{ - return nullptr != _mainWindow; -} - -void EGLView::end() -{ - if(_mainWindow) - glfwSetWindowShouldClose(_mainWindow,1); -} - -void EGLView::swapBuffers() -{ - if(_mainWindow) - glfwSwapBuffers(_mainWindow); -} - -bool EGLView::windowShouldClose() -{ - if(_mainWindow) - return glfwWindowShouldClose(_mainWindow); - else - return true; -} - -void EGLView::pollEvents() -{ - glfwPollEvents(); -} - -void EGLView::setIMEKeyboardState(bool /*bOpen*/) -{ - -} - -void EGLView::setFrameZoomFactor(float zoomFactor) -{ - _frameZoomFactor = zoomFactor; - Director::getInstance()->setProjection(Director::getInstance()->getProjection()); -} - -float EGLView::getFrameZoomFactor() -{ - return _frameZoomFactor; -} - -void EGLView::setFrameSize(float width, float height) -{ - EGLViewProtocol::setFrameSize(width, height); -} - -void EGLView::setViewPortInPoints(float x , float y , float w , float h) -{ - glViewport((GLint)(x * _scaleX * _frameZoomFactor + _viewPortRect.origin.x * _frameZoomFactor), - (GLint)(y * _scaleY * _frameZoomFactor + _viewPortRect.origin.y * _frameZoomFactor), - (GLsizei)(w * _scaleX * _frameZoomFactor), - (GLsizei)(h * _scaleY * _frameZoomFactor)); -} - -void EGLView::setScissorInPoints(float x , float y , float w , float h) -{ - glScissor((GLint)(x * _scaleX * _frameZoomFactor + _viewPortRect.origin.x * _frameZoomFactor), - (GLint)(y * _scaleY * _frameZoomFactor + _viewPortRect.origin.y * _frameZoomFactor), - (GLsizei)(w * _scaleX * _frameZoomFactor), - (GLsizei)(h * _scaleY * _frameZoomFactor)); -} - -EGLView* EGLView::getInstance() -{ - CCASSERT(nullptr != s_pEglView, "EGL singleton should not be null"); - return s_pEglView; -} - -// XXX: deprecated -EGLView* EGLView::sharedOpenGLView() -{ - return EGLView::getInstance(); -} - -NS_CC_END // end of namespace cocos2d; diff --git a/cocos/2d/platform/mac/CCEventDispatcherMac.h b/cocos/2d/platform/mac/CCEventDispatcherMac.h deleted file mode 100644 index df47784455..0000000000 --- a/cocos/2d/platform/mac/CCEventDispatcherMac.h +++ /dev/null @@ -1,277 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 Ricardo Quesada -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2011 Zynga Inc. -Copyright (c) 2013-2014 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. -****************************************************************************/ - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import -#ifndef __CC_EVENT_DISPATCHER_MAC_H__ -#define __CC_EVENT_DISPATCHER_MAC_H__ - -#import - -#import "EAGLView.h" -//#import "../../Support/uthash.h" // hack: uthash needs to be imported before utlist to prevent warning -//#import "../../Support/utlist.h" -#import "ccConfig.h" - -//NS_CC_BEGIN; -#pragma mark - MouseEventDelegate - -/** MouseEventDelegate protocol. - Implement it in your node to receive any of mouse events - */ -@protocol CCMouseEventDelegate -@optional - -// -// left -// -/** called when the "mouseDown" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccMouseDown:(NSEvent*)event; - -/** called when the "mouseDragged" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccMouseDragged:(NSEvent*)event; - -/** called when the "mouseMoved" event is received. - Return YES to avoid propagating the event to other delegates. - By default, "mouseMoved" is disabled. To enable it, send the "setAcceptsMouseMovedEvents:YES" message to the main window. - */ --(BOOL) ccMouseMoved:(NSEvent*)event; - -/** called when the "mouseUp" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccMouseUp:(NSEvent*)event; - - -// -// right -// - -/** called when the "rightMouseDown" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccRightMouseDown:(NSEvent*)event; - -/** called when the "rightMouseDragged" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccRightMouseDragged:(NSEvent*)event; - -/** called when the "rightMouseUp" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccRightMouseUp:(NSEvent*)event; - -// -// other -// - -/** called when the "otherMouseDown" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccOtherMouseDown:(NSEvent*)event; - -/** called when the "otherMouseDragged" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccOtherMouseDragged:(NSEvent*)event; - -/** called when the "otherMouseUp" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccOtherMouseUp:(NSEvent*)event; - -// -// scroll wheel -// - -/** called when the "scrollWheel" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccScrollWheel:(NSEvent *)theEvent; - - -// -// enter / exit -// - -/** called when the "mouseEntered" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (void)ccMouseEntered:(NSEvent *)theEvent; - -/** called when the "mouseExited" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (void)ccMouseExited:(NSEvent *)theEvent; - -@end - -#pragma mark - KeyboardEventDelegate - -/** KeyboardEventDelegate protocol. - Implement it in your node to receive any of keyboard events - */ -@protocol CCKeyboardEventDelegate -@optional -/** called when the "keyUp" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccKeyUp:(NSEvent*)event; - -/** called when the "keyDown" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccKeyDown:(NSEvent*)event; -/** called when the "flagsChanged" event is received. - Return YES to avoid propagating the event to other delegates. - */ --(BOOL) ccFlagsChanged:(NSEvent*)event; -@end - -#pragma mark - -#pragma mark TouchEventDelegate - -/** TouchEventDelegate protocol. - Implement it in your node to receive any of touch events - */ -@protocol CCTouchEventDelegate -@optional -/** called when the "touchesBegan" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccTouchesBeganWithEvent:(NSEvent *)event; - -/** called when the "touchesMoved" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccTouchesMovedWithEvent:(NSEvent *)event; - -/** called when the "touchesEnded" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccTouchesEndedWithEvent:(NSEvent *)event; - -/** called when the "touchesCancelled" event is received. - Return YES to avoid propagating the event to other delegates. - */ -- (BOOL)ccTouchesCancelledWithEvent:(NSEvent *)event; - -@end - - -#pragma mark - EventDispatcher - -struct _listEntry; - -/** EventDispatcher - - This is object is responsible for dispatching the events: - - Mouse events - - Keyboard events - - Touch events - - Only available on Mac - */ -@interface CCEventDispatcher : NSObject { - - BOOL dispatchEvents_; - - struct _listEntry *keyboardDelegates_; - struct _listEntry *mouseDelegates_; - struct _listEntry *touchDelegates_; -} - -@property (nonatomic, readwrite) BOOL dispatchEvents; - - -/** EventDispatcher singleton */ -+(CCEventDispatcher*) sharedDispatcher; - -#pragma mark EventDispatcher - Mouse - -/** Adds a mouse delegate to the dispatcher's list. - Delegates with a lower priority value will be called before higher priority values. - All the events will be propgated to all the delegates, unless the one delegate returns YES. - - IMPORTANT: The delegate will be retained. - */ --(void) addMouseDelegate:(id) delegate priority:(NSInteger)priority; - -/** removes a mouse delegate */ --(void) removeMouseDelegate:(id) delegate; - -/** Removes all mouse delegates, releasing all the delegates */ --(void) removeAllMouseDelegates; - -#pragma mark EventDispatcher - Keyboard - -/** Adds a Keyboard delegate to the dispatcher's list. - Delegates with a lower priority value will be called before higher priority values. - All the events will be propgated to all the delegates, unless the one delegate returns YES. - - IMPORTANT: The delegate will be retained. - */ --(void) addKeyboardDelegate:(id) delegate priority:(NSInteger)priority; - -/** removes a mouse delegate */ --(void) removeKeyboardDelegate:(id) delegate; - -/** Removes all mouse delegates, releasing all the delegates */ --(void) removeAllKeyboardDelegates; - -#pragma mark EventDispatcher - Touches - -/** Adds a Touch delegate to the dispatcher's list. - Delegates with a lower priority value will be called before higher priority values. - All the events will be propgated to all the delegates, unless the one delegate returns YES. - - IMPORTANT: The delegate will be retained. - */ -- (void)addTouchDelegate:(id)delegate priority:(NSInteger)priority; - -/** Removes a touch delegate */ -- (void)removeTouchDelegate:(id) delegate; - -/** Removes all touch delegates, releasing all the delegates */ -- (void)removeAllTouchDelegates; - -#pragma mark EventDispatcher - Dispatch Events - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD --(void) dispatchQueuedEvents; -#endif - -@end - -//NS_CC_END; -#endif // __CC_EVENT_DISPATCHER_MAC_H__ diff --git a/cocos/2d/platform/mac/CCEventDispatcherMac.mm b/cocos/2d/platform/mac/CCEventDispatcherMac.mm deleted file mode 100644 index 691383d36a..0000000000 --- a/cocos/2d/platform/mac/CCEventDispatcherMac.mm +++ /dev/null @@ -1,649 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 Ricardo Quesada -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2011 Zynga Inc. -Copyright (c) 2013-2014 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. -****************************************************************************/ - -// Only compile this code on Mac. These files should not be included on your iOS project. -// But in case they are included, it won't be compiled. -#import - -#import "CCEventDispatcherMac.h" -#import "ccConfig.h" -#include "utlist.h" - -#include "CCDirector.h" - -//NS_CC_BEGIN; -static CCEventDispatcher *sharedDispatcher = nil; - -enum { - // mouse - kImplementsMouseDown = 1 << 0, - kImplementsMouseMoved = 1 << 1, - kImplementsMouseDragged = 1 << 2, - kImplementsMouseUp = 1 << 3, - kImplementsRightMouseDown = 1 << 4, - kImplementsRightMouseDragged = 1 << 5, - kImplementsRightMouseUp = 1 << 6, - kImplementsOtherMouseDown = 1 << 7, - kImplementsOtherMouseDragged = 1 << 8, - kImplementsOtherMouseUp = 1 << 9, - kImplementsScrollWheel = 1 << 10, - kImplementsMouseEntered = 1 << 11, - kImplementsMouseExited = 1 << 12, - - kImplementsTouchesBegan = 1 << 13, - kImplementsTouchesMoved = 1 << 14, - kImplementsTouchesEnded = 1 << 15, - kImplementsTouchesCancelled = 1 << 16, - - // keyboard - kImplementsKeyUp = 1 << 0, - kImplementsKeyDown = 1 << 1, - kImplementsFlagsChanged = 1 << 2, -}; - - -typedef struct _listEntry -{ - struct _listEntry *prev, *next; - id delegate; - NSInteger priority; - NSUInteger flags; -} tListEntry; - - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD - -#define QUEUE_EVENT_MAX 128 -struct _eventQueue { - SEL selector; - NSEvent *event; -}; - -static struct _eventQueue eventQueue[QUEUE_EVENT_MAX]; -static int eventQueueCount; - -#endif // CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD - - -@implementation CCEventDispatcher - -@synthesize dispatchEvents=dispatchEvents_; - - -+(CCEventDispatcher*) sharedDispatcher -{ - @synchronized(self) { - if (sharedDispatcher == nil) - sharedDispatcher = [[self alloc] init]; // assignment not done here - } - return sharedDispatcher; -} - -+(id) allocWithZone:(NSZone *)zone -{ - @synchronized(self) { - NSAssert(sharedDispatcher == nil, @"Attempted to allocate a second instance of a singleton."); - return [super allocWithZone:zone]; - } - return nil; // on subsequent allocation attempts return nil -} - --(id) init -{ - if( (self = [super init]) ) - { - // events enabled by default - dispatchEvents_ = YES; - - // delegates - keyboardDelegates_ = nullptr; - mouseDelegates_ = nullptr; - touchDelegates_ = nullptr; - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD - eventQueueCount = 0; -#endif - } - - return self; -} - -- (void) dealloc -{ - [super dealloc]; -} - -#pragma mark EventDispatcher - add / remove delegates - --(void) addDelegate:(id)delegate priority:(NSInteger)priority flags:(NSUInteger)flags list:(tListEntry**)list -{ - tListEntry *listElement = (tListEntry *)malloc( sizeof(*listElement) ); - - listElement->delegate = [delegate retain]; - listElement->priority = priority; - listElement->flags = flags; - listElement->next = listElement->prev = nullptr; - - // empty list ? - if( ! *list ) { - DL_APPEND( *list, listElement ); - - } else { - BOOL added = NO; - - for( tListEntry *elem = *list; elem ; elem = elem->next ) { - if( priority < elem->priority ) { - - if( elem == *list ) - DL_PREPEND(*list, listElement); - else { - listElement->next = elem; - listElement->prev = elem->prev; - - elem->prev->next = listElement; - elem->prev = listElement; - } - - added = YES; - break; - } - } - - // Not added? priority has the higher value. Append it. - if( !added ) - DL_APPEND(*list, listElement); - } -} - --(void) removeDelegate:(id)delegate fromList:(tListEntry**)list -{ - tListEntry *entry, *tmp; - - // updates with priority < 0 - DL_FOREACH_SAFE( *list, entry, tmp ) { - if( entry->delegate == delegate ) { - DL_DELETE( *list, entry ); - [delegate release]; - free(entry); - break; - } - } -} - --(void) removeAllDelegatesFromList:(tListEntry**)list -{ - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( *list, entry, tmp ) { - DL_DELETE( *list, entry ); - free(entry); - } -} - - --(void) addMouseDelegate:(id) delegate priority:(NSInteger)priority -{ - NSUInteger flags = 0; - - flags |= ( [delegate respondsToSelector:@selector(ccMouseDown:)] ? kImplementsMouseDown : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccMouseDragged:)] ? kImplementsMouseDragged : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccMouseMoved:)] ? kImplementsMouseMoved : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccMouseUp:)] ? kImplementsMouseUp : 0 ); - - flags |= ( [delegate respondsToSelector:@selector(ccRightMouseDown:)] ? kImplementsRightMouseDown : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccRightMouseDragged:)] ? kImplementsRightMouseDragged : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccRightMouseUp:)] ? kImplementsRightMouseUp : 0 ); - - flags |= ( [delegate respondsToSelector:@selector(ccOtherMouseDown:)] ? kImplementsOtherMouseDown : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccOtherMouseDragged:)] ? kImplementsOtherMouseDragged : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccOtherMouseUp:)] ? kImplementsOtherMouseUp : 0 ); - - flags |= ( [delegate respondsToSelector:@selector(ccMouseEntered:)] ? kImplementsMouseEntered : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccMouseExited:)] ? kImplementsMouseExited : 0 ); - - flags |= ( [delegate respondsToSelector:@selector(ccScrollWheel:)] ? kImplementsScrollWheel : 0 ); - - [self addDelegate:delegate priority:priority flags:flags list:&mouseDelegates_]; -} - --(void) removeMouseDelegate:(id) delegate -{ - [self removeDelegate:delegate fromList:&mouseDelegates_]; -} - --(void) removeAllMouseDelegates -{ - [self removeAllDelegatesFromList:&mouseDelegates_]; -} - --(void) addKeyboardDelegate:(id) delegate priority:(NSInteger)priority -{ - NSUInteger flags = 0; - - flags |= ( [delegate respondsToSelector:@selector(ccKeyUp:)] ? kImplementsKeyUp : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccKeyDown:)] ? kImplementsKeyDown : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccFlagsChanged:)] ? kImplementsFlagsChanged : 0 ); - - [self addDelegate:delegate priority:priority flags:flags list:&keyboardDelegates_]; -} - --(void) removeKeyboardDelegate:(id) delegate -{ - [self removeDelegate:delegate fromList:&keyboardDelegates_]; -} - --(void) removeAllKeyboardDelegates -{ - [self removeAllDelegatesFromList:&keyboardDelegates_]; -} - --(void) addTouchDelegate:(id) delegate priority:(NSInteger)priority -{ - NSUInteger flags = 0; - - flags |= ( [delegate respondsToSelector:@selector(ccTouchesBeganWithEvent:)] ? kImplementsTouchesBegan : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccTouchesMovedWithEvent:)] ? kImplementsTouchesMoved : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccTouchesEndedWithEvent:)] ? kImplementsTouchesEnded : 0 ); - flags |= ( [delegate respondsToSelector:@selector(ccTouchesCancelledWithEvent:)] ? kImplementsTouchesCancelled : 0 ); - - [self addDelegate:delegate priority:priority flags:flags list:&touchDelegates_]; -} - --(void) removeTouchDelegate:(id) delegate -{ - [self removeDelegate:delegate fromList:&touchDelegates_]; -} - --(void) removeAllTouchDelegates -{ - [self removeAllDelegatesFromList:&touchDelegates_]; -} - - -#pragma mark EventDispatcher - Mouse events -// -// Mouse events -// - -// -// Left -// -- (void)mouseDown:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsMouseDown ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseDown:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)mouseMoved:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsMouseMoved ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseMoved:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)mouseDragged:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsMouseDragged ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseDragged:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)mouseUp:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsMouseUp ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseUp:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -// -// Mouse Right -// -- (void)rightMouseDown:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsRightMouseDown ) { - void *swallows = [entry->delegate performSelector:@selector(ccRightMouseDown:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)rightMouseDragged:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsRightMouseDragged ) { - void *swallows = [entry->delegate performSelector:@selector(ccRightMouseDragged:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)rightMouseUp:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsRightMouseUp ) { - void *swallows = [entry->delegate performSelector:@selector(ccRightMouseUp:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -// -// Mouse Other -// -- (void)otherMouseDown:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsOtherMouseDown ) { - void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseDown:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)otherMouseDragged:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsOtherMouseDragged ) { - void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseDragged:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)otherMouseUp:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsOtherMouseUp ) { - void *swallows = [entry->delegate performSelector:@selector(ccOtherMouseUp:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -// -// Scroll Wheel -// -- (void)scrollWheel:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsScrollWheel ) { - void *swallows = [entry->delegate performSelector:@selector(ccScrollWheel:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -// -// Mouse enter / exit -- (void)mouseExited:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsMouseEntered ) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseEntered:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)mouseEntered:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( mouseDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsMouseExited) { - void *swallows = [entry->delegate performSelector:@selector(ccMouseExited:) withObject:event]; - if( swallows ) - break; - } - } - } -} - - -#pragma mark EventDispatcher - Keyboard events - -// Keyboard events -- (void)keyDown:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; -// cocos2d::Director::getInstance()->getKeyboardDispatcher()->dispatchKeyboardEvent(event.keyCode, true); - - DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsKeyDown ) { - void *swallows = [entry->delegate performSelector:@selector(ccKeyDown:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)keyUp:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; -// cocos2d::Director::getInstance()->getKeyboardDispatcher()->dispatchKeyboardEvent(event.keyCode, false); - - DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsKeyUp ) { - void *swallows = [entry->delegate performSelector:@selector(ccKeyUp:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)flagsChanged:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( keyboardDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsFlagsChanged ) { - void *swallows = [entry->delegate performSelector:@selector(ccFlagsChanged:) withObject:event]; - if( swallows ) - break; - } - } - } -} - - -#pragma mark EventDispatcher - Touch events - -- (void)touchesBeganWithEvent:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsTouchesBegan) { - void *swallows = [entry->delegate performSelector:@selector(ccTouchesBeganWithEvent:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)touchesMovedWithEvent:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsTouchesMoved) { - void *swallows = [entry->delegate performSelector:@selector(ccTouchesMovedWithEvent:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)touchesEndedWithEvent:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsTouchesEnded) { - void *swallows = [entry->delegate performSelector:@selector(ccTouchesEndedWithEvent:) withObject:event]; - if( swallows ) - break; - } - } - } -} - -- (void)touchesCancelledWithEvent:(NSEvent *)event -{ - if( dispatchEvents_ ) { - tListEntry *entry, *tmp; - - DL_FOREACH_SAFE( touchDelegates_, entry, tmp ) { - if ( entry->flags & kImplementsTouchesCancelled) { - void *swallows = [entry->delegate performSelector:@selector(ccTouchesCancelledWithEvent:) withObject:event]; - if( swallows ) - break; - } - } - } -} - - -#pragma mark EventDispatcher - queue events - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD --(void) queueEvent:(NSEvent*)event selector:(SEL)selector -{ - NSAssert( eventQueueCount < QUEUE_EVENT_MAX, @"CCEventDispatcher: recompile. Increment QUEUE_EVENT_MAX value"); - - @synchronized (self) { - eventQueue[eventQueueCount].selector = selector; - eventQueue[eventQueueCount].event = [event copy]; - - eventQueueCount++; - } -} - --(void) dispatchQueuedEvents -{ - @synchronized (self) { - for( int i=0; i < eventQueueCount; i++ ) { - SEL sel = eventQueue[i].selector; - NSEvent *event = eventQueue[i].event; - - [self performSelector:sel withObject:event]; - - [event release]; - } - - eventQueueCount = 0; - } -} -#endif // CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD - -//NS_CC_END; -@end diff --git a/cocos/2d/platform/mac/CCGL.h b/cocos/2d/platform/mac/CCGL.h index cfdb173068..5bd3bc4a58 100644 --- a/cocos/2d/platform/mac/CCGL.h +++ b/cocos/2d/platform/mac/CCGL.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef __PLATFORM_MAC_CCGL_H__ #define __PLATFORM_MAC_CCGL_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_MAC + #import #import #import @@ -42,3 +45,5 @@ THE SOFTWARE. #endif // __PLATFORM_MAC_CCGL_H__ + +#endif //s CC_TARGET_PLATFORM == CC_PLATFORM_MAC diff --git a/cocos/2d/platform/mac/CCImage.mm b/cocos/2d/platform/mac/CCImage.mm index fea424d8a6..5d27e0f9d0 100644 --- a/cocos/2d/platform/mac/CCImage.mm +++ b/cocos/2d/platform/mac/CCImage.mm @@ -23,6 +23,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_MAC + #include "CCImageCommon_cpp.h" #include #include @@ -231,3 +234,4 @@ bool Image::initWithString( NS_CC_END +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC diff --git a/cocos/2d/platform/mac/CCPlatformDefine.h b/cocos/2d/platform/mac/CCPlatformDefine.h index ca87ebf069..eaec140a36 100644 --- a/cocos/2d/platform/mac/CCPlatformDefine.h +++ b/cocos/2d/platform/mac/CCPlatformDefine.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef __CCPLATFORMDEFINE_H__ #define __CCPLATFORMDEFINE_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_MAC + #include #define CC_DLL @@ -47,6 +50,6 @@ THE SOFTWARE. #endif #endif - +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC #endif /* __CCPLATFORMDEFINE_H__*/ diff --git a/cocos/2d/platform/mac/CCStdC.h b/cocos/2d/platform/mac/CCStdC.h index 804abebceb..4f639579b5 100644 --- a/cocos/2d/platform/mac/CCStdC.h +++ b/cocos/2d/platform/mac/CCStdC.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef __CC_STD_C_H__ #define __CC_STD_C_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_MAC + #include "CCPlatformMacros.h" #include #include @@ -45,4 +48,6 @@ THE SOFTWARE. #define MAX(x,y) (((x) < (y)) ? (y) : (x)) #endif // MAX +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC + #endif // __CC_STD_C_H__ diff --git a/cocos/2d/platform/mac/CCWindow.h b/cocos/2d/platform/mac/CCWindow.h deleted file mode 100644 index 78ac008922..0000000000 --- a/cocos/2d/platform/mac/CCWindow.h +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2014 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. -****************************************************************************/ - -#ifndef __CC_WINDOW_H__ -#define __CC_WINDOW_H__ - -#import - - -@interface CCWindow : NSWindow -{ -} -- (id) initWithFrame:(NSRect)frame fullscreen:(BOOL)fullscreen; - -@end - -#endif // __CC_WINDOW_H__ \ No newline at end of file diff --git a/cocos/2d/platform/mac/CCWindow.m b/cocos/2d/platform/mac/CCWindow.m deleted file mode 100644 index 97d442d29a..0000000000 --- a/cocos/2d/platform/mac/CCWindow.m +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2014 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. -****************************************************************************/ - -#import "CCWindow.h" -#import "EAGLView.h" - -@implementation CCWindow - -- (id) initWithFrame:(NSRect)frame fullscreen:(BOOL)fullscreen -{ - int styleMask = fullscreen ? NSBackingStoreBuffered : ( NSTitledWindowMask | NSClosableWindowMask ); - self = [self initWithContentRect:frame - styleMask:styleMask - backing:NSBackingStoreBuffered - defer:YES]; - - if (self != nil) - { - if(fullscreen) - { - [self setLevel:NSMainMenuWindowLevel+1]; - [self setHidesOnDeactivate:YES]; - [self setHasShadow:NO]; - } - - [self setAcceptsMouseMovedEvents:NO]; - [self setOpaque:YES]; - } - return self; -} - -- (BOOL) canBecomeKeyWindow -{ - return YES; -} - -- (BOOL) canBecomeMainWindow -{ - return YES; -} - -- (void) keyDown:(NSEvent *)event -{ - // exit fullscreen if user pressed esc - if([event keyCode] == 53) - { - CCEAGLView* eaglView = [CCEAGLView sharedEGLView]; - - // cancel full screen - if( [eaglView isFullScreen] ) - [eaglView setFullScreen:NO]; - - // let another responder take it - else - [super keyDown:event]; - } -} - -@end - diff --git a/cocos/2d/platform/mac/EAGLView.h b/cocos/2d/platform/mac/EAGLView.h deleted file mode 100644 index 8c8ecd477f..0000000000 --- a/cocos/2d/platform/mac/EAGLView.h +++ /dev/null @@ -1,120 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2014 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. -****************************************************************************/ - -#ifndef __EAGLVIEW_MAC_H__ -#define __EAGLVIEW_MAC_H__ - -#import -#import "ccConfig.h" - -//PROTOCOLS: - -@protocol CCMacEventDelegate -// Mouse -- (void)mouseDown:(NSEvent *)theEvent; -- (void)mouseUp:(NSEvent *)theEvent; -- (void)mouseMoved:(NSEvent *)theEvent; -- (void)mouseDragged:(NSEvent *)theEvent; -- (void)rightMouseDown:(NSEvent*)event; -- (void)rightMouseDragged:(NSEvent*)event; -- (void)rightMouseUp:(NSEvent*)event; -- (void)otherMouseDown:(NSEvent*)event; -- (void)otherMouseDragged:(NSEvent*)event; -- (void)otherMouseUp:(NSEvent*)event; -- (void)scrollWheel:(NSEvent *)theEvent; -- (void)mouseEntered:(NSEvent *)theEvent; -- (void)mouseExited:(NSEvent *)theEvent; - - -// Keyboard -- (void)keyDown:(NSEvent *)theEvent; -- (void)keyUp:(NSEvent *)theEvent; -- (void)flagsChanged:(NSEvent *)theEvent; - -// Touches -- (void)touchesBeganWithEvent:(NSEvent *)event; -- (void)touchesMovedWithEvent:(NSEvent *)event; -- (void)touchesEndedWithEvent:(NSEvent *)event; -- (void)touchesCancelledWithEvent:(NSEvent *)event; - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD -- (void)queueEvent:(NSEvent*)event selector:(SEL)selector; -#endif - -@end - -/** MacGLView - - Only available for Mac OS X - */ -@interface CCEAGLView : NSOpenGLView { - id eventDelegate_; - - BOOL isFullScreen_; - NSWindow *fullScreenWindow_; - - // cache - NSWindow *windowGLView_; - NSView *superViewGLView_; - NSRect originalWinRect_; // Original size and position - - float frameZoomFactor_; -} - -@property (nonatomic, readwrite, assign) id eventDelegate; - -// whether or not the view is in fullscreen mode -@property (nonatomic, readonly) BOOL isFullScreen; - -@property (nonatomic, readwrite) float frameZoomFactor; - -// initializes the MacGLView with a frame rect and an OpenGL context -- (id) initWithFrame:(NSRect)frameRect shareContext:(NSOpenGLContext*)context; - -- (id) initWithFrame:(NSRect)frameRect pixelFormat:(NSOpenGLPixelFormat *)format; - -/** uses and locks the OpenGL context */ --(void) lockOpenGLContext; - -/** unlocks the openGL context */ --(void) unlockOpenGLContext; - -/** returns the depth format of the view in BPP */ -- (NSUInteger) depthFormat; - -- (void) setFrameZoomFactor:(float)frameZoomFactor; - -// get the view object -+(id) sharedEGLView; - --(int) getWidth; --(int) getHeight; --(void) swapBuffers; - --(void) setFullScreen:(BOOL)fullscreen; - -@end -#endif // __EAGLVIEW_MAC_H__ - diff --git a/cocos/2d/platform/mac/EAGLView.mm b/cocos/2d/platform/mac/EAGLView.mm deleted file mode 100644 index 68573ba99f..0000000000 --- a/cocos/2d/platform/mac/EAGLView.mm +++ /dev/null @@ -1,490 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2014 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. -****************************************************************************/ - -/* - * Idea of subclassing NSOpenGLView was taken from "TextureUpload" Apple's sample - */ - -#import - -#import "EAGLView.h" -#import "CCEGLView.h" -#import -#import "CCDirector.h" -#import "ccConfig.h" -#import "CCSet.h" -#import "CCTouch.h" -#import "CCIMEDispatcher.h" -#import "CCWindow.h" -#import "CCEventDispatcherMac.h" -#import "CCEGLView.h" - - -//USING_NS_CC; -static CCEAGLView *view; - -@implementation CCEAGLView - -@synthesize eventDelegate = eventDelegate_, isFullScreen = isFullScreen_, frameZoomFactor=frameZoomFactor_; - -+(id) sharedEGLView -{ - return view; -} - -- (id) initWithFrame:(NSRect)frameRect -{ - self = [self initWithFrame:frameRect shareContext:nil]; - return self; -} - -- (id) initWithFrame:(NSRect)frameRect shareContext:(NSOpenGLContext*)context -{ - NSOpenGLPixelFormatAttribute attribs[] = - { -// NSOpenGLPFAAccelerated, -// NSOpenGLPFANoRecovery, - NSOpenGLPFADoubleBuffer, - NSOpenGLPFADepthSize, 24, - - 0 - }; - - NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs]; - - if (!pixelFormat) - NSLog(@"No OpenGL pixel format"); - - if( (self = [super initWithFrame:frameRect pixelFormat:[pixelFormat autorelease]]) ) { - - if( context ) - [self setOpenGLContext:context]; - - // event delegate - eventDelegate_ = [CCEventDispatcher sharedDispatcher]; - } - - cocos2d::EGLView::getInstance()->setFrameSize(frameRect.size.width, frameRect.size.height); - - frameZoomFactor_ = 1.0f; - - view = self; - return self; -} - -- (id) initWithFrame:(NSRect)frameRect pixelFormat:(NSOpenGLPixelFormat *)format{ - // event delegate - eventDelegate_ = [CCEventDispatcher sharedDispatcher]; - - cocos2d::EGLView::getInstance()->setFrameSize(frameRect.size.width, frameRect.size.height); - - frameZoomFactor_ = 1.0f; - - view = self; - - [super initWithFrame:frameRect pixelFormat:format]; - - return self; -} - -- (void) update -{ - // XXX: Should I do something here ? - [super update]; -} - -- (void) prepareOpenGL -{ - // XXX: Initialize OpenGL context - - [super prepareOpenGL]; - - // Make this openGL context current to the thread - // (i.e. all openGL on this thread calls will go to this context) - [[self openGLContext] makeCurrentContext]; - - // Synchronize buffer swaps with vertical refresh rate - GLint swapInt = 1; - [[self openGLContext] setValues:&swapInt forParameter:NSOpenGLCPSwapInterval]; - -// GLint order = -1; -// [[self openGLContext] setValues:&order forParameter:NSOpenGLCPSurfaceOrder]; -} - -- (NSUInteger) depthFormat -{ - return 24; -} - -- (void) setFrameZoomFactor:(float)frameZoomFactor -{ - frameZoomFactor_ = frameZoomFactor; - - NSRect winRect = [[self window] frame]; - NSRect viewRect = [self frame]; - - // compute the margin width and margin height - float diffX = winRect.size.width - viewRect.size.width; - float diffY = winRect.size.height - viewRect.size.height; - - // new window width and height - float newWindowWidth = (int)(viewRect.size.width * frameZoomFactor + diffX); - float newWindowHeight = (int)(viewRect.size.height * frameZoomFactor + diffY); - - // display window in the center of the screen - NSRect screenRect = [[NSScreen mainScreen] frame]; - float originX = (screenRect.size.width - newWindowWidth) / 2; - float originY = (screenRect.size.height - newWindowHeight) / 2; - - [[self window] setFrame:NSMakeRect(originX, originY, newWindowWidth, newWindowHeight) display:true]; -} - -- (void) reshape -{ - // We draw on a secondary thread through the display link - // When resizing the view, -reshape is called automatically on the main thread - // Add a mutex around to avoid the threads accessing the context simultaneously when resizing - - [self lockOpenGLContext]; - -// NSRect rect = [self bounds]; - - cocos2d::Director *director = cocos2d::Director::getInstance(); -// CGSize size = NSSizeToCGSize(rect.size); -// cocos2d::Size ccsize = cocos2d::Size(size.width, size.height); - //director->reshapeProjection(ccsize); - - // avoid flicker - director->drawScene(); -// [self setNeedsDisplay:YES]; - - [self unlockOpenGLContext]; -} - --(void) lockOpenGLContext -{ - NSOpenGLContext *glContext = [self openGLContext]; - NSAssert( glContext, @"FATAL: could not get openGL context"); - - [glContext makeCurrentContext]; - CGLLockContext((CGLContextObj)[glContext CGLContextObj]); -} - --(void) unlockOpenGLContext -{ - NSOpenGLContext *glContext = [self openGLContext]; - NSAssert( glContext, @"FATAL: could not get openGL context"); - - CGLUnlockContext((CGLContextObj)[glContext CGLContextObj]); -} - -- (void) dealloc -{ - CCLOGINFO("deallocing CCEAGLView: %p", self); - [super dealloc]; -} - --(int) getWidth -{ - NSSize bound = [self bounds].size; - return bound.width; -} - --(int) getHeight -{ - NSSize bound = [self bounds].size; - return bound.height; -} - --(void) swapBuffers -{ -} - -// -// setFullScreen code taken from GLFullScreen example by Apple -// -- (void) setFullScreen:(BOOL)fullscreen -{ - // Mac OS X 10.6 and later offer a simplified mechanism to create full-screen contexts -#if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5 - - if (isFullScreen_ == fullscreen) - return; - - CCEAGLView *openGLview = [[self class] sharedEGLView]; - - if( fullscreen ) { - originalWinRect_ = [openGLview frame]; - - // Cache normal window and superview of openGLView - if(!windowGLView_) - windowGLView_ = [[openGLview window] retain]; - - [superViewGLView_ release]; - superViewGLView_ = [[openGLview superview] retain]; - - - // Get screen size - NSRect displayRect = [[NSScreen mainScreen] frame]; - - // Create a screen-sized window on the display you want to take over - fullScreenWindow_ = [[CCWindow alloc] initWithFrame:displayRect fullscreen:YES]; - - // Remove glView from window - [openGLview removeFromSuperview]; - - // Set new frame - [openGLview setFrame:displayRect]; - - // Attach glView to fullscreen window - [fullScreenWindow_ setContentView:openGLview]; - - // Show the fullscreen window - [fullScreenWindow_ makeKeyAndOrderFront:self]; - [fullScreenWindow_ makeMainWindow]; - //[fullScreenWindow_ setNextResponder:superViewGLView_]; - - } else { - - // Remove glView from fullscreen window - [openGLview removeFromSuperview]; - - // Release fullscreen window - [fullScreenWindow_ release]; - fullScreenWindow_ = nil; - - // Attach glView to superview - [superViewGLView_ addSubview:openGLview]; - - // Set new frame - [openGLview setFrame:originalWinRect_]; - - // Show the window - [windowGLView_ makeKeyAndOrderFront:self]; - [windowGLView_ makeMainWindow]; - } - - // issue #1189 - [windowGLView_ makeFirstResponder:openGLview]; - - isFullScreen_ = fullscreen; - - //[openGLview retain]; // Retain +1 - - // is this necessary? - // re-configure glView - //cocos2d::Director *director = cocos2d::Director::getInstance(); - //director->setOpenGLView(openGLview); //[self setView:openGLview]; - - //[openGLview release]; // Retain -1 - - [openGLview setNeedsDisplay:YES]; -#else -#error Full screen is not supported for Mac OS 10.5 or older yet -#error If you don't want FullScreen support, you can safely remove these 2 lines -#endif -} - -#if CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD -#define DISPATCH_EVENT(__event__, __selector__) [eventDelegate_ queueEvent:__event__ selector:__selector__]; -#else -#define DISPATCH_EVENT(__event__, __selector__) \ - id obj = eventDelegate_; \ - [obj performSelector:__selector__ \ - onThread:[(cocos2d::Director*)[Director sharedDirector] runningThread] \ - withObject:__event__ \ - waitUntilDone:NO]; -#endif - -#pragma mark CCEAGLView - Mouse events - -- (void)mouseDown:(NSEvent *)theEvent -{ - NSPoint event_location = [theEvent locationInWindow]; - NSPoint local_point = [self convertPoint:event_location fromView:nil]; - - float x = local_point.x; - float y = [self getHeight] - local_point.y; - - NSInteger ids[1] = {0}; - float xs[1] = {0.0f}; - float ys[1] = {0.0f}; - - ids[0] = [theEvent eventNumber]; - xs[0] = x / frameZoomFactor_; - ys[0] = y / frameZoomFactor_; - - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, (int*)ids, xs, ys); -} - -- (void)mouseMoved:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)mouseDragged:(NSEvent *)theEvent -{ - NSPoint event_location = [theEvent locationInWindow]; - NSPoint local_point = [self convertPoint:event_location fromView:nil]; - - float x = local_point.x; - float y = [self getHeight] - local_point.y; - - NSInteger ids[1] = {0}; - float xs[1] = {0.0f}; - float ys[1] = {0.0f}; - - ids[0] = [theEvent eventNumber]; - xs[0] = x / frameZoomFactor_; - ys[0] = y / frameZoomFactor_; - - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(1, (int*)ids, xs, ys); -} - -- (void)mouseUp:(NSEvent *)theEvent -{ - NSPoint event_location = [theEvent locationInWindow]; - NSPoint local_point = [self convertPoint:event_location fromView:nil]; - - float x = local_point.x; - float y = [self getHeight] - local_point.y; - - NSInteger ids[1] = {0}; - float xs[1] = {0.0f}; - float ys[1] = {0.0f}; - - ids[0] = [theEvent eventNumber]; - xs[0] = x / frameZoomFactor_; - ys[0] = y / frameZoomFactor_; - - cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, (int*)ids, xs, ys); -} - -- (void)rightMouseDown:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - - // pass the event along to the next responder (like your NSWindow subclass) - [super rightMouseDown:theEvent]; -} - -- (void)rightMouseDragged:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super rightMouseDragged:theEvent]; -} - -- (void)rightMouseUp:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super rightMouseUp:theEvent]; -} - -- (void)otherMouseDown:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super otherMouseDown:theEvent]; -} - -- (void)otherMouseDragged:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super otherMouseDragged:theEvent]; -} - -- (void)otherMouseUp:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super otherMouseUp:theEvent]; -} - -- (void)mouseEntered:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super mouseEntered:theEvent]; -} - -- (void)mouseExited:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super mouseExited:theEvent]; -} - --(void) scrollWheel:(NSEvent *)theEvent { - DISPATCH_EVENT(theEvent, _cmd); - [super scrollWheel:theEvent]; -} - -#pragma mark CCEAGLView - Key events - --(BOOL) becomeFirstResponder -{ - return YES; -} - --(BOOL) acceptsFirstResponder -{ - return YES; -} - --(BOOL) resignFirstResponder -{ - return YES; -} - -- (void)keyDown:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); - - // pass the event along to the next responder (like your NSWindow subclass) - [super keyDown:theEvent]; -} - -- (void)keyUp:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); - - // pass the event along to the next responder (like your NSWindow subclass) - [super keyUp:theEvent]; -} - -- (void)flagsChanged:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -#pragma mark CCEAGLView - Touch events -- (void)touchesBeganWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)touchesMovedWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)touchesEndedWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} - -- (void)touchesCancelledWithEvent:(NSEvent *)theEvent -{ - DISPATCH_EVENT(theEvent, _cmd); -} -@end diff --git a/cocos/2d/platform/win32/CCApplication.cpp b/cocos/2d/platform/win32/CCApplication.cpp index 85fe2a4a4e..767917c0de 100644 --- a/cocos/2d/platform/win32/CCApplication.cpp +++ b/cocos/2d/platform/win32/CCApplication.cpp @@ -22,8 +22,12 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #include "CCApplication.h" -#include "CCEGLView.h" +#include "CCGLView.h" #include "CCDirector.h" #include #include "platform/CCFileUtils.h" @@ -72,16 +76,17 @@ int Application::run() return 0; } - EGLView* pMainWnd = EGLView::getInstance(); + auto director = Director::getInstance(); + auto glview = director->getOpenGLView(); - while(!pMainWnd->windowShouldClose()) + while(!glview->windowShouldClose()) { QueryPerformanceCounter(&nNow); if (nNow.QuadPart - nLast.QuadPart > _animationInterval.QuadPart) { nLast.QuadPart = nNow.QuadPart; - Director::getInstance()->mainLoop(); - pMainWnd->pollEvents(); + director->mainLoop(); + glview->pollEvents(); } else { @@ -94,8 +99,8 @@ int Application::run() * when we want to close the window, we should call Director::end(); * then call Director::mainLoop to do release of internal resources */ - Director::getInstance()->end(); - Director::getInstance()->mainLoop(); + director->end(); + director->mainLoop(); return true; } @@ -148,6 +153,9 @@ LanguageType Application::getCurrentLanguage() case LANG_SPANISH: ret = LanguageType::SPANISH; break; + case LANG_DUTCH: + ret = LanguageType::DUTCH; + break; case LANG_RUSSIAN: ret = LanguageType::RUSSIAN; break; @@ -245,3 +253,5 @@ static void PVRFrameEnableControlWindow(bool bEnable) RegCloseKey(hKey); } + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 diff --git a/cocos/2d/platform/win32/CCApplication.h b/cocos/2d/platform/win32/CCApplication.h index bd392a4f8c..c003280228 100644 --- a/cocos/2d/platform/win32/CCApplication.h +++ b/cocos/2d/platform/win32/CCApplication.h @@ -25,6 +25,9 @@ THE SOFTWARE. #ifndef __CC_APPLICATION_WIN32_H__ #define __CC_APPLICATION_WIN32_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #include "CCStdC.h" #include "platform/CCCommon.h" #include "platform/CCApplicationProtocol.h" @@ -101,4 +104,6 @@ protected: NS_CC_END +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #endif // __CC_APPLICATION_WIN32_H__ diff --git a/cocos/2d/platform/win32/CCCommon.cpp b/cocos/2d/platform/win32/CCCommon.cpp index 3aa3d6458f..86aa90f293 100644 --- a/cocos/2d/platform/win32/CCCommon.cpp +++ b/cocos/2d/platform/win32/CCCommon.cpp @@ -22,6 +22,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #include "platform/CCCommon.h" #include "CCStdC.h" @@ -55,3 +59,5 @@ void LuaLog(const char *pszMsg) } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 diff --git a/cocos/2d/platform/win32/CCDevice.cpp b/cocos/2d/platform/win32/CCDevice.cpp index e934679bdc..50c0bb579c 100644 --- a/cocos/2d/platform/win32/CCDevice.cpp +++ b/cocos/2d/platform/win32/CCDevice.cpp @@ -22,6 +22,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #include "platform/CCDevice.h" #include "CCStdC.h" @@ -47,4 +51,6 @@ void Device::setAccelerometerEnabled(bool isEnabled) void Device::setAccelerometerInterval(float interval) {} -NS_CC_END \ No newline at end of file +NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 diff --git a/cocos/2d/platform/win32/CCEGLView.h b/cocos/2d/platform/win32/CCEGLView.h deleted file mode 100644 index 17f9e4de06..0000000000 --- a/cocos/2d/platform/win32/CCEGLView.h +++ /dev/null @@ -1,107 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010-2012 cocos2d-x.org -Copyright (c) 2013-2014 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. -****************************************************************************/ - -#ifndef __CC_EGLVIEW_WIN32_H__ -#define __CC_EGLVIEW_WIN32_H__ - -#include "CCStdC.h" -#include "platform/CCCommon.h" -#include "CCGeometry.h" -#include "platform/CCEGLViewProtocol.h" - -#include "glfw3.h" - -NS_CC_BEGIN - -class EGL; - -class CC_DLL EGLView : public EGLViewProtocol -{ -public: - /** - * @js ctor - */ - EGLView(); - /** - * @js NA - * @lua NA - */ - virtual ~EGLView(); - - /* override functions */ - virtual bool isOpenGLReady(); - virtual void end(); - virtual void swapBuffers(); - virtual void setFrameSize(float width, float height); - virtual void setIMEKeyboardState(bool bOpen); - /* - *frameZoomFactor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop. - */ - bool init(const char* viewName, float width, float height, float frameZoomFactor = 1.0f); -public: - - //void resize(int width, int height); - float getFrameZoomFactor(); - //void centerWindow(); - - typedef void (*LPFN_ACCELEROMETER_KEYHOOK)( UINT message,WPARAM wParam, LPARAM lParam ); - void setAccelerometerKeyHook( LPFN_ACCELEROMETER_KEYHOOK lpfnAccelerometerKeyHook ); - - virtual void setViewPortInPoints(float x , float y , float w , float h); - virtual void setScissorInPoints(float x , float y , float w , float h); - - // static function - /** - @brief get the shared main open gl window - */ - static EGLView* getInstance(); - - /** @deprecated Use getInstance() instead */ - CC_DEPRECATED_ATTRIBUTE static EGLView* sharedOpenGLView(); -protected: - /* - * Set zoom factor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop. - */ - void setFrameZoomFactor(float fZoomFactor); -private: - bool _captured; - LPFN_ACCELEROMETER_KEYHOOK _lpfnAccelerometerKeyHook; - bool _supportTouch; - - int _frameBufferSize[2]; - float _frameZoomFactor; - static EGLView* s_pEglView; -public: - bool windowShouldClose(); - - void pollEvents(); - GLFWwindow* getWindow() const { return _mainWindow; } -private: - GLFWwindow* _mainWindow; -}; - -NS_CC_END - -#endif // end of __CC_EGLVIEW_WIN32_H__ diff --git a/cocos/2d/platform/win32/CCFileUtilsWin32.cpp b/cocos/2d/platform/win32/CCFileUtilsWin32.cpp index 8f70d1ba88..a1ce524bbe 100644 --- a/cocos/2d/platform/win32/CCFileUtilsWin32.cpp +++ b/cocos/2d/platform/win32/CCFileUtilsWin32.cpp @@ -22,6 +22,10 @@ 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 "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #include "CCFileUtilsWin32.h" #include "platform/CCCommon.h" #include @@ -303,3 +307,6 @@ string FileUtilsWin32::getWritablePath() const } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + diff --git a/cocos/2d/platform/win32/CCFileUtilsWin32.h b/cocos/2d/platform/win32/CCFileUtilsWin32.h index d11d148f07..6441e61037 100644 --- a/cocos/2d/platform/win32/CCFileUtilsWin32.h +++ b/cocos/2d/platform/win32/CCFileUtilsWin32.h @@ -25,6 +25,9 @@ THE SOFTWARE. #ifndef __CC_FILEUTILS_WIN32_H__ #define __CC_FILEUTILS_WIN32_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #include "platform/CCFileUtils.h" #include "CCPlatformMacros.h" #include "ccTypes.h" @@ -101,5 +104,7 @@ protected: NS_CC_END +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #endif // __CC_FILEUTILS_WIN32_H__ diff --git a/cocos/2d/platform/win32/CCGL.h b/cocos/2d/platform/win32/CCGL.h index 4d2d0f9002..6f6a9fee9f 100644 --- a/cocos/2d/platform/win32/CCGL.h +++ b/cocos/2d/platform/win32/CCGL.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef __CCGL_H__ #define __CCGL_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #include "GL/glew.h" #define CC_GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8 @@ -36,4 +39,6 @@ THE SOFTWARE. #define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02 #define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03 +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #endif // __CCGL_H__ diff --git a/cocos/2d/platform/win32/CCImage.cpp b/cocos/2d/platform/win32/CCImage.cpp index 8cc3f508e5..a753d3e9c7 100644 --- a/cocos/2d/platform/win32/CCImage.cpp +++ b/cocos/2d/platform/win32/CCImage.cpp @@ -23,6 +23,10 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #define __CC_PLATFORM_IMAGE_CPP__ + +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #if _MSC_VER #include #endif @@ -440,3 +444,5 @@ bool Image::initWithString( } NS_CC_END + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 diff --git a/cocos/2d/platform/win32/CCPlatformDefine.h b/cocos/2d/platform/win32/CCPlatformDefine.h index 964544860a..d0e3e4cb1e 100644 --- a/cocos/2d/platform/win32/CCPlatformDefine.h +++ b/cocos/2d/platform/win32/CCPlatformDefine.h @@ -25,6 +25,9 @@ THE SOFTWARE. #ifndef __CCPLATFORMDEFINE_H__ #define __CCPLATFORMDEFINE_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #ifdef __MINGW32__ #include #endif @@ -55,6 +58,6 @@ THE SOFTWARE. #endif #endif - +#endif //s CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #endif /* __CCPLATFORMDEFINE_H__*/ diff --git a/cocos/2d/platform/win32/CCStdC.cpp b/cocos/2d/platform/win32/CCStdC.cpp index 15862bc0ad..5b7683cea0 100644 --- a/cocos/2d/platform/win32/CCStdC.cpp +++ b/cocos/2d/platform/win32/CCStdC.cpp @@ -25,6 +25,9 @@ THE SOFTWARE. #include "CCStdC.h" +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #ifndef __MINGW32__ NS_CC_BEGIN @@ -45,3 +48,5 @@ int gettimeofday(struct timeval * val, struct timezone *) NS_CC_END #endif // __MINGW32__ + +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 diff --git a/cocos/2d/platform/win32/CCStdC.h b/cocos/2d/platform/win32/CCStdC.h index 47677d29c9..cdac427c5b 100644 --- a/cocos/2d/platform/win32/CCStdC.h +++ b/cocos/2d/platform/win32/CCStdC.h @@ -26,6 +26,9 @@ THE SOFTWARE. #ifndef __CC_STD_C_H__ #define __CC_STD_C_H__ +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + //typedef SSIZE_T ssize_t; // ssize_t was redefined as int in libwebsockets.h. // Therefore, to avoid conflict, we needs the same definition. @@ -151,5 +154,9 @@ inline errno_t strcpy_s(char *strDestination, size_t numberOfElements, #undef min #undef max +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #endif // __CC_STD_C_H__ + + diff --git a/cocos/2d/platform/win32/compat/stdint.h b/cocos/2d/platform/win32/compat/stdint.h index c66fbb817c..a7130075ca 100644 --- a/cocos/2d/platform/win32/compat/stdint.h +++ b/cocos/2d/platform/win32/compat/stdint.h @@ -29,13 +29,16 @@ // /////////////////////////////////////////////////////////////////////////////// +#ifndef _MSC_STDINT_H_ // [ +#define _MSC_STDINT_H_ + +#include "CCPlatformConfig.h" +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + #ifndef _MSC_VER // [ #error "Use this header only with Microsoft Visual C++ compilers!" #endif // _MSC_VER ] -#ifndef _MSC_STDINT_H_ // [ -#define _MSC_STDINT_H_ - #if _MSC_VER > 1000 #pragma once #endif @@ -243,5 +246,6 @@ typedef uint64_t uintmax_t; #endif // __STDC_CONSTANT_MACROS ] +#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #endif // _MSC_STDINT_H_ ] diff --git a/cocos/2d/platform/ios/CCEGLView.h b/cocos/2d/renderer/CCBatchCommand.cpp similarity index 54% rename from cocos/2d/platform/ios/CCEGLView.h rename to cocos/2d/renderer/CCBatchCommand.cpp index 3dce046feb..6b8d77c518 100644 --- a/cocos/2d/platform/ios/CCEGLView.h +++ b/cocos/2d/renderer/CCBatchCommand.cpp @@ -1,5 +1,4 @@ /**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -23,70 +22,52 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef __CC_EGLVIEW_IPHONE_H__ -#define __CC_EGLVIEW_IPHONE_H__ -#include "platform/CCCommon.h" -#include "platform/CCEGLViewProtocol.h" +#include "renderer/CCBatchCommand.h" +#include "ccGLStateCache.h" +#include "CCTextureAtlas.h" +#include "CCTexture2D.h" NS_CC_BEGIN - - -class CC_DLL EGLView : public EGLViewProtocol +BatchCommand::BatchCommand() +: _textureID(0) +, _blendType(BlendFunc::DISABLE) +, _textureAtlas(nullptr) { -public: - /** - * @js NA - * @lua NA - */ - EGLView(); - /** - * @js NA - * @lua NA - */ - ~EGLView(); - /** - * @js NA - * @lua NA - */ - virtual bool isOpenGLReady(); - /** - * @js NA - * @lua NA - */ - virtual bool setContentScaleFactor(float contentScaleFactor); + _type = RenderCommand::Type::BATCH_COMMAND; + _shader = nullptr; +} + +void BatchCommand::init(float globalOrder, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform) +{ + CCASSERT(shader, "shader cannot be nill"); + CCASSERT(textureAtlas, "textureAtlas cannot be nill"); - // keep compatible - /** - * @js NA - * @lua NA - */ - virtual void end(); - /** - * @js NA - * @lua NA - */ - virtual void swapBuffers(); - /** - * @js NA - * @lua NA - */ - virtual void setIMEKeyboardState(bool bOpen); + _globalOrder = globalOrder; + _textureID = textureAtlas->getTexture()->getName(); + _blendType = blendType; + _shader = shader; - /** returns the singleton - * @js NA - */ - static EGLView* getInstance(); + _textureAtlas = textureAtlas; - /** @deprecated Use getInstance() instead - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE static EGLView* sharedOpenGLView(); + _mv = modelViewTransform; +} -}; +BatchCommand::~BatchCommand() +{ +} -NS_CC_END +void BatchCommand::execute() +{ + // Set material + _shader->use(); + _shader->setUniformsForBuiltins(_mv); + GL::bindTexture2D(_textureID); + GL::blendFunc(_blendType.src, _blendType.dst); -#endif // end of __CC_EGLVIEW_IPHONE_H__ + // Draw + _textureAtlas->drawQuads(); +} + +NS_CC_END \ No newline at end of file diff --git a/cocos/2d/CCFontAtlasFactory.h b/cocos/2d/renderer/CCBatchCommand.h similarity index 65% rename from cocos/2d/CCFontAtlasFactory.h rename to cocos/2d/renderer/CCBatchCommand.h index 2a10cc8d63..a33f4ad891 100644 --- a/cocos/2d/CCFontAtlasFactory.h +++ b/cocos/2d/renderer/CCBatchCommand.h @@ -1,19 +1,18 @@ /**************************************************************************** - Copyright (c) 2013 Zynga Inc. Copyright (c) 2013-2014 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 @@ -23,26 +22,43 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef _CCFontAtlasFactory_h_ -#define _CCFontAtlasFactory_h_ - -#include "cocos2d.h" -#include "CCFontAtlas.h" +#ifndef _CC_BATCHCOMMAND_H_ +#define _CC_BATCHCOMMAND_H_ +#include "CCRenderCommand.h" +#include "CCGLProgram.h" +#include "CCRenderCommandPool.h" +#include "kazmath/kazmath.h" NS_CC_BEGIN -class CC_DLL FontAtlasFactory -{ - -public: - - static FontAtlas * createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false); - static FontAtlas * createAtlasFromFNT(const std::string& fntFilePath); - -private: -}; +class TextureAtlas; +#define CC_NO_TEXTURE 0 + +class BatchCommand : public RenderCommand +{ +public: + + BatchCommand(); + ~BatchCommand(); + + void init(float depth, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform); + + void execute(); + +protected: + //Material + int32_t _materialID; + GLuint _textureID; + GLProgram* _shader; + BlendFunc _blendType; + + TextureAtlas *_textureAtlas; + + // ModelView transform + kmMat4 _mv; +}; NS_CC_END -#endif /* defined(_CCFontAtlasFactory_h_) */ +#endif //_CC_BATCHCOMMAND_H_ diff --git a/cocos/2d/renderer/CCCustomCommand.cpp b/cocos/2d/renderer/CCCustomCommand.cpp index 790bd13e69..c324032116 100644 --- a/cocos/2d/renderer/CCCustomCommand.cpp +++ b/cocos/2d/renderer/CCCustomCommand.cpp @@ -22,23 +22,19 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCCustomCommand.h" +#include "renderer/CCCustomCommand.h" NS_CC_BEGIN CustomCommand::CustomCommand() -:RenderCommand() -, func(nullptr) -, _viewport(0) -, _depth(0) +: func(nullptr) { _type = RenderCommand::Type::CUSTOM_COMMAND; } -void CustomCommand::init(int viewport, int32_t depth) +void CustomCommand::init(float globalOrder) { - _viewport = viewport; - _depth = depth; + _globalOrder = globalOrder; } CustomCommand::~CustomCommand() @@ -46,17 +42,6 @@ CustomCommand::~CustomCommand() } -int64_t CustomCommand::generateID() -{ - _id = 0; - - _id = (int64_t)_viewport << 61 - | (int64_t)1 << 60 // translucent - | (int64_t)_depth << 36; - - return _id; -} - void CustomCommand::execute() { if(func) diff --git a/cocos/2d/renderer/CCCustomCommand.h b/cocos/2d/renderer/CCCustomCommand.h index 7ff4c3e3ca..03fdead69a 100644 --- a/cocos/2d/renderer/CCCustomCommand.h +++ b/cocos/2d/renderer/CCCustomCommand.h @@ -39,14 +39,7 @@ public: public: - void init(int viewport, int32_t depth); - - // +----------+----------+-----+-----------------------------------+ - // | | | | | | - // | ViewPort | Transluc | | Depth | | - // | 3 bits | 1 bit | | 24 bits | | - // +----------+----------+-----+----------------+------------------+ - virtual int64_t generateID(); + void init(float depth); void execute(); @@ -54,8 +47,6 @@ public: std::function func; protected: - int _viewport; - int32_t _depth; }; NS_CC_END diff --git a/cocos/2d/renderer/CCFrustum.cpp b/cocos/2d/renderer/CCFrustum.cpp index e02236e3b0..4f88e2356f 100644 --- a/cocos/2d/renderer/CCFrustum.cpp +++ b/cocos/2d/renderer/CCFrustum.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCFrustum.h" +#include "renderer/CCFrustum.h" #include "CCConsole.h" #include diff --git a/cocos/2d/renderer/CCGroupCommand.cpp b/cocos/2d/renderer/CCGroupCommand.cpp index 8bd6f85888..95b9a5ccb5 100644 --- a/cocos/2d/renderer/CCGroupCommand.cpp +++ b/cocos/2d/renderer/CCGroupCommand.cpp @@ -23,8 +23,8 @@ ****************************************************************************/ -#include "CCGroupCommand.h" -#include "CCRenderer.h" +#include "renderer/CCGroupCommand.h" +#include "renderer/CCRenderer.h" #include "CCDirector.h" NS_CC_BEGIN @@ -86,18 +86,14 @@ void GroupCommandManager::releaseGroupID(int groupID) } GroupCommand::GroupCommand() -:RenderCommand() -, _viewport(0) -, _depth(0) { _type = RenderCommand::Type::GROUP_COMMAND; _renderQueueID = GroupCommandManager::getInstance()->getGroupID(); } -void GroupCommand::init(int viewport, int32_t depth) +void GroupCommand::init(float globalOrder) { - _viewport = viewport; - _depth = depth; + _globalOrder = globalOrder; GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID); _renderQueueID = GroupCommandManager::getInstance()->getGroupID(); } @@ -107,15 +103,4 @@ GroupCommand::~GroupCommand() GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID); } -int64_t GroupCommand::generateID() -{ - _id = 0; - - _id = (int64_t)_viewport << 61 - | (int64_t)1 << 60 // translucent - | (int64_t)_depth << 36; - - return _id; -} - NS_CC_END diff --git a/cocos/2d/renderer/CCGroupCommand.h b/cocos/2d/renderer/CCGroupCommand.h index 7a6b6e511c..42c23d02b9 100644 --- a/cocos/2d/renderer/CCGroupCommand.h +++ b/cocos/2d/renderer/CCGroupCommand.h @@ -56,23 +56,11 @@ public: GroupCommand(); ~GroupCommand(); -public: + void init(float depth); - void init(int viewport, int32_t depth); - - // +----------+----------+-----+-----------------------------------+ - // | | | | | | - // | ViewPort | Transluc | | Depth | | - // | 3 bits | 1 bit | | 24 bits | | - // +----------+----------+-----+----------------+------------------+ - virtual int64_t generateID() override; - - inline bool isTranslucent() {return true;} - inline int getRenderQueueID() {return _renderQueueID;} + inline int getRenderQueueID() const {return _renderQueueID;} protected: - int _viewport; - int32_t _depth; int _renderQueueID; }; diff --git a/cocos/2d/renderer/CCQuadCommand.cpp b/cocos/2d/renderer/CCQuadCommand.cpp index b69fd075d3..9cae10d701 100644 --- a/cocos/2d/renderer/CCQuadCommand.cpp +++ b/cocos/2d/renderer/CCQuadCommand.cpp @@ -29,88 +29,36 @@ NS_CC_BEGIN QuadCommand::QuadCommand() -:RenderCommand() -,_viewport(0) -,_depth(0) -,_textureID(0) +:_textureID(0) ,_blendType(BlendFunc::DISABLE) -,_quadCount(0) -,_capacity(0) +,_quadsCount(0) { _type = RenderCommand::Type::QUAD_COMMAND; _shader = nullptr; - _quad = nullptr; + _quads = nullptr; } -void QuadCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, const kmMat4 &mv) +void QuadCommand::init(float globalOrder, GLuint textureID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, const kmMat4 &mv) { - _viewport = viewport; - _depth = depth; + _globalOrder = globalOrder; _textureID = textureID; _blendType = blendType; - _quadCount = quadCount; _shader = shader; - if(quadCount > _capacity ) { - //TODO find a better way to manage quads, current way will result in memory be wasted -// _quad = (V3F_C4B_T2F_Quad*)malloc(sizeof(V3F_C4B_T2F_Quad) * quadCount); - _quad = (V3F_C4B_T2F_Quad*) realloc(_quad, sizeof(*quad) * quadCount ); - _capacity = quadCount; - } + _quadsCount = quadCount; + _quads = quad; - _quadCount = quadCount; - memcpy(_quad, quad, sizeof(V3F_C4B_T2F_Quad) * quadCount); + _mv = mv; - for(int i=0; ibl.vertices.x; - vec1.y = q->bl.vertices.y; - vec1.z = q->bl.vertices.z; - kmVec3Transform(&out1, &vec1, &mv); - q->bl.vertices.x = out1.x; - q->bl.vertices.y = out1.y; - q->bl.vertices.z = out1.z; - - kmVec3 vec2, out2; - vec2.x = q->br.vertices.x; - vec2.y = q->br.vertices.y; - vec2.z = q->br.vertices.z; - kmVec3Transform(&out2, &vec2, &mv); - q->br.vertices.x = out2.x; - q->br.vertices.y = out2.y; - q->br.vertices.z = out2.z; - - kmVec3 vec3, out3; - vec3.x = q->tr.vertices.x; - vec3.y = q->tr.vertices.y; - vec3.z = q->tr.vertices.z; - kmVec3Transform(&out3, &vec3, &mv); - q->tr.vertices.x = out3.x; - q->tr.vertices.y = out3.y; - q->tr.vertices.z = out3.z; - - kmVec3 vec4, out4; - vec4.x = q->tl.vertices.x; - vec4.y = q->tl.vertices.y; - vec4.z = q->tl.vertices.z; - kmVec3Transform(&out4, &vec4, &mv); - q->tl.vertices.x = out4.x; - q->tl.vertices.y = out4.y; - q->tl.vertices.z = out4.z; - } + generateMaterialID(); } QuadCommand::~QuadCommand() { - free(_quad); } -int64_t QuadCommand::generateID() +void QuadCommand::generateMaterialID() { - _id = 0; - //Generate Material ID //TODO fix shader ID generation CCASSERT(_shader->getProgram() < pow(2,10), "ShaderID is greater than 2^10"); @@ -148,19 +96,12 @@ int64_t QuadCommand::generateID() // | Shader ID (10 bits) | Blend ID (4 bits) | Texture ID (18 bits) | // +---------------------+-------------------+----------------------+ - _materialID = (int32_t)_shader->getProgram() << 22 - | (int32_t)blendID << 18 - | (int32_t)_textureID << 0; - - //Generate RenderCommandID - _id = (int64_t)_viewport << 61 - | (int64_t)1 << 60 //translucent - | (int64_t)_depth << 36; - - return _id; + _materialID = (uint32_t)_shader->getProgram() << 22 + | (uint32_t)blendID << 18 + | (uint32_t)_textureID << 0; } -void QuadCommand::useMaterial() +void QuadCommand::useMaterial() const { _shader->use(); diff --git a/cocos/2d/renderer/CCQuadCommand.h b/cocos/2d/renderer/CCQuadCommand.h index 411dc4913b..42411f48e9 100644 --- a/cocos/2d/renderer/CCQuadCommand.h +++ b/cocos/2d/renderer/CCQuadCommand.h @@ -41,41 +41,31 @@ public: QuadCommand(); ~QuadCommand(); - void init(int viewport, int32_t depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, + void init(float depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quads, ssize_t quadCount, const kmMat4& mv); - // +----------+----------+-----+-----------------------------------+ - // | | | | | | - // | ViewPort | Transluc | | Depth | Material ID | - // | 3 bits | 1 bit | | 24 bits | 24 bit2 | - // +----------+----------+-----+----------------+------------------+ - virtual int64_t generateID(); - - void useMaterial(); + void useMaterial() const; //TODO use material to decide if it is translucent inline bool isTranslucent() const { return true; } - inline int32_t getMaterialID() const { return _materialID; } + void generateMaterialID(); + inline uint32_t getMaterialID() const { return _materialID; } inline GLuint getTextureID() const { return _textureID; } - inline V3F_C4B_T2F_Quad* getQuad() const { return _quad; } + inline V3F_C4B_T2F_Quad* getQuads() const { return _quads; } - inline ssize_t getQuadCount() const { return _quadCount; } + inline ssize_t getQuadCount() const { return _quadsCount; } inline GLProgram* getShader() const { return _shader; } inline BlendFunc getBlendType() const { return _blendType; } + + inline const kmMat4& getModelView() const { return _mv; } protected: - int32_t _materialID; - - //Key Data - int _viewport; /// Which view port it belongs to - - //TODO use material to determine if it's translucent - int32_t _depth; + uint32_t _materialID; //Maternal GLuint _textureID; @@ -85,9 +75,10 @@ protected: BlendFunc _blendType; - V3F_C4B_T2F_Quad* _quad; - ssize_t _quadCount; - ssize_t _capacity; + V3F_C4B_T2F_Quad* _quads; + ssize_t _quadsCount; + + kmMat4 _mv; }; NS_CC_END diff --git a/cocos/2d/renderer/CCRenderCommand.cpp b/cocos/2d/renderer/CCRenderCommand.cpp index 71fee4edb0..578f28d426 100644 --- a/cocos/2d/renderer/CCRenderCommand.cpp +++ b/cocos/2d/renderer/CCRenderCommand.cpp @@ -28,9 +28,9 @@ NS_CC_BEGIN RenderCommand::RenderCommand() +: _type(RenderCommand::Type::UNKNOWN_COMMAND) +, _globalOrder(0) { - _id = 0; - _type = RenderCommand::Type::UNKNOWN_COMMAND; } RenderCommand::~RenderCommand() @@ -57,9 +57,7 @@ void printBits(ssize_t const size, void const * const ptr) void RenderCommand::printID() { - printf("CommandID: "); - printBits(sizeof(_id), &_id); - printf("\n"); + printf("Command Depth: %f\n", _globalOrder); } NS_CC_END \ No newline at end of file diff --git a/cocos/2d/renderer/CCRenderCommand.h b/cocos/2d/renderer/CCRenderCommand.h index 930ed1ecde..688f65feb7 100644 --- a/cocos/2d/renderer/CCRenderCommand.h +++ b/cocos/2d/renderer/CCRenderCommand.h @@ -33,25 +33,27 @@ NS_CC_BEGIN -//TODO make RenderCommand inherent from Object +/** Base class of the RenderCommand hierarchy. + The Renderer knows how to render RenderCommands. + */ class RenderCommand { public: enum class Type { + UNKNOWN_COMMAND, QUAD_COMMAND, CUSTOM_COMMAND, + BATCH_COMMAND, GROUP_COMMAND, - UNKNOWN_COMMAND, }; - virtual int64_t generateID() = 0; - /** Get Render Command Id */ - virtual inline int64_t getID() { return _id; } - - virtual inline Type getType() { return _type; } + inline float getGlobalOrder() const { return _globalOrder; } + + /** Returns the Command type */ + inline Type getType() const { return _type; } protected: RenderCommand(); @@ -59,9 +61,11 @@ protected: void printID(); - //Generated IDs - int64_t _id; /// used for sorting render commands + // Type used in order to avoid dynamic cast, faster Type _type; + + // commands are sort by depth + float _globalOrder; }; NS_CC_END diff --git a/cocos/2d/renderer/CCRenderer.cpp b/cocos/2d/renderer/CCRenderer.cpp index 2763f71ef6..a99822e332 100644 --- a/cocos/2d/renderer/CCRenderer.cpp +++ b/cocos/2d/renderer/CCRenderer.cpp @@ -22,29 +22,84 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCRenderer.h" +#include "renderer/CCRenderer.h" +#include "renderer/CCQuadCommand.h" +#include "renderer/CCBatchCommand.h" +#include "renderer/CCCustomCommand.h" +#include "renderer/CCGroupCommand.h" #include "CCShaderCache.h" #include "ccGLStateCache.h" -#include "CCCustomCommand.h" -#include "renderer/CCQuadCommand.h" -#include "CCGroupCommand.h" #include "CCConfiguration.h" #include "CCDirector.h" #include "CCEventDispatcher.h" #include "CCEventListenerCustom.h" #include "CCEventType.h" -#include // for std::stable_sort +#include NS_CC_BEGIN -using namespace std; + +bool compareRenderCommand(RenderCommand* a, RenderCommand* b) +{ + return a->getGlobalOrder() < b->getGlobalOrder(); +} + +void RenderQueue::push_back(RenderCommand* command) +{ + float z = command->getGlobalOrder(); + if(z < 0) + _queueNegZ.push_back(command); + else if(z > 0) + _queuePosZ.push_back(command); + else + _queue0.push_back(command); +} + +ssize_t RenderQueue::size() const +{ + return _queueNegZ.size() + _queue0.size() + _queuePosZ.size(); +} + +void RenderQueue::sort() +{ + // Don't sort _queue0, it already comes sorted + std::sort(std::begin(_queueNegZ), std::end(_queueNegZ), compareRenderCommand); + std::sort(std::begin(_queuePosZ), std::end(_queuePosZ), compareRenderCommand); +} + +RenderCommand* RenderQueue::operator[](ssize_t index) const +{ + if(index < _queueNegZ.size()) + return _queueNegZ[index]; + + index -= _queueNegZ.size(); + + if(index < _queue0.size()) + return _queue0[index]; + + index -= _queue0.size(); + + if(index < _queuePosZ.size()) + return _queuePosZ[index]; + + CCASSERT(false, "invalid index"); + return nullptr; +} + +void RenderQueue::clear() +{ + _queueNegZ.clear(); + _queue0.clear(); + _queuePosZ.clear(); +} +// +// +// #define DEFAULT_RENDER_QUEUE 0 Renderer::Renderer() :_lastMaterialID(0) -,_firstCommand(0) -,_lastCommand(0) ,_numQuads(0) ,_glViewAssigned(false) #if CC_ENABLE_CACHE_TEXTURE_DATA @@ -57,6 +112,7 @@ Renderer::Renderer() _renderGroups.push_back(defaultRenderQueue); RenderStackElement elelment = {DEFAULT_RENDER_QUEUE, 0}; _renderStack.push(elelment); + _batchedQuadCommands.reserve(BATCH_QUADCOMMAND_RESEVER_SIZE); } Renderer::~Renderer() @@ -176,13 +232,14 @@ void Renderer::mapBuffers() void Renderer::addCommand(RenderCommand* command) { - command->generateID(); - _renderGroups[_commandGroupStack.top()].push_back(command); + int renderQueue =_commandGroupStack.top(); + addCommand(command, renderQueue); } void Renderer::addCommand(RenderCommand* command, int renderQueue) { - command->generateID(); + CCASSERT(renderQueue >=0, "Invalid render queue"); + CCASSERT(command->getType() != RenderCommand::Type::UNKNOWN_COMMAND, "Invalid Command Type"); _renderGroups[renderQueue].push_back(command); } @@ -203,11 +260,6 @@ int Renderer::createRenderQueue() return (int)_renderGroups.size() - 1; } -bool compareRenderCommand(RenderCommand* a, RenderCommand* b) -{ - return a->getID() < b->getID(); -} - void Renderer::render() { //Uncomment this once everything is rendered by new renderer @@ -219,9 +271,9 @@ void Renderer::render() { //Process render commands //1. Sort render commands based on ID - for (auto it = _renderGroups.begin(); it != _renderGroups.end(); ++it) + for (auto &renderqueue : _renderGroups) { - std::stable_sort((*it).begin(), (*it).end(), compareRenderCommand); + renderqueue.sort(); } while(!_renderStack.empty()) @@ -229,46 +281,51 @@ void Renderer::render() RenderQueue currRenderQueue = _renderGroups[_renderStack.top().renderQueueID]; size_t len = currRenderQueue.size(); - //Refresh the batch command index in case the renderStack has changed. - _firstCommand = _lastCommand = _renderStack.top().currentIndex; - //Process RenderQueue for(size_t i = _renderStack.top().currentIndex; i < len; i++) { - _renderStack.top().currentIndex = _lastCommand = i; + _renderStack.top().currentIndex = i; auto command = currRenderQueue[i]; auto commandType = command->getType(); if(commandType == RenderCommand::Type::QUAD_COMMAND) { - QuadCommand* cmd = static_cast(command); - ssize_t cmdQuadCount = cmd->getQuadCount(); + auto cmd = static_cast(command); + CCASSERT(nullptr!= cmd, "Illegal command for RenderCommand Taged as QUAD_COMMAND"); //Batch quads - if(_numQuads + cmdQuadCount > VBO_SIZE) + if(_numQuads + cmd->getQuadCount() > VBO_SIZE) { - CCASSERT(cmdQuadCount < VBO_SIZE, "VBO is not big enough for quad data, please break the quad data down or use customized render command"); + CCASSERT(cmd->getQuadCount()>= 0 && cmd->getQuadCount() < VBO_SIZE, "VBO is not big enough for quad data, please break the quad data down or use customized render command"); //Draw batched quads if VBO is full - _lastCommand --; drawBatchedQuads(); - _lastCommand ++; } + + _batchedQuadCommands.push_back(cmd); + + memcpy(_quads + _numQuads, cmd->getQuads(), sizeof(V3F_C4B_T2F_Quad) * cmd->getQuadCount()); + convertToWorldCoordinates(_quads + _numQuads, cmd->getQuadCount(), cmd->getModelView()); - memcpy(_quads + _numQuads, cmd->getQuad(), sizeof(V3F_C4B_T2F_Quad) * cmdQuadCount); - _numQuads += cmdQuadCount; + _numQuads += cmd->getQuadCount(); } else if(commandType == RenderCommand::Type::CUSTOM_COMMAND) { flush(); - CustomCommand* cmd = static_cast(command); + auto cmd = static_cast(command); + cmd->execute(); + } + else if(commandType == RenderCommand::Type::BATCH_COMMAND) + { + flush(); + auto cmd = static_cast(command); cmd->execute(); } else if(commandType == RenderCommand::Type::GROUP_COMMAND) { flush(); - GroupCommand* cmd = static_cast(command); + auto cmd = static_cast(command); _renderStack.top().currentIndex = i + 1; @@ -281,6 +338,7 @@ void Renderer::render() } else { + CCASSERT(true, "Invalid command"); flush(); } } @@ -315,10 +373,32 @@ void Renderer::render() } RenderStackElement element = {DEFAULT_RENDER_QUEUE, 0}; _renderStack.push(element); - _firstCommand = _lastCommand = 0; _lastMaterialID = 0; } +void Renderer::convertToWorldCoordinates(V3F_C4B_T2F_Quad* quads, ssize_t quantity, const kmMat4& modelView) +{ +// kmMat4 matrixP, mvp; +// kmGLGetMatrix(KM_GL_PROJECTION, &matrixP); +// kmMat4Multiply(&mvp, &matrixP, &modelView); + + for(ssize_t i=0; ibl.vertices; + kmVec3Transform(vec1, vec1, &modelView); + + kmVec3 *vec2 = (kmVec3*)&q->br.vertices; + kmVec3Transform(vec2, vec2, &modelView); + + kmVec3 *vec3 = (kmVec3*)&q->tr.vertices; + kmVec3Transform(vec3, vec3, &modelView); + + kmVec3 *vec4 = (kmVec3*)&q->tl.vertices; + kmVec3Transform(vec4, vec4, &modelView); + } +} + void Renderer::drawBatchedQuads() { //TODO we can improve the draw performance by insert material switching command before hand. @@ -327,9 +407,8 @@ void Renderer::drawBatchedQuads() int startQuad = 0; //Upload buffer to VBO - if(_numQuads <= 0) + if(_numQuads <= 0 || _batchedQuadCommands.empty()) { - _firstCommand = _lastCommand; return; } @@ -338,6 +417,13 @@ void Renderer::drawBatchedQuads() //Set VBO data glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); + // option 1: subdata +// glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * n , &_quads[start] ); + + // option 2: data +// glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * (n-start), &quads_[start], GL_DYNAMIC_DRAW); + + // option 3: orphaning + glMapBuffer glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * (_numQuads), nullptr, GL_DYNAMIC_DRAW); void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); memcpy(buf, _quads, sizeof(_quads[0])* (_numQuads)); @@ -353,7 +439,7 @@ void Renderer::drawBatchedQuads() #define kQuadSize sizeof(_quads[0].bl) glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); - glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(_quads[0]) * _numQuads , _quads); + glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * _numQuads , _quads, GL_DYNAMIC_DRAW); GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); @@ -370,31 +456,27 @@ void Renderer::drawBatchedQuads() } //Start drawing verties in batch - for(size_t i = _firstCommand; i <= _lastCommand; i++) + //for(auto i = _batchedQuadCommands.begin(); i != _batchedQuadCommands.end(); ++i) + for(const auto& cmd : _batchedQuadCommands) { - RenderCommand* command = _renderGroups[_renderStack.top().renderQueueID][i]; - if (command->getType() == RenderCommand::Type::QUAD_COMMAND) + if(_lastMaterialID != cmd->getMaterialID()) { - QuadCommand* cmd = static_cast(command); - if(_lastMaterialID != cmd->getMaterialID()) + //Draw quads + if(quadsToDraw > 0) { - //Draw quads - if(quadsToDraw > 0) - { - glDrawElements(GL_TRIANGLES, (GLsizei) quadsToDraw*6, GL_UNSIGNED_SHORT, (GLvoid*) (startQuad*6*sizeof(_indices[0])) ); - CC_INCREMENT_GL_DRAWS(1); + glDrawElements(GL_TRIANGLES, (GLsizei) quadsToDraw*6, GL_UNSIGNED_SHORT, (GLvoid*) (startQuad*6*sizeof(_indices[0])) ); + CC_INCREMENT_GL_DRAWS(1); - startQuad += quadsToDraw; - quadsToDraw = 0; - } - - //Use new material - cmd->useMaterial(); - _lastMaterialID = cmd->getMaterialID(); + startQuad += quadsToDraw; + quadsToDraw = 0; } - quadsToDraw += cmd->getQuadCount(); + //Use new material + cmd->useMaterial(); + _lastMaterialID = cmd->getMaterialID(); } + + quadsToDraw += cmd->getQuadCount(); } //Draw any remaining quad @@ -415,8 +497,7 @@ void Renderer::drawBatchedQuads() glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } - - _firstCommand = _lastCommand + 1; + _batchedQuadCommands.clear(); _numQuads = 0; } @@ -426,4 +507,4 @@ void Renderer::flush() _lastMaterialID = 0; } -NS_CC_END \ No newline at end of file +NS_CC_END diff --git a/cocos/2d/renderer/CCRenderer.h b/cocos/2d/renderer/CCRenderer.h index e732547130..3d637394ae 100644 --- a/cocos/2d/renderer/CCRenderer.h +++ b/cocos/2d/renderer/CCRenderer.h @@ -36,19 +36,40 @@ NS_CC_BEGIN class EventListenerCustom; +class QuadCommand; -typedef std::vector RenderQueue; +/** Class that knows how to sort the Commands. + Since the commands that have z==0 are "pushed back" in + the correct order, the only Commands that need to be sorted, + are the ones that have z <0 and z >0. + And that is what this class does. +*/ +class RenderQueue { + +public: + void push_back(RenderCommand* command); + ssize_t size() const; + void sort(); + RenderCommand* operator[](ssize_t index) const; + void clear(); + +protected: + std::vector _queueNegZ; + std::vector _queue0; + std::vector _queuePosZ; +}; struct RenderStackElement { int renderQueueID; - size_t currentIndex; + ssize_t currentIndex; }; class Renderer { public: static const int VBO_SIZE = 65536 / 6; + static const int BATCH_QUADCOMMAND_RESEVER_SIZE = 64; Renderer(); ~Renderer(); @@ -75,18 +96,20 @@ protected: void mapBuffers(); void drawBatchedQuads(); + //Draw the previews queued quads and flush previous context void flush(); + void convertToWorldCoordinates(V3F_C4B_T2F_Quad* quads, ssize_t quantity, const kmMat4& modelView); + std::stack _commandGroupStack; std::stack _renderStack; std::vector _renderGroups; - int _lastMaterialID; + uint32_t _lastMaterialID; - size_t _firstCommand; - size_t _lastCommand; + std::vector _batchedQuadCommands; V3F_C4B_T2F_Quad _quads[VBO_SIZE]; GLushort _indices[6 * VBO_SIZE]; diff --git a/cocos/base/CCAutoreleasePool.cpp b/cocos/base/CCAutoreleasePool.cpp index 5e551ec3aa..3ce5ea4d65 100644 --- a/cocos/base/CCAutoreleasePool.cpp +++ b/cocos/base/CCAutoreleasePool.cpp @@ -27,54 +27,71 @@ THE SOFTWARE. NS_CC_BEGIN -static PoolManager* s_pPoolManager = NULL; - AutoreleasePool::AutoreleasePool() +: _name("") +#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) +, _isClearing(false) +#endif { _managedObjectArray.reserve(150); + PoolManager::getInstance()->push(this); +} + +AutoreleasePool::AutoreleasePool(const std::string &name) +: _name(name) +#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) +, _isClearing(false) +#endif +{ + _managedObjectArray.reserve(150); + PoolManager::getInstance()->push(this); } AutoreleasePool::~AutoreleasePool() { CCLOGINFO("deallocing AutoreleasePool: %p", this); + clear(); + + PoolManager::getInstance()->pop(); } void AutoreleasePool::addObject(Object* object) { - _managedObjectArray.pushBack(object); - - CCASSERT(object->_reference > 1, "reference count should be greater than 1"); - ++(object->_autoReleaseCount); - object->release(); // no ref count, in this case autorelease pool added. -} - -void AutoreleasePool::removeObject(Object* object) -{ - for (unsigned int i = 0; i < object->_autoReleaseCount; ++i) - { - _managedObjectArray.eraseObject(object, false); - } + _managedObjectArray.push_back(object); } void AutoreleasePool::clear() { - if (!_managedObjectArray.empty()) +#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) + _isClearing = true; +#endif + for (const auto &obj : _managedObjectArray) { - //CCAutoreleasePool* pReleasePool; -#ifdef _DEBUG - int nIndex = _managedObjectArray.size() - 1; + obj->release(); + } + _managedObjectArray.clear(); +#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) + _isClearing = false; #endif +} - for(const auto &obj : _managedObjectArray) { - --(obj->_autoReleaseCount); - //(*it)->release(); - //delete (*it); -#ifdef _DEBUG - nIndex--; -#endif - } +bool AutoreleasePool::contains(Object* object) const +{ + for (const auto& obj : _managedObjectArray) + { + if (obj == object) + return true; + } + return false; +} - _managedObjectArray.clear(); +void AutoreleasePool::dump() +{ + CCLOG("autorelease pool: %s, number of managed object %d\n", _name.c_str(), static_cast(_managedObjectArray.size())); + CCLOG("%20s%20s%20s", "Object pointer", "Object id", "reference count"); + for (const auto &obj : _managedObjectArray) + { + CCLOG("%20p%20u%20u\n", obj, obj->_ID, obj->getReferenceCount()); } } @@ -85,105 +102,77 @@ void AutoreleasePool::clear() // //-------------------------------------------------------------------- -PoolManager* PoolManager::sharedPoolManager() +PoolManager* PoolManager::s_singleInstance = nullptr; + +PoolManager* PoolManager::getInstance() { - if (s_pPoolManager == NULL) + if (s_singleInstance == nullptr) { - s_pPoolManager = new PoolManager(); + s_singleInstance = new PoolManager(); + // Add the first auto release pool + s_singleInstance->_curReleasePool = new AutoreleasePool("cocos2d autorelease pool"); + s_singleInstance->_releasePoolStack.push_back(s_singleInstance->_curReleasePool); } - return s_pPoolManager; + return s_singleInstance; } -void PoolManager::purgePoolManager() +void PoolManager::destroyInstance() { - CC_SAFE_DELETE(s_pPoolManager); + delete s_singleInstance; + s_singleInstance = nullptr; } PoolManager::PoolManager() { - _releasePoolStack.reserve(150); - _curReleasePool = 0; } PoolManager::~PoolManager() { CCLOGINFO("deallocing PoolManager: %p", this); - finalize(); - - // we only release the last autorelease pool here - _curReleasePool = 0; - _releasePoolStack.erase(0); -} - -void PoolManager::finalize() -{ - if (!_releasePoolStack.empty()) + + while (!_releasePoolStack.empty()) { - for(const auto &pool : _releasePoolStack) { - pool->clear(); - } + AutoreleasePool* pool = _releasePoolStack.back(); + _releasePoolStack.pop_back(); + + delete pool; } } -void PoolManager::push() + +AutoreleasePool* PoolManager::getCurrentPool() const { - AutoreleasePool* pool = new AutoreleasePool(); //ref = 1 + return _curReleasePool; +} + +bool PoolManager::isObjectInPools(Object* obj) const +{ + for (const auto& pool : _releasePoolStack) + { + if (pool->contains(obj)) + return true; + } + return false; +} + +void PoolManager::push(AutoreleasePool *pool) +{ + _releasePoolStack.push_back(pool); _curReleasePool = pool; - - _releasePoolStack.pushBack(pool); //ref = 2 - - pool->release(); //ref = 1 } void PoolManager::pop() { - if (! _curReleasePool) + // Can not pop the pool that created by engine + CC_ASSERT(_releasePoolStack.size() >= 1); + + _releasePoolStack.pop_back(); + + // Should update _curReleasePool if a temple pool is released + if (_releasePoolStack.size() > 1) { - return; + _curReleasePool = _releasePoolStack.back(); } - - ssize_t count = _releasePoolStack.size(); - - _curReleasePool->clear(); - - if (count > 1) - { - _releasePoolStack.erase(count-1); - -// if(nCount > 1) -// { -// _curReleasePool = _releasePoolStack.at(count - 2); -// return; -// } - _curReleasePool = _releasePoolStack.at(count - 2); - } - - /*_curReleasePool = NULL;*/ -} - -void PoolManager::removeObject(Object* object) -{ - CCASSERT(_curReleasePool, "current auto release pool should not be null"); - - _curReleasePool->removeObject(object); -} - -void PoolManager::addObject(Object* object) -{ - getCurReleasePool()->addObject(object); -} - - -AutoreleasePool* PoolManager::getCurReleasePool() -{ - if(!_curReleasePool) - { - push(); - } - - CCASSERT(_curReleasePool, "current auto release pool should not be null"); - - return _curReleasePool; } NS_CC_END diff --git a/cocos/base/CCAutoreleasePool.h b/cocos/base/CCAutoreleasePool.h index d6ee35349b..63461f6262 100644 --- a/cocos/base/CCAutoreleasePool.h +++ b/cocos/base/CCAutoreleasePool.h @@ -25,8 +25,10 @@ THE SOFTWARE. #ifndef __AUTORELEASEPOOL_H__ #define __AUTORELEASEPOOL_H__ +#include +#include +#include #include "CCObject.h" -#include "CCVector.h" NS_CC_BEGIN @@ -35,24 +37,21 @@ NS_CC_BEGIN * @{ */ -class CC_DLL AutoreleasePool : public Object +class CC_DLL AutoreleasePool { - /** - * The underlying array of object managed by the pool. - * - * Although Array retains the object once when an object is added, proper - * Object::release() is called outside the array to make sure that the pool - * does not affect the managed object's reference count. So an object can - * be destructed properly by calling Object::release() even if the object - * is in the pool. - */ - Vector _managedObjectArray; public: /** + * @warn Don't create an auto release pool in heap, create it in stack. * @js NA * @lua NA */ AutoreleasePool(); + + /** + * Create an autorelease pool with specific name. This name is useful for debugging. + */ + AutoreleasePool(const std::string &name); + /** * @js NA * @lua NA @@ -72,15 +71,6 @@ public: */ void addObject(Object *object); - /** - * Remove a given object from this pool. - * - * @param object The object to be removed from the pool. - * @js NA - * @lua NA - */ - void removeObject(Object *object); - /** * Clear the autorelease pool. * @@ -90,88 +80,91 @@ public: * @lua NA */ void clear(); + +#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) + /** + * Whether the pool is doing `clear` operation. + */ + bool isClearing() const { return _isClearing; }; +#endif + + /** + * Checks whether the pool contains the specified object. + */ + bool contains(Object* object) const; + + /** + * Dump the objects that are put into autorelease pool. It is used for debugging. + * + * The result will look like: + * Object pointer address object id reference count + * + */ + void dump(); + +private: + /** + * The underlying array of object managed by the pool. + * + * Although Array retains the object once when an object is added, proper + * Object::release() is called outside the array to make sure that the pool + * does not affect the managed object's reference count. So an object can + * be destructed properly by calling Object::release() even if the object + * is in the pool. + */ + std::vector _managedObjectArray; + std::string _name; + +#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) + /** + * The flag for checking whether the pool is doing `clear` operation. + */ + bool _isClearing; +#endif }; class CC_DLL PoolManager { - Vector _releasePoolStack; - AutoreleasePool *_curReleasePool; - - AutoreleasePool *getCurReleasePool(); public: /** * @js NA * @lua NA */ - static PoolManager* sharedPoolManager(); + CC_DEPRECATED_ATTRIBUTE static PoolManager* sharedPoolManager() { return getInstance(); } + static PoolManager* getInstance(); + /** * @js NA * @lua NA */ - static void purgePoolManager(); + CC_DEPRECATED_ATTRIBUTE static void purgePoolManager() { destroyInstance(); } + static void destroyInstance(); + /** - * @js NA - * @lua NA + * Get current auto release pool, there is at least one auto release pool that created by engine. + * You can create your own auto release pool at demand, which will be put into auto releae pool stack. */ - PoolManager(); - /** - * @js NA - * @lua NA - */ - ~PoolManager(); + AutoreleasePool *getCurrentPool() const; - /** - * Clear all the AutoreleasePool on the pool stack. - * @js NA - * @lua NA - */ - void finalize(); + bool isObjectInPools(Object* obj) const; - /** - * Push a new AutoreleasePool to the pool stack. - * @js NA - * @lua NA - */ - void push(); - - /** - * Pop one AutoreleasePool from the pool stack. - * - * This method will ensure that there is at least one AutoreleasePool on - * the stack. - * - * The AutoreleasePool being poped is destructed. - * @js NA - * @lua NA - */ - void pop(); - - /** - * Remove a given object from the current autorelease pool. - * - * @param object The object to be removed. - * - * @see AutoreleasePool::removeObject - * @js NA - * @lua NA - */ - void removeObject(Object *object); - - /** - * Add a given object to the current autorelease pool. - * - * @param object The object to add. - * - * @see AutoreleasePool::addObject - * @js NA - * @lua NA - */ - void addObject(Object *object); /** * @js NA * @lua NA */ friend class AutoreleasePool; + +private: + PoolManager(); + ~PoolManager(); + + void push(AutoreleasePool *pool); + void pop(); + + static PoolManager* s_singleInstance; + + std::deque _releasePoolStack; + AutoreleasePool *_curReleasePool; }; // end of base_nodes group diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 9437fc105c..ac7e62c855 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -50,7 +50,7 @@ #include "CCScheduler.h" #include "CCScene.h" #include "CCPlatformConfig.h" -#include "CCFileUtils.h" +#include "platform/CCFileUtils.h" #include "CCConfiguration.h" #include "CCTextureCache.h" @@ -144,24 +144,7 @@ static const char* inet_ntop(int af, const void* src, char* dst, int cnt) // Free functions to log // -// XXX: Deprecated -void CCLog(const char * format, ...) -{ - va_list args; - va_start(args, format); - log(format, args); - va_end(args); -} - -void log(const char * format, ...) -{ - va_list args; - va_start(args, format); - log(format, args); - va_end(args); -} - -void log(const char *format, va_list args) +static void _log(const char *format, va_list args) { char buf[MAX_LOG_LENGTH]; @@ -175,10 +158,8 @@ void log(const char *format, va_list args) WCHAR wszBuf[MAX_LOG_LENGTH] = {0}; MultiByteToWideChar(CP_UTF8, 0, buf, -1, wszBuf, sizeof(wszBuf)); OutputDebugStringW(wszBuf); - OutputDebugStringA("\n"); - WideCharToMultiByte(CP_ACP, 0, wszBuf, sizeof(wszBuf), buf, sizeof(buf), NULL, FALSE); - printf("%s\n", buf); + printf("%s", buf); #else // Linux, Mac, iOS, etc @@ -189,6 +170,22 @@ void log(const char *format, va_list args) Director::getInstance()->getConsole()->log(buf); } +// XXX: Deprecated +void CCLog(const char * format, ...) +{ + va_list args; + va_start(args, format); + _log(format, args); + va_end(args); +} + +void log(const char * format, ...) +{ + va_list args; + va_start(args, format); + _log(format, args); + va_end(args); +} // // Console code @@ -392,7 +389,7 @@ void Console::commandTextures(int fd, const char *command) { Scheduler *sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread( [&](){ - mydprintf(fd, "%s", TextureCache::getInstance()->getCachedTextureInfo().c_str()); + mydprintf(fd, "%s", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } ); } @@ -517,7 +514,7 @@ void Console::loop() timeout.tv_sec = 0; /* 0.016 seconds. Wake up once per frame at 60PFS */ - timeout.tv_usec = 016000; + timeout.tv_usec = 16000; while(!_endThread) { diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 1218bf8066..7a06d3423f 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -58,7 +58,6 @@ static const int MAX_LOG_LENGTH = 16*1024; @brief Output Debug message. */ void CC_DLL log(const char * format, ...) CC_FORMAT_PRINTF(1, 2); -void CC_DLL log(const char * format, va_list args); /** Console is helper class that lets the developer control the game from TCP connection. Console will spawn a new thread that will listen to a specified TCP port. diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index 450b39bc2e..9f7b6b17f6 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -25,10 +25,17 @@ #ifndef __CCMAP_H__ #define __CCMAP_H__ +#define USE_STD_UNORDERED_MAP 1 + #include "ccMacros.h" #include "CCObject.h" #include + +#if USE_STD_UNORDERED_MAP #include +#else +#include +#endif NS_CC_BEGIN @@ -44,7 +51,11 @@ public: // ------------------------------------------ // Iterators // ------------------------------------------ +#if USE_STD_UNORDERED_MAP typedef std::unordered_map RefMap; +#else + typedef std::map RefMap; +#endif typedef typename RefMap::iterator iterator; typedef typename RefMap::const_iterator const_iterator; @@ -104,25 +115,39 @@ public: /** Sets capacity of the map */ void reserve(ssize_t capacity) { +#if USE_STD_UNORDERED_MAP _data.reserve(capacity); +#endif } /** Returns the number of buckets in the Map container. */ ssize_t bucketCount() const { +#if USE_STD_UNORDERED_MAP return _data.bucket_count(); +#else + return 0; +#endif } /** Returns the number of elements in bucket n. */ ssize_t bucketSize(ssize_t n) const { +#if USE_STD_UNORDERED_MAP return _data.bucket_size(n); +#else + return 0; +#endif } /** Returns the bucket number where the element with key k is located. */ ssize_t bucket(const K& k) const { +#if USE_STD_UNORDERED_MAP return _data.bucket(k); +#else + return 0; +#endif } /** The number of elements in the map. */ @@ -144,9 +169,11 @@ public: std::vector keys() const { std::vector keys; - + if (!_data.empty()) { + keys.reserve(_data.size()); + for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter) { keys.push_back(iter->first); @@ -160,14 +187,21 @@ public: { std::vector keys; - for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter) + if (!_data.empty()) { - if (iter->second == object) + keys.reserve(_data.size() / 10); + + for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter) { - keys.push_back(iter->first); + if (iter->second == object) + { + keys.push_back(iter->first); + } } } + keys.shrink_to_fit(); + return keys; } diff --git a/cocos/base/CCObject.cpp b/cocos/base/CCObject.cpp index 09dc4399f6..8a6c096e41 100644 --- a/cocos/base/CCObject.cpp +++ b/cocos/base/CCObject.cpp @@ -33,8 +33,7 @@ NS_CC_BEGIN Object::Object() : _luaID(0) -, _reference(1) // when the object is created, the reference count of it is 1 -, _autoReleaseCount(0) +, _referenceCount(1) // when the object is created, the reference count of it is 1 { static unsigned int uObjectCount = 0; @@ -43,13 +42,6 @@ Object::Object() Object::~Object() { - // if the object is managed, we should remove it - // from pool manager - if (_autoReleaseCount > 0) - { - PoolManager::sharedPoolManager()->removeObject(this); - } - // if the object is referenced by Lua engine, remove it if (_luaID) { @@ -67,18 +59,65 @@ Object::~Object() Object* Object::autorelease() { - PoolManager::sharedPoolManager()->addObject(this); + PoolManager::getInstance()->getCurrentPool()->addObject(this); return this; } + + +void Object::release() +{ + CCASSERT(_referenceCount > 0, "reference count should greater than 0"); + --_referenceCount; + + if (_referenceCount == 0) + { +#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) + auto poolManager = PoolManager::getInstance(); + if (!poolManager->getCurrentPool()->isClearing() && poolManager->isObjectInPools(this)) + { + // Trigger an assert if the reference count is 0 but the object is still in autorelease pool. + // This happens when 'autorelease/release' were not used in pairs with 'new/retain'. + // + // Wrong usage (1): + // + // auto obj = Node::create(); // Ref = 1, but it's an autorelease object which means it was in the autorelease pool. + // obj->autorelease(); // Wrong: If you wish to invoke autorelease several times, you should retain `obj` first. + // + // Wrong usage (2): + // + // auto obj = Node::create(); + // obj->release(); // Wrong: obj is an autorelease object, it will be released when clearing current pool. + // + // Correct usage (1): + // + // auto obj = Node::create(); + // |- new Node(); // `new` is the pair of the `autorelease` of next line + // |- autorelease(); // The pair of `new Node`. + // + // obj->retain(); + // obj->autorelease(); // This `autorelease` is the pair of `retain` of previous line. + // + // Correct usage (2): + // + // auto obj = Node::create(); + // obj->retain(); + // obj->release(); // This `release` is the pair of `retain` of previous line. + CCASSERT(false, "The reference shouldn't be 0 because it is still in autorelease pool."); + } +#endif + delete this; + } +} + bool Object::isSingleReference() const { - return _reference == 1; + return _referenceCount == 1; } -unsigned int Object::retainCount() const +unsigned int Object::getReferenceCount() const { - return _reference; + return _referenceCount; } bool Object::isEqual(const Object *object) diff --git a/cocos/base/CCObject.h b/cocos/base/CCObject.h index 2280508856..414bc8d1fb 100644 --- a/cocos/base/CCObject.h +++ b/cocos/base/CCObject.h @@ -71,14 +71,12 @@ class CC_DLL Object { public: /// object id, ScriptSupport need public _ID - unsigned int _ID; + unsigned int _ID; /// Lua reference id - int _luaID; + int _luaID; protected: /// count of references - unsigned int _reference; - /// count of autorelease - unsigned int _autoReleaseCount; + unsigned int _referenceCount; public: /** * Constructor @@ -105,14 +103,7 @@ public: * @see retain, autorelease * @js NA */ - inline void release() - { - CCASSERT(_reference > 0, "reference count should greater than 0"); - --_reference; - - if (_reference == 0) - delete this; - } + void release(); /** * Retains the ownership. @@ -124,8 +115,8 @@ public: */ inline void retain() { - CCASSERT(_reference > 0, "reference count should greater than 0"); - ++_reference; + CCASSERT(_referenceCount > 0, "reference count should greater than 0"); + ++_referenceCount; } /** @@ -152,7 +143,7 @@ public: * @returns Whether the object's reference count is 1. * @js NA */ - bool isSingleReference() const; + CC_DEPRECATED_ATTRIBUTE bool isSingleReference() const; /** * Returns the object's current reference count. @@ -160,7 +151,8 @@ public: * @returns The object's reference count. * @js NA */ - unsigned int retainCount() const; + CC_DEPRECATED_ATTRIBUTE unsigned int retainCount() const { return getReferenceCount(); }; + unsigned int getReferenceCount() const; /** * Returns a boolean value that indicates whether this object and a given diff --git a/cocos/editor-support/cocosbuilder/CCBAnimationManager.h b/cocos/editor-support/cocosbuilder/CCBAnimationManager.h index 14328af61d..f1f351a631 100644 --- a/cocos/editor-support/cocosbuilder/CCBAnimationManager.h +++ b/cocos/editor-support/cocosbuilder/CCBAnimationManager.h @@ -1,7 +1,11 @@ #ifndef __CCB_CCBANIMATION_MANAGER_H__ #define __CCB_CCBANIMATION_MANAGER_H__ -#include "cocos2d.h" +#include "CCMap.h" +#include "CCActionInterval.h" +#include "CCActionInstant.h" +#include "CCActionEase.h" + #include "extensions/ExtensionMacros.h" #include "CCBSequence.h" #include "CCBSequenceProperty.h" diff --git a/cocos/editor-support/cocosbuilder/CCBKeyframe.h b/cocos/editor-support/cocosbuilder/CCBKeyframe.h index 49779319cc..e3c009e2df 100644 --- a/cocos/editor-support/cocosbuilder/CCBKeyframe.h +++ b/cocos/editor-support/cocosbuilder/CCBKeyframe.h @@ -1,7 +1,9 @@ #ifndef __CCB_KEYFRAME_H__ #define __CCB_KEYFRAME_H__ -#include "cocos2d.h" +#include "CCObject.h" +#include "CCValue.h" + namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCBMemberVariableAssigner.h b/cocos/editor-support/cocosbuilder/CCBMemberVariableAssigner.h index 7c429ed505..4cafab98d6 100644 --- a/cocos/editor-support/cocosbuilder/CCBMemberVariableAssigner.h +++ b/cocos/editor-support/cocosbuilder/CCBMemberVariableAssigner.h @@ -1,7 +1,6 @@ #ifndef _CCB_CCBMEMBERVARIABLEASSIGNER_H_ #define _CCB_CCBMEMBERVARIABLEASSIGNER_H_ -#include "cocos2d.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index f190b72def..056f2553d0 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -1,7 +1,13 @@ -#include "CCBReader.h" - +#include #include +#include "CCDirector.h" +#include "platform/CCFileUtils.h" +#include "CCScene.h" +#include "CCTextureCache.h" +#include "CCSpriteFrameCache.h" + +#include "CCBReader.h" #include "CCNodeLoader.h" #include "CCNodeLoaderLibrary.h" #include "CCNodeLoaderListener.h" @@ -11,7 +17,7 @@ #include "CCBSequenceProperty.h" #include "CCBKeyframe.h" -#include + using namespace std; using namespace cocos2d; diff --git a/cocos/editor-support/cocosbuilder/CCBReader.h b/cocos/editor-support/cocosbuilder/CCBReader.h index 69306227ed..3c2a39c763 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.h +++ b/cocos/editor-support/cocosbuilder/CCBReader.h @@ -1,9 +1,12 @@ #ifndef _CCB_CCBREADER_H_ #define _CCB_CCBREADER_H_ -#include "cocos2d.h" #include #include +#include "CCNode.h" +#include "CCData.h" +#include "CCMap.h" + #include "CCBSequence.h" #include "extensions/GUI/CCControlExtension/CCControl.h" diff --git a/cocos/editor-support/cocosbuilder/CCBSelectorResolver.h b/cocos/editor-support/cocosbuilder/CCBSelectorResolver.h index f054c284c5..110d2ced61 100644 --- a/cocos/editor-support/cocosbuilder/CCBSelectorResolver.h +++ b/cocos/editor-support/cocosbuilder/CCBSelectorResolver.h @@ -1,7 +1,6 @@ #ifndef _CCB_CCBSELECTORRESOLVER_H_ #define _CCB_CCBSELECTORRESOLVER_H_ -#include "cocos2d.h" #include "extensions//GUI/CCControlExtension/CCInvocation.h" diff --git a/cocos/editor-support/cocosbuilder/CCBSequence.h b/cocos/editor-support/cocosbuilder/CCBSequence.h index dd7c1a899f..045fa536b5 100644 --- a/cocos/editor-support/cocosbuilder/CCBSequence.h +++ b/cocos/editor-support/cocosbuilder/CCBSequence.h @@ -2,7 +2,8 @@ #define __CCB_CCSEQUENCE_H__ #include -#include "cocos2d.h" + +#include "CCObject.h" #include "CCBSequenceProperty.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h index 03ca04799f..fe19b15596 100644 --- a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h +++ b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h @@ -1,7 +1,8 @@ #ifndef __CCB_SEQUENCE_PROPERTY_H__ #define __CCB_SEQUENCE_PROPERTY_H__ -#include "cocos2d.h" +#include "CCObject.h" +#include "CCVector.h" #include "CCBKeyframe.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.h b/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.h index ae5cb20011..c24239c3f2 100644 --- a/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.h +++ b/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.h @@ -1,6 +1,9 @@ #ifndef _CCB_CCLABELBMFONTLOADER_H_ #define _CCB_CCLABELBMFONTLOADER_H_ +#include "CCObject.h" +#include "CCLabelBMFont.h" + #include "CCNodeLoader.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h b/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h index de0ca00d42..aa0fc0cdfe 100644 --- a/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h +++ b/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h @@ -1,6 +1,9 @@ #ifndef _CCB_CCLABELTTFLOADER_H_ #define _CCB_CCLABELTTFLOADER_H_ +#include "CCObject.h" +#include "CCLabelTTF.h" + #include "CCNodeLoader.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCMenuItemLoader.h b/cocos/editor-support/cocosbuilder/CCMenuItemLoader.h index 5db15eacba..1156a46f13 100644 --- a/cocos/editor-support/cocosbuilder/CCMenuItemLoader.h +++ b/cocos/editor-support/cocosbuilder/CCMenuItemLoader.h @@ -1,6 +1,9 @@ #ifndef _CCB_CCMENUITEMLOADER_H_ #define _CCB_CCMENUITEMLOADER_H_ +#include "CCObject.h" +#include "CCMenuItem.h" + #include "CCLayerLoader.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCMenuLoader.h b/cocos/editor-support/cocosbuilder/CCMenuLoader.h index 851913c74c..75ff815f26 100644 --- a/cocos/editor-support/cocosbuilder/CCMenuLoader.h +++ b/cocos/editor-support/cocosbuilder/CCMenuLoader.h @@ -2,6 +2,8 @@ #define _CCB_CCMENULOADER_H_ #include "CCLayerLoader.h" +#include "CCObject.h" +#include "CCMenu.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.h b/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.h index 7923d3c681..7dd0ed5ea8 100644 --- a/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.h +++ b/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.h @@ -1,7 +1,6 @@ #ifndef __CCB_CCNODE_RELATIVEPOSITIONING_H__ #define __CCB_CCNODE_RELATIVEPOSITIONING_H__ -#include "cocos2d.h" #include "CCBReader.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp index adb7b8d095..598f6cad11 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp @@ -1,9 +1,12 @@ +#include "cocos2d.h" + #include "CCNodeLoader.h" #include "CCBSelectorResolver.h" #include "CCBMemberVariableAssigner.h" #include "CCBAnimationManager.h" #include "CCNode+CCBRelativePositioning.h" + using namespace std; using namespace cocos2d; using namespace cocos2d::extension; diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.h b/cocos/editor-support/cocosbuilder/CCNodeLoader.h index bb18d03866..e67fcb047f 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.h +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.h @@ -2,7 +2,6 @@ #define _CCB_CCNODELOADER_H_ #include "extensions/GUI/CCControlExtension/CCInvocation.h" -#include "cocos2d.h" #include "CCBReader.h" #include "extensions/GUI/CCControlExtension/CCControl.h" diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.h b/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.h index c75276d22f..6fe711feda 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.h +++ b/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.h @@ -1,7 +1,6 @@ #ifndef _CCB_CCNODELOADERLIBRARY_H_ #define _CCB_CCNODELOADERLIBRARY_H_ -#include "cocos2d.h" #include "CCBReader.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoaderListener.h b/cocos/editor-support/cocosbuilder/CCNodeLoaderListener.h index cf6c53e543..dedaafa51e 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoaderListener.h +++ b/cocos/editor-support/cocosbuilder/CCNodeLoaderListener.h @@ -1,7 +1,6 @@ #ifndef _CCB_CCNODELOADERLISTENER_H_ #define _CCB_CCNODELOADERLISTENER_H_ -#include "cocos2d.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.h b/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.h index feced7312e..64efbdecba 100644 --- a/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.h +++ b/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.h @@ -1,6 +1,9 @@ #ifndef _CCB_CCPARTICLESYSTEMQUADLOADER_H_ #define _CCB_CCPARTICLESYSTEMQUADLOADER_H_ +#include "CCObject.h" +#include "CCParticleSystemQuad.h" + #include "CCNodeLoader.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocostudio/CCActionEaseEx.h b/cocos/editor-support/cocostudio/CCActionEaseEx.h index 0350d4d590..0a88c77e69 100644 --- a/cocos/editor-support/cocostudio/CCActionEaseEx.h +++ b/cocos/editor-support/cocostudio/CCActionEaseEx.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __ActionEaseEx_H__ #define __ActionEaseEx_H__ -#include "cocos2d.h" #include "cocostudio/CocoStudio.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCActionFrame.h b/cocos/editor-support/cocostudio/CCActionFrame.h index 5b152f4eb3..9ff01ddf05 100644 --- a/cocos/editor-support/cocostudio/CCActionFrame.h +++ b/cocos/editor-support/cocostudio/CCActionFrame.h @@ -25,7 +25,8 @@ THE SOFTWARE. #ifndef __ActionFRAME_H__ #define __ActionFRAME_H__ -#include "cocos2d.h" +#include "CCGeometry.h" +#include "CCActionInterval.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCActionFrameEasing.h b/cocos/editor-support/cocostudio/CCActionFrameEasing.h index 65c9ad3a05..1ae824e482 100644 --- a/cocos/editor-support/cocostudio/CCActionFrameEasing.h +++ b/cocos/editor-support/cocostudio/CCActionFrameEasing.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __ActionFrameEasing_H__ #define __ActionFrameEasing_H__ -#include "cocos2d.h" +#include "CCObject.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCActionManagerEx.h b/cocos/editor-support/cocostudio/CCActionManagerEx.h index e24c48d436..ba4e0c7804 100644 --- a/cocos/editor-support/cocostudio/CCActionManagerEx.h +++ b/cocos/editor-support/cocostudio/CCActionManagerEx.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __ActionMANAGER_H__ #define __ActionMANAGER_H__ -#include "cocos2d.h" #include "cocostudio/CCActionObject.h" #include "cocostudio/DictionaryHelper.h" diff --git a/cocos/editor-support/cocostudio/CCActionNode.h b/cocos/editor-support/cocostudio/CCActionNode.h index 42e4d0e4ee..9a2195327d 100644 --- a/cocos/editor-support/cocostudio/CCActionNode.h +++ b/cocos/editor-support/cocostudio/CCActionNode.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __ActionNODE_H__ #define __ActionNODE_H__ -#include "cocos2d.h" #include "cocostudio/CCActionFrame.h" #include "cocostudio/DictionaryHelper.h" diff --git a/cocos/editor-support/cocostudio/CCActionObject.cpp b/cocos/editor-support/cocostudio/CCActionObject.cpp index eeba39d121..57291ae369 100644 --- a/cocos/editor-support/cocostudio/CCActionObject.cpp +++ b/cocos/editor-support/cocostudio/CCActionObject.cpp @@ -25,6 +25,10 @@ THE SOFTWARE. #include "cocostudio/CCActionObject.h" #include "cocostudio/DictionaryHelper.h" +#include "CCDirector.h" +#include "CCScheduler.h" +#include "CCActionInstant.h" + using namespace cocos2d; namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCActionObject.h b/cocos/editor-support/cocostudio/CCActionObject.h index 8d33a2017f..249489b620 100644 --- a/cocos/editor-support/cocostudio/CCActionObject.h +++ b/cocos/editor-support/cocostudio/CCActionObject.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __ActionObject_H__ #define __ActionObject_H__ -#include "cocos2d.h" #include "CCActionNode.h" #include "cocostudio/DictionaryHelper.h" diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index decc3cc0c2..80d6a4dca7 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -28,9 +28,12 @@ THE SOFTWARE. #include "cocostudio/CCDataReaderHelper.h" #include "cocostudio/CCDatas.h" #include "cocostudio/CCSkin.h" + #include "renderer/CCQuadCommand.h" -#include "CCRenderer.h" -#include "CCGroupCommand.h" +#include "renderer/CCRenderer.h" +#include "renderer/CCGroupCommand.h" +#include "CCShaderCache.h" +#include "CCDrawingPrimitives.h" #if ENABLE_PHYSICS_BOX2D_DETECT #include "Box2D/Box2D.h" @@ -570,7 +573,7 @@ void CCArmature::drawContour() } DrawPrimitives::drawPoly( points, (unsigned int)length, true ); - delete points; + delete []points; } } } diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index 0848ab6226..de05838940 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "CCSpriteFrameCache.h" #include "cocostudio/CCArmatureDataManager.h" #include "cocostudio/CCTransformHelp.h" diff --git a/cocos/editor-support/cocostudio/CCArmatureDefine.h b/cocos/editor-support/cocostudio/CCArmatureDefine.h index 934b7bc43d..8c8eca2608 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDefine.h +++ b/cocos/editor-support/cocostudio/CCArmatureDefine.h @@ -26,8 +26,6 @@ THE SOFTWARE. #define __CCARMATUREDEFINE_H__ -#include "cocos2d.h" - #define VERSION_COMBINED 0.30f #define VERSION_CHANGE_ROTATION_RANGE 1.0f #define VERSION_COLOR_READING 1.1f diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index 45dcade7d6..752e4911a9 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -26,8 +26,11 @@ THE SOFTWARE. #include "cocostudio/CCArmatureDefine.h" #include "cocostudio/CCArmature.h" #include "cocostudio/CCSkin.h" -#include "CCRenderer.h" -#include "CCGroupCommand.h" + +#include "renderer/CCRenderer.h" +#include "renderer/CCGroupCommand.h" +#include "CCShaderCache.h" +#include "CCDirector.h" using namespace cocos2d; @@ -153,7 +156,7 @@ void BatchNode::draw() void BatchNode::generateGroupCommand() { Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand->init(0,_vertexZ); + _groupCommand->init(_globalZOrder); renderer->addCommand(_groupCommand); renderer->pushGroup(_groupCommand->getRenderQueueID()); diff --git a/cocos/editor-support/cocostudio/CCBatchNode.h b/cocos/editor-support/cocostudio/CCBatchNode.h index 1de8a963a2..f0ce41df2f 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.h +++ b/cocos/editor-support/cocostudio/CCBatchNode.h @@ -25,6 +25,7 @@ THE SOFTWARE. #ifndef __CCBATCHNODE_H__ #define __CCBATCHNODE_H__ +#include "CCNode.h" #include "cocostudio/CCArmatureDefine.h" namespace cocos2d { diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 4bd7883a43..dbaa142020 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -145,7 +145,7 @@ void Bone::setBoneData(BoneData *boneData) } _name = _boneData->name; - _ZOrder = _boneData->zOrder; + _localZOrder = _boneData->zOrder; _displayManager->initDisplayList(boneData); } @@ -283,11 +283,11 @@ void Bone::updateZOrder() if (_dataVersion >= VERSION_COMBINED) { int zorder = _tweenData->zOrder + _boneData->zOrder; - setZOrder(zorder); + setLocalZOrder(zorder); } else { - setZOrder(_tweenData->zOrder); + setLocalZOrder(_tweenData->zOrder); } } @@ -374,10 +374,10 @@ Tween *Bone::getTween() return _tween; } -void Bone::setZOrder(int zOrder) +void Bone::setLocalZOrder(int zOrder) { - if (_ZOrder != zOrder) - Node::setZOrder(zOrder); + if (_localZOrder != zOrder) + Node::setLocalZOrder(zOrder); } kmMat4 Bone::getNodeToArmatureTransform() const diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index db153a1da5..c81583a8c9 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -143,7 +143,7 @@ public: //! Update zorder void updateZOrder(); - virtual void setZOrder(int zOrder) override; + virtual void setLocalZOrder(int zOrder) override; Tween *getTween(); diff --git a/cocos/editor-support/cocostudio/CCComBase.h b/cocos/editor-support/cocostudio/CCComBase.h index 59dfccbe7f..2f32d20045 100644 --- a/cocos/editor-support/cocostudio/CCComBase.h +++ b/cocos/editor-support/cocostudio/CCComBase.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __CC_EXTENTIONS_CCCOMBASE_H__ #define __CC_EXTENTIONS_CCCOMBASE_H__ -#include "cocos2d.h" #include "ObjectFactory.h" #include "DictionaryHelper.h" #include diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 452f25d9b8..13ceb9db6d 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -22,7 +22,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "platform/CCFileUtils.h" +#include "CCDirector.h" +#include "CCScheduler.h" + #include "tinyxml2.h" + #include "cocostudio/CCDataReaderHelper.h" #include "cocostudio/CCArmatureDataManager.h" #include "cocostudio/CCTransformHelp.h" @@ -288,7 +293,7 @@ void DataReaderHelper::addDataFromFile(const std::string& filePath) std::string str = &filePathStr[startPos]; // Read content from file - std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); + std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); std::string contentStr = FileUtils::getInstance()->getStringFromFile(fullPath); DataInfo dataInfo; @@ -384,7 +389,7 @@ void DataReaderHelper::addDataFromFileAsync(const std::string& imagePath, const size_t startPos = filePathStr.find_last_of("."); std::string str = &filePathStr[startPos]; - std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); + std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); // XXX fileContent is being leaked data->fileContent = FileUtils::getInstance()->getStringFromFile(fullPath); @@ -461,7 +466,7 @@ void DataReaderHelper::addDataAsyncCallBack(float dt) if (0 == _asyncRefCount) { _asyncRefTotalCount = 0; - CCDirector::getInstance()->getScheduler()->unscheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this); + Director::getInstance()->getScheduler()->unscheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this); } } } diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/CCDataReaderHelper.h index 03ed25133b..ac580d6385 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.h @@ -35,6 +35,7 @@ THE SOFTWARE. #include #include #include +#include namespace tinyxml2 { diff --git a/cocos/editor-support/cocostudio/CCDatas.h b/cocos/editor-support/cocostudio/CCDatas.h index 42ac9ae2f6..6ee2adbcf6 100644 --- a/cocos/editor-support/cocostudio/CCDatas.h +++ b/cocos/editor-support/cocostudio/CCDatas.h @@ -25,6 +25,12 @@ THE SOFTWARE. #ifndef __CCARMATURE_DATAS_H__ #define __CCARMATURE_DATAS_H__ +#include "CCObject.h" +#include "ccTypes.h" +#include "CCVector.h" +#include "CCMap.h" +#include "CCAffineTransform.h" +#include "CCNode.h" #include "cocostudio/CCArmatureDefine.h" #include "cocostudio/CCTweenFunction.h" diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index 20f826cb2b..72428edfff 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -30,6 +30,8 @@ THE SOFTWARE. #include "cocostudio/CCArmatureDataManager.h" #include "cocostudio/CCTransformHelp.h" +#include "CCParticleSystemQuad.h" + using namespace cocos2d; namespace cocostudio { @@ -115,7 +117,7 @@ void DisplayFactory::updateDisplay(Bone *bone, float dt, bool dirty) anchorPoint = PointApplyTransform(anchorPoint, displayTransform); displayTransform.mat[12] = anchorPoint.x; displayTransform.mat[13] = anchorPoint.y; - kmMat4 t = TransformConcat(displayTransform, bone->getArmature()->getNodeToParentTransform()); + kmMat4 t = TransformConcat( bone->getArmature()->getNodeToParentTransform(),displayTransform); detector->updateTransform(t); } while (0); diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index c2ce242a47..70863f5f92 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -28,6 +28,8 @@ THE SOFTWARE. #include "cocostudio/CCUtilMath.h" #include "cocostudio/CCSkin.h" +#include "CCParticleSystemQuad.h" + using namespace cocos2d; namespace cocostudio { @@ -63,7 +65,7 @@ DisplayManager::~DisplayManager() if( _displayRenderNode ) { _displayRenderNode->removeFromParentAndCleanup(true); - if(_displayRenderNode->retainCount() > 0) + if(_displayRenderNode->getReferenceCount() > 0) CC_SAFE_RELEASE_NULL(_displayRenderNode); } diff --git a/cocos/editor-support/cocostudio/CCInputDelegate.cpp b/cocos/editor-support/cocostudio/CCInputDelegate.cpp index 3f3d94745e..1bafbe42f2 100644 --- a/cocos/editor-support/cocostudio/CCInputDelegate.cpp +++ b/cocos/editor-support/cocostudio/CCInputDelegate.cpp @@ -23,6 +23,11 @@ THE SOFTWARE. ****************************************************************************/ #include "cocostudio/CCInputDelegate.h" +#include "CCDirector.h" +#include "platform/CCDevice.h" +#include "CCEventListenerTouch.h" +#include "CCEventListenerAcceleration.h" +#include "CCEventListenerKeyboard.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/CCInputDelegate.h b/cocos/editor-support/cocostudio/CCInputDelegate.h index 81cd4c9218..9341179bf8 100644 --- a/cocos/editor-support/cocostudio/CCInputDelegate.h +++ b/cocos/editor-support/cocostudio/CCInputDelegate.h @@ -25,7 +25,12 @@ THE SOFTWARE. #ifndef __CC_EXTENTIONS_CCINPUTDELEGATE_H__ #define __CC_EXTENTIONS_CCINPUTDELEGATE_H__ -#include "cocos2d.h" +#include "CCPlatformMacros.h" +#include "CCTouch.h" +#include "CCEvent.h" +#include "ccTypes.h" +#include "CCEventKeyboard.h" +#include "CCEventListener.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 349bba5dfe..a8bd016948 100644 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -331,7 +331,7 @@ void WidgetPropertiesReader0250::setPropsForWidgetFromJsonDictionary(Widget*widg widget->setVisible(DICTOOL->getBooleanValue_json(options, "visible")); } int z = DICTOOL->getIntValue_json(options, "ZOrder"); - widget->setZOrder(z); + widget->setLocalZOrder(z); } void WidgetPropertiesReader0250::setColorPropsForWidgetFromJsonDictionary(Widget *widget, const rapidjson::Value&options) @@ -1062,7 +1062,7 @@ void WidgetPropertiesReader0300::setPropsForWidgetFromJsonDictionary(Widget*widg widget->setVisible(DICTOOL->getBooleanValue_json(options, "visible")); } int z = DICTOOL->getIntValue_json(options, "ZOrder"); - widget->setZOrder(z); + widget->setLocalZOrder(z); bool layout = DICTOOL->checkObjectExist_json(options, "layoutParameter"); if (layout) diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index 12b18604ff..ba7818826b 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -144,10 +144,10 @@ Node* SceneReader::createObject(const rapidjson::Value &dict, cocos2d::Node* par { gb->addComponent(com); } - else - { - CC_SAFE_RELEASE_NULL(com); - } + else + { + com = nullptr; + } } if(_fnSelector != nullptr) { @@ -203,7 +203,7 @@ void SceneReader::setPropertyFromJsonDict(const rapidjson::Value &root, cocos2d: node->setTag(nTag); int nZorder = DICTOOL->getIntValue_json(root, "zorder"); - node->setZOrder(nZorder); + node->setLocalZOrder(nZorder); float fScaleX = DICTOOL->getFloatValue_json(root, "scalex", 1.0); float fScaleY = DICTOOL->getFloatValue_json(root, "scaley", 1.0); diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.h b/cocos/editor-support/cocostudio/CCSSceneReader.h index 6b72b82574..19ca837c6a 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.h +++ b/cocos/editor-support/cocostudio/CCSSceneReader.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __CCSSCENEREADER_H__ #define __CCSSCENEREADER_H__ -#include "cocos2d.h" #include "cocostudio/DictionaryHelper.h" diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index 94ba291e2b..e68239b803 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -22,11 +22,17 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "CCSpriteFrame.h" +#include "CCSpriteFrameCache.h" +#include "CCDirector.h" +#include "renderer/CCRenderer.h" + #include "cocostudio/CCSkin.h" #include "cocostudio/CCTransformHelp.h" #include "cocostudio/CCSpriteFrameCacheHelper.h" #include "cocostudio/CCArmature.h" + using namespace cocos2d; namespace cocostudio { @@ -197,7 +203,7 @@ void Skin::updateTransform() kmMat4 Skin::getNodeToWorldTransform() const { - return TransformConcat(_transform, _bone->getArmature()->getNodeToWorldTransform()); + return TransformConcat( _bone->getArmature()->getNodeToWorldTransform(), _transform); } kmMat4 Skin::getNodeToWorldTransformAR() const @@ -210,7 +216,7 @@ kmMat4 Skin::getNodeToWorldTransformAR() const displayTransform.mat[12] = anchorPoint.x; displayTransform.mat[13] = anchorPoint.y; - return TransformConcat(displayTransform, _bone->getArmature()->getNodeToWorldTransform()); + return TransformConcat( _bone->getArmature()->getNodeToWorldTransform(),displayTransform); } void Skin::draw() @@ -219,7 +225,7 @@ void Skin::draw() kmGLGetMatrix(KM_GL_MODELVIEW, &mv); //TODO implement z order - _quadCommand.init(0, _vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, mv); + _quadCommand.init(_globalZOrder, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, mv); Director::getInstance()->getRenderer()->addCommand(&_quadCommand); } diff --git a/cocos/editor-support/cocostudio/CCSkin.h b/cocos/editor-support/cocostudio/CCSkin.h index e0f255e70d..4798b2345b 100644 --- a/cocos/editor-support/cocostudio/CCSkin.h +++ b/cocos/editor-support/cocostudio/CCSkin.h @@ -25,9 +25,11 @@ THE SOFTWARE. #ifndef __CCSKIN_H__ #define __CCSKIN_H__ +#include "CCSprite.h" +#include "renderer/CCQuadCommand.h" + #include "cocostudio/CCArmatureDefine.h" #include "cocostudio/CCBone.h" -#include "renderer/CCQuadCommand.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp index c5399ba479..1c226668db 100644 --- a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp @@ -24,6 +24,8 @@ THE SOFTWARE. #include "cocostudio/CCSpriteFrameCacheHelper.h" +#include "CCSpriteFrameCache.h" + using namespace cocos2d; @@ -49,7 +51,7 @@ void SpriteFrameCacheHelper::purge() void SpriteFrameCacheHelper::addSpriteFrameFromFile(const std::string& plistPath, const std::string& imagePath) { - CCSpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath, imagePath); + SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath, imagePath); } SpriteFrameCacheHelper::SpriteFrameCacheHelper() diff --git a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h index 75797c1aa2..452666a67d 100644 --- a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h @@ -24,8 +24,10 @@ THE SOFTWARE. #ifndef __CCSPRITEFRAMECACHEHELPER_H__ #define __CCSPRITEFRAMECACHEHELPER_H__ +#include "CCPlatformMacros.h" #include "cocostudio/CCArmatureDefine.h" #include +#include namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCUtilMath.h b/cocos/editor-support/cocostudio/CCUtilMath.h index b10690d620..cc27ccae86 100644 --- a/cocos/editor-support/cocostudio/CCUtilMath.h +++ b/cocos/editor-support/cocostudio/CCUtilMath.h @@ -25,6 +25,7 @@ THE SOFTWARE. #ifndef __CCUTILMATH_H__ #define __CCUTILMATH_H__ +#include "CCSprite.h" #include "cocostudio/CCArmatureDefine.h" #include diff --git a/cocos/editor-support/cocostudio/DictionaryHelper.cpp b/cocos/editor-support/cocostudio/DictionaryHelper.cpp index 0c46694e7b..436c345d0c 100644 --- a/cocos/editor-support/cocostudio/DictionaryHelper.cpp +++ b/cocos/editor-support/cocostudio/DictionaryHelper.cpp @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "CCPlatformMacros.h" #include "cocostudio/DictionaryHelper.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/DictionaryHelper.h b/cocos/editor-support/cocostudio/DictionaryHelper.h index 58f58455f5..cefb9610ff 100644 --- a/cocos/editor-support/cocostudio/DictionaryHelper.h +++ b/cocos/editor-support/cocostudio/DictionaryHelper.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __DICTIONARYHELPER_H__ #define __DICTIONARYHELPER_H__ -#include "cocos2d.h" #include "json/document.h" #define DICTOOL DictionaryHelper::getInstance() diff --git a/cocos/editor-support/cocostudio/TriggerObj.cpp b/cocos/editor-support/cocostudio/TriggerObj.cpp index 83d7bdcfbc..ffdfdfe48c 100644 --- a/cocos/editor-support/cocostudio/TriggerObj.cpp +++ b/cocos/editor-support/cocostudio/TriggerObj.cpp @@ -178,7 +178,6 @@ void TriggerObj::serialize(const rapidjson::Value &val) CCASSERT(con != nullptr, ""); con->serialize(subDict); con->init(); - con->autorelease(); _cons.pushBack(con); } @@ -199,7 +198,6 @@ void TriggerObj::serialize(const rapidjson::Value &val) } act->serialize(subDict); act->init(); - act->autorelease(); _acts.pushBack(act); } diff --git a/cocos/editor-support/spine/Atlas.cpp b/cocos/editor-support/spine/Atlas.cpp index b63c923618..8addbc11d5 100644 --- a/cocos/editor-support/spine/Atlas.cpp +++ b/cocos/editor-support/spine/Atlas.cpp @@ -142,7 +142,7 @@ static int readTuple (const char* end, Str tuple[]) { } static char* mallocString (Str* str) { - int length = str->end - str->begin; + long length = str->end - str->begin; char* string = MALLOC(char, length + 1); memcpy(string, str->begin, length); string[length] = '\0'; @@ -150,7 +150,7 @@ static char* mallocString (Str* str) { } static int indexOf (const char** array, int count, Str* str) { - int length = str->end - str->begin; + long length = str->end - str->begin; int i; for (i = count - 1; i >= 0; i--) if (strncmp(array[i], str->begin, length) == 0) return i; @@ -162,7 +162,7 @@ static int equals (Str* str, const char* other) { } static int toInt (Str* str) { - return strtol(str->begin, (char**)&str->end, 10); + return static_cast(strtol(str->begin, (char**)&str->end, 10)); } static spAtlas* abortAtlas (spAtlas* self) { @@ -177,7 +177,7 @@ static const char* textureFilterNames[] = {"Nearest", "Linear", "MipMap", "MipMa spAtlas* spAtlas_readAtlas (const char* begin, int length, const char* dir) { int count; const char* end = begin + length; - int dirLength = strlen(dir); + size_t dirLength = strlen(dir); int needsSlash = dirLength > 0 && dir[dirLength - 1] != '/' && dir[dirLength - 1] != '\\'; spAtlas* self = NEW(spAtlas); @@ -289,7 +289,7 @@ spAtlas* spAtlas_readAtlas (const char* begin, int length, const char* dir) { } spAtlas* spAtlas_readAtlasFile (const char* path) { - int dirLength; + long dirLength; char *dir; int length; const char* data; diff --git a/cocos/editor-support/spine/CCSkeleton.cpp b/cocos/editor-support/spine/CCSkeleton.cpp index 9051679a98..82c0ed50cd 100644 --- a/cocos/editor-support/spine/CCSkeleton.cpp +++ b/cocos/editor-support/spine/CCSkeleton.cpp @@ -131,7 +131,7 @@ void Skeleton::draw() kmGLMatrixMode(KM_GL_MODELVIEW); kmGLGetMatrix(KM_GL_MODELVIEW, &_oldTransMatrix); - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Skeleton::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/editor-support/spine/CCSkeleton.h b/cocos/editor-support/spine/CCSkeleton.h index f1cffffea6..a2460ca690 100644 --- a/cocos/editor-support/spine/CCSkeleton.h +++ b/cocos/editor-support/spine/CCSkeleton.h @@ -35,7 +35,11 @@ #define SPINE_CCSKELETON_H_ #include -#include "cocos2d.h" + +#include "CCNode.h" +#include "CCProtocols.h" +#include "CCTextureAtlas.h" +#include "renderer/CCCustomCommand.h" namespace spine { diff --git a/cocos/editor-support/spine/CCSkeletonAnimation.h b/cocos/editor-support/spine/CCSkeletonAnimation.h index 228a07b88e..3c09ee28c3 100644 --- a/cocos/editor-support/spine/CCSkeletonAnimation.h +++ b/cocos/editor-support/spine/CCSkeletonAnimation.h @@ -36,7 +36,6 @@ #include #include -#include "cocos2d.h" namespace spine { diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index e4c9c1f66f..93889d7ce0 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -30,9 +30,9 @@ THE SOFTWARE. #include "CCShaderCache.h" #include "CCDirector.h" #include "CCDrawingPrimitives.h" -#include "CCRenderer.h" -#include "CCGroupCommand.h" -#include "CCCustomCommand.h" +#include "renderer/CCRenderer.h" +#include "renderer/CCGroupCommand.h" +#include "renderer/CCCustomCommand.h" NS_CC_BEGIN @@ -210,18 +210,18 @@ void Layout::stencilClippingVisit() Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand.init(0,_vertexZ); + _groupCommand.init(_globalZOrder); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); - _beforeVisitCmdStencil.init(0,_vertexZ); + _beforeVisitCmdStencil.init(_globalZOrder); _beforeVisitCmdStencil.func = CC_CALLBACK_0(Layout::onBeforeVisitStencil, this); renderer->addCommand(&_beforeVisitCmdStencil); _clippingStencil->visit(); - _afterDrawStencilCmd.init(0,_vertexZ); + _afterDrawStencilCmd.init(_globalZOrder); _afterDrawStencilCmd.func = CC_CALLBACK_0(Layout::onAfterDrawStencil, this); renderer->addCommand(&_afterDrawStencilCmd); @@ -235,7 +235,7 @@ void Layout::stencilClippingVisit() { auto node = _children.at(i); - if ( node && node->getZOrder() < 0 ) + if ( node && node->getLocalZOrder() < 0 ) node->visit(); else break; @@ -251,7 +251,7 @@ void Layout::stencilClippingVisit() this->draw(); } - _afterVisitCmdStencil.init(0,_vertexZ); + _afterVisitCmdStencil.init(_globalZOrder); _afterVisitCmdStencil.func = CC_CALLBACK_0(Layout::onAfterVisitStencil, this); renderer->addCommand(&_afterVisitCmdStencil); @@ -324,7 +324,8 @@ void Layout::onBeforeVisitScissor() { Rect clippingRect = getClippingRect(); glEnable(GL_SCISSOR_TEST); - EGLView::getInstance()->setScissorInPoints(clippingRect.origin.x, clippingRect.origin.y, clippingRect.size.width, clippingRect.size.height); + auto glview = Director::getInstance()->getOpenGLView(); + glview->setScissorInPoints(clippingRect.origin.x, clippingRect.origin.y, clippingRect.size.width, clippingRect.size.height); } void Layout::onAfterVisitScissor() @@ -336,13 +337,13 @@ void Layout::scissorClippingVisit() { Renderer* renderer = Director::getInstance()->getRenderer(); - _beforeVisitCmdScissor.init(0, _vertexZ); + _beforeVisitCmdScissor.init(_globalZOrder); _beforeVisitCmdScissor.func = CC_CALLBACK_0(Layout::onBeforeVisitScissor, this); renderer->addCommand(&_beforeVisitCmdScissor); Node::visit(); - _afterVisitCmdScissor.init(0, _vertexZ); + _afterVisitCmdScissor.init(_globalZOrder); _afterVisitCmdScissor.func = CC_CALLBACK_0(Layout::onAfterVisitScissor, this); renderer->addCommand(&_afterVisitCmdScissor); } @@ -651,14 +652,14 @@ void Layout::addBackGroundImage() if (_backGroundScale9Enabled) { _backGroundImage = extension::Scale9Sprite::create(); - _backGroundImage->setZOrder(-1); + _backGroundImage->setLocalZOrder(-1); Node::addChild(_backGroundImage, BACKGROUNDIMAGE_Z, -1); static_cast(_backGroundImage)->setPreferredSize(_size); } else { _backGroundImage = Sprite::create(); - _backGroundImage->setZOrder(-1); + _backGroundImage->setLocalZOrder(-1); Node::addChild(_backGroundImage, BACKGROUNDIMAGE_Z, -1); } _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); diff --git a/cocos/gui/UILayout.h b/cocos/gui/UILayout.h index fffb6aaad1..327707d7c8 100644 --- a/cocos/gui/UILayout.h +++ b/cocos/gui/UILayout.h @@ -195,7 +195,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) */ virtual void addChild(Node * child, int zOrder) override; /** @@ -204,7 +204,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) * @param tag A interger to identify the node easily. Please refer to setTag(int) */ virtual void addChild(Node* child, int zOrder, int tag) override; diff --git a/cocos/gui/UIListView.cpp b/cocos/gui/UIListView.cpp index ba6a567aef..8c732f6e70 100644 --- a/cocos/gui/UIListView.cpp +++ b/cocos/gui/UIListView.cpp @@ -378,7 +378,7 @@ void ListView::refreshView() for (int i=0; isetZOrder(i); + item->setLocalZOrder(i); remedyLayoutParameter(item); } updateInnerContainerSize(); diff --git a/cocos/gui/UIScrollView.h b/cocos/gui/UIScrollView.h index ae49fa02ea..0b196cef55 100644 --- a/cocos/gui/UIScrollView.h +++ b/cocos/gui/UIScrollView.h @@ -242,7 +242,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) */ virtual void addChild(Node * child, int zOrder) override; /** @@ -251,7 +251,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) * @param tag A interger to identify the node easily. Please refer to setTag(int) */ virtual void addChild(Node* child, int zOrder, int tag) override; diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index e28f4d8db0..d83c7a42db 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -255,7 +255,7 @@ Widget* Widget::getChildByName(const char *name) void Widget::addNode(Node* node) { - addNode(node, node->getZOrder(), node->getTag()); + addNode(node, node->getLocalZOrder(), node->getTag()); } void Widget::addNode(Node * node, int zOrder) @@ -1040,7 +1040,7 @@ void Widget::copyProperties(Widget *widget) setBright(widget->isBright()); setTouchEnabled(widget->isTouchEnabled()); _touchPassedEnabled = false; - setZOrder(widget->getZOrder()); + setLocalZOrder(widget->getLocalZOrder()); setTag(widget->getTag()); setName(widget->getName()); setActionTag(widget->getActionTag()); diff --git a/cocos/gui/UIWidget.h b/cocos/gui/UIWidget.h index d07bc4bee8..3827c60db2 100644 --- a/cocos/gui/UIWidget.h +++ b/cocos/gui/UIWidget.h @@ -212,7 +212,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) */ virtual void addChild(Node * child, int zOrder) override; /** @@ -221,7 +221,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) * @param tag A interger to identify the node easily. Please refer to setTag(int) */ virtual void addChild(Node* child, int zOrder, int tag) override; diff --git a/cocos/network/HttpClient.cpp b/cocos/network/HttpClient.cpp index cc19b72524..771a23c6f8 100644 --- a/cocos/network/HttpClient.cpp +++ b/cocos/network/HttpClient.cpp @@ -25,10 +25,17 @@ ****************************************************************************/ #include "HttpClient.h" + #include #include +#include + #include +#include "CCVector.h" +#include "CCDirector.h" +#include "CCScheduler.h" + #include "curl/curl.h" #include "platform/CCFileUtils.h" diff --git a/cocos/network/HttpClient.h b/cocos/network/HttpClient.h index 74f498e942..8c57bb2586 100644 --- a/cocos/network/HttpClient.h +++ b/cocos/network/HttpClient.h @@ -27,8 +27,6 @@ #ifndef __CCHTTPREQUEST_H__ #define __CCHTTPREQUEST_H__ -#include "cocos2d.h" - #include "network/HttpRequest.h" #include "network/HttpResponse.h" #include "network/HttpClient.h" diff --git a/cocos/network/HttpRequest.h b/cocos/network/HttpRequest.h index 50d660bca3..8ca5eee84d 100644 --- a/cocos/network/HttpRequest.h +++ b/cocos/network/HttpRequest.h @@ -26,7 +26,8 @@ #ifndef __HTTP_REQUEST_H__ #define __HTTP_REQUEST_H__ -#include "cocos2d.h" +#include "CCPlatformMacros.h" +#include "CCObject.h" NS_CC_BEGIN diff --git a/cocos/network/HttpResponse.h b/cocos/network/HttpResponse.h index 764ddde120..ebad23ec64 100644 --- a/cocos/network/HttpResponse.h +++ b/cocos/network/HttpResponse.h @@ -26,7 +26,6 @@ #ifndef __HTTP_RESPONSE__ #define __HTTP_RESPONSE__ -#include "cocos2d.h" #include "network/HttpRequest.h" NS_CC_BEGIN diff --git a/cocos/network/SocketIO.cpp b/cocos/network/SocketIO.cpp index c38ed4c70d..cc4b489e32 100644 --- a/cocos/network/SocketIO.cpp +++ b/cocos/network/SocketIO.cpp @@ -28,9 +28,12 @@ ****************************************************************************/ #include "SocketIO.h" +#include "CCDirector.h" +#include "CCScheduler.h" #include "WebSocket.h" #include "HttpClient.h" #include +#include NS_CC_BEGIN diff --git a/cocos/network/SocketIO.h b/cocos/network/SocketIO.h index 599a6c4cd0..8562fc1ba9 100644 --- a/cocos/network/SocketIO.h +++ b/cocos/network/SocketIO.h @@ -59,7 +59,10 @@ in the onClose method the pointer should be set to NULL or used to connect to a #ifndef __CC_SOCKETIO_H__ #define __CC_SOCKETIO_H__ -#include "cocos2d.h" +#include "CCPlatformMacros.h" +#include "CCMap.h" + +#include NS_CC_BEGIN diff --git a/cocos/network/WebSocket.cpp b/cocos/network/WebSocket.cpp index 5e17487567..3b5b3559f7 100644 --- a/cocos/network/WebSocket.cpp +++ b/cocos/network/WebSocket.cpp @@ -28,6 +28,8 @@ ****************************************************************************/ #include "WebSocket.h" +#include "CCDirector.h" +#include "CCScheduler.h" #include #include @@ -521,7 +523,7 @@ int WebSocket::onSocketCallback(struct libwebsocket_context *ctx, size_t remaining = data->len - data->issued; size_t n = std::min(remaining, c_bufferSize ); - CCLOG("[websocket:send] total: %d, sent: %d, remaining: %d, buffer size: %d", data->len, data->issued, remaining, n); + CCLOG("[websocket:send] total: %d, sent: %d, remaining: %d, buffer size: %d", static_cast(data->len), static_cast(data->issued), static_cast(remaining), static_cast(n)); unsigned char* buf = new unsigned char[LWS_SEND_BUFFER_PRE_PADDING + n + LWS_SEND_BUFFER_POST_PADDING]; diff --git a/cocos/network/WebSocket.h b/cocos/network/WebSocket.h index 738abf2c2f..3d4e9bf737 100644 --- a/cocos/network/WebSocket.h +++ b/cocos/network/WebSocket.h @@ -30,8 +30,11 @@ #ifndef __CC_WEBSOCKET_H__ #define __CC_WEBSOCKET_H__ -#include "cocos2d.h" +#include "CCPlatformMacros.h" +#include "CCStdC.h" #include +#include +#include struct libwebsocket; struct libwebsocket_context; @@ -153,8 +156,8 @@ private: unsigned int _port; std::string _path; - size_t _pendingFrameDataLen; - unsigned int _currentDataLen; + ssize_t _pendingFrameDataLen; + ssize_t _currentDataLen; char *_currentData; friend class WsThreadHelper; diff --git a/cocos/network/proj.win32/libNetwork.vcxproj b/cocos/network/proj.win32/libNetwork.vcxproj index 088538dfed..761ab39423 100644 --- a/cocos/network/proj.win32/libNetwork.vcxproj +++ b/cocos/network/proj.win32/libNetwork.vcxproj @@ -80,7 +80,7 @@ Disabled $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;..\Include;$(EngineRoot)cocos;$(EngineRoot)external\websockets\include\win32;$(EngineRoot)external\curl\include\win32;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_DEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;COCOS2D_DEBUG=1;%(PreprocessorDefinitions) false EnableFastChecks MultiThreadedDebugDLL diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 52ba0f527d..09574a22cc 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -300,29 +300,29 @@ protected: virtual ~PhysicsBody(); protected: - Node* _node; - std::vector _joints; - Vector _shapes; - PhysicsWorld* _world; - PhysicsBodyInfo* _info; - bool _dynamic; - bool _enable; - bool _rotationEnable; - bool _gravityEnable; - bool _massDefault; - bool _momentDefault; - float _mass; - float _area; - float _density; - float _moment; - float _linearDamping; - float _angularDamping; - int _tag; + Node* _node; + std::vector _joints; + Vector _shapes; + PhysicsWorld* _world; + PhysicsBodyInfo* _info; + bool _dynamic; + bool _enable; + bool _rotationEnable; + bool _gravityEnable; + bool _massDefault; + bool _momentDefault; + float _mass; + float _area; + float _density; + float _moment; + float _linearDamping; + float _angularDamping; + int _tag; - int _categoryBitmask; - int _collisionBitmask; - int _contactTestBitmask; - int _group; + int _categoryBitmask; + int _collisionBitmask; + int _contactTestBitmask; + int _group; friend class PhysicsWorld; friend class PhysicsShape; diff --git a/cocos/physics/CCPhysicsContact.h b/cocos/physics/CCPhysicsContact.h index 987e5daf47..74092ba3b0 100644 --- a/cocos/physics/CCPhysicsContact.h +++ b/cocos/physics/CCPhysicsContact.h @@ -58,7 +58,7 @@ typedef struct PhysicsContactData /** * @brief Contact infomation. it will created automatically when two shape contact with each other. and it will destoried automatically when two shape separated. */ -class PhysicsContact : Event +class PhysicsContact : public Event { public: diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index bca81f35b4..4ce0a2bb2a 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -55,7 +55,7 @@ typedef struct PhysicsRayCastInfo { PhysicsShape* shape; Point start; - Point end; + Point end; //< in lua, it's name is "ended" Point contact; Vect normal; float fraction; diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index bab1d8a7c5..6e36c31880 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit bab1d8a7c5d8b29f14c8dc19158a8bb994f0e970 +Subproject commit 6e36c31880076ac22d67eea982030927250ef7f3 diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 6510b90167..aa52f94223 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -6,15 +6,12 @@ // Copyright (c) 2012 Zynga Inc. All rights reserved. // -#include -#include -#include -#include -#include -#include -#include #include "ScriptingCore.h" -#include "jsdbgapi.h" + +// Removed in Firefox v27, use 'js/OldDebugAPI.h' instead +//#include "jsdbgapi.h" +#include "js/OldDebugAPI.h" + #include "cocos2d.h" #include "local-storage/LocalStorage.h" #include "cocos2d_specifics.hpp" @@ -30,6 +27,13 @@ #endif #include +#include +#include +#include +#include +#include +#include +#include #ifdef ANDROID #include @@ -46,7 +50,7 @@ #include "js_bindings_config.h" -#if DEBUG +#if COCOS2D_DEBUG #define TRACE_DEBUGGER_SERVER(...) CCLOG(__VA_ARGS__) #else #define TRACE_DEBUGGER_SERVER(...) @@ -80,7 +84,7 @@ static std::unordered_map filename_script; // port ~> socket map static std::unordered_map ports_sockets; // name ~> globals -static std::unordered_map globals; +static std::unordered_map globals; static void ReportException(JSContext *cx) { @@ -215,12 +219,12 @@ void js_log(const char *format, ...) { #define JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES 1 -JSBool JSBCore_platform(JSContext *cx, uint32_t argc, jsval *vp) +bool JSBCore_platform(JSContext *cx, uint32_t argc, jsval *vp) { if (argc!=0) { JS_ReportError(cx, "Invalid number of arguments in __getPlatform"); - return JS_FALSE; + return false; } JSString * platform; @@ -237,15 +241,15 @@ JSBool JSBCore_platform(JSContext *cx, uint32_t argc, jsval *vp) JS_SET_RVAL(cx, vp, ret); - return JS_TRUE; + return true; }; -JSBool JSBCore_version(JSContext *cx, uint32_t argc, jsval *vp) +bool JSBCore_version(JSContext *cx, uint32_t argc, jsval *vp) { if (argc!=0) { JS_ReportError(cx, "Invalid number of arguments in __getVersion"); - return JS_FALSE; + return false; } char version[256]; @@ -255,15 +259,15 @@ JSBool JSBCore_version(JSContext *cx, uint32_t argc, jsval *vp) jsval ret = STRING_TO_JSVAL(js_version); JS_SET_RVAL(cx, vp, ret); - return JS_TRUE; + return true; }; -JSBool JSBCore_os(JSContext *cx, uint32_t argc, jsval *vp) +bool JSBCore_os(JSContext *cx, uint32_t argc, jsval *vp) { if (argc!=0) { JS_ReportError(cx, "Invalid number of arguments in __getOS"); - return JS_FALSE; + return false; } JSString * os; @@ -292,21 +296,21 @@ JSBool JSBCore_os(JSContext *cx, uint32_t argc, jsval *vp) jsval ret = STRING_TO_JSVAL(os); JS_SET_RVAL(cx, vp, ret); - return JS_TRUE; + return true; }; -JSBool JSB_core_restartVM(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_core_restartVM(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==0, cx, JS_FALSE, "Invalid number of arguments in executeScript"); + JSB_PRECONDITION2(argc==0, cx, false, "Invalid number of arguments in executeScript"); ScriptingCore::getInstance()->reset(); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; }; void registerDefaultClasses(JSContext* cx, JSObject* global) { // first, try to get the ns JS::RootedValue nsval(cx); - JSObject *ns; + JS::RootedObject ns(cx); JS_GetProperty(cx, global, "cc", &nsval); if (nsval == JSVAL_VOID) { ns = JS_NewObject(cx, NULL, NULL, NULL); @@ -371,8 +375,8 @@ void ScriptingCore::string_report(jsval val) { LOGD("val : (JSVAL_IS_NULL(val)"); // return 1; } else if ((JSVAL_IS_BOOLEAN(val)) && - (JS_FALSE == (JSVAL_TO_BOOLEAN(val)))) { - LOGD("val : (return value is JS_FALSE"); + (false == (JSVAL_TO_BOOLEAN(val)))) { + LOGD("val : (return value is false"); // return 1; } else if (JSVAL_IS_STRING(val)) { JSString *str = JS_ValueToString(this->getGlobalContext(), val); @@ -384,8 +388,8 @@ void ScriptingCore::string_report(jsval val) { } } else if (JSVAL_IS_NUMBER(val)) { double number; - if (JS_FALSE == - JS_ValueToNumber(this->getGlobalContext(), val, &number)) { + if (false == + JS::ToNumber(this->getGlobalContext(), JS::RootedValue(_cx, val), &number)) { LOGD("val : return number could not be converted"); } else { LOGD("val : return number =\n%f", number); @@ -393,7 +397,7 @@ void ScriptingCore::string_report(jsval val) { } } -JSBool ScriptingCore::evalString(const char *string, jsval *outVal, const char *filename, JSContext* cx, JSObject* global) +bool ScriptingCore::evalString(const char *string, jsval *outVal, const char *filename, JSContext* cx, JSObject* global) { if (cx == NULL) cx = _cx; @@ -405,14 +409,14 @@ JSBool ScriptingCore::evalString(const char *string, jsval *outVal, const char * JSScript* script = JS_CompileScript(cx, global, string, strlen(string), filename, 1); if (script) { - JSBool evaluatedOK = JS_ExecuteScript(cx, global, script, outVal); - if (JS_FALSE == evaluatedOK) + bool evaluatedOK = JS_ExecuteScript(cx, global, script, outVal); + if (false == evaluatedOK) { - fprintf(stderr, "(evaluatedOK == JS_FALSE)\n"); + fprintf(stderr, "(evaluatedOK == false)\n"); } return evaluatedOK; } - return JS_FALSE; + return false; } void ScriptingCore::start() { @@ -441,11 +445,11 @@ void ScriptingCore::removeAllRoots(JSContext *cx) { static JSPrincipals shellTrustedPrincipals = { 1 }; -static JSBool -CheckObjectAccess(JSContext *cx, js::HandleObject obj, js::HandleId id, JSAccessMode mode, - js::MutableHandleValue vp) +static bool +CheckObjectAccess(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JSAccessMode mode, + JS::MutableHandleValue vp) { - return JS_TRUE; + return true; } static JSSecurityCallbacks securityCallbacks = { @@ -477,7 +481,9 @@ void ScriptingCore::createGlobalContext() { this->_cx = JS_NewContext(_rt, 8192); - JS_SetOptions(this->_cx, JSOPTION_TYPE_INFERENCE); + // Removed in Firefox v27 +// JS_SetOptions(this->_cx, JSOPTION_TYPE_INFERENCE); + JS::ContextOptionsRef(_cx).setTypeInference(true); // JS_SetVersion(this->_cx, JSVERSION_LATEST); @@ -512,7 +518,7 @@ static std::string RemoveFileExt(const std::string& filePath) { } } -JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* cx) +bool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* cx) { if (!path) { return false; @@ -530,8 +536,8 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c JSAutoCompartment ac(cx, global); - js::RootedScript script(cx); - js::RootedObject obj(cx, global); + JS::RootedScript script(cx); + JS::RootedObject obj(cx, global); // a) check jsc file first std::string byteCodePath = RemoveFileExt(std::string(path)) + BYTE_CODE_FILE_EXT; @@ -564,14 +570,14 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c #endif } - JSBool evaluatedOK = false; + bool evaluatedOK = false; if (script) { jsval rval; filename_script[path] = script; - JSAutoCompartment ac(cx, global); + evaluatedOK = JS_ExecuteScript(cx, global, script, &rval); - if (JS_FALSE == evaluatedOK) { - cocos2d::log("(evaluatedOK == JS_FALSE)"); + if (false == evaluatedOK) { + cocos2d::log("(evaluatedOK == false)"); JS_ReportPendingException(cx); } } @@ -627,7 +633,7 @@ void ScriptingCore::reportError(JSContext *cx, const char *message, JSErrorRepor }; -JSBool ScriptingCore::log(JSContext* cx, uint32_t argc, jsval *vp) +bool ScriptingCore::log(JSContext* cx, uint32_t argc, jsval *vp) { if (argc > 0) { JSString *string = NULL; @@ -637,7 +643,7 @@ JSBool ScriptingCore::log(JSContext* cx, uint32_t argc, jsval *vp) js_log("%s", wrapper.get()); } } - return JS_TRUE; + return true; } @@ -656,28 +662,28 @@ void ScriptingCore::removeScriptObjectByObject(Object* pObj) } -JSBool ScriptingCore::setReservedSpot(uint32_t i, JSObject *obj, jsval value) { +bool ScriptingCore::setReservedSpot(uint32_t i, JSObject *obj, jsval value) { JS_SetReservedSlot(obj, i, value); - return JS_TRUE; + return true; } -JSBool ScriptingCore::executeScript(JSContext *cx, uint32_t argc, jsval *vp) +bool ScriptingCore::executeScript(JSContext *cx, uint32_t argc, jsval *vp) { if (argc >= 1) { jsval* argv = JS_ARGV(cx, vp); JSString* str = JS_ValueToString(cx, argv[0]); JSStringWrapper path(str); - JSBool res = false; + bool res = false; if (argc == 2 && argv[1].isString()) { JSString* globalName = JSVAL_TO_STRING(argv[1]); JSStringWrapper name(globalName); -// js::RootedObject* rootedGlobal = globals[name]; +// JS::RootedObject* rootedGlobal = globals[name]; JSObject* debugObj = ScriptingCore::getInstance()->getDebugGlobal(); if (debugObj) { res = ScriptingCore::getInstance()->runScript(path.get(), debugObj); } else { JS_ReportError(cx, "Invalid global object: %s", name.get()); - return JS_FALSE; + return false; } } else { JSObject* glob = JS::CurrentGlobalOrNull(cx); @@ -685,14 +691,14 @@ JSBool ScriptingCore::executeScript(JSContext *cx, uint32_t argc, jsval *vp) } return res; } - return JS_TRUE; + return true; } -JSBool ScriptingCore::forceGC(JSContext *cx, uint32_t argc, jsval *vp) +bool ScriptingCore::forceGC(JSContext *cx, uint32_t argc, jsval *vp) { JSRuntime *rt = JS_GetRuntime(cx); JS_GC(rt); - return JS_TRUE; + return true; } //static void dumpNamedRoot(const char *name, void *addr, JSGCRootType type, void *data) @@ -700,43 +706,43 @@ JSBool ScriptingCore::forceGC(JSContext *cx, uint32_t argc, jsval *vp) // CCLOG("Root: '%s' at %p", name, addr); //} -JSBool ScriptingCore::dumpRoot(JSContext *cx, uint32_t argc, jsval *vp) +bool ScriptingCore::dumpRoot(JSContext *cx, uint32_t argc, jsval *vp) { // JS_DumpNamedRoots is only available on DEBUG versions of SpiderMonkey. // Mac and Simulator versions were compiled with DEBUG. -#if DEBUG +#if COCOS2D_DEBUG // JSContext *_cx = ScriptingCore::getInstance()->getGlobalContext(); // JSRuntime *rt = JS_GetRuntime(_cx); // JS_DumpNamedRoots(rt, dumpNamedRoot, NULL); // JS_DumpHeap(rt, stdout, NULL, JSTRACE_OBJECT, NULL, 2, NULL); #endif - return JS_TRUE; + return true; } -JSBool ScriptingCore::addRootJS(JSContext *cx, uint32_t argc, jsval *vp) +bool ScriptingCore::addRootJS(JSContext *cx, uint32_t argc, jsval *vp) { if (argc == 1) { JSObject *o = NULL; - if (JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "o", &o) == JS_TRUE) { - if (JS_AddNamedObjectRoot(cx, &o, "from-js") == JS_FALSE) { + if (JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "o", &o) == true) { + if (JS_AddNamedObjectRoot(cx, &o, "from-js") == false) { LOGD("something went wrong when setting an object to the root"); } } - return JS_TRUE; + return true; } - return JS_FALSE; + return false; } -JSBool ScriptingCore::removeRootJS(JSContext *cx, uint32_t argc, jsval *vp) +bool ScriptingCore::removeRootJS(JSContext *cx, uint32_t argc, jsval *vp) { if (argc == 1) { JSObject *o = NULL; - if (JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "o", &o) == JS_TRUE) { + if (JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "o", &o) == true) { JS_RemoveObjectRoot(cx, &o); } - return JS_TRUE; + return true; } - return JS_FALSE; + return false; } void ScriptingCore::pauseSchedulesAndActions(js_proxy_t* p) @@ -870,8 +876,9 @@ int ScriptingCore::handleTouchesEvent(void* data) for (auto& touch : touches) { - jsval jsret; - getJSTouchObject(this->_cx, touch, jsret); + jsval jsval; + getJSTouchObject(this->_cx, touch, jsval); + JS::RootedValue jsret(_cx, jsval); if (!JS_SetElement(this->_cx, jsretArr, count, &jsret)) { break; @@ -937,10 +944,10 @@ bool ScriptingCore::executeFunctionWithObjectData(Node *self, const char *name, return false; } -JSBool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, uint32_t argc /* = 0 */, jsval *vp /* = NULL */, jsval* retVal /* = NULL */) +bool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, uint32_t argc /* = 0 */, jsval *vp /* = NULL */, jsval* retVal /* = NULL */) { - JSBool bRet = JS_FALSE; - JSBool hasAction; + bool bRet = false; + bool hasAction; JSContext* cx = this->_cx; JS::RootedValue temp_retval(cx); JSObject* obj = JSVAL_TO_OBJECT(owner); @@ -1005,7 +1012,7 @@ int ScriptingCore::handleKeypadEvent(void* data) if (p) { - JSBool ret = JS_FALSE; + bool ret = false; switch(action) { case EventKeyboard::KeyCode::KEY_BACKSPACE: @@ -1054,7 +1061,8 @@ int ScriptingCore::executeCustomTouchesEvent(EventTouch::EventCode eventType, { jsval jsret; getJSTouchObject(this->_cx, touch, jsret); - if (!JS_SetElement(this->_cx, jsretArr, count, &jsret)) { + JS::RootedValue jsval(_cx, jsret); + if (!JS_SetElement(this->_cx, jsretArr, count, &jsval)) { break; } ++count; @@ -1167,7 +1175,7 @@ bool ScriptingCore::parseConfig(ConfigType type, const std::string &str) jsval args[2]; args[0] = int32_to_jsval(_cx, static_cast(type)); args[1] = std_string_to_jsval(_cx, str); - return (JS_TRUE == executeFunctionWithOwner(OBJECT_TO_JSVAL(_global), "__onParseConfig", 2, args)); + return (true == executeFunctionWithOwner(OBJECT_TO_JSVAL(_global), "__onParseConfig", 2, args)); } #pragma mark - Debug @@ -1225,7 +1233,7 @@ static bool NS_ProcessNextEvent() return true; } -JSBool JSBDebug_enterNestedEventLoop(JSContext* cx, unsigned argc, jsval* vp) +bool JSBDebug_enterNestedEventLoop(JSContext* cx, unsigned argc, jsval* vp) { enum { NS_OK = 0, @@ -1247,26 +1255,26 @@ JSBool JSBDebug_enterNestedEventLoop(JSContext* cx, unsigned argc, jsval* vp) "nested event didn't unwind properly"); JS_SET_RVAL(cx, vp, UINT_TO_JSVAL(s_nestedLoopLevel)); - return JS_TRUE; + return true; } -JSBool JSBDebug_exitNestedEventLoop(JSContext* cx, unsigned argc, jsval* vp) +bool JSBDebug_exitNestedEventLoop(JSContext* cx, unsigned argc, jsval* vp) { if (s_nestedLoopLevel > 0) { --s_nestedLoopLevel; } else { JS_SET_RVAL(cx, vp, UINT_TO_JSVAL(0)); - return JS_TRUE; + return true; } JS_SET_RVAL(cx, vp, UINT_TO_JSVAL(s_nestedLoopLevel)); - return JS_TRUE; + return true; } -JSBool JSBDebug_getEventLoopNestLevel(JSContext* cx, unsigned argc, jsval* vp) +bool JSBDebug_getEventLoopNestLevel(JSContext* cx, unsigned argc, jsval* vp) { JS_SET_RVAL(cx, vp, UINT_TO_JSVAL(s_nestedLoopLevel)); - return JS_TRUE; + return true; } //#pragma mark - Debugger @@ -1387,7 +1395,7 @@ static void serverEntryPoint(void) } // while(true) } -JSBool JSBDebug_BufferWrite(JSContext* cx, unsigned argc, jsval* vp) +bool JSBDebug_BufferWrite(JSContext* cx, unsigned argc, jsval* vp) { if (argc == 1) { jsval* argv = JS_ARGV(cx, vp); @@ -1396,7 +1404,7 @@ JSBool JSBDebug_BufferWrite(JSContext* cx, unsigned argc, jsval* vp) outData.append(strWrapper.get()); _clientSocketWriteAndClearString(outData); } - return JS_TRUE; + return true; } void ScriptingCore::enableDebugger() @@ -1405,10 +1413,13 @@ void ScriptingCore::enableDebugger() { JSAutoCompartment ac0(_cx, _global); - JS_SetDebugMode(_cx, JS_TRUE); + JS_SetDebugMode(_cx, true); _debugGlobal = NewGlobalObject(_cx, true); - JS_WrapObject(_cx, &_debugGlobal); + // Adds the debugger object to root, otherwise it may be collected by GC. + JS_AddObjectRoot(_cx, &_debugGlobal); + JS::RootedObject rootedDebugObj(_cx, _debugGlobal); + JS_WrapObject(_cx, &rootedDebugObj); JSAutoCompartment ac(_cx, _debugGlobal); // these are used in the debug program JS_DefineFunction(_cx, _debugGlobal, "log", ScriptingCore::log, 0, JSPROP_READONLY | JSPROP_PERMANENT); @@ -1423,7 +1434,7 @@ void ScriptingCore::enableDebugger() // prepare the debugger jsval argv = OBJECT_TO_JSVAL(_global); jsval outval; - JSBool ok = JS_CallFunctionName(_cx, _debugGlobal, "_prepareDebugger", 1, &argv, &outval); + bool ok = JS_CallFunctionName(_cx, _debugGlobal, "_prepareDebugger", 1, &argv, &outval); if (!ok) { JS_ReportPendingException(_cx); } @@ -1447,7 +1458,7 @@ JSObject* NewGlobalObject(JSContext* cx, bool debug) return NULL; } JSAutoCompartment ac(cx, glob); - JSBool ok = JS_TRUE; + bool ok = true; ok = JS_InitStandardClasses(cx, glob); if (ok) JS_InitReflect(cx, glob); @@ -1461,28 +1472,28 @@ JSObject* NewGlobalObject(JSContext* cx, bool debug) return glob; } -JSBool jsb_set_reserved_slot(JSObject *obj, uint32_t idx, jsval value) +bool jsb_set_reserved_slot(JSObject *obj, uint32_t idx, jsval value) { - JSClass *klass = JS_GetClass(obj); + const JSClass *klass = JS_GetClass(obj); unsigned int slots = JSCLASS_RESERVED_SLOTS(klass); if ( idx >= slots ) - return JS_FALSE; + return false; JS_SetReservedSlot(obj, idx, value); - return JS_TRUE; + return true; } -JSBool jsb_get_reserved_slot(JSObject *obj, uint32_t idx, jsval& ret) +bool jsb_get_reserved_slot(JSObject *obj, uint32_t idx, jsval& ret) { - JSClass *klass = JS_GetClass(obj); + const JSClass *klass = JS_GetClass(obj); unsigned int slots = JSCLASS_RESERVED_SLOTS(klass); if ( idx >= slots ) - return JS_FALSE; + return false; ret = JS_GetReservedSlot(obj, idx); - return JS_TRUE; + return true; } js_proxy_t* jsb_new_proxy(void* nativeObj, JSObject* jsObj) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.h b/cocos/scripting/javascript/bindings/ScriptingCore.h index fcf08fef99..6379b4493e 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.h +++ b/cocos/scripting/javascript/bindings/ScriptingCore.h @@ -9,16 +9,18 @@ #ifndef __SCRIPTING_CORE_H__ #define __SCRIPTING_CORE_H__ -#include -#include + +#include "jsapi.h" +#include "jsfriendapi.h" #include "cocos2d.h" #include "js_bindings_config.h" #include "js_bindings_core.h" -#include "jsapi.h" -#include "jsfriendapi.h" #include "spidermonkey_specifics.h" #include "js_manual_conversions.h" +#include +#include + void js_log(const char *format, ...); typedef void (*sc_register_sth)(JSContext* cx, JSObject* global); @@ -92,7 +94,7 @@ public: virtual bool handleAssert(const char *msg) { return false; } bool executeFunctionWithObjectData(cocos2d::Node *self, const char *name, JSObject *obj); - JSBool executeFunctionWithOwner(jsval owner, const char *name, uint32_t argc = 0, jsval* vp = NULL, jsval* retVal = NULL); + bool executeFunctionWithOwner(jsval owner, const char *name, uint32_t argc = 0, jsval* vp = NULL, jsval* retVal = NULL); void executeJSFunctionWithThisObj(jsval thisObj, jsval callback, uint32_t argc = 0, jsval* vp = NULL, jsval* retVal = NULL); @@ -102,13 +104,13 @@ public: * @param outVal The jsval that will hold the return value of the evaluation. * Can be NULL. */ - JSBool evalString(const char *string, jsval *outVal, const char *filename = NULL, JSContext* cx = NULL, JSObject* global = NULL); + bool evalString(const char *string, jsval *outVal, const char *filename = NULL, JSContext* cx = NULL, JSObject* global = NULL); /** * will run the specified string * @param string The path of the script to be run */ - JSBool runScript(const char *path, JSObject* global = NULL, JSContext* cx = NULL); + bool runScript(const char *path, JSObject* global = NULL, JSContext* cx = NULL); /** * initialize everything @@ -166,14 +168,14 @@ public: * @param argc * @param vp */ - static JSBool log(JSContext *cx, uint32_t argc, jsval *vp); + static bool log(JSContext *cx, uint32_t argc, jsval *vp); - JSBool setReservedSpot(uint32_t i, JSObject *obj, jsval value); + bool setReservedSpot(uint32_t i, JSObject *obj, jsval value); /** * run a script from script :) */ - static JSBool executeScript(JSContext *cx, uint32_t argc, jsval *vp); + static bool executeScript(JSContext *cx, uint32_t argc, jsval *vp); /** * Force a cycle of GC @@ -181,10 +183,10 @@ public: * @param argc * @param vp */ - static JSBool forceGC(JSContext *cx, uint32_t argc, jsval *vp); - static JSBool dumpRoot(JSContext *cx, uint32_t argc, jsval *vp); - static JSBool addRootJS(JSContext *cx, uint32_t argc, jsval *vp); - static JSBool removeRootJS(JSContext *cx, uint32_t argc, jsval *vp); + static bool forceGC(JSContext *cx, uint32_t argc, jsval *vp); + static bool dumpRoot(JSContext *cx, uint32_t argc, jsval *vp); + static bool addRootJS(JSContext *cx, uint32_t argc, jsval *vp); + static bool removeRootJS(JSContext *cx, uint32_t argc, jsval *vp); /** * enable the debug environment @@ -207,8 +209,8 @@ public: JSObject* NewGlobalObject(JSContext* cx, bool debug = false); -JSBool jsb_set_reserved_slot(JSObject *obj, uint32_t idx, jsval value); -JSBool jsb_get_reserved_slot(JSObject *obj, uint32_t idx, jsval& ret); +bool jsb_set_reserved_slot(JSObject *obj, uint32_t idx, jsval value); +bool jsb_get_reserved_slot(JSObject *obj, uint32_t idx, jsval& ret); js_proxy_t* jsb_new_proxy(void* nativeObj, JSObject* jsObj); js_proxy_t* jsb_get_native_proxy(void* nativeObj); diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id index 0e67c34489..d4a08b968a 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_auto_classes.cpp.REMOVED.git-id @@ -1 +1 @@ -2a8f07a22574900290f772ad5a580ef9fc57a9b8 \ No newline at end of file +69a76886ff5f4a52af8ac6d91c439cf31fddad06 \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id index 264696d780..aa3741a69b 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.cpp.REMOVED.git-id @@ -1 +1 @@ -ac3eca550f3b923d03d042ed63edf3b66cc183b7 \ No newline at end of file +e4d9556ecc7430330bd9f65eef6dcb095b2b36fc \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.h index accf523d5e..e9dc4f87d9 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.h +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_functions.h @@ -10,279 +10,279 @@ #ifdef __cplusplus extern "C" { #endif -JSBool JSB_cpArbiterGetCount(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetDepth(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetElasticity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetFriction(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetNormal(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetPoint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterIgnore(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterIsFirstContact(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterSetElasticity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterSetFriction(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterSetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterTotalImpulse(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterTotalImpulseWithFriction(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterTotalKE(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpAreaForCircle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpAreaForSegment(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBArea(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBClampVect(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBContainsBB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBContainsVect(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBExpand(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBIntersects(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBIntersectsSegment(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBMerge(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBMergedArea(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBNewForCircle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBSegmentQuery(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBBWrapVect(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyActivate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyActivateStatic(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyApplyForce(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyApplyImpulse(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyDestroy(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyFree(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetAngVel(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetAngVelLimit(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetAngle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetForce(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetMass(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetMoment(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetPos(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetRot(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetSpace(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetTorque(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetVel(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetVelAtLocalPoint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetVelAtWorldPoint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetVelLimit(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyInit(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyInitStatic(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyIsRogue(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyIsSleeping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyIsStatic(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyKineticEnergy(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyLocal2World(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyNewStatic(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyResetForces(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetAngVel(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetAngVelLimit(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetAngle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetForce(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetMass(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetMoment(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetPos(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetTorque(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetVel(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetVelLimit(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySleep(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySleepWithGroup(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyUpdatePosition(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyUpdateVelocity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyWorld2Local(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBoxShapeNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBoxShapeNew2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpCircleShapeGetOffset(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpCircleShapeGetRadius(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpCircleShapeNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintActivateBodies(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintDestroy(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintFree(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetA(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetErrorBias(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetImpulse(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetMaxBias(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetMaxForce(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintGetSpace(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintSetErrorBias(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintSetMaxBias(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpConstraintSetMaxForce(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringGetDamping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringGetRestAngle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringGetStiffness(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringSetDamping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringSetRestAngle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedRotarySpringSetStiffness(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringGetDamping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringGetRestLength(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringGetStiffness(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringSetDamping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringSetRestLength(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpDampedSpringSetStiffness(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGearJointGetPhase(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGearJointGetRatio(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGearJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGearJointSetPhase(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGearJointSetRatio(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointGetGrooveA(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointGetGrooveB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointSetGrooveA(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpGrooveJointSetGrooveB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpInitChipmunk(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpMomentForBox(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpMomentForBox2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpMomentForCircle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpMomentForSegment(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointGetDist(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPinJointSetDist(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPivotJointGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPivotJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPivotJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPivotJointNew2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPivotJointSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPivotJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPolyShapeGetNumVerts(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpPolyShapeGetVert(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointGetAngle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointGetPhase(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointGetRatchet(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointSetAngle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointSetPhase(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRatchetJointSetRatchet(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpResetShapeIdCounter(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRotaryLimitJointGetMax(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRotaryLimitJointGetMin(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRotaryLimitJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRotaryLimitJointSetMax(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRotaryLimitJointSetMin(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSegmentShapeGetA(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSegmentShapeGetB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSegmentShapeGetNormal(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSegmentShapeGetRadius(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSegmentShapeNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSegmentShapeSetNeighbors(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeCacheBB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeDestroy(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeFree(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetBB(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetCollisionType(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetElasticity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetFriction(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetGroup(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetLayers(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetSensor(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetSpace(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeGetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapePointQuery(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetCollisionType(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetElasticity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetFriction(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetGroup(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetLayers(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetSensor(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeSetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpShapeUpdate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSimpleMotorGetRate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSimpleMotorNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSimpleMotorSetRate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointGetMax(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointGetMin(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointSetMax(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSlideJointSetMin(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceActivateShapesTouchingShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceAddBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceAddConstraint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceAddShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceAddStaticShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceContainsBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceContainsConstraint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceContainsShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceDestroy(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceFree(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetCollisionBias(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetCollisionPersistence(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetCollisionSlop(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetCurrentTimeStep(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetDamping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetEnableContactGraph(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetGravity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetIdleSpeedThreshold(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetIterations(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetSleepTimeThreshold(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceGetStaticBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceInit(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceIsLocked(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceNew(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpacePointQueryFirst(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceReindexShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceReindexShapesForBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceReindexStatic(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceRemoveBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceRemoveConstraint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceRemoveShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceRemoveStaticShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetCollisionBias(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetCollisionPersistence(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetCollisionSlop(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetDamping(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetEnableContactGraph(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetGravity(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetIdleSpeedThreshold(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetIterations(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceSetSleepTimeThreshold(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceStep(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceUseSpatialHash(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpfabs(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpfclamp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpfclamp01(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpflerp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpflerpconst(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpfmax(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpfmin(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvadd(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvclamp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvcross(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvdist(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvdistsq(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvdot(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpveql(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvforangle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvlength(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvlengthsq(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvlerp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvlerpconst(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvmult(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvnear(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvneg(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvnormalize(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvnormalize_safe(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvperp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvproject(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvrotate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvrperp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvslerp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvslerpconst(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvsub(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvtoangle(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpvunrotate(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterGetCount(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterGetDepth(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterGetElasticity(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterGetFriction(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterGetNormal(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterGetPoint(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterGetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterIgnore(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterIsFirstContact(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterSetElasticity(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterSetFriction(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterSetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterTotalImpulse(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterTotalImpulseWithFriction(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterTotalKE(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpAreaForCircle(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpAreaForSegment(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBBArea(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBBClampVect(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBBContainsBB(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBBContainsVect(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBBExpand(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBBIntersects(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBBIntersectsSegment(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBBMerge(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBBMergedArea(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBBNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBBNewForCircle(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBBSegmentQuery(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBBWrapVect(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyActivate(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyActivateStatic(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyApplyForce(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyApplyImpulse(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyDestroy(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyFree(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetAngVel(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetAngVelLimit(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetAngle(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetForce(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetMass(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetMoment(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetPos(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetRot(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetSpace(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetTorque(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetVel(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetVelAtLocalPoint(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetVelAtWorldPoint(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetVelLimit(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyInit(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyInitStatic(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyIsRogue(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyIsSleeping(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyIsStatic(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyKineticEnergy(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyLocal2World(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyNewStatic(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyResetForces(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodySetAngVel(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodySetAngVelLimit(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodySetAngle(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodySetForce(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodySetMass(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodySetMoment(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodySetPos(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodySetTorque(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodySetVel(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodySetVelLimit(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodySleep(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodySleepWithGroup(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyUpdatePosition(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyUpdateVelocity(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyWorld2Local(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBoxShapeNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBoxShapeNew2(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpCircleShapeGetOffset(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpCircleShapeGetRadius(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpCircleShapeNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpConstraintActivateBodies(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpConstraintDestroy(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpConstraintFree(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpConstraintGetA(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpConstraintGetB(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpConstraintGetErrorBias(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpConstraintGetImpulse(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpConstraintGetMaxBias(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpConstraintGetMaxForce(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpConstraintGetSpace(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpConstraintSetErrorBias(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpConstraintSetMaxBias(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpConstraintSetMaxForce(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedRotarySpringGetDamping(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedRotarySpringGetRestAngle(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedRotarySpringGetStiffness(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedRotarySpringNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedRotarySpringSetDamping(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedRotarySpringSetRestAngle(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedRotarySpringSetStiffness(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedSpringGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedSpringGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedSpringGetDamping(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedSpringGetRestLength(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedSpringGetStiffness(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedSpringNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedSpringSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedSpringSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedSpringSetDamping(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedSpringSetRestLength(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpDampedSpringSetStiffness(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpGearJointGetPhase(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpGearJointGetRatio(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpGearJointNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpGearJointSetPhase(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpGearJointSetRatio(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpGrooveJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpGrooveJointGetGrooveA(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpGrooveJointGetGrooveB(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpGrooveJointNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpGrooveJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpGrooveJointSetGrooveA(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpGrooveJointSetGrooveB(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpInitChipmunk(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpMomentForBox(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpMomentForBox2(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpMomentForCircle(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpMomentForSegment(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPinJointGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPinJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPinJointGetDist(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPinJointNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPinJointSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPinJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPinJointSetDist(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPivotJointGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPivotJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPivotJointNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPivotJointNew2(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPivotJointSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPivotJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPolyShapeGetNumVerts(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPolyShapeGetVert(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpRatchetJointGetAngle(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpRatchetJointGetPhase(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpRatchetJointGetRatchet(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpRatchetJointNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpRatchetJointSetAngle(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpRatchetJointSetPhase(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpRatchetJointSetRatchet(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpResetShapeIdCounter(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpRotaryLimitJointGetMax(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpRotaryLimitJointGetMin(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpRotaryLimitJointNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpRotaryLimitJointSetMax(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpRotaryLimitJointSetMin(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSegmentShapeGetA(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSegmentShapeGetB(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSegmentShapeGetNormal(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSegmentShapeGetRadius(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSegmentShapeNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSegmentShapeSetNeighbors(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeCacheBB(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeDestroy(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeFree(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeGetBB(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeGetBody(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeGetCollisionType(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeGetElasticity(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeGetFriction(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeGetGroup(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeGetLayers(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeGetSensor(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeGetSpace(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeGetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapePointQuery(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeSetBody(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeSetCollisionType(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeSetElasticity(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeSetFriction(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeSetGroup(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeSetLayers(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeSetSensor(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeSetSurfaceVelocity(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpShapeUpdate(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSimpleMotorGetRate(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSimpleMotorNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSimpleMotorSetRate(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSlideJointGetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSlideJointGetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSlideJointGetMax(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSlideJointGetMin(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSlideJointNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSlideJointSetAnchr1(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSlideJointSetAnchr2(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSlideJointSetMax(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSlideJointSetMin(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceActivateShapesTouchingShape(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceAddBody(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceAddConstraint(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceAddShape(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceAddStaticShape(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceContainsBody(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceContainsConstraint(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceContainsShape(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceDestroy(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceFree(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceGetCollisionBias(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceGetCollisionPersistence(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceGetCollisionSlop(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceGetCurrentTimeStep(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceGetDamping(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceGetEnableContactGraph(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceGetGravity(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceGetIdleSpeedThreshold(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceGetIterations(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceGetSleepTimeThreshold(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceGetStaticBody(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceInit(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceIsLocked(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceNew(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpacePointQueryFirst(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceReindexShape(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceReindexShapesForBody(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceReindexStatic(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceRemoveBody(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceRemoveConstraint(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceRemoveShape(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceRemoveStaticShape(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceSetCollisionBias(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceSetCollisionPersistence(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceSetCollisionSlop(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceSetDamping(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceSetEnableContactGraph(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceSetGravity(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceSetIdleSpeedThreshold(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceSetIterations(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceSetSleepTimeThreshold(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceStep(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceUseSpatialHash(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpfabs(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpfclamp(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpfclamp01(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpflerp(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpflerpconst(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpfmax(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpfmin(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvadd(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvclamp(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvcross(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvdist(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvdistsq(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvdot(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpveql(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvforangle(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvlength(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvlengthsq(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvlerp(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvlerpconst(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvmult(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvnear(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvneg(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvnormalize(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvnormalize_safe(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvperp(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvproject(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvrotate(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvrperp(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvslerp(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvslerpconst(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvsub(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvtoangle(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpvunrotate(JSContext *cx, uint32_t argc, jsval *vp); #ifdef __cplusplus } diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp index a26529e0cd..89ce8042fc 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.cpp @@ -22,13 +22,12 @@ * THE SOFTWARE. */ +#include "jsapi.h" +#include "jsfriendapi.h" #include "extensions/cocos-ext.h" #include "js_bindings_config.h" #ifdef JSB_INCLUDE_CHIPMUNK -#include "jsapi.h" -#include "jsfriendapi.h" - #include "js_bindings_chipmunk_manual.h" #include "js_manual_conversions.h" @@ -37,7 +36,7 @@ USING_NS_CC_EXT; void static freeSpaceChildren(cpSpace *space); template -static JSBool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp) { +static bool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp) { TypeTest t; T* cobj = new T(); cobj->autorelease(); @@ -54,7 +53,7 @@ static JSBool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp) { JS_AddObjectRoot(cx, &pp->obj); JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(_tmp)); - return JS_TRUE; + return true; } #pragma mark - convertions @@ -76,7 +75,7 @@ void JSPROXY_CCPhysicsSprite_finalize(JSFreeOp *fop, JSObject *obj) // Arguments: // Ret value: cpBody* (N/A) -JSBool JSPROXY_CCPhysicsSprite_getCPBody(JSContext *cx, uint32_t argc, jsval *vp) { +bool JSPROXY_CCPhysicsSprite_getCPBody(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); @@ -88,12 +87,12 @@ JSBool JSPROXY_CCPhysicsSprite_getCPBody(JSContext *cx, uint32_t argc, jsval *vp jsval ret_jsval = c_class_to_jsval( cx, ret_val, JSB_cpBody_object, JSB_cpBody_class, "cpBody" ); JS_SET_RVAL(cx, vp, ret_jsval); - return JS_TRUE; + return true; } // Arguments: // Ret value: BOOL (b) -JSBool JSPROXY_CCPhysicsSprite_ignoreBodyRotation(JSContext *cx, uint32_t argc, jsval *vp) { +bool JSPROXY_CCPhysicsSprite_ignoreBodyRotation(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); @@ -104,12 +103,12 @@ JSBool JSPROXY_CCPhysicsSprite_ignoreBodyRotation(JSContext *cx, uint32_t argc, ret_val = real->isIgnoreBodyRotation(); JS_SET_RVAL(cx, vp, BOOLEAN_TO_JSVAL(ret_val)); - return JS_TRUE; + return true; } // Arguments: cpBody* // Ret value: void (None) -JSBool JSPROXY_CCPhysicsSprite_setCPBody_(JSContext *cx, uint32_t argc, jsval *vp) { +bool JSPROXY_CCPhysicsSprite_setCPBody_(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); @@ -117,21 +116,21 @@ JSBool JSPROXY_CCPhysicsSprite_setCPBody_(JSContext *cx, uint32_t argc, jsval *v TEST_NATIVE_OBJECT(cx, real) jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpBody* arg0; ok &= jsval_to_opaque( cx, *argvp++, (void**)&arg0 ); - if( ! ok ) return JS_FALSE; + if( ! ok ) return false; real->setCPBody((cpBody*)arg0); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: BOOL // Ret value: void (None) -JSBool JSPROXY_CCPhysicsSprite_setIgnoreBodyRotation_(JSContext *cx, uint32_t argc, jsval *vp) { +bool JSPROXY_CCPhysicsSprite_setIgnoreBodyRotation_(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); @@ -139,15 +138,15 @@ JSBool JSPROXY_CCPhysicsSprite_setIgnoreBodyRotation_(JSContext *cx, uint32_t ar TEST_NATIVE_OBJECT(cx, real) jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - JSBool arg0; + bool ok = true; + bool arg0; ok &= JS_ValueToBoolean( cx, *argvp++, &arg0 ); - if( ! ok ) return JS_FALSE; + if( ! ok ) return false; real->setIgnoreBodyRotation((bool)arg0); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } /* @@ -169,14 +168,14 @@ void JSB_CCPhysicsDebugNode_finalize(JSFreeOp *fop, JSObject *obj) // Arguments: cpSpace* // Ret value: PhysicsDebugNode* (o) -JSBool JSB_CCPhysicsDebugNode_debugNodeForCPSpace__static(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_CCPhysicsDebugNode_debugNodeForCPSpace__static(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpSpace* arg0; ok &= jsval_to_opaque( cx, *argvp++, (void**)&arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); PhysicsDebugNode* ret = PhysicsDebugNode::create(arg0); jsval jsret; @@ -201,40 +200,40 @@ JSBool JSB_CCPhysicsDebugNode_debugNodeForCPSpace__static(JSContext *cx, uint32_ } while (0); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } // Arguments: cpSpace* // Ret value: void (None) -JSBool JSB_CCPhysicsDebugNode_setSpace_(JSContext *cx, uint32_t argc, jsval *vp) { +bool JSB_CCPhysicsDebugNode_setSpace_(JSContext *cx, uint32_t argc, jsval *vp) { JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(jsthis); PhysicsDebugNode* real = (PhysicsDebugNode *)(proxy ? proxy->ptr : NULL); TEST_NATIVE_OBJECT(cx, real) - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpSpace* arg0; ok &= jsval_to_opaque( cx, *argvp++, (void**)&arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); real->setSpace(arg0); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: // Ret value: cpSpace* (N/A) -JSBool JSB_CCPhysicsDebugNode_space(JSContext *cx, uint32_t argc, jsval *vp) { +bool JSB_CCPhysicsDebugNode_space(JSContext *cx, uint32_t argc, jsval *vp) { JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(jsthis); PhysicsDebugNode* real = (PhysicsDebugNode *)(proxy ? proxy->ptr : NULL); TEST_NATIVE_OBJECT(cx, real) - JSB_PRECONDITION2( argc == 0, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 0, cx, false, "Invalid number of arguments" ); cpSpace* ret_val; ret_val = real->getSpace(); @@ -242,7 +241,7 @@ JSBool JSB_CCPhysicsDebugNode_space(JSContext *cx, uint32_t argc, jsval *vp) { jsval ret_jsval = opaque_to_jsval( cx, ret_val ); JS_SET_RVAL(cx, vp, ret_jsval); - return JS_TRUE; + return true; } void JSB_CCPhysicsDebugNode_createClass(JSContext *cx, JSObject* globalObj, const char* name ) @@ -299,16 +298,16 @@ void JSB_CCPhysicsDebugNode_createClass(JSContext *cx, JSObject* globalObj, cons // Arguments: NSString*, CGRect // Ret value: PhysicsSprite* (o) -JSBool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32_t argc, jsval *vp) { +bool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); - JSBool ok = JS_TRUE; + bool ok = true; if (argc == 2) { const char* arg0; std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); cocos2d::Rect arg1; ok &= jsval_to_ccrect(cx, argv[1], &arg1); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); PhysicsSprite* ret = PhysicsSprite::create(arg0, arg1); @@ -332,12 +331,12 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32 } } while (0); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } if (argc == 1) { const char* arg0; std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); PhysicsSprite* ret = PhysicsSprite::create(arg0); @@ -360,15 +359,15 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithFile_rect__static(JSContext *cx, uint32 } } while (0); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } - return JS_FALSE; + return false; } // Arguments: SpriteFrame* // Ret value: PhysicsSprite* (o) -JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrame__static(JSContext *cx, uint32_t argc, jsval *vp) { +bool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrame__static(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); cocos2d::SpriteFrame* arg0; if (argc >= 1) { @@ -401,14 +400,14 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrame__static(JSContext *cx, uint } } while (0); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } // Arguments: NSString* // Ret value: PhysicsSprite* (o) -JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrameName__static(JSContext *cx, uint32_t argc, jsval *vp) { +bool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrameName__static(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); - JSBool ok = JS_TRUE; + bool ok = true; const char* arg0; std::string arg0_tmp; if (argc == 1) { @@ -435,11 +434,11 @@ JSBool JSPROXY_CCPhysicsSprite_spriteWithSpriteFrameName__static(JSContext *cx, } } while (0); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); - return JS_FALSE; + return false; } void JSPROXY_CCPhysicsSprite_createClass(JSContext *cx, JSObject* globalObj) @@ -499,7 +498,7 @@ void JSPROXY_CCPhysicsSprite_createClass(JSContext *cx, JSObject* globalObj) void register_CCPhysicsSprite(JSContext *cx, JSObject *obj) { JS::RootedValue nsval(cx); - JSObject *ns; + JS::RootedObject ns(cx); JS_GetProperty(cx, obj, "cc", &nsval); if (nsval == JSVAL_VOID) { ns = JS_NewObject(cx, NULL, NULL, NULL); @@ -514,7 +513,7 @@ void register_CCPhysicsSprite(JSContext *cx, JSObject *obj) { void register_CCPhysicsDebugNode(JSContext *cx, JSObject *obj) { JS::RootedValue nsval(cx); - JSObject *ns; + JS::RootedObject ns(cx); JS_GetProperty(cx, obj, "cc", &nsval); if (nsval == JSVAL_VOID) { ns = JS_NewObject(cx, NULL, NULL, NULL); @@ -527,10 +526,10 @@ void register_CCPhysicsDebugNode(JSContext *cx, JSObject *obj) { JSB_CCPhysicsDebugNode_createClass(cx, obj, "PhysicsDebugNode"); } -JSBool jsval_to_cpBB( JSContext *cx, jsval vp, cpBB *ret ) +bool jsval_to_cpBB( JSContext *cx, jsval vp, cpBB *ret ) { - JSObject *jsobj; - JSBool ok = JS_ValueToObject( cx, vp, &jsobj ); + JS::RootedObject jsobj(cx); + bool ok = JS_ValueToObject( cx, JS::RootedValue(cx, vp), &jsobj ); JSB_PRECONDITION( ok, "Error converting value to object"); JSB_PRECONDITION( jsobj, "Not a valid JS object"); @@ -538,7 +537,7 @@ JSBool jsval_to_cpBB( JSContext *cx, jsval vp, cpBB *ret ) JS::RootedValue valb(cx); JS::RootedValue valr(cx); JS::RootedValue valt(cx); - ok = JS_TRUE; + ok = true; ok &= JS_GetProperty(cx, jsobj, "l", &vall); ok &= JS_GetProperty(cx, jsobj, "b", &valb); ok &= JS_GetProperty(cx, jsobj, "r", &valr); @@ -546,10 +545,10 @@ JSBool jsval_to_cpBB( JSContext *cx, jsval vp, cpBB *ret ) JSB_PRECONDITION( ok, "Error obtaining point properties"); double l, b, r, t; - ok &= JS_ValueToNumber(cx, vall, &l); - ok &= JS_ValueToNumber(cx, valb, &b); - ok &= JS_ValueToNumber(cx, valr, &r); - ok &= JS_ValueToNumber(cx, valt, &t); + ok &= JS::ToNumber(cx, vall, &l); + ok &= JS::ToNumber(cx, valb, &b); + ok &= JS::ToNumber(cx, valr, &r); + ok &= JS::ToNumber(cx, valt, &t); JSB_PRECONDITION( ok, "Error converting value to numbers"); ret->l = l; @@ -557,7 +556,7 @@ JSBool jsval_to_cpBB( JSContext *cx, jsval vp, cpBB *ret ) ret->r = r; ret->t = t; - return JS_TRUE; + return true; } jsval cpBB_to_jsval(JSContext *cx, cpBB bb ) @@ -579,11 +578,11 @@ jsval cpBB_to_jsval(JSContext *cx, cpBB bb ) // this function expect to receive an array of numbers, and not an array of vects // OK: [1,2, 3,4, 5,6] <- expected // BAD: [{x:1, y:2}, {x:3,y:4}, {x:5, y:6}] <- not expected -JSBool jsval_to_array_of_cpvect( JSContext *cx, jsval vp, cpVect**verts, int *numVerts) +bool jsval_to_array_of_cpvect( JSContext *cx, jsval vp, cpVect**verts, int *numVerts) { // Parsing sequence - JSObject *jsobj; - JSBool ok = JS_ValueToObject( cx, vp, &jsobj ); + JS::RootedObject jsobj(cx); + bool ok = JS_ValueToObject( cx, JS::RootedValue(cx, vp), &jsobj ); JSB_PRECONDITION( ok, "Error converting value to object"); JSB_PRECONDITION( jsobj && JS_IsArrayObject( cx, jsobj), "Object must be an array"); @@ -596,11 +595,11 @@ JSBool jsval_to_array_of_cpvect( JSContext *cx, jsval vp, cpVect**verts, int *nu cpVect *array = (cpVect*)malloc( sizeof(cpVect) * len/2); for( uint32_t i=0; i< len;i++ ) { - jsval valarg; + JS::RootedValue valarg(cx); JS_GetElement(cx, jsobj, i, &valarg); double value; - ok = JS_ValueToNumber(cx, valarg, &value); + ok = JS::ToNumber(cx, valarg, &value); JSB_PRECONDITION( ok, "Error converting value to nsobject"); if(i%2==0) @@ -612,7 +611,7 @@ JSBool jsval_to_array_of_cpvect( JSContext *cx, jsval vp, cpVect**verts, int *nu *numVerts = len/2; *verts = array; - return JS_TRUE; + return true; } #pragma mark - Collision Handler @@ -667,11 +666,11 @@ static cpBool myCollisionBegin(cpArbiter *arb, cpSpace *space, void *data) JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval rval; - JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->begin), 2, args, &rval); + bool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->begin), 2, args, &rval); JSB_PRECONDITION2(ok, handler->cx, cpFalse, "Error calling collision callback: begin"); if( JSVAL_IS_BOOLEAN(rval) ) { - JSBool ret = JSVAL_TO_BOOLEAN(rval); + bool ret = JSVAL_TO_BOOLEAN(rval); return (cpBool)ret; } return cpTrue; @@ -693,11 +692,11 @@ static cpBool myCollisionPre(cpArbiter *arb, cpSpace *space, void *data) JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval rval; - JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->pre), 2, args, &rval); - JSB_PRECONDITION2(ok, handler->cx, JS_FALSE, "Error calling collision callback: pre"); + bool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->pre), 2, args, &rval); + JSB_PRECONDITION2(ok, handler->cx, false, "Error calling collision callback: pre"); if( JSVAL_IS_BOOLEAN(rval) ) { - JSBool ret = JSVAL_TO_BOOLEAN(rval); + bool ret = JSVAL_TO_BOOLEAN(rval); return (cpBool)ret; } return cpTrue; @@ -720,7 +719,7 @@ static void myCollisionPost(cpArbiter *arb, cpSpace *space, void *data) JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval ignore; - JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->post), 2, args, &ignore); + bool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->post), 2, args, &ignore); JSB_PRECONDITION2(ok, handler->cx, , "Error calling collision callback: Post"); } @@ -740,7 +739,7 @@ static void myCollisionSeparate(cpArbiter *arb, cpSpace *space, void *data) JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET jsval ignore; - JSBool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->separate), 2, args, &ignore); + bool ok = JS_CallFunctionValue( handler->cx, handler->jsthis, OBJECT_TO_JSVAL(handler->separate), 2, args, &ignore); JSB_PRECONDITION2(ok, handler->cx, , "Error calling collision callback: Separate");} #pragma mark - cpSpace @@ -794,13 +793,13 @@ void JSB_cpSpace_finalize(JSFreeOp *fop, JSObject *jsthis) #pragma mark addCollisionHandler static -JSBool __jsb_cpSpace_addCollisionHandler(JSContext *cx, jsval *vp, jsval *argvp, cpSpace *space, unsigned int is_oo) +bool __jsb_cpSpace_addCollisionHandler(JSContext *cx, jsval *vp, jsval *argvp, cpSpace *space, unsigned int is_oo) { struct collision_handler *handler = (struct collision_handler*) malloc( sizeof(*handler) ); JSB_PRECONDITION(handler, "Error allocating memory"); - JSBool ok = JS_TRUE; + bool ok = true; // args ok &= jsval_to_int(cx, *argvp++, (int32_t*) &handler->typeA ); @@ -864,28 +863,28 @@ JSBool __jsb_cpSpace_addCollisionHandler(JSContext *cx, jsval *vp, jsval *argvp, JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } -JSBool JSB_cpSpaceAddCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpSpaceAddCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==7, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==7, cx, false, "Invalid number of arguments"); jsval *argvp = JS_ARGV(cx,vp); // args cpSpace *space; - JSBool ok = jsval_to_opaque( cx, *argvp++, (void**)&space); + bool ok = jsval_to_opaque( cx, *argvp++, (void**)&space); JSB_PRECONDITION(ok, "Error parsing arguments"); return __jsb_cpSpace_addCollisionHandler(cx, vp, argvp, space, 0); } // method -JSBool JSB_cpSpace_addCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpSpace_addCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==6, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==6, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); JSB_PRECONDITION( jsthis, "Invalid jsthis object"); @@ -898,9 +897,9 @@ JSBool JSB_cpSpace_addCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) #pragma mark removeCollisionHandler static -JSBool __jsb_cpSpace_removeCollisionHandler(JSContext *cx, jsval *vp, jsval *argvp, cpSpace *space) +bool __jsb_cpSpace_removeCollisionHandler(JSContext *cx, jsval *vp, jsval *argvp, cpSpace *space) { - JSBool ok = JS_TRUE; + bool ok = true; cpCollisionType typeA; cpCollisionType typeB; @@ -932,18 +931,18 @@ JSBool __jsb_cpSpace_removeCollisionHandler(JSContext *cx, jsval *vp, jsval *arg } JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Free function -JSBool JSB_cpSpaceRemoveCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpSpaceRemoveCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==3, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==3, cx, false, "Invalid number of arguments"); jsval *argvp = JS_ARGV(cx,vp); cpSpace* space; - JSBool ok = jsval_to_opaque( cx, *argvp++, (void**)&space); + bool ok = jsval_to_opaque( cx, *argvp++, (void**)&space); JSB_PRECONDITION(ok, "Error parsing arguments"); @@ -951,9 +950,9 @@ JSBool JSB_cpSpaceRemoveCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp } // method -JSBool JSB_cpSpace_removeCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpSpace_removeCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==2, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==2, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); JSB_PRECONDITION( jsthis, "Invalid jsthis object"); @@ -968,14 +967,14 @@ JSBool JSB_cpSpace_removeCollisionHandler(JSContext *cx, uint32_t argc, jsval *v // Arguments: cpBody* // Ret value: cpBody* -JSBool JSB_cpSpace_addBody(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); +bool JSB_cpSpace_addBody(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); cpSpace* arg0 = (cpSpace*) proxy->handle; jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpBody* arg1; jsval retval = *argvp; struct jsb_c_proxy_s *retproxy; @@ -990,19 +989,19 @@ JSBool JSB_cpSpace_addBody(JSContext *cx, uint32_t argc, jsval *vp) { // addBody returns the same object that was added, so return it without conversions JS_SET_RVAL(cx, vp, retval); - return JS_TRUE; + return true; } // Arguments: cpConstraint* // Ret value: cpConstraint* -JSBool JSB_cpSpace_addConstraint(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); +bool JSB_cpSpace_addConstraint(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); cpSpace* arg0 = (cpSpace*) proxy->handle; jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpConstraint* arg1; jsval retval = *argvp; struct jsb_c_proxy_s *retproxy; @@ -1017,19 +1016,19 @@ JSBool JSB_cpSpace_addConstraint(JSContext *cx, uint32_t argc, jsval *vp) { // addConstraint returns the same object that was added, so return it without conversions JS_SET_RVAL(cx, vp, retval); - return JS_TRUE; + return true; } // Arguments: cpShape* // Ret value: cpShape* -JSBool JSB_cpSpace_addShape(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); +bool JSB_cpSpace_addShape(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); cpSpace* arg0 = (cpSpace*) proxy->handle; jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpShape* arg1; jsval retval = *argvp; struct jsb_c_proxy_s *retproxy; @@ -1044,19 +1043,19 @@ JSBool JSB_cpSpace_addShape(JSContext *cx, uint32_t argc, jsval *vp) { // addShape returns the same object that was added, so return it without conversions JS_SET_RVAL(cx, vp, retval); - return JS_TRUE; + return true; } // Arguments: cpShape* // Ret value: cpShape* -JSBool JSB_cpSpace_addStaticShape(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); +bool JSB_cpSpace_addStaticShape(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); cpSpace* arg0 = (cpSpace*) proxy->handle; jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpShape* arg1; jsval retval = *argvp; struct jsb_c_proxy_s *retproxy; @@ -1071,21 +1070,21 @@ JSBool JSB_cpSpace_addStaticShape(JSContext *cx, uint32_t argc, jsval *vp) { // addStaticShape returns the same object that was added, so return it without conversions JS_SET_RVAL(cx, vp, retval); - return JS_TRUE; + return true; } #pragma mark Remove functios. Untoot JSObjects // Arguments: cpBody* // Ret value: void -JSBool JSB_cpSpace_removeBody(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); +bool JSB_cpSpace_removeBody(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); cpSpace* arg0 = (cpSpace*) proxy->handle; jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpBody* arg1; struct jsb_c_proxy_s *retproxy; @@ -1096,19 +1095,19 @@ JSBool JSB_cpSpace_removeBody(JSContext *cx, uint32_t argc, jsval *vp) { JS_RemoveObjectRoot(cx, &retproxy->jsobj); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: cpConstraint* // Ret value: void -JSBool JSB_cpSpace_removeConstraint(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); +bool JSB_cpSpace_removeConstraint(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); cpSpace* arg0 = (cpSpace*) proxy->handle; jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpConstraint* arg1; struct jsb_c_proxy_s *retproxy; @@ -1119,19 +1118,19 @@ JSBool JSB_cpSpace_removeConstraint(JSContext *cx, uint32_t argc, jsval *vp) { JS_RemoveObjectRoot(cx, &retproxy->jsobj); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: cpShape* // Ret value: void -JSBool JSB_cpSpace_removeShape(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); +bool JSB_cpSpace_removeShape(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); cpSpace* arg0 = (cpSpace*) proxy->handle; jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpShape* arg1; struct jsb_c_proxy_s *retproxy; @@ -1142,19 +1141,19 @@ JSBool JSB_cpSpace_removeShape(JSContext *cx, uint32_t argc, jsval *vp) { JS_RemoveObjectRoot(cx, &retproxy->jsobj); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: cpShape* // Ret value: void -JSBool JSB_cpSpace_removeStaticShape(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); +bool JSB_cpSpace_removeStaticShape(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsthis); cpSpace* arg0 = (cpSpace*) proxy->handle; jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpShape* arg1; struct jsb_c_proxy_s *retproxy; @@ -1165,19 +1164,20 @@ JSBool JSB_cpSpace_removeStaticShape(JSContext *cx, uint32_t argc, jsval *vp) { JS_RemoveObjectRoot(cx, &retproxy->jsobj); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } #pragma mark - Arbiter #pragma mark getBodies static -JSBool __jsb_cpArbiter_getBodies(JSContext *cx, jsval *vp, jsval *argvp, cpArbiter *arbiter, unsigned int is_oo) +bool __jsb_cpArbiter_getBodies(JSContext *cx, jsval *vp, jsval *argvp, cpArbiter *arbiter, unsigned int is_oo) { cpBody *bodyA; cpBody *bodyB; cpArbiterGetBodies(arbiter, &bodyA, &bodyB); - jsval valA, valB; + JS::RootedValue valA(cx); + JS::RootedValue valB(cx); if( is_oo ) { valA = c_class_to_jsval(cx, bodyA, JSB_cpBody_object, JSB_cpBody_class, "cpArbiter"); valB = c_class_to_jsval(cx, bodyB, JSB_cpBody_object, JSB_cpBody_class, "cpArbiter"); @@ -1186,33 +1186,33 @@ JSBool __jsb_cpArbiter_getBodies(JSContext *cx, jsval *vp, jsval *argvp, cpArbit valB = opaque_to_jsval(cx, bodyB); } - JSObject *jsobj = JS_NewArrayObject(cx, 2, NULL); + JS::RootedObject jsobj(cx, JS_NewArrayObject(cx, 2, NULL)); JS_SetElement(cx, jsobj, 0, &valA); JS_SetElement(cx, jsobj, 1, &valB); JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); - return JS_TRUE; + return true; } // Free function -JSBool JSB_cpArbiterGetBodies(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpArbiterGetBodies(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); jsval *argvp = JS_ARGV(cx,vp); cpArbiter* arbiter; if( ! jsval_to_opaque( cx, *argvp++, (void**)&arbiter ) ) - return JS_FALSE; + return false; return __jsb_cpArbiter_getBodies(cx, vp, argvp, arbiter, 0); } // Method -JSBool JSB_cpArbiter_getBodies(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpArbiter_getBodies(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==0, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==0, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); JSB_PRECONDITION( jsthis, "Invalid jsthis object"); @@ -1226,13 +1226,14 @@ JSBool JSB_cpArbiter_getBodies(JSContext *cx, uint32_t argc, jsval *vp) #pragma mark getShapes static -JSBool __jsb_cpArbiter_getShapes(JSContext *cx, jsval *vp, jsval *argvp, cpArbiter *arbiter, unsigned int is_oo) +bool __jsb_cpArbiter_getShapes(JSContext *cx, jsval *vp, jsval *argvp, cpArbiter *arbiter, unsigned int is_oo) { cpShape *shapeA; cpShape *shapeB; cpArbiterGetShapes(arbiter, &shapeA, &shapeB); - jsval valA, valB; + JS::RootedValue valA(cx); + JS::RootedValue valB(cx); if( is_oo ) { valA = c_class_to_jsval(cx, shapeA, JSB_cpShape_object, JSB_cpShape_class, "cpShape"); valB = c_class_to_jsval(cx, shapeB, JSB_cpShape_object, JSB_cpShape_class, "cpShape"); @@ -1241,33 +1242,33 @@ JSBool __jsb_cpArbiter_getShapes(JSContext *cx, jsval *vp, jsval *argvp, cpArbit valB = opaque_to_jsval(cx, shapeB); } - JSObject *jsobj = JS_NewArrayObject(cx, 2, NULL); + JS::RootedObject jsobj(cx, JS_NewArrayObject(cx, 2, NULL)); JS_SetElement(cx, jsobj, 0, &valA); JS_SetElement(cx, jsobj, 1, &valB); JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); - return JS_TRUE; + return true; } // function -JSBool JSB_cpArbiterGetShapes(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpArbiterGetShapes(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); jsval *argvp = JS_ARGV(cx,vp); cpArbiter* arbiter; if( ! jsval_to_opaque( cx, *argvp++, (void**) &arbiter ) ) - return JS_FALSE; + return false; return __jsb_cpArbiter_getShapes(cx, vp, argvp, arbiter, 0); } // method -JSBool JSB_cpArbiter_getShapes(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpArbiter_getShapes(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==0, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==0, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); JSB_PRECONDITION( jsthis, "Invalid jsthis object"); @@ -1282,16 +1283,16 @@ JSBool JSB_cpArbiter_getShapes(JSContext *cx, uint32_t argc, jsval *vp) #pragma mark constructor // Manually added to identify static vs dynamic bodies -JSBool JSB_cpBody_constructor(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpBody_constructor(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==2, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==2, cx, false, "Invalid number of arguments"); JSObject *jsobj = JS_NewObject(cx, JSB_cpBody_class, JSB_cpBody_object, NULL); - jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + JS::CallArgs argvp = JS::CallArgsFromVp(argc, vp); + bool ok = true; double m; double i; - ok &= JS_ValueToNumber( cx, *argvp++, &m ); - ok &= JS_ValueToNumber( cx, *argvp++, &i ); + ok &= JS::ToNumber( cx, argvp[0], &m ); + ok &= JS::ToNumber( cx, argvp[1], &i ); JSB_PRECONDITION(ok, "Error processing arguments"); cpBody *ret_body = NULL; @@ -1310,37 +1311,37 @@ JSBool JSB_cpBody_constructor(JSContext *cx, uint32_t argc, jsval *vp) jsb_set_jsobject_for_proxy(jsobj, ret_body); JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); - return JS_TRUE; + return true; } #pragma mark getUserData static -JSBool __jsb_cpBody_getUserData(JSContext *cx, jsval *vp, jsval *argvp, cpBody *body) +bool __jsb_cpBody_getUserData(JSContext *cx, jsval *vp, jsval *argvp, cpBody *body) { JSObject *data = (JSObject*) cpBodyGetUserData(body); JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(data)); - return JS_TRUE; + return true; } // free function -JSBool JSB_cpBodyGetUserData(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpBodyGetUserData(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); jsval *argvp = JS_ARGV(cx,vp); cpBody *body; if( ! jsval_to_opaque( cx, *argvp++, (void**) &body ) ) - return JS_FALSE; + return false; return __jsb_cpBody_getUserData(cx, vp, argvp, body); } // method -JSBool JSB_cpBody_getUserData(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpBody_getUserData(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==0, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==0, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); JSB_PRECONDITION( jsthis, "Invalid jsthis object"); @@ -1354,36 +1355,36 @@ JSBool JSB_cpBody_getUserData(JSContext *cx, uint32_t argc, jsval *vp) #pragma mark setUserData static -JSBool __jsb_cpBody_setUserData(JSContext *cx, jsval *vp, jsval *argvp, cpBody *body) +bool __jsb_cpBody_setUserData(JSContext *cx, jsval *vp, jsval *argvp, cpBody *body) { - JSObject *jsobj; + JS::RootedObject jsobj(cx); - JSBool ok = JS_ValueToObject(cx, *argvp++, &jsobj); + bool ok = JS_ValueToObject(cx, JS::RootedValue(cx, *argvp), &jsobj); JSB_PRECONDITION(ok, "Error parsing arguments"); cpBodySetUserData(body, jsobj); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // free function -JSBool JSB_cpBodySetUserData(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpBodySetUserData(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==2, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==2, cx, false, "Invalid number of arguments"); jsval *argvp = JS_ARGV(cx,vp); cpBody *body; - JSBool ok = jsval_to_opaque( cx, *argvp++, (void**) &body ); + bool ok = jsval_to_opaque( cx, *argvp++, (void**) &body ); JSB_PRECONDITION(ok, "Error parsing arguments"); return __jsb_cpBody_setUserData(cx, vp, argvp, body); } // method -JSBool JSB_cpBody_setUserData(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpBody_setUserData(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); JSB_PRECONDITION( jsthis, "Invalid jsthis object"); @@ -1396,74 +1397,74 @@ JSBool JSB_cpBody_setUserData(JSContext *cx, uint32_t argc, jsval *vp) #pragma mark - Poly related // cpFloat cpAreaForPoly(const int numVerts, const cpVect *verts); -JSBool JSB_cpAreaForPoly(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpAreaForPoly(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpVect *verts; int numVerts; ok &= jsval_to_array_of_cpvect( cx, *argvp++, &verts, &numVerts); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error parsing array"); + JSB_PRECONDITION2(ok, cx, false, "Error parsing array"); cpFloat area = cpAreaForPoly(numVerts, verts); free(verts); JS_SET_RVAL(cx, vp, DOUBLE_TO_JSVAL(area)); - return JS_TRUE; + return true; } // cpFloat cpMomentForPoly(cpFloat m, int numVerts, const cpVect *verts, cpVect offset); -JSBool JSB_cpMomentForPoly(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpMomentForPoly(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==3, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==3, cx, false, "Invalid number of arguments"); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpVect *verts; cpVect offset; int numVerts; double m; - ok &= JS_ValueToNumber(cx, *argvp++, &m); + ok &= JS::ToNumber(cx, JS::RootedValue(cx, *argvp++), &m); ok &= jsval_to_array_of_cpvect( cx, *argvp++, &verts, &numVerts); ok &= jsval_to_cpVect( cx, *argvp++, (cpVect*) &offset ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error parsing args"); + JSB_PRECONDITION2(ok, cx, false, "Error parsing args"); cpFloat moment = cpMomentForPoly((cpFloat)m, numVerts, verts, offset); free(verts); JS_SET_RVAL(cx, vp, DOUBLE_TO_JSVAL(moment)); - return JS_TRUE; + return true; } // cpVect cpCentroidForPoly(const int numVerts, const cpVect *verts); -JSBool JSB_cpCentroidForPoly(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpCentroidForPoly(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpVect *verts; int numVerts; ok &= jsval_to_array_of_cpvect( cx, *argvp++, &verts, &numVerts); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error parsing args"); + JSB_PRECONDITION2(ok, cx, false, "Error parsing args"); cpVect centroid = cpCentroidForPoly(numVerts, verts); free(verts); JS_SET_RVAL(cx, vp, cpVect_to_jsval(cx, (cpVect)centroid)); - return JS_TRUE; + return true; } // void cpRecenterPoly(const int numVerts, cpVect *verts); -JSBool JSB_cpRecenterPoly(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpRecenterPoly(JSContext *cx, uint32_t argc, jsval *vp) { CCASSERT(false, "NOT IMPLEMENTED"); - return JS_FALSE; + return false; } #pragma mark - Object Oriented Chipmunk @@ -1475,14 +1476,14 @@ JSBool JSB_cpRecenterPoly(JSContext *cx, uint32_t argc, jsval *vp) JSClass* JSB_cpBase_class = NULL; JSObject* JSB_cpBase_object = NULL; // Constructor -JSBool JSB_cpBase_constructor(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpBase_constructor(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc==1, cx, JS_FALSE, "Invalid arguments. Expecting 1"); + JSB_PRECONDITION2( argc==1, cx, false, "Invalid arguments. Expecting 1"); JSObject *jsobj = JS_NewObject(cx, JSB_cpBase_class, JSB_cpBase_object, NULL); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; void *handle = NULL; @@ -1494,7 +1495,7 @@ JSBool JSB_cpBase_constructor(JSContext *cx, uint32_t argc, jsval *vp) jsb_set_jsobject_for_proxy(jsobj, handle); JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); - return JS_TRUE; + return true; } // Destructor @@ -1505,37 +1506,37 @@ void JSB_cpBase_finalize(JSFreeOp *fop, JSObject *obj) // should not delete the handle since it was manually added } -JSBool JSB_cpBase_getHandle(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpBase_getHandle(JSContext *cx, uint32_t argc, jsval *vp) { JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); JSB_PRECONDITION( jsthis, "Invalid jsthis object"); - JSB_PRECONDITION2(argc==0, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==0, cx, false, "Invalid number of arguments"); struct jsb_c_proxy_s* proxy = jsb_get_c_proxy_for_jsobject(jsthis); void *handle = proxy->handle; jsval ret_val = opaque_to_jsval(cx, handle); JS_SET_RVAL(cx, vp, ret_val); - return JS_TRUE; + return true; } -JSBool JSB_cpBase_setHandle(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpBase_setHandle(JSContext *cx, uint32_t argc, jsval *vp) { JSObject* jsthis = (JSObject *)JS_THIS_OBJECT(cx, vp); JSB_PRECONDITION( jsthis, "Invalid jsthis object"); - JSB_PRECONDITION2(argc==1, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==1, cx, false, "Invalid number of arguments"); jsval *argvp = JS_ARGV(cx,vp); void *handle; - JSBool ok = jsval_to_opaque(cx, *argvp++, &handle); + bool ok = jsval_to_opaque(cx, *argvp++, &handle); JSB_PRECONDITION( ok, "Invalid parsing arguments"); jsb_set_c_proxy_for_jsobject(jsthis, handle, JSB_C_FLAG_DO_NOT_CALL_FREE); jsb_set_jsobject_for_proxy(jsthis, handle); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } @@ -1566,18 +1567,18 @@ void JSB_cpBase_createClass(JSContext *cx, JSObject* globalObj, const char* name }; JSB_cpBase_object = JS_InitClass(cx, globalObj, NULL, JSB_cpBase_class, JSB_cpBase_constructor,0,properties,funcs,NULL,st_funcs); - JSBool found; - JS_SetPropertyAttributes(cx, globalObj, name, JSPROP_ENUMERATE | JSPROP_READONLY, &found); +// bool found; +// JS_SetPropertyAttributes(cx, globalObj, name, JSPROP_ENUMERATE | JSPROP_READONLY, &found); } // Manual "methods" // Constructor -JSBool JSB_cpPolyShape_constructor(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_cpPolyShape_constructor(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2(argc==3, cx, JS_FALSE, "Invalid number of arguments"); + JSB_PRECONDITION2(argc==3, cx, false, "Invalid number of arguments"); JSObject *jsobj = JS_NewObject(cx, JSB_cpPolyShape_class, JSB_cpPolyShape_object, NULL); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; cpBody* body; cpVect *verts; cpVect offset; int numVerts; @@ -1594,7 +1595,7 @@ JSBool JSB_cpPolyShape_constructor(JSContext *cx, uint32_t argc, jsval *vp) free(verts); - return JS_TRUE; + return true; } diff --git a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h index 6807bd63e1..1247c9c6f3 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h +++ b/cocos/scripting/javascript/bindings/chipmunk/js_bindings_chipmunk_manual.h @@ -26,60 +26,59 @@ #ifndef __js_bindings_chipmunk_manual #define __js_bindings_chipmunk_manual +#include "jsapi.h" #include "js_bindings_config.h" #include "js_manual_conversions.h" #include "ScriptingCore.h" #ifdef JSB_INCLUDE_CHIPMUNK #include "chipmunk.h" -#include "jsapi.h" - #include "js_bindings_chipmunk_auto_classes.h" // Free Functions -JSBool JSB_cpSpaceAddCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpaceRemoveCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceAddCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpaceRemoveCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetBodies(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiterGetShapes(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterGetBodies(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiterGetShapes(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodyGetUserData(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBodySetUserData(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodyGetUserData(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBodySetUserData(JSContext *cx, uint32_t argc, jsval *vp); // poly related -JSBool JSB_cpAreaForPoly(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpMomentForPoly(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpCentroidForPoly(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpRecenterPoly(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpAreaForPoly(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpMomentForPoly(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpCentroidForPoly(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpRecenterPoly(JSContext *cx, uint32_t argc, jsval *vp); // "Methods" from the OO API -JSBool JSB_cpSpace_addCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_removeCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpace_addCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpace_removeCollisionHandler(JSContext *cx, uint32_t argc, jsval *vp); // manually wrapped for rooting/unrooting purposes -JSBool JSB_cpSpace_addBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_addConstraint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_addShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_addStaticShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_removeBody(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_removeConstraint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_removeShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpSpace_removeStaticShape(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpace_addBody(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpace_addConstraint(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpace_addShape(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpace_addStaticShape(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpace_removeBody(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpace_removeConstraint(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpace_removeShape(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpSpace_removeStaticShape(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiter_getBodies(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpArbiter_getShapes(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiter_getBodies(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpArbiter_getShapes(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBody_constructor(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBody_getUserData(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_cpBody_setUserData(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBody_constructor(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBody_getUserData(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpBody_setUserData(JSContext *cx, uint32_t argc, jsval *vp); // convertions jsval cpBB_to_jsval(JSContext *cx, cpBB bb ); -JSBool jsval_to_cpBB( JSContext *cx, jsval vp, cpBB *ret ); -JSBool jsval_to_array_of_cpvect( JSContext *cx, jsval vp, cpVect**verts, int *numVerts); +bool jsval_to_cpBB( JSContext *cx, jsval vp, cpBB *ret ); +bool jsval_to_array_of_cpvect( JSContext *cx, jsval vp, cpVect**verts, int *numVerts); // requires cocos2d #define cpVect_to_jsval CGPoint_to_jsval @@ -94,7 +93,7 @@ extern void register_CCPhysicsSprite(JSContext *cx, JSObject *obj); extern void register_CCPhysicsDebugNode(JSContext *cx, JSObject *obj); // Manual constructor / destructors -JSBool JSB_cpPolyShape_constructor(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_cpPolyShape_constructor(JSContext *cx, uint32_t argc, jsval *vp); void JSB_cpSpace_finalize(JSFreeOp *fop, JSObject *obj); #endif // JSB_INCLUDE_CHIPMUNK diff --git a/cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj b/cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj index 9148f9376f..4d53ec5d40 100644 --- a/cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj +++ b/cocos/scripting/javascript/bindings/chipmunk/libJSBindingForChipmunk.vcxproj @@ -76,7 +76,7 @@ Level3 Disabled - WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_WINDOWS;_DEBUG;_LIB;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) true diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index a33c70d7bd..deb41d8d8b 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -16af4ad046f4db00af7a229d89c406054d8616c3 \ No newline at end of file +4a8fbf7e1224b4274fa6789b670ebc9a6da97ded \ No newline at end of file diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp index e43b3804dd..c4dabf4b36 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.hpp @@ -1,8 +1,8 @@ #ifndef __JS_COCOS2D_X_SPECIFICS_H__ #define __JS_COCOS2D_X_SPECIFICS_H__ -#include "jsapi.h" #include "ScriptingCore.h" +#include "platform/CCSAXParser.h" class JSScheduleWrapper; @@ -200,5 +200,44 @@ private: }; +class CC_DLL __JSSAXDelegator: public cocos2d::SAXDelegator +{ +public: + static __JSSAXDelegator* getInstance() { + static __JSSAXDelegator* pInstance = NULL; + if (pInstance == NULL) { + pInstance = new __JSSAXDelegator(); + } + return pInstance; + }; + + ~__JSSAXDelegator(); + + cocos2d::SAXParser* getParser(); + + std::string parse(const std::string& path); + + bool preloadPlist(const std::string& path) { + return true; + } + + std::string getList(const std::string& path) { + return path; + } + + // implement pure virtual methods of SAXDelegator + void startElement(void *ctx, const char *name, const char **atts); + void endElement(void *ctx, const char *name); + void textHandler(void *ctx, const char *ch, int len); + +private: + cocos2d::SAXParser _parser; + JSObject* _obj; + std::string _result; + bool _isStoringCharacters; + std::string _currentValue; +}; + + #endif diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.cpp b/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.cpp index 30586d41fb..c55ab28df6 100644 --- a/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.cpp +++ b/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.cpp @@ -73,7 +73,7 @@ jsval CCBScriptCallbackProxy::getJSOwner() { return owner; } -JSBool js_cocos2dx_CCBAnimationManager_animationCompleteCallback(JSContext *cx, uint32_t argc, jsval *vp) +bool js_cocos2dx_CCBAnimationManager_animationCompleteCallback(JSContext *cx, uint32_t argc, jsval *vp) { if (argc >= 1) { jsval *argv = JS_ARGV(cx, vp); @@ -94,15 +94,15 @@ JSBool js_cocos2dx_CCBAnimationManager_animationCompleteCallback(JSContext *cx, JS_SetReservedSlot(proxy->obj, 0, argv[0]); JS_SetReservedSlot(proxy->obj, 1, argv[1]); - return JS_TRUE; + return true; } - return JS_FALSE; + return false; } -JSBool js_cocos2dx_CCBReader_readNodeGraphFromFile(JSContext *cx, uint32_t argc, jsval *vp) +bool js_cocos2dx_CCBReader_readNodeGraphFromFile(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); - JSBool ok = JS_TRUE; + bool ok = true; JSObject *obj; cocosbuilder::CCBReader* cobj; obj = JS_THIS_OBJECT(cx, vp); @@ -122,7 +122,7 @@ JSBool js_cocos2dx_CCBReader_readNodeGraphFromFile(JSContext *cx, uint32_t argc, TEST_NATIVE_OBJECT(cx, arg1) } while (0); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); cocos2d::Node* ret = cobj->readNodeGraphFromFile(arg0, arg1); jsval jsret; do { @@ -134,12 +134,12 @@ JSBool js_cocos2dx_CCBReader_readNodeGraphFromFile(JSContext *cx, uint32_t argc, } } while (0); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } if (argc == 1) { const char* arg0; std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); cocos2d::Node* ret = cobj->readNodeGraphFromFile(arg0); jsval jsret; do { @@ -151,7 +151,7 @@ JSBool js_cocos2dx_CCBReader_readNodeGraphFromFile(JSContext *cx, uint32_t argc, } } while (0); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } if (argc == 3) { const char* arg0; @@ -167,7 +167,7 @@ JSBool js_cocos2dx_CCBReader_readNodeGraphFromFile(JSContext *cx, uint32_t argc, cocos2d::Size arg2; ok &= jsval_to_ccsize(cx, argv[2], &arg2); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); cocos2d::Node* ret = cobj->readNodeGraphFromFile(arg0, arg1, arg2); jsval jsret; do { @@ -179,15 +179,15 @@ JSBool js_cocos2dx_CCBReader_readNodeGraphFromFile(JSContext *cx, uint32_t argc, } } while (0); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } - return JS_FALSE; + return false; } -JSBool js_cocos2dx_CCBReader_createSceneWithNodeGraphFromFile(JSContext *cx, uint32_t argc, jsval *vp) +bool js_cocos2dx_CCBReader_createSceneWithNodeGraphFromFile(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); - JSBool ok = JS_TRUE; + bool ok = true; JSObject *obj; cocosbuilder::CCBReader* cobj; obj = JS_THIS_OBJECT(cx, vp); @@ -207,7 +207,7 @@ JSBool js_cocos2dx_CCBReader_createSceneWithNodeGraphFromFile(JSContext *cx, uin TEST_NATIVE_OBJECT(cx, arg1) } while (0); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); cocos2d::Scene* ret = cobj->createSceneWithNodeGraphFromFile(arg0, arg1); jsval jsret; do { @@ -219,12 +219,12 @@ JSBool js_cocos2dx_CCBReader_createSceneWithNodeGraphFromFile(JSContext *cx, uin } } while (0); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } if (argc == 1) { const char* arg0; std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str(); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); cocos2d::Scene* ret = cobj->createSceneWithNodeGraphFromFile(arg0); jsval jsret; do { @@ -236,7 +236,7 @@ JSBool js_cocos2dx_CCBReader_createSceneWithNodeGraphFromFile(JSContext *cx, uin } } while (0); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } if (argc == 3) { const char* arg0; @@ -252,7 +252,7 @@ JSBool js_cocos2dx_CCBReader_createSceneWithNodeGraphFromFile(JSContext *cx, uin cocos2d::Size arg2; ok &= jsval_to_ccsize(cx, argv[2], &arg2); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); cocos2d::Scene* ret = cobj->createSceneWithNodeGraphFromFile(arg0, arg1, arg2); jsval jsret; do { @@ -264,14 +264,14 @@ JSBool js_cocos2dx_CCBReader_createSceneWithNodeGraphFromFile(JSContext *cx, uin } } while (0); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } - return JS_FALSE; + return false; } -JSBool js_CocosBuilder_create(JSContext *cx, uint32_t argc, jsval *vp) +bool js_CocosBuilder_create(JSContext *cx, uint32_t argc, jsval *vp) { NodeLoaderLibrary * ccNodeLoaderLibrary = NodeLoaderLibrary::getInstance(); @@ -295,7 +295,7 @@ JSBool js_CocosBuilder_create(JSContext *cx, uint32_t argc, jsval *vp) jsret = JSVAL_NULL; } JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } @@ -304,7 +304,7 @@ extern JSObject* jsb_cocosbuilder_CCBAnimationManager_prototype; void register_CCBuilderReader(JSContext *cx, JSObject *obj) { JS::RootedValue nsval(cx); - JSObject *ns; + JS::RootedObject ns(cx); JS_GetProperty(cx, obj, "cc", &nsval); if (nsval == JSVAL_VOID) { ns = JS_NewObject(cx, NULL, NULL, NULL); diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.h b/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.h index b1b3b187cc..a1e122bad7 100644 --- a/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.h +++ b/cocos/scripting/javascript/bindings/cocosbuilder/js_bindings_ccbreader.h @@ -8,7 +8,6 @@ #ifndef __JS_BINDINGS_CCBREADER_H__ #define __JS_BINDINGS_CCBREADER_H__ -#include "jsapi.h" #include "cocosbuilder_specifics.hpp" #include "cocosbuilder/CocosBuilder.h" @@ -54,7 +53,7 @@ protected: }; void register_CCBuilderReader(JSContext *cx, JSObject *global); -JSBool js_CocosBuilder_Run(JSContext *cx, uint32_t argc, jsval *vp); +bool js_CocosBuilder_Run(JSContext *cx, uint32_t argc, jsval *vp); #endif /* __JS_BINDINGS_CCBREADER_H__ */ diff --git a/cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj b/cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj index d6f2eb8d12..9a886cfaf6 100644 --- a/cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj +++ b/cocos/scripting/javascript/bindings/cocosbuilder/libJSBindingForBuilder.vcxproj @@ -74,7 +74,7 @@ Level3 Disabled - WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_WINDOWS;_DEBUG;_LIB;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\editor-support\cocosbuilder;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) true diff --git a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp index b50022aba9..630b36e11f 100644 --- a/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp +++ b/cocos/scripting/javascript/bindings/cocostudio/jsb_cocos2dx_studio_manual.cpp @@ -127,12 +127,12 @@ void JSArmatureWrapper::frameCallbackFunc(cocostudio::Bone *bone, const std::str } } -static JSBool js_cocos2dx_ArmatureAnimation_setMovementEventCallFunc(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_ArmatureAnimation_setMovementEventCallFunc(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 2) { jsval *argv = JS_ARGV(cx, vp); @@ -146,18 +146,18 @@ static JSBool js_cocos2dx_ArmatureAnimation_setMovementEventCallFunc(JSContext * cobj->setMovementEventCallFunc(CC_CALLBACK_0(JSArmatureWrapper::movementCallbackFunc, tmpObj, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); - return JS_TRUE; + return true; } JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; + return false; } -static JSBool js_cocos2dx_ArmatureAnimation_setFrameEventCallFunc(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_ArmatureAnimation_setFrameEventCallFunc(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); cocostudio::ArmatureAnimation* cobj = (cocostudio::ArmatureAnimation *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 2) { jsval *argv = JS_ARGV(cx, vp); @@ -171,18 +171,18 @@ static JSBool js_cocos2dx_ArmatureAnimation_setFrameEventCallFunc(JSContext *cx, cobj->setFrameEventCallFunc(CC_CALLBACK_0(JSArmatureWrapper::frameCallbackFunc, tmpObj, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)); - return JS_TRUE; + return true; } JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; + return false; } -static JSBool jsb_Animation_addArmatureFileInfoAsyncCallFunc(JSContext *cx, uint32_t argc, jsval *vp) +static bool jsb_Animation_addArmatureFileInfoAsyncCallFunc(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); cocostudio::ArmatureDataManager* cobj = (cocostudio::ArmatureDataManager *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 3) { jsval *argv = JS_ARGV(cx, vp); @@ -198,7 +198,7 @@ static JSBool jsb_Animation_addArmatureFileInfoAsyncCallFunc(JSContext *cx, uint cobj->addArmatureFileInfoAsync(ret.c_str(), tmpObj, schedule_selector(JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc)); - return JS_TRUE; + return true; } if(argc == 5){ @@ -221,32 +221,31 @@ static JSBool jsb_Animation_addArmatureFileInfoAsyncCallFunc(JSContext *cx, uint cobj->addArmatureFileInfoAsync(imagePath.c_str(), plistPath.c_str(), configFilePath.c_str(), tmpObj, schedule_selector(JSArmatureWrapper::addArmatureFileInfoAsyncCallbackFunc)); - return JS_TRUE; + return true; } JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; + return false; } -JSBool js_cocos2dx_studio_ColliderBody_getCalculatedVertexList(JSContext *cx, uint32_t argc, jsval *vp) +bool js_cocos2dx_studio_ColliderBody_getCalculatedVertexList(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); cocostudio::ColliderBody* cobj = (cocostudio::ColliderBody *)(proxy ? proxy->ptr : nullptr); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 0) { const std::vector& ret = cobj->getCalculatedVertexList(); - JSObject *jsretArr = JS_NewArrayObject(cx, 0, nullptr); + JS::RootedObject jsretArr(cx, JS_NewArrayObject(cx, 0, nullptr)); jsval jsret; //CCObject* obj; int i = 0; - for(std::vector::const_iterator it = ret.begin(); it != ret.end(); it++) + for(const auto& point : ret) { - const cocos2d::Point& point = *it; JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); if (!tmp) break; - JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(point.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + bool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(point.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(point.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); - jsval jsTmp = OBJECT_TO_JSVAL(tmp); + JS::RootedValue jsTmp(cx, OBJECT_TO_JSVAL(tmp)); if(!ok || !JS_SetElement(cx, jsretArr, i, &jsTmp)) { break; @@ -255,11 +254,11 @@ JSBool js_cocos2dx_studio_ColliderBody_getCalculatedVertexList(JSContext *cx, ui } jsret = OBJECT_TO_JSVAL(jsretArr); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); - return JS_FALSE; + return false; } extern JSObject* jsb_cocostudio_ArmatureAnimation_prototype; diff --git a/cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj b/cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj index 2212730521..93b9800237 100644 --- a/cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj +++ b/cocos/scripting/javascript/bindings/cocostudio/libJSBindingForStudio.vcxproj @@ -73,7 +73,7 @@ Level3 Disabled - WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_WINDOWS;_DEBUG;_LIB;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\editor-support\cocostudio;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) true diff --git a/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp b/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp index e98e062ad6..9868db1c70 100644 --- a/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp +++ b/cocos/scripting/javascript/bindings/extension/jsb_cocos2dx_extension_manual.cpp @@ -69,13 +69,13 @@ private: bool _needUnroot; }; -static JSBool js_cocos2dx_CCScrollView_setDelegate(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_CCScrollView_setDelegate(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); cocos2d::extension::ScrollView* cobj = (cocos2d::extension::ScrollView *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 1) { @@ -90,10 +90,10 @@ static JSBool js_cocos2dx_CCScrollView_setDelegate(JSContext *cx, uint32_t argc, nativeDelegate->release(); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); - return JS_FALSE; + return false; } @@ -193,13 +193,13 @@ private: bool _needUnroot; }; -static JSBool js_cocos2dx_CCTableView_setDelegate(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_CCTableView_setDelegate(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); cocos2d::extension::TableView* cobj = (cocos2d::extension::TableView *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 1) { @@ -223,10 +223,10 @@ static JSBool js_cocos2dx_CCTableView_setDelegate(JSContext *cx, uint32_t argc, nativeDelegate->release(); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); - return JS_FALSE; + return false; } class JSB_TableViewDataSource @@ -261,7 +261,7 @@ public: JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); Size size; - JSBool isSucceed = jsval_to_ccsize(cx, ret, &size); + bool isSucceed = jsval_to_ccsize(cx, ret, &size); if (isSucceed) return size; } return Size::ZERO; @@ -296,7 +296,7 @@ public: { JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); ssize_t count = 0; - JSBool isSucceed = jsval_to_ssize(cx, ret, &count); + bool isSucceed = jsval_to_ssize(cx, ret, &count); if (isSucceed) return count; } return 0; @@ -325,7 +325,7 @@ private: JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JSBool hasAction; + bool hasAction; JS::RootedValue temp_retval(cx); jsval dataVal = OBJECT_TO_JSVAL(p->obj); @@ -356,7 +356,7 @@ private: if (!p) return false; JSContext* cx = ScriptingCore::getInstance()->getGlobalContext(); - JSBool hasAction; + bool hasAction; JS::RootedValue temp_retval(cx); jsval dataVal[2]; dataVal[0] = OBJECT_TO_JSVAL(p->obj); @@ -377,9 +377,9 @@ private: return false; } - JSBool ret = JS_CallFunctionName(cx, obj, jsFunctionName.c_str(), + bool ret = JS_CallFunctionName(cx, obj, jsFunctionName.c_str(), 2, dataVal, &retVal); - return ret == JS_TRUE ? true : false; + return ret == true ? true : false; } return false; } @@ -389,13 +389,13 @@ private: bool _needUnroot; }; -static JSBool js_cocos2dx_CCTableView_setDataSource(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_CCTableView_setDataSource(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); cocos2d::extension::TableView* cobj = (cocos2d::extension::TableView *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 1) { JSB_TableViewDataSource* pNativeSource = new JSB_TableViewDataSource(); @@ -416,17 +416,17 @@ static JSBool js_cocos2dx_CCTableView_setDataSource(JSContext *cx, uint32_t argc pNativeSource->release(); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } JS_ReportError(cx, "wrong number of arguments"); - return JS_FALSE; + return false; } -static JSBool js_cocos2dx_CCTableView_create(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_CCTableView_create(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); - JSBool ok = JS_TRUE; + bool ok = true; if (argc == 3 || argc == 2) { @@ -467,9 +467,9 @@ static JSBool js_cocos2dx_CCTableView_create(JSContext *cx, uint32_t argc, jsval JSObject *tmpObj = JSVAL_TO_OBJECT(argv[2]); proxy = jsb_get_js_proxy(tmpObj); arg2 = (cocos2d::Node*)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( arg2, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( arg2, cx, false, "Invalid Native Object"); } while (0); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); ret->initWithViewSize(arg1, arg2); } ret->reloadData(); @@ -482,11 +482,11 @@ static JSBool js_cocos2dx_CCTableView_create(JSContext *cx, uint32_t argc, jsval pNativeSource->release(); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } JS_ReportError(cx, "wrong number of arguments"); - return JS_FALSE; + return false; } class JSB_EditBoxDelegate @@ -566,13 +566,13 @@ private: bool _needUnroot; }; -static JSBool js_cocos2dx_CCEditBox_setDelegate(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_CCEditBox_setDelegate(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); cocos2d::extension::EditBox* cobj = (cocos2d::extension::EditBox *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 1) { @@ -587,10 +587,10 @@ static JSBool js_cocos2dx_CCEditBox_setDelegate(JSContext *cx, uint32_t argc, js nativeDelegate->release(); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 1); - return JS_FALSE; + return false; } @@ -682,22 +682,22 @@ private: std::multimap JSB_ControlButtonTarget::_jsNativeTargetMap; -static JSBool js_cocos2dx_CCControl_addTargetWithActionForControlEvents(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_CCControl_addTargetWithActionForControlEvents(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); cocos2d::extension::Control* cobj = (cocos2d::extension::Control *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); - JSBool ok = JS_TRUE; + bool ok = true; if (argc == 3) { JSObject* jsDelegate = JSVAL_TO_OBJECT(argv[0]); JSObject* jsFunc = JSVAL_TO_OBJECT(argv[1]); Control::EventType arg2; ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing control event"); + JSB_PRECONDITION2(ok, cx, false, "Error processing control event"); // Check whether the target already exists. auto range = JSB_ControlButtonTarget::_jsNativeTargetMap.equal_range(jsDelegate); @@ -707,7 +707,7 @@ static JSBool js_cocos2dx_CCControl_addTargetWithActionForControlEvents(JSContex { // Return true directly. JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } } @@ -736,26 +736,26 @@ static JSBool js_cocos2dx_CCControl_addTargetWithActionForControlEvents(JSContex JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 3); - return JS_FALSE; + return false; } -static JSBool js_cocos2dx_CCControl_removeTargetWithActionForControlEvents(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_CCControl_removeTargetWithActionForControlEvents(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); cocos2d::extension::Control* cobj = (cocos2d::extension::Control *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); - JSBool ok = JS_TRUE; + bool ok = true; if (argc == 3) { Control::EventType arg2; ok &= jsval_to_int32(cx, argv[2], (int32_t *)&arg2); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing control event"); + JSB_PRECONDITION2(ok, cx, false, "Error processing control event"); obj = JSVAL_TO_OBJECT(argv[0]); JSObject* jsFunc = JSVAL_TO_OBJECT(argv[1]); @@ -775,10 +775,10 @@ static JSBool js_cocos2dx_CCControl_removeTargetWithActionForControlEvents(JSCon cobj->removeTargetWithActionForControlEvents(nativeTargetToRemoved, cccontrol_selector(JSB_ControlButtonTarget::onEvent), arg2); - return JS_TRUE; + return true; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 3); - return JS_FALSE; + return false; } extern JSObject* jsb_cocos2d_extension_ScrollView_prototype; diff --git a/cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj b/cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj index b9ea3695d9..68413ba642 100644 --- a/cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj +++ b/cocos/scripting/javascript/bindings/extension/libJSBindingForExtension.vcxproj @@ -73,7 +73,7 @@ Level3 Disabled - WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_WINDOWS;_DEBUG;_LIB;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\network;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) true diff --git a/cocos/scripting/javascript/bindings/gui/jsb_cocos2dx_gui_manual.cpp b/cocos/scripting/javascript/bindings/gui/jsb_cocos2dx_gui_manual.cpp index e0832bc2ba..773306569e 100644 --- a/cocos/scripting/javascript/bindings/gui/jsb_cocos2dx_gui_manual.cpp +++ b/cocos/scripting/javascript/bindings/gui/jsb_cocos2dx_gui_manual.cpp @@ -78,12 +78,12 @@ void JSStudioEventListenerWrapper::eventCallbackFunc(Object* sender,int eventTyp } } -static JSBool js_cocos2dx_UIWidget_addTouchEventListener(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_UIWidget_addTouchEventListener(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); gui::Widget* cobj = (gui::Widget *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 2) { jsval *argv = JS_ARGV(cx, vp); @@ -97,18 +97,18 @@ static JSBool js_cocos2dx_UIWidget_addTouchEventListener(JSContext *cx, uint32_t cobj->addTouchEventListener(tmpObj, toucheventselector(JSStudioEventListenerWrapper::eventCallbackFunc)); - return JS_TRUE; + return true; } JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; + return false; } -static JSBool js_cocos2dx_UICheckBox_addEventListener(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_UICheckBox_addEventListener(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); gui::CheckBox* cobj = (gui::CheckBox *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 2) { jsval *argv = JS_ARGV(cx, vp); @@ -122,18 +122,18 @@ static JSBool js_cocos2dx_UICheckBox_addEventListener(JSContext *cx, uint32_t ar cobj->addEventListenerCheckBox(tmpObj, checkboxselectedeventselector(JSStudioEventListenerWrapper::eventCallbackFunc)); - return JS_TRUE; + return true; } JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; + return false; } -static JSBool js_cocos2dx_UISlider_addEventListener(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_UISlider_addEventListener(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); gui::Slider* cobj = (gui::Slider *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 2) { jsval *argv = JS_ARGV(cx, vp); @@ -147,18 +147,18 @@ static JSBool js_cocos2dx_UISlider_addEventListener(JSContext *cx, uint32_t argc cobj->addEventListenerSlider(tmpObj, sliderpercentchangedselector(JSStudioEventListenerWrapper::eventCallbackFunc)); - return JS_TRUE; + return true; } JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; + return false; } -static JSBool js_cocos2dx_UITextField_addEventListener(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_UITextField_addEventListener(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); gui::TextField* cobj = (gui::TextField *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 2) { jsval *argv = JS_ARGV(cx, vp); @@ -172,18 +172,18 @@ static JSBool js_cocos2dx_UITextField_addEventListener(JSContext *cx, uint32_t a cobj->addEventListenerTextField(tmpObj, textfieldeventselector(JSStudioEventListenerWrapper::eventCallbackFunc)); - return JS_TRUE; + return true; } JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; + return false; } -static JSBool js_cocos2dx_UIPageView_addEventListener(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_UIPageView_addEventListener(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); gui::PageView* cobj = (gui::PageView *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 2) { jsval *argv = JS_ARGV(cx, vp); @@ -197,18 +197,18 @@ static JSBool js_cocos2dx_UIPageView_addEventListener(JSContext *cx, uint32_t ar cobj->addEventListenerPageView(tmpObj, pagevieweventselector(JSStudioEventListenerWrapper::eventCallbackFunc)); - return JS_TRUE; + return true; } JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; + return false; } -static JSBool js_cocos2dx_UIListView_addEventListener(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_UIListView_addEventListener(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); gui::ListView* cobj = (gui::ListView *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 2) { jsval *argv = JS_ARGV(cx, vp); @@ -222,57 +222,58 @@ static JSBool js_cocos2dx_UIListView_addEventListener(JSContext *cx, uint32_t ar cobj->addEventListenerListView(tmpObj, listvieweventselector(JSStudioEventListenerWrapper::eventCallbackFunc)); - return JS_TRUE; + return true; } JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; + return false; } -static JSBool js_cocos2dx_LayoutParameter_setMargin(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_LayoutParameter_setMargin(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); gui::LayoutParameter* cobj = (gui::LayoutParameter *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 1) { - jsval *argv = JS_ARGV(cx, vp); + JS::CallArgs argv = CallArgsFromVp(argc, vp); - JSObject *tmp; + JS::RootedObject tmp(cx); JS::RootedValue jsleft(cx), jstop(cx),jsright(cx),jsbottom(cx); double left, top,right,bottom; - JSBool ok = argv[0].isObject() && + bool ok = argv[0].isObject() && JS_ValueToObject(cx, argv[0], &tmp) && JS_GetProperty(cx, tmp, "left", &jsleft) && JS_GetProperty(cx, tmp, "top", &jstop) && JS_GetProperty(cx, tmp, "right", &jsright) && - JS_GetProperty(cx, tmp, "bottom", &jsbottom) && - JS_ValueToNumber(cx, jsleft, &left) && - JS_ValueToNumber(cx, jstop, &top) && - JS_ValueToNumber(cx, jsright, &right) && - JS_ValueToNumber(cx, jsbottom, &bottom); + JS_GetProperty(cx, tmp, "bottom", &jsbottom); + + left = jsleft.toNumber(); + top = jstop.toNumber(); + right = jsright.toNumber(); + bottom = jsbottom.toNumber(); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, false, "Error processing arguments"); cobj->setMargin(gui::Margin(left,top,right,bottom)); - return JS_TRUE; + return true; } JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; + return false; } -static JSBool js_cocos2dx_LayoutParameter_getMargin(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_LayoutParameter_getMargin(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); gui::LayoutParameter* cobj = (gui::LayoutParameter *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (argc == 0) { JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); - if (!tmp) return JS_FALSE; + if (!tmp) return false; gui::Margin margin = cobj->getMargin(); - JSBool ok = JS_DefineProperty(cx, tmp, "left", DOUBLE_TO_JSVAL(margin.left), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + bool ok = JS_DefineProperty(cx, tmp, "left", DOUBLE_TO_JSVAL(margin.left), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "top", DOUBLE_TO_JSVAL(margin.top), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "right", DOUBLE_TO_JSVAL(margin.right), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "bottom", DOUBLE_TO_JSVAL(margin.bottom), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); @@ -282,12 +283,12 @@ static JSBool js_cocos2dx_LayoutParameter_getMargin(JSContext *cx, uint32_t argc } else { - return JS_FALSE; + return false; } - return JS_TRUE; + return true; } JS_ReportError(cx, "Invalid number of arguments"); - return JS_FALSE; + return false; } extern JSObject* jsb_cocos2d_gui_Widget_prototype; diff --git a/cocos/scripting/javascript/bindings/gui/libJSBindingForGui.vcxproj b/cocos/scripting/javascript/bindings/gui/libJSBindingForGui.vcxproj index cdb7034ee0..6540a76968 100644 --- a/cocos/scripting/javascript/bindings/gui/libJSBindingForGui.vcxproj +++ b/cocos/scripting/javascript/bindings/gui/libJSBindingForGui.vcxproj @@ -73,7 +73,7 @@ Level3 Disabled - WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_WINDOWS;_DEBUG;_LIB;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\editor-support\cocostudio;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) true diff --git a/cocos/scripting/javascript/bindings/js_bindings_config.h b/cocos/scripting/javascript/bindings/js_bindings_config.h index b4a5702029..5e58a3eb9b 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_config.h +++ b/cocos/scripting/javascript/bindings/js_bindings_config.h @@ -50,7 +50,7 @@ if( ! JS_IsExceptionPending( globalContext ) ) { \ JS_ReportError( globalContext, __VA_ARGS__ ); \ } \ - return JS_FALSE; \ + return false; \ } \ } while(0) #define JSB_PRECONDITION2( condition, context, ret_value, ...) do { \ @@ -88,33 +88,6 @@ #endif // JSB_REPRESENT_LONGLONG_AS_STR -/** @def JSB_INCLUDE_NS - Whether or not it should include JS bindings for basic NS* / Cocoa / CocoaTouch objects. - It should be enabled in order to support bindings for any objective-c projects. - Not needed for pure C projects. - Enabled by default. - */ -#ifndef JSB_INCLUDE_NS -#define JSB_INCLUDE_NS 1 -#endif // JSB_INCLUDE_NS - - -/** @def JSB_INCLUDE_COCOS2D - Whether or not it should include JS bindings for cocos2d. - */ -#ifndef JSB_INCLUDE_COCOS2D -#define JSB_INCLUDE_COCOS2D 1 - -#include "cocos2d.h" -#if defined(__CC_PLATFORM_IOS) -#define JSB_INCLUDE_COCOS2D_IOS 1 -#elif defined(__CC_PLATFORM_MAC) -#define JSB_INCLUDE_COCOS2D_MAC 1 -#endif - -#endif // JSB_INCLUDE_COCOS2D - - /** @def JSB_INCLUDE_CHIPMUNK Whether or not it should include JS bindings for Chipmunk */ diff --git a/cocos/scripting/javascript/bindings/js_bindings_core.cpp b/cocos/scripting/javascript/bindings/js_bindings_core.cpp index 19d63c30e3..e4254f0598 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_core.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_core.cpp @@ -24,15 +24,12 @@ #include "js_bindings_config.h" #include "js_bindings_core.h" - // cocos2d + chipmunk registration files #include "chipmunk/js_bindings_chipmunk_registration.h" - +#include "cocos2d.h" //#pragma mark - Hash -using namespace cocos2d; - typedef struct _hashJSObject { JSObject *jsObject; @@ -161,8 +158,8 @@ void jsb_set_c_proxy_for_jsobject( JSObject *jsobj, void *handle, unsigned long //#pragma mark Do Nothing - Callbacks -JSBool JSB_do_nothing(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_do_nothing(JSContext *cx, uint32_t argc, jsval *vp) { JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } diff --git a/cocos/scripting/javascript/bindings/js_bindings_core.h b/cocos/scripting/javascript/bindings/js_bindings_core.h index 33553a9287..25e5b73d53 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_core.h +++ b/cocos/scripting/javascript/bindings/js_bindings_core.h @@ -26,9 +26,6 @@ #include "jsapi.h" #include "jsfriendapi.h" -#include "cocos2d.h" -#include "chipmunk.h" -#include "SimpleAudioEngine.h" #ifdef __cplusplus extern "C" { @@ -71,7 +68,7 @@ extern "C" { // needed for callbacks. It does nothing. - JSBool JSB_do_nothing(JSContext *cx, uint32_t argc, jsval *vp); + bool JSB_do_nothing(JSContext *cx, uint32_t argc, jsval *vp); #ifdef __cplusplus } diff --git a/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp b/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp index 9f92a8602c..38bef1ee1d 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp +++ b/cocos/scripting/javascript/bindings/js_bindings_opengl.cpp @@ -8,10 +8,10 @@ void GLNode::draw() { if( proxy ) { JSObject *jsObj = proxy->obj; if (jsObj) { - JSBool found; + bool found; JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET JS_HasProperty(cx, jsObj, "draw", &found); - if (found == JS_TRUE) { + if (found == true) { JS::RootedValue rval(cx); JS::RootedValue fval(cx); jsval *argv = NULL; unsigned argc=0; @@ -27,7 +27,7 @@ void GLNode::draw() { JSClass *js_cocos2dx_GLNode_class; JSObject *js_cocos2dx_GLNode_prototype; -JSBool js_cocos2dx_GLNode_constructor(JSContext *cx, uint32_t argc, jsval *vp) +bool js_cocos2dx_GLNode_constructor(JSContext *cx, uint32_t argc, jsval *vp) { if (argc == 0) { @@ -53,16 +53,16 @@ JSBool js_cocos2dx_GLNode_constructor(JSContext *cx, uint32_t argc, jsval *vp) JS_AddNamedObjectRoot(cx, &p->obj, "cocos2d::GLNode"); - return JS_TRUE; + return true; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); - return JS_FALSE; + return false; } void js_cocos2dx_GLNode_finalize(JSFreeOp *fop, JSObject *obj) { } -static JSBool js_cocos2dx_GLNode_ctor(JSContext *cx, uint32_t argc, jsval *vp) +static bool js_cocos2dx_GLNode_ctor(JSContext *cx, uint32_t argc, jsval *vp) { JSObject *obj = JS_THIS_OBJECT(cx, vp); GLNode *nobj = new GLNode(); @@ -70,10 +70,10 @@ static JSBool js_cocos2dx_GLNode_ctor(JSContext *cx, uint32_t argc, jsval *vp) nobj->autorelease(); JS_AddNamedObjectRoot(cx, &p->obj, "GLNode"); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } -JSBool js_cocos2dx_GLNode_create(JSContext *cx, uint32_t argc, jsval *vp) +bool js_cocos2dx_GLNode_create(JSContext *cx, uint32_t argc, jsval *vp) { GLNode* ret = new GLNode(); jsval jsret; @@ -86,7 +86,7 @@ JSBool js_cocos2dx_GLNode_create(JSContext *cx, uint32_t argc, jsval *vp) } } while (0); JS_SET_RVAL(cx, vp, jsret); - return JS_TRUE; + return true; } extern JSObject* jsb_cocos2d_Node_prototype; @@ -128,8 +128,8 @@ void js_register_cocos2dx_GLNode(JSContext *cx, JSObject *global) { NULL, // no static properties st_funcs); // make the class enumerable in the registered namespace - JSBool found; - JS_SetPropertyAttributes(cx, global, "GLNode", JSPROP_ENUMERATE | JSPROP_READONLY, &found); +// bool found; +// JS_SetPropertyAttributes(cx, global, "GLNode", JSPROP_ENUMERATE | JSPROP_READONLY, &found); // add the proto and JSClass to the type->js info hash table TypeTest t; diff --git a/cocos/scripting/javascript/bindings/js_bindings_opengl.h b/cocos/scripting/javascript/bindings/js_bindings_opengl.h index 84c2f97c67..1128317765 100644 --- a/cocos/scripting/javascript/bindings/js_bindings_opengl.h +++ b/cocos/scripting/javascript/bindings/js_bindings_opengl.h @@ -1,4 +1,3 @@ -#include "cocos2d.h" #include "ScriptingCore.h" #include "cocos2d_specifics.hpp" diff --git a/cocos/scripting/javascript/bindings/js_manual_conversions.cpp b/cocos/scripting/javascript/bindings/js_manual_conversions.cpp index 5a9bc016ba..bd5e49b910 100644 --- a/cocos/scripting/javascript/bindings/js_manual_conversions.cpp +++ b/cocos/scripting/javascript/bindings/js_manual_conversions.cpp @@ -3,8 +3,6 @@ // Copyright (c) 2012 Zynga Inc. All rights reserved. // -#include "jsapi.h" -#include "jsfriendapi.h" #include "ScriptingCore.h" #include "js_bindings_config.h" #include "js_manual_conversions.h" @@ -83,7 +81,7 @@ JSFunctionWrapper::~JSFunctionWrapper() JS_RemoveObjectRoot(this->_cx, &this->_jsthis); } -JSBool JSFunctionWrapper::invoke(unsigned int argc, jsval *argv, jsval &rval) +bool JSFunctionWrapper::invoke(unsigned int argc, jsval *argv, jsval &rval) { JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET @@ -96,15 +94,15 @@ static Color3B getColorFromJSObject(JSContext *cx, JSObject *colorObject) Color3B out; JS_GetProperty(cx, colorObject, "r", &jsr); double fontR = 0.0; - JS_ValueToNumber(cx, jsr, &fontR); + JS::ToNumber(cx, jsr, &fontR); JS_GetProperty(cx, colorObject, "g", &jsr); double fontG = 0.0; - JS_ValueToNumber(cx, jsr, &fontG); + JS::ToNumber(cx, jsr, &fontG); JS_GetProperty(cx, colorObject, "b", &jsr); double fontB = 0.0; - JS_ValueToNumber(cx, jsr, &fontB); + JS::ToNumber(cx, jsr, &fontB); // the out out.r = (unsigned char)fontR; @@ -120,11 +118,11 @@ static Size getSizeFromJSObject(JSContext *cx, JSObject *sizeObject) Size out; JS_GetProperty(cx, sizeObject, "width", &jsr); double width = 0.0; - JS_ValueToNumber(cx, jsr, &width); + JS::ToNumber(cx, jsr, &width); JS_GetProperty(cx, sizeObject, "height", &jsr); double height = 0.0; - JS_ValueToNumber(cx, jsr, &height); + JS::ToNumber(cx, jsr, &height); // the out @@ -134,16 +132,16 @@ static Size getSizeFromJSObject(JSContext *cx, JSObject *sizeObject) return out; } -JSBool jsval_to_opaque( JSContext *cx, jsval vp, void **r) +bool jsval_to_opaque( JSContext *cx, jsval vp, void **r) { #ifdef __LP64__ // begin - JSObject *tmp_arg; - JSBool ok = JS_ValueToObject( cx, vp, &tmp_arg ); - JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION2( tmp_arg && JS_IsTypedArrayObject( tmp_arg ), cx, JS_FALSE, "Not a TypedArray object"); - JSB_PRECONDITION2( JS_GetTypedArrayByteLength( tmp_arg ) == sizeof(void*), cx, JS_FALSE, "Invalid Typed Array length"); + JS::RootedObject tmp_arg(cx); + bool ok = JS_ValueToObject( cx, JS::RootedValue(cx, vp), &tmp_arg ); + JSB_PRECONDITION2( ok, cx, false, "Error converting value to object"); + JSB_PRECONDITION2( tmp_arg && JS_IsTypedArrayObject( tmp_arg ), cx, false, "Not a TypedArray object"); + JSB_PRECONDITION2( JS_GetTypedArrayByteLength( tmp_arg ) == sizeof(void*), cx, false, "Invalid Typed Array length"); uint32_t* arg_array = (uint32_t*)JS_GetArrayBufferViewData( tmp_arg ); uint64_t ret = arg_array[0]; @@ -154,13 +152,13 @@ JSBool jsval_to_opaque( JSContext *cx, jsval vp, void **r) assert( sizeof(int)==4); int32_t ret; if( ! jsval_to_int32(cx, vp, &ret ) ) - return JS_FALSE; + return false; #endif *r = (void*)ret; - return JS_TRUE; + return true; } -JSBool jsval_to_int( JSContext *cx, jsval vp, int *ret ) +bool jsval_to_int( JSContext *cx, jsval vp, int *ret ) { // Since this is called to cast uint64 to uint32, // it is needed to initialize the value to 0 first @@ -202,20 +200,20 @@ jsval c_class_to_jsval( JSContext *cx, void* handle, JSObject* object, JSClass * return OBJECT_TO_JSVAL(jsobj); } -JSBool jsval_to_c_class( JSContext *cx, jsval vp, void **out_native, struct jsb_c_proxy_s **out_proxy) +bool jsval_to_c_class( JSContext *cx, jsval vp, void **out_native, struct jsb_c_proxy_s **out_proxy) { - JSObject *jsobj; - JSBool ok = JS_ValueToObject(cx, vp, &jsobj); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error converting jsval to object"); + JS::RootedObject jsobj(cx); + bool ok = JS_ValueToObject( cx, JS::RootedValue(cx, vp), &jsobj ); + JSB_PRECONDITION2(ok, cx, false, "Error converting jsval to object"); struct jsb_c_proxy_s *proxy = jsb_get_c_proxy_for_jsobject(jsobj); *out_native = proxy->handle; if( out_proxy ) *out_proxy = proxy; - return JS_TRUE; + return true; } -JSBool jsval_to_uint( JSContext *cx, jsval vp, unsigned int *ret ) +bool jsval_to_uint( JSContext *cx, jsval vp, unsigned int *ret ) { // Since this is called to cast uint64 to uint32, // it is needed to initialize the value to 0 first @@ -274,10 +272,10 @@ jsval longlong_to_jsval( JSContext *cx, long long number ) #endif } -JSBool jsval_to_charptr( JSContext *cx, jsval vp, const char **ret ) +bool jsval_to_charptr( JSContext *cx, jsval vp, const char **ret ) { JSString *jsstr = JS_ValueToString( cx, vp ); - JSB_PRECONDITION2( jsstr, cx, JS_FALSE, "invalid string" ); + JSB_PRECONDITION2( jsstr, cx, false, "invalid string" ); // root it vp = STRING_TO_JSVAL(jsstr); @@ -287,11 +285,11 @@ JSBool jsval_to_charptr( JSContext *cx, jsval vp, const char **ret ) // XXX: It is converted to String and then back to char* to autorelease the created object. String *tmp = String::create(strWrapper.get()); - JSB_PRECONDITION2( tmp, cx, JS_FALSE, "Error creating string from UTF8"); + JSB_PRECONDITION2( tmp, cx, false, "Error creating string from UTF8"); *ret = tmp->getCString(); - return JS_TRUE; + return true; } jsval charptr_to_jsval( JSContext *cx, const char *str) @@ -299,11 +297,11 @@ jsval charptr_to_jsval( JSContext *cx, const char *str) return c_string_to_jsval(cx, str); } -JSBool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, void **data, JSArrayBufferViewType t) +bool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, void **data, JSArrayBufferViewType t) { - JSObject *jsobj; - JSBool ok = JS_ValueToObject( cx, vp, &jsobj ); - JSB_PRECONDITION2( ok && jsobj, cx, JS_FALSE, "Error converting value to object"); + JS::RootedObject jsobj(cx); + bool ok = JS_ValueToObject( cx, JS::RootedValue(cx, vp), &jsobj ); + JSB_PRECONDITION2( ok && jsobj, cx, false, "Error converting value to object"); // WebGL supports TypedArray and sequences for some of its APIs. So when converting a TypedArray, we should // also check for a possible non-Typed Array JS object, like a JS Array. @@ -312,7 +310,7 @@ JSBool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, *count = JS_GetTypedArrayLength(jsobj); JSArrayBufferViewType type = JS_GetArrayBufferViewType(jsobj); - JSB_PRECONDITION2(t==type, cx, JS_FALSE, "TypedArray type different than expected type"); + JSB_PRECONDITION2(t==type, cx, false, "TypedArray type different than expected type"); switch (t) { case js::ArrayBufferView::TYPE_INT8: @@ -335,7 +333,7 @@ JSBool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, break; default: - JSB_PRECONDITION2(false, cx, JS_FALSE, "Unsupported typedarray type"); + JSB_PRECONDITION2(false, cx, false, "Unsupported typedarray type"); break; } } else if( JS_IsArrayObject(cx, jsobj)) { @@ -346,7 +344,7 @@ JSBool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, for( uint32_t i=0; ix = (float)x; ret->y = (float)y; - return JS_TRUE; + return true; } -JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, Acceleration* ret) { - JSObject *tmp; +bool jsval_to_ccacceleration(JSContext* cx,jsval v, Acceleration* ret) { + JS::RootedObject tmp(cx); JS::RootedValue jsx(cx); JS::RootedValue jsy(cx); JS::RootedValue jsz(cx); JS::RootedValue jstimestamp(cx); double x, y, timestamp, z; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && + bool ok = v.isObject() && + JS_ValueToObject(cx, JS::RootedValue(cx, v), &tmp) && JS_GetProperty(cx, tmp, "x", &jsx) && JS_GetProperty(cx, tmp, "y", &jsy) && JS_GetProperty(cx, tmp, "z", &jsz) && JS_GetProperty(cx, tmp, "timestamp", &jstimestamp) && - JS_ValueToNumber(cx, jsx, &x) && - JS_ValueToNumber(cx, jsy, &y) && - JS_ValueToNumber(cx, jsz, &z) && - JS_ValueToNumber(cx, jstimestamp, ×tamp); + JS::ToNumber(cx, jsx, &x) && + JS::ToNumber(cx, jsy, &y) && + JS::ToNumber(cx, jsz, &z) && + JS::ToNumber(cx, jstimestamp, ×tamp); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, false, "Error processing arguments"); ret->x = x; ret->y = y; ret->z = z; ret->timestamp = timestamp; - return JS_TRUE; + return true; } -JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** ret) +bool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** ret) { - JSBool ok = JS_TRUE; + bool ok = true; Array* pArray = Array::create(); for( int i=0; i < argc; i++ ) { double num = 0.0; - // optimization: JS_ValueToNumber is expensive. And can convert an string like "12" to a number + // optimization: JS::ToNumber is expensive. And can convert an string like "12" to a number if ( JSVAL_IS_NUMBER(*vp)) { - ok &= JS_ValueToNumber(cx, *vp, &num ); + ok &= JS::ToNumber(cx, JS::RootedValue(cx, *vp), &num ); if (!ok) { break; } @@ -596,11 +594,11 @@ JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, Array** r vp++; } *ret = pArray; - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, false, "Error processing arguments"); return ok; } -JSBool jsvals_variadic_to_ccvaluevector( JSContext *cx, jsval *vp, int argc, cocos2d::ValueVector* ret) +bool jsvals_variadic_to_ccvaluevector( JSContext *cx, jsval *vp, int argc, cocos2d::ValueVector* ret) { for (int i = 0; i < argc; i++) @@ -615,7 +613,7 @@ JSBool jsvals_variadic_to_ccvaluevector( JSContext *cx, jsval *vp, int argc, coc { // It's a normal js object. ValueMap dictVal; - JSBool ok = jsval_to_ccvaluemap(cx, value, &dictVal); + bool ok = jsval_to_ccvaluemap(cx, value, &dictVal); if (ok) { ret->push_back(Value(dictVal)); @@ -624,7 +622,7 @@ JSBool jsvals_variadic_to_ccvaluevector( JSContext *cx, jsval *vp, int argc, coc else { // It's a js array object. ValueVector arrVal; - JSBool ok = jsval_to_ccvaluevector(cx, value, &arrVal); + bool ok = jsval_to_ccvaluevector(cx, value, &arrVal); if (ok) { ret->push_back(Value(arrVal)); @@ -639,7 +637,7 @@ JSBool jsvals_variadic_to_ccvaluevector( JSContext *cx, jsval *vp, int argc, coc else if (JSVAL_IS_NUMBER(value)) { double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, value, &number); + bool ok = JS::ToNumber(cx, JS::RootedValue(cx, value), &number); if (ok) { ret->push_back(Value(number)); @@ -647,8 +645,8 @@ JSBool jsvals_variadic_to_ccvaluevector( JSContext *cx, jsval *vp, int argc, coc } else if (JSVAL_IS_BOOLEAN(value)) { - JSBool boolVal = JS_FALSE; - JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + bool boolVal = false; + bool ok = JS_ValueToBoolean(cx, value, &boolVal); if (ok) { ret->push_back(Value(boolVal)); @@ -662,138 +660,138 @@ JSBool jsvals_variadic_to_ccvaluevector( JSContext *cx, jsval *vp, int argc, coc vp++; } - return JS_TRUE; + return true; } -JSBool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret) { - JSObject *tmp; +bool jsval_to_ccrect(JSContext *cx, jsval v, Rect* ret) { + JS::RootedObject tmp(cx); JS::RootedValue jsx(cx); JS::RootedValue jsy(cx); JS::RootedValue jswidth(cx); JS::RootedValue jsheight(cx); double x, y, width, height; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && + bool ok = v.isObject() && + JS_ValueToObject(cx, JS::RootedValue(cx, v), &tmp) && JS_GetProperty(cx, tmp, "x", &jsx) && JS_GetProperty(cx, tmp, "y", &jsy) && JS_GetProperty(cx, tmp, "width", &jswidth) && JS_GetProperty(cx, tmp, "height", &jsheight) && - JS_ValueToNumber(cx, jsx, &x) && - JS_ValueToNumber(cx, jsy, &y) && - JS_ValueToNumber(cx, jswidth, &width) && - JS_ValueToNumber(cx, jsheight, &height); + JS::ToNumber(cx, jsx, &x) && + JS::ToNumber(cx, jsy, &y) && + JS::ToNumber(cx, jswidth, &width) && + JS::ToNumber(cx, jsheight, &height); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, false, "Error processing arguments"); ret->origin.x = x; ret->origin.y = y; ret->size.width = width; ret->size.height = height; - return JS_TRUE; + return true; } -JSBool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret) { - JSObject *tmp; +bool jsval_to_ccsize(JSContext *cx, jsval v, Size* ret) { + JS::RootedObject tmp(cx); JS::RootedValue jsw(cx); JS::RootedValue jsh(cx); double w, h; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && + bool ok = v.isObject() && + JS_ValueToObject(cx, JS::RootedValue(cx, v), &tmp) && JS_GetProperty(cx, tmp, "width", &jsw) && JS_GetProperty(cx, tmp, "height", &jsh) && - JS_ValueToNumber(cx, jsw, &w) && - JS_ValueToNumber(cx, jsh, &h); + JS::ToNumber(cx, jsw, &w) && + JS::ToNumber(cx, jsh, &h); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, false, "Error processing arguments"); ret->width = w; ret->height = h; - return JS_TRUE; + return true; } -JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret) { - JSObject *tmp; +bool jsval_to_cccolor4b(JSContext *cx, jsval v, Color4B* ret) { + JS::RootedObject tmp(cx); JS::RootedValue jsr(cx); JS::RootedValue jsg(cx); JS::RootedValue jsb(cx); JS::RootedValue jsa(cx); double r, g, b, a; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && + bool ok = v.isObject() && + JS_ValueToObject(cx, JS::RootedValue(cx, v), &tmp) && JS_GetProperty(cx, tmp, "r", &jsr) && JS_GetProperty(cx, tmp, "g", &jsg) && JS_GetProperty(cx, tmp, "b", &jsb) && JS_GetProperty(cx, tmp, "a", &jsa) && - JS_ValueToNumber(cx, jsr, &r) && - JS_ValueToNumber(cx, jsg, &g) && - JS_ValueToNumber(cx, jsb, &b) && - JS_ValueToNumber(cx, jsa, &a); + JS::ToNumber(cx, jsr, &r) && + JS::ToNumber(cx, jsg, &g) && + JS::ToNumber(cx, jsb, &b) && + JS::ToNumber(cx, jsa, &a); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, false, "Error processing arguments"); ret->r = r; ret->g = g; ret->b = b; ret->a = a; - return JS_TRUE; + return true; } -JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret) { - JSObject *tmp; +bool jsval_to_cccolor4f(JSContext *cx, jsval v, Color4F* ret) { + JS::RootedObject tmp(cx); JS::RootedValue jsr(cx); JS::RootedValue jsg(cx); JS::RootedValue jsb(cx); JS::RootedValue jsa(cx); double r, g, b, a; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && + bool ok = v.isObject() && + JS_ValueToObject(cx, JS::RootedValue(cx, v), &tmp) && JS_GetProperty(cx, tmp, "r", &jsr) && JS_GetProperty(cx, tmp, "g", &jsg) && JS_GetProperty(cx, tmp, "b", &jsb) && JS_GetProperty(cx, tmp, "a", &jsa) && - JS_ValueToNumber(cx, jsr, &r) && - JS_ValueToNumber(cx, jsg, &g) && - JS_ValueToNumber(cx, jsb, &b) && - JS_ValueToNumber(cx, jsa, &a); + JS::ToNumber(cx, jsr, &r) && + JS::ToNumber(cx, jsg, &g) && + JS::ToNumber(cx, jsb, &b) && + JS::ToNumber(cx, jsa, &a); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, false, "Error processing arguments"); ret->r = r; ret->g = g; ret->b = b; ret->a = a; - return JS_TRUE; + return true; } -JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret) { - JSObject *tmp; +bool jsval_to_cccolor3b(JSContext *cx, jsval v, Color3B* ret) { + JS::RootedObject tmp(cx); JS::RootedValue jsr(cx); JS::RootedValue jsg(cx); JS::RootedValue jsb(cx); double r, g, b; - JSBool ok = v.isObject() && - JS_ValueToObject(cx, v, &tmp) && + bool ok = v.isObject() && + JS_ValueToObject(cx, JS::RootedValue(cx, v), &tmp) && JS_GetProperty(cx, tmp, "r", &jsr) && JS_GetProperty(cx, tmp, "g", &jsg) && JS_GetProperty(cx, tmp, "b", &jsb) && - JS_ValueToNumber(cx, jsr, &r) && - JS_ValueToNumber(cx, jsg, &g) && - JS_ValueToNumber(cx, jsb, &b); + JS::ToNumber(cx, jsr, &r) && + JS::ToNumber(cx, jsg, &g) && + JS::ToNumber(cx, jsb, &b); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, false, "Error processing arguments"); ret->r = r; ret->g = g; ret->b = b; - return JS_TRUE; + return true; } -JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int *numPoints) { +bool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int *numPoints) { // Parsing sequence - JSObject *jsobj; - JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); - JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + JS::RootedObject jsobj(cx); + bool ok = v.isObject() && JS_ValueToObject( cx, JS::RootedValue(cx, v), &jsobj ); + JSB_PRECONDITION3( ok, cx, false, "Error converting value to object"); + JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, false, "Object must be an array"); uint32_t len; JS_GetArrayLength(cx, jsobj, &len); @@ -801,32 +799,32 @@ JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, Point **points, int * Point *array = (Point*)malloc( sizeof(Point) * len); for( uint32_t i=0; i< len;i++ ) { - jsval valarg; + JS::RootedValue valarg(cx); JS_GetElement(cx, jsobj, i, &valarg); ok = jsval_to_ccpoint(cx, valarg, &array[i]); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, false, "Error processing arguments"); } *numPoints = len; *points = array; - return JS_TRUE; + return true; } -JSBool jsval_to_ccarray(JSContext* cx, jsval v, __Array** ret) +bool jsval_to_ccarray(JSContext* cx, jsval v, __Array** ret) { - JSObject *jsobj; - JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); - JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + JS::RootedObject jsobj(cx); + bool ok = v.isObject() && JS_ValueToObject( cx, JS::RootedValue(cx, v), &jsobj ); + JSB_PRECONDITION3( ok, cx, false, "Error converting value to object"); + JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, false, "Object must be an array"); uint32_t len = 0; JS_GetArrayLength(cx, jsobj, &len); __Array* arr = __Array::createWithCapacity(len); for (uint32_t i=0; i < len; i++) { - jsval value; + JS::RootedValue value(cx); if (JS_GetElement(cx, jsobj, i, &value)) { if (value.isObject()) { @@ -843,7 +841,7 @@ JSBool jsval_to_ccarray(JSContext* cx, jsval v, __Array** ret) else if (!JS_IsArrayObject(cx, tmp)){ // It's a normal js object. __Dictionary* dictVal = NULL; - JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); + ok = jsval_to_ccdictionary(cx, value, &dictVal); if (ok) { arr->addObject(dictVal); } @@ -851,7 +849,7 @@ JSBool jsval_to_ccarray(JSContext* cx, jsval v, __Array** ret) else { // It's a js array object. __Array* arrVal = NULL; - JSBool ok = jsval_to_ccarray(cx, value, &arrVal); + ok = jsval_to_ccarray(cx, value, &arrVal); if (ok) { arr->addObject(arrVal); } @@ -864,15 +862,15 @@ JSBool jsval_to_ccarray(JSContext* cx, jsval v, __Array** ret) } else if (JSVAL_IS_NUMBER(value)) { double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, value, &number); + ok = JS::ToNumber(cx, value, &number); if (ok) { arr->addObject(Double::create(number)); // CCLOG("iterate array: value = %lf", number); } } else if (JSVAL_IS_BOOLEAN(value)) { - JSBool boolVal = JS_FALSE; - JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + bool boolVal = false; + ok = JS_ValueToBoolean(cx, value, &boolVal); if (ok) { arr->addObject(Bool::create(boolVal)); // CCLOG("iterate object: value = %d", boolVal); @@ -884,10 +882,10 @@ JSBool jsval_to_ccarray(JSContext* cx, jsval v, __Array** ret) } } *ret = arr; - return JS_TRUE; + return true; } -JSBool jsval_to_ccvalue(JSContext* cx, jsval v, cocos2d::Value* ret) +bool jsval_to_ccvalue(JSContext* cx, jsval v, cocos2d::Value* ret) { if (v.isObject()) { @@ -897,7 +895,7 @@ JSBool jsval_to_ccvalue(JSContext* cx, jsval v, cocos2d::Value* ret) { // It's a normal js object. ValueMap dictVal; - JSBool ok = jsval_to_ccvaluemap(cx, v, &dictVal); + bool ok = jsval_to_ccvaluemap(cx, v, &dictVal); if (ok) { *ret = Value(dictVal); @@ -906,7 +904,7 @@ JSBool jsval_to_ccvalue(JSContext* cx, jsval v, cocos2d::Value* ret) else { // It's a js array object. ValueVector arrVal; - JSBool ok = jsval_to_ccvaluevector(cx, v, &arrVal); + bool ok = jsval_to_ccvaluevector(cx, v, &arrVal); if (ok) { *ret = Value(arrVal); @@ -921,15 +919,15 @@ JSBool jsval_to_ccvalue(JSContext* cx, jsval v, cocos2d::Value* ret) else if (JSVAL_IS_NUMBER(v)) { double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, v, &number); + bool ok = JS::ToNumber(cx, JS::RootedValue(cx, v), &number); if (ok) { *ret = Value(number); } } else if (JSVAL_IS_BOOLEAN(v)) { - JSBool boolVal = JS_FALSE; - JSBool ok = JS_ValueToBoolean(cx, v, &boolVal); + bool boolVal = false; + bool ok = JS_ValueToBoolean(cx, v, &boolVal); if (ok) { *ret = Value(boolVal); } @@ -938,20 +936,20 @@ JSBool jsval_to_ccvalue(JSContext* cx, jsval v, cocos2d::Value* ret) CCASSERT(false, "not supported type"); } - return JS_TRUE; + return true; } -JSBool jsval_to_ccvaluemap(JSContext* cx, jsval v, cocos2d::ValueMap* ret) +bool jsval_to_ccvaluemap(JSContext* cx, jsval v, cocos2d::ValueMap* ret) { if (JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) { - return JS_TRUE; + return true; } JSObject* tmp = JSVAL_TO_OBJECT(v); if (!tmp) { CCLOG("%s", "jsval_to_ccvaluemap: the jsval is not an object."); - return JS_FALSE; + return false; } JSObject* it = JS_NewPropertyIterator(cx, tmp); @@ -963,7 +961,7 @@ JSBool jsval_to_ccvaluemap(JSContext* cx, jsval v, cocos2d::ValueMap* ret) jsid idp; jsval key; if (! JS_NextProperty(cx, it, &idp) || ! JS_IdToValue(cx, idp, &key)) { - return JS_FALSE; // error + return false; // error } if (key == JSVAL_VOID) { @@ -986,7 +984,7 @@ JSBool jsval_to_ccvaluemap(JSContext* cx, jsval v, cocos2d::ValueMap* ret) { // It's a normal js object. ValueMap dictVal; - JSBool ok = jsval_to_ccvaluemap(cx, value, &dictVal); + bool ok = jsval_to_ccvaluemap(cx, value, &dictVal); if (ok) { dict[keyWrapper.get()] = Value(dictVal); @@ -995,7 +993,7 @@ JSBool jsval_to_ccvaluemap(JSContext* cx, jsval v, cocos2d::ValueMap* ret) else { // It's a js array object. ValueVector arrVal; - JSBool ok = jsval_to_ccvaluevector(cx, value, &arrVal); + bool ok = jsval_to_ccvaluevector(cx, value, &arrVal); if (ok) { dict[keyWrapper.get()] = Value(arrVal); @@ -1011,7 +1009,7 @@ JSBool jsval_to_ccvaluemap(JSContext* cx, jsval v, cocos2d::ValueMap* ret) else if (JSVAL_IS_NUMBER(value)) { double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, value, &number); + bool ok = JS::ToNumber(cx, value, &number); if (ok) { dict[keyWrapper.get()] = Value(number); // CCLOG("iterate object: key = %s, value = %lf", keyWrapper.get().c_str(), number); @@ -1019,8 +1017,8 @@ JSBool jsval_to_ccvaluemap(JSContext* cx, jsval v, cocos2d::ValueMap* ret) } else if (JSVAL_IS_BOOLEAN(value)) { - JSBool boolVal = JS_FALSE; - JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + bool boolVal = false; + bool ok = JS_ValueToBoolean(cx, value, &boolVal); if (ok) { dict[keyWrapper.get()] = Value(boolVal); // CCLOG("iterate object: key = %s, value = %d", keyWrapper.get().c_str(), boolVal); @@ -1031,20 +1029,20 @@ JSBool jsval_to_ccvaluemap(JSContext* cx, jsval v, cocos2d::ValueMap* ret) } } - return JS_TRUE; + return true; } -JSBool jsval_to_ccvaluemapintkey(JSContext* cx, jsval v, cocos2d::ValueMapIntKey* ret) +bool jsval_to_ccvaluemapintkey(JSContext* cx, jsval v, cocos2d::ValueMapIntKey* ret) { if (JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) { - return JS_TRUE; + return true; } JSObject* tmp = JSVAL_TO_OBJECT(v); if (!tmp) { CCLOG("%s", "jsval_to_ccvaluemap: the jsval is not an object."); - return JS_FALSE; + return false; } JSObject* it = JS_NewPropertyIterator(cx, tmp); @@ -1056,7 +1054,7 @@ JSBool jsval_to_ccvaluemapintkey(JSContext* cx, jsval v, cocos2d::ValueMapIntKey jsid idp; jsval key; if (! JS_NextProperty(cx, it, &idp) || ! JS_IdToValue(cx, idp, &key)) { - return JS_FALSE; // error + return false; // error } if (key == JSVAL_VOID) { @@ -1079,7 +1077,7 @@ JSBool jsval_to_ccvaluemapintkey(JSContext* cx, jsval v, cocos2d::ValueMapIntKey { // It's a normal js object. ValueMap dictVal; - JSBool ok = jsval_to_ccvaluemap(cx, value, &dictVal); + bool ok = jsval_to_ccvaluemap(cx, value, &dictVal); if (ok) { dict[keyVal] = Value(dictVal); @@ -1088,7 +1086,7 @@ JSBool jsval_to_ccvaluemapintkey(JSContext* cx, jsval v, cocos2d::ValueMapIntKey else { // It's a js array object. ValueVector arrVal; - JSBool ok = jsval_to_ccvaluevector(cx, value, &arrVal); + bool ok = jsval_to_ccvaluevector(cx, value, &arrVal); if (ok) { dict[keyVal] = Value(arrVal); @@ -1103,15 +1101,15 @@ JSBool jsval_to_ccvaluemapintkey(JSContext* cx, jsval v, cocos2d::ValueMapIntKey else if (JSVAL_IS_NUMBER(value)) { double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, value, &number); + bool ok = JS::ToNumber(cx, value, &number); if (ok) { dict[keyVal] = Value(number); } } else if (JSVAL_IS_BOOLEAN(value)) { - JSBool boolVal = JS_FALSE; - JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + bool boolVal = false; + bool ok = JS_ValueToBoolean(cx, value, &boolVal); if (ok) { dict[keyVal] = Value(boolVal); } @@ -1121,23 +1119,23 @@ JSBool jsval_to_ccvaluemapintkey(JSContext* cx, jsval v, cocos2d::ValueMapIntKey } } - return JS_TRUE; + return true; } -JSBool jsval_to_ccvaluevector(JSContext* cx, jsval v, cocos2d::ValueVector* ret) +bool jsval_to_ccvaluevector(JSContext* cx, jsval v, cocos2d::ValueVector* ret) { - JSObject *jsobj; - JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); - JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + JS::RootedObject jsArr(cx); + bool ok = v.isObject() && JS_ValueToObject( cx, JS::RootedValue(cx, v), &jsArr ); + JSB_PRECONDITION3( ok, cx, false, "Error converting value to object"); + JSB_PRECONDITION3( jsArr && JS_IsArrayObject( cx, jsArr), cx, false, "Object must be an array"); uint32_t len = 0; - JS_GetArrayLength(cx, jsobj, &len); + JS_GetArrayLength(cx, jsArr, &len); for (uint32_t i=0; i < len; i++) { - jsval value; - if (JS_GetElement(cx, jsobj, i, &value)) + JS::RootedValue value(cx); + if (JS_GetElement(cx, jsArr, i, &value)) { if (value.isObject()) { @@ -1148,7 +1146,7 @@ JSBool jsval_to_ccvaluevector(JSContext* cx, jsval v, cocos2d::ValueVector* ret) { // It's a normal js object. ValueMap dictVal; - JSBool ok = jsval_to_ccvaluemap(cx, value, &dictVal); + ok = jsval_to_ccvaluemap(cx, value, &dictVal); if (ok) { ret->push_back(Value(dictVal)); @@ -1157,7 +1155,7 @@ JSBool jsval_to_ccvaluevector(JSContext* cx, jsval v, cocos2d::ValueVector* ret) else { // It's a js array object. ValueVector arrVal; - JSBool ok = jsval_to_ccvaluevector(cx, value, &arrVal); + ok = jsval_to_ccvaluevector(cx, value, &arrVal); if (ok) { ret->push_back(Value(arrVal)); @@ -1172,7 +1170,7 @@ JSBool jsval_to_ccvaluevector(JSContext* cx, jsval v, cocos2d::ValueVector* ret) else if (JSVAL_IS_NUMBER(value)) { double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, value, &number); + ok = JS::ToNumber(cx, value, &number); if (ok) { ret->push_back(Value(number)); @@ -1180,8 +1178,8 @@ JSBool jsval_to_ccvaluevector(JSContext* cx, jsval v, cocos2d::ValueVector* ret) } else if (JSVAL_IS_BOOLEAN(value)) { - JSBool boolVal = JS_FALSE; - JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + bool boolVal = false; + ok = JS_ValueToBoolean(cx, value, &boolVal); if (ok) { ret->push_back(Value(boolVal)); @@ -1194,31 +1192,31 @@ JSBool jsval_to_ccvaluevector(JSContext* cx, jsval v, cocos2d::ValueVector* ret) } } - return JS_TRUE; + return true; } -JSBool jsval_to_ssize( JSContext *cx, jsval vp, ssize_t* size) +bool jsval_to_ssize( JSContext *cx, jsval vp, ssize_t* size) { - JSBool ret = JS_FALSE; + bool ret = false; int32_t sizeInt32 = 0; ret = jsval_to_int32(cx, vp, &sizeInt32); *size = sizeInt32; return ret; } -JSBool jsval_to_std_vector_string( JSContext *cx, jsval vp, std::vector* ret) +bool jsval_to_std_vector_string( JSContext *cx, jsval vp, std::vector* ret) { - JSObject *jsobj; - JSBool ok = vp.isObject() && JS_ValueToObject( cx, vp, &jsobj ); - JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + JS::RootedObject jsobj(cx); + bool ok = vp.isObject() && JS_ValueToObject( cx, JS::RootedValue(cx, vp), &jsobj ); + JSB_PRECONDITION3( ok, cx, false, "Error converting value to object"); + JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, false, "Object must be an array"); uint32_t len = 0; JS_GetArrayLength(cx, jsobj, &len); for (uint32_t i=0; i < len; i++) { - jsval value; + JS::RootedValue value(cx); if (JS_GetElement(cx, jsobj, i, &value)) { if (JSVAL_IS_STRING(value)) @@ -1229,33 +1227,33 @@ JSBool jsval_to_std_vector_string( JSContext *cx, jsval vp, std::vector* ret) +bool jsval_to_std_vector_int( JSContext *cx, jsval vp, std::vector* ret) { - JSObject *jsobj; - JSBool ok = vp.isObject() && JS_ValueToObject( cx, vp, &jsobj ); - JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + JS::RootedObject jsobj(cx); + bool ok = vp.isObject() && JS_ValueToObject( cx, JS::RootedValue(cx, vp), &jsobj ); + JSB_PRECONDITION3( ok, cx, false, "Error converting value to object"); + JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, false, "Object must be an array"); uint32_t len = 0; JS_GetArrayLength(cx, jsobj, &len); for (uint32_t i=0; i < len; i++) { - jsval value; + JS::RootedValue value(cx); if (JS_GetElement(cx, jsobj, i, &value)) { if (JSVAL_IS_NUMBER(value)) { double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, value, &number); + ok = JS::ToNumber(cx, value, &number); if (ok) { ret->push_back(static_cast(number)); @@ -1264,12 +1262,12 @@ JSBool jsval_to_std_vector_int( JSContext *cx, jsval vp, std::vector* ret) else { JS_ReportError(cx, "not supported type in array"); - return JS_FALSE; + return false; } } } - return JS_TRUE; + return true; } // native --> jsval @@ -1282,7 +1280,7 @@ jsval ccarray_to_jsval(JSContext* cx, __Array *arr) int i = 0; CCARRAY_FOREACH(arr, obj) { - jsval arrElement; + JS::RootedValue arrElement(cx); //First, check whether object is associated with js object. js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); @@ -1311,7 +1309,7 @@ jsval ccarray_to_jsval(JSContext* cx, __Array *arr) } else if ((intVal = dynamic_cast<__Integer*>(obj))) { arrElement = INT_TO_JSVAL(intVal->getValue()); } else if ((boolVal = dynamic_cast<__Bool*>(obj))) { - arrElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); + arrElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? true : false); } else { CCASSERT(false, "the type isn't suppored."); } @@ -1359,7 +1357,7 @@ jsval ccdictionary_to_jsval(JSContext* cx, __Dictionary* dict) } else if ((intVal = dynamic_cast<__Integer*>(obj))) { dictElement = INT_TO_JSVAL(intVal->getValue()); } else if ((boolVal = dynamic_cast<__Bool*>(obj))) { - dictElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? JS_TRUE : JS_FALSE); + dictElement = BOOLEAN_TO_JSVAL(boolVal->getValue() ? true : false); } else { CCASSERT(false, "the type isn't suppored."); } @@ -1373,18 +1371,18 @@ jsval ccdictionary_to_jsval(JSContext* cx, __Dictionary* dict) return OBJECT_TO_JSVAL(jsRet); } -JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, __Dictionary** ret) +bool jsval_to_ccdictionary(JSContext* cx, jsval v, __Dictionary** ret) { if (JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) { *ret = NULL; - return JS_TRUE; + return true; } JSObject* tmp = JSVAL_TO_OBJECT(v); if (!tmp) { CCLOG("%s", "jsval_to_ccdictionary: the jsval is not an object."); - return JS_FALSE; + return false; } JSObject* it = JS_NewPropertyIterator(cx, tmp); @@ -1395,7 +1393,7 @@ JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, __Dictionary** ret) jsid idp; jsval key; if (! JS_NextProperty(cx, it, &idp) || ! JS_IdToValue(cx, idp, &key)) { - return JS_FALSE; // error + return false; // error } if (key == JSVAL_VOID) { @@ -1428,7 +1426,7 @@ JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, __Dictionary** ret) else if (!JS_IsArrayObject(cx, tmp)){ // It's a normal js object. __Dictionary* dictVal = NULL; - JSBool ok = jsval_to_ccdictionary(cx, value, &dictVal); + bool ok = jsval_to_ccdictionary(cx, value, &dictVal); if (ok) { dict->setObject(dictVal, keyWrapper.get()); } @@ -1436,7 +1434,7 @@ JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, __Dictionary** ret) else { // It's a js array object. __Array* arrVal = NULL; - JSBool ok = jsval_to_ccarray(cx, value, &arrVal); + bool ok = jsval_to_ccarray(cx, value, &arrVal); if (ok) { dict->setObject(arrVal, keyWrapper.get()); } @@ -1449,15 +1447,15 @@ JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, __Dictionary** ret) } else if (JSVAL_IS_NUMBER(value)) { double number = 0.0; - JSBool ok = JS_ValueToNumber(cx, value, &number); + bool ok = JS::ToNumber(cx, value, &number); if (ok) { dict->setObject(Double::create(number), keyWrapper.get()); // CCLOG("iterate object: key = %s, value = %lf", keyWrapper.get().c_str(), number); } } else if (JSVAL_IS_BOOLEAN(value)) { - JSBool boolVal = JS_FALSE; - JSBool ok = JS_ValueToBoolean(cx, value, &boolVal); + bool boolVal = false; + bool ok = JS_ValueToBoolean(cx, value, &boolVal); if (ok) { dict->setObject(Bool::create(boolVal), keyWrapper.get()); // CCLOG("iterate object: key = %s, value = %d", keyWrapper.get().c_str(), boolVal); @@ -1469,12 +1467,12 @@ JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, __Dictionary** ret) } *ret = dict; - return JS_TRUE; + return true; } -JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret) +bool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret) { - JSObject *tmp; + JS::RootedObject tmp(cx); JS::RootedValue jsa(cx); JS::RootedValue jsb(cx); JS::RootedValue jsc(cx); @@ -1482,24 +1480,24 @@ JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, AffineTransform* ret) JS::RootedValue jstx(cx); JS::RootedValue jsty(cx); double a, b, c, d, tx, ty; - JSBool ok = JS_ValueToObject(cx, v, &tmp) && + bool ok = JS_ValueToObject(cx, JS::RootedValue(cx, v), &tmp) && JS_GetProperty(cx, tmp, "a", &jsa) && JS_GetProperty(cx, tmp, "b", &jsb) && JS_GetProperty(cx, tmp, "c", &jsc) && JS_GetProperty(cx, tmp, "d", &jsd) && JS_GetProperty(cx, tmp, "tx", &jstx) && JS_GetProperty(cx, tmp, "ty", &jsty) && - JS_ValueToNumber(cx, jsa, &a) && - JS_ValueToNumber(cx, jsb, &b) && - JS_ValueToNumber(cx, jsc, &c) && - JS_ValueToNumber(cx, jsd, &d) && - JS_ValueToNumber(cx, jstx, &tx) && - JS_ValueToNumber(cx, jsty, &ty); + JS::ToNumber(cx, jsa, &a) && + JS::ToNumber(cx, jsb, &b) && + JS::ToNumber(cx, jsc, &c) && + JS::ToNumber(cx, jsd, &d) && + JS::ToNumber(cx, jstx, &tx) && + JS::ToNumber(cx, jsty, &ty); - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, false, "Error processing arguments"); *ret = AffineTransformMake(a, b, c, d, tx, ty); - return JS_TRUE; + return true; } // From native type to jsval @@ -1540,7 +1538,7 @@ jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length /* = -1 */) jsval ret = JSVAL_NULL; int utf16_size = 0; - jschar* strUTF16 = (jschar*)cc_utf8_to_utf16(v, length, &utf16_size); + jschar* strUTF16 = (jschar*)cc_utf8_to_utf16(v, (int)length, &utf16_size); if (strUTF16 && utf16_size > 0) { JSString* str = JS_NewUCStringCopyN(cx, strUTF16, utf16_size); @@ -1555,7 +1553,7 @@ jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length /* = -1 */) jsval ccpoint_to_jsval(JSContext* cx, const Point& v) { JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + bool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); if (ok) { return OBJECT_TO_JSVAL(tmp); @@ -1566,7 +1564,7 @@ jsval ccpoint_to_jsval(JSContext* cx, const Point& v) { jsval ccacceleration_to_jsval(JSContext* cx, const Acceleration& v) { JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + bool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "z", DOUBLE_TO_JSVAL(v.z), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "timestamp", DOUBLE_TO_JSVAL(v.timestamp), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); @@ -1579,7 +1577,7 @@ jsval ccacceleration_to_jsval(JSContext* cx, const Acceleration& v) { jsval ccrect_to_jsval(JSContext* cx, const Rect& v) { JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.origin.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + bool ok = JS_DefineProperty(cx, tmp, "x", DOUBLE_TO_JSVAL(v.origin.x), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "y", DOUBLE_TO_JSVAL(v.origin.y), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.size.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.size.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); @@ -1592,7 +1590,7 @@ jsval ccrect_to_jsval(JSContext* cx, const Rect& v) { jsval ccsize_to_jsval(JSContext* cx, const Size& v) { JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + bool ok = JS_DefineProperty(cx, tmp, "width", DOUBLE_TO_JSVAL(v.width), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "height", DOUBLE_TO_JSVAL(v.height), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); if (ok) { return OBJECT_TO_JSVAL(tmp); @@ -1603,7 +1601,7 @@ jsval ccsize_to_jsval(JSContext* cx, const Size& v) { jsval cccolor4b_to_jsval(JSContext* cx, const Color4B& v) { JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + bool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "a", INT_TO_JSVAL(v.a), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); @@ -1616,7 +1614,7 @@ jsval cccolor4b_to_jsval(JSContext* cx, const Color4B& v) { jsval cccolor4f_to_jsval(JSContext* cx, const Color4F& v) { JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "r", DOUBLE_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + bool ok = JS_DefineProperty(cx, tmp, "r", DOUBLE_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "g", DOUBLE_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(v.b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(v.a), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); @@ -1629,7 +1627,7 @@ jsval cccolor4f_to_jsval(JSContext* cx, const Color4F& v) { jsval cccolor3b_to_jsval(JSContext* cx, const Color3B& v) { JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + bool ok = JS_DefineProperty(cx, tmp, "r", INT_TO_JSVAL(v.r), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "g", INT_TO_JSVAL(v.g), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "b", INT_TO_JSVAL(v.b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); if (ok) { @@ -1642,7 +1640,7 @@ jsval ccaffinetransform_to_jsval(JSContext* cx, const AffineTransform& t) { JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); if (!tmp) return JSVAL_NULL; - JSBool ok = JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(t.a), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && + bool ok = JS_DefineProperty(cx, tmp, "a", DOUBLE_TO_JSVAL(t.a), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "b", DOUBLE_TO_JSVAL(t.b), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "c", DOUBLE_TO_JSVAL(t.c), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && JS_DefineProperty(cx, tmp, "d", DOUBLE_TO_JSVAL(t.d), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) && @@ -1658,7 +1656,7 @@ jsval FontDefinition_to_jsval(JSContext* cx, const FontDefinition& t) { JSObject *tmp = JS_NewObject(cx, NULL, NULL, NULL); if (!tmp) return JSVAL_NULL; - JSBool ok = JS_TRUE; + bool ok = true; ok &= JS_DefineProperty(cx, tmp, "fontName", std_string_to_jsval(cx, t._fontName), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT); @@ -1694,12 +1692,12 @@ jsval FontDefinition_to_jsval(JSContext* cx, const FontDefinition& t) return JSVAL_NULL; } -JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) +bool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) { - JSObject *jsobj; + JS::RootedObject jsobj(cx); - if (!JS_ValueToObject( cx, vp, &jsobj ) ) - return JS_FALSE; + if (!JS_ValueToObject( cx, JS::RootedValue(cx, vp), &jsobj ) ) + return false; JSB_PRECONDITION( jsobj, "Not a valid JS object"); @@ -1733,13 +1731,13 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) } // font size - JSBool hasProperty; + bool hasProperty; JS_HasProperty(cx, jsobj, "fontSize", &hasProperty); if ( hasProperty ) { JS_GetProperty(cx, jsobj, "fontSize", &jsr); double fontSize = 0.0; - JS_ValueToNumber(cx, jsr, &fontSize); + JS::ToNumber(cx, jsr, &fontSize); out->_fontSize = fontSize; } else @@ -1753,7 +1751,7 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) { JS_GetProperty(cx, jsobj, "fontAlignmentH", &jsr); double fontAlign = 0.0; - JS_ValueToNumber(cx, jsr, &fontAlign); + JS::ToNumber(cx, jsr, &fontAlign); out->_alignment = (TextHAlignment)(int)fontAlign; } else @@ -1767,7 +1765,7 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) { JS_GetProperty(cx, jsobj, "fontAlignmentV", &jsr); double fontAlign = 0.0; - JS_ValueToNumber(cx, jsr, &fontAlign); + JS::ToNumber(cx, jsr, &fontAlign); out->_vertAlignment = (TextVAlignment)(int)fontAlign; } else @@ -1781,9 +1779,9 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) { JS_GetProperty(cx, jsobj, "fontFillColor", &jsr); - JSObject *jsobjColor; - if (!JS_ValueToObject( cx, jsr, &jsobjColor ) ) - return JS_FALSE; + JS::RootedObject jsobjColor(cx); + if (!JS_ValueToObject( cx, JS::RootedValue(cx, jsr), &jsobjColor ) ) + return false; out->_fontFillColor = getColorFromJSObject(cx, jsobjColor); } @@ -1794,9 +1792,9 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) { JS_GetProperty(cx, jsobj, "fontDimensions", &jsr); - JSObject *jsobjSize; - if (!JS_ValueToObject( cx, jsr, &jsobjSize ) ) - return JS_FALSE; + JS::RootedObject jsobjSize(cx); + if (!JS_ValueToObject( cx, JS::RootedValue(cx, jsr), &jsobjSize ) ) + return false; out->_dimensions = getSizeFromJSObject(cx, jsobjSize); } @@ -1821,9 +1819,9 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) { JS_GetProperty(cx, jsobj, "shadowOffset", &jsr); - JSObject *jsobjShadowOffset; + JS::RootedObject jsobjShadowOffset(cx); if (!JS_ValueToObject( cx, jsr, &jsobjShadowOffset ) ) - return JS_FALSE; + return false; out->_shadow._shadowOffset = getSizeFromJSObject(cx, jsobjShadowOffset); } @@ -1833,7 +1831,7 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) { JS_GetProperty(cx, jsobj, "shadowBlur", &jsr); double shadowBlur = 0.0; - JS_ValueToNumber(cx, jsr, &shadowBlur); + JS::ToNumber(cx, jsr, &shadowBlur); out->_shadow._shadowBlur = shadowBlur; } @@ -1843,7 +1841,7 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) { JS_GetProperty(cx, jsobj, "shadowOpacity", &jsr); double shadowOpacity = 0.0; - JS_ValueToNumber(cx, jsr, &shadowOpacity); + JS::ToNumber(cx, jsr, &shadowOpacity); out->_shadow._shadowOpacity = shadowOpacity; } } @@ -1868,9 +1866,9 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) { JS_GetProperty(cx, jsobj, "strokeColor", &jsr); - JSObject *jsobjStrokeColor; + JS::RootedObject jsobjStrokeColor(cx); if (!JS_ValueToObject( cx, jsr, &jsobjStrokeColor ) ) - return JS_FALSE; + return false; out->_stroke._strokeColor = getColorFromJSObject(cx, jsobjStrokeColor); } @@ -1880,54 +1878,54 @@ JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, FontDefinition *out ) { JS_GetProperty(cx, jsobj, "strokeSize", &jsr); double strokeSize = 0.0; - JS_ValueToNumber(cx, jsr, &strokeSize); + JS::ToNumber(cx, jsr, &strokeSize); out->_stroke._strokeSize = strokeSize; } } } // we are done here - return JS_TRUE; + return true; } #define JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES -JSBool jsval_to_CCPoint( JSContext *cx, jsval vp, Point *ret ) +bool jsval_to_CCPoint( JSContext *cx, jsval vp, Point *ret ) { #ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - JSObject *jsobj; - if( ! JS_ValueToObject( cx, vp, &jsobj ) ) - return JS_FALSE; + JS::RootedObject jsobj(cx); + if( ! JS_ValueToObject( cx, JS::RootedValue(cx, vp), &jsobj ) ) + return false; JSB_PRECONDITION( jsobj, "Not a valid JS object"); JS::RootedValue valx(cx); JS::RootedValue valy(cx); - JSBool ok = JS_TRUE; + bool ok = true; ok &= JS_GetProperty(cx, jsobj, "x", &valx); ok &= JS_GetProperty(cx, jsobj, "y", &valy); if( ! ok ) - return JS_FALSE; + return false; double x, y; - ok &= JS_ValueToNumber(cx, valx, &x); - ok &= JS_ValueToNumber(cx, valy, &y); + ok &= JS::ToNumber(cx, valx, &x); + ok &= JS::ToNumber(cx, valy, &y); if( ! ok ) - return JS_FALSE; + return false; ret->x = x; ret->y = y; - return JS_TRUE; + return true; #else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES JSObject *tmp_arg; if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) - return JS_FALSE; + return false; JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); @@ -1935,47 +1933,47 @@ JSBool jsval_to_CCPoint( JSContext *cx, jsval vp, Point *ret ) *ret = *(Point*)JS_GetArrayBufferViewData( tmp_arg, cx ); - return JS_TRUE; + return true; #endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES } -JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *ret ) +bool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *ret ) { #ifdef JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES - JSObject *jsobj; - if( ! JS_ValueToObject( cx, vp, &jsobj ) ) - return JS_FALSE; + JS::RootedObject jsobj(cx); + if( ! JS_ValueToObject( cx, JS::RootedValue(cx, vp), &jsobj ) ) + return false; JSB_PRECONDITION( jsobj, "Not a valid JS object"); JS::RootedValue valx(cx); JS::RootedValue valy(cx); - JSBool ok = JS_TRUE; + bool ok = true; ok &= JS_GetProperty(cx, jsobj, "x", &valx); ok &= JS_GetProperty(cx, jsobj, "y", &valy); if( ! ok ) - return JS_FALSE; + return false; double x, y; - ok &= JS_ValueToNumber(cx, valx, &x); - ok &= JS_ValueToNumber(cx, valy, &y); + ok &= JS::ToNumber(cx, valx, &x); + ok &= JS::ToNumber(cx, valy, &y); if( ! ok ) - return JS_FALSE; + return false; ret->x = x; ret->y = y; - return JS_TRUE; + return true; #else // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES JSObject *tmp_arg; if( ! JS_ValueToObject( cx, vp, &tmp_arg ) ) - return JS_FALSE; + return false; JSB_PRECONDITION( tmp_arg && JS_IsTypedArrayObject( tmp_arg, cx ), "Not a TypedArray object"); @@ -1983,7 +1981,7 @@ JSBool jsval_to_CGPoint( JSContext *cx, jsval vp, cpVect *ret ) *ret = *(cpVect*)JS_GetArrayBufferViewData( tmp_arg, cx ); - return JS_TRUE; + return true; #endif // #! JSB_COMPATIBLE_WITH_COCOS2D_HTML5_BASIC_TYPES } @@ -2156,7 +2154,7 @@ jsval ccvaluevector_to_jsval(JSContext* cx, const cocos2d::ValueVector& v) int i = 0; for (const auto& obj : v) { - jsval arrElement; + JS::RootedValue arrElement(cx); switch (obj.getType()) { diff --git a/cocos/scripting/javascript/bindings/js_manual_conversions.h b/cocos/scripting/javascript/bindings/js_manual_conversions.h index 4820c13bea..a00e9c97bc 100644 --- a/cocos/scripting/javascript/bindings/js_manual_conversions.h +++ b/cocos/scripting/javascript/bindings/js_manual_conversions.h @@ -6,10 +6,12 @@ #define __JS_MANUAL_CONVERSIONS_H__ #include "jsapi.h" +#include "jsfriendapi.h" #include "js_bindings_core.h" #include "js_bindings_config.h" #include "cocos2d.h" #include "spidermonkey_specifics.h" +#include "chipmunk.h" // just a simple utility to avoid mem leaking when using JSString class JSStringWrapper @@ -38,7 +40,7 @@ public: JSFunctionWrapper(JSContext* cx, JSObject *jsthis, jsval fval); ~JSFunctionWrapper(); - JSBool invoke(unsigned int argc, jsval *argv, jsval &rval); + bool invoke(unsigned int argc, jsval *argv, jsval &rval); private: JSContext *_cx; JSObject *_jsthis; @@ -47,50 +49,50 @@ private: CC_DISALLOW_COPY_AND_ASSIGN(JSFunctionWrapper); }; -JSBool jsval_to_opaque( JSContext *cx, jsval vp, void **out ); -JSBool jsval_to_int( JSContext *cx, jsval vp, int *out); -JSBool jsval_to_uint( JSContext *cx, jsval vp, unsigned int *out); -JSBool jsval_to_c_class( JSContext *cx, jsval vp, void **out_native, struct jsb_c_proxy_s **out_proxy); +bool jsval_to_opaque( JSContext *cx, jsval vp, void **out ); +bool jsval_to_int( JSContext *cx, jsval vp, int *out); +bool jsval_to_uint( JSContext *cx, jsval vp, unsigned int *out); +bool jsval_to_c_class( JSContext *cx, jsval vp, void **out_native, struct jsb_c_proxy_s **out_proxy); /** converts a jsval (JS string) into a char */ -JSBool jsval_to_charptr( JSContext *cx, jsval vp, const char **out); +bool jsval_to_charptr( JSContext *cx, jsval vp, const char **out); jsval opaque_to_jsval( JSContext *cx, void* opaque); jsval c_class_to_jsval( JSContext *cx, void* handle, JSObject* object, JSClass *klass, const char* class_name); /* Converts a char ptr into a jsval (using JS string) */ jsval charptr_to_jsval( JSContext *cx, const char *str); -JSBool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, void **data, JSArrayBufferViewType t); -JSBool JSB_get_arraybufferview_dataptr( JSContext *cx, jsval vp, GLsizei *count, GLvoid **data ); +bool JSB_jsval_typedarray_to_dataptr( JSContext *cx, jsval vp, GLsizei *count, void **data, JSArrayBufferViewType t); +bool JSB_get_arraybufferview_dataptr( JSContext *cx, jsval vp, GLsizei *count, GLvoid **data ); // some utility functions // to native -JSBool jsval_to_ushort( JSContext *cx, jsval vp, unsigned short *ret ); -JSBool jsval_to_int32( JSContext *cx, jsval vp, int32_t *ret ); -JSBool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *ret ); -JSBool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *ret ); -JSBool jsval_to_long( JSContext *cx, jsval vp, long *out); -JSBool jsval_to_ulong( JSContext *cx, jsval vp, unsigned long *out); -JSBool jsval_to_long_long(JSContext *cx, jsval v, long long* ret); -JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret); -JSBool jsval_to_ccpoint(JSContext *cx, jsval v, cocos2d::Point* ret); -JSBool jsval_to_ccrect(JSContext *cx, jsval v, cocos2d::Rect* ret); -JSBool jsval_to_ccsize(JSContext *cx, jsval v, cocos2d::Size* ret); -JSBool jsval_to_cccolor4b(JSContext *cx, jsval v, cocos2d::Color4B* ret); -JSBool jsval_to_cccolor4f(JSContext *cx, jsval v, cocos2d::Color4F* ret); -JSBool jsval_to_cccolor3b(JSContext *cx, jsval v, cocos2d::Color3B* ret); -JSBool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, cocos2d::Point **points, int *numPoints); -JSBool jsval_to_ccarray(JSContext* cx, jsval v, cocos2d::__Array** ret); -JSBool jsval_to_ccdictionary(JSContext* cx, jsval v, cocos2d::__Dictionary** ret); -JSBool jsval_to_ccacceleration(JSContext* cx,jsval v, cocos2d::Acceleration* ret); -JSBool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, cocos2d::__Array** ret); +bool jsval_to_ushort( JSContext *cx, jsval vp, unsigned short *ret ); +bool jsval_to_int32( JSContext *cx, jsval vp, int32_t *ret ); +bool jsval_to_uint32( JSContext *cx, jsval vp, uint32_t *ret ); +bool jsval_to_uint16( JSContext *cx, jsval vp, uint16_t *ret ); +bool jsval_to_long( JSContext *cx, jsval vp, long *out); +bool jsval_to_ulong( JSContext *cx, jsval vp, unsigned long *out); +bool jsval_to_long_long(JSContext *cx, jsval v, long long* ret); +bool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret); +bool jsval_to_ccpoint(JSContext *cx, jsval v, cocos2d::Point* ret); +bool jsval_to_ccrect(JSContext *cx, jsval v, cocos2d::Rect* ret); +bool jsval_to_ccsize(JSContext *cx, jsval v, cocos2d::Size* ret); +bool jsval_to_cccolor4b(JSContext *cx, jsval v, cocos2d::Color4B* ret); +bool jsval_to_cccolor4f(JSContext *cx, jsval v, cocos2d::Color4F* ret); +bool jsval_to_cccolor3b(JSContext *cx, jsval v, cocos2d::Color3B* ret); +bool jsval_to_ccarray_of_CCPoint(JSContext* cx, jsval v, cocos2d::Point **points, int *numPoints); +bool jsval_to_ccarray(JSContext* cx, jsval v, cocos2d::__Array** ret); +bool jsval_to_ccdictionary(JSContext* cx, jsval v, cocos2d::__Dictionary** ret); +bool jsval_to_ccacceleration(JSContext* cx,jsval v, cocos2d::Acceleration* ret); +bool jsvals_variadic_to_ccarray( JSContext *cx, jsval *vp, int argc, cocos2d::__Array** ret); // forward declaration js_proxy_t* jsb_get_js_proxy(JSObject* jsObj); template -JSBool jsvals_variadic_to_ccvector( JSContext *cx, jsval *vp, int argc, cocos2d::Vector* ret) +bool jsvals_variadic_to_ccvector( JSContext *cx, jsval *vp, int argc, cocos2d::Vector* ret) { - JSBool ok = JS_TRUE; + bool ok = true; for (int i = 0; i < argc; i++) { @@ -106,29 +108,31 @@ JSBool jsvals_variadic_to_ccvector( JSContext *cx, jsval *vp, int argc, cocos2d: vp++; } - JSB_PRECONDITION3(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION3(ok, cx, false, "Error processing arguments"); return ok; } -JSBool jsvals_variadic_to_ccvaluevector( JSContext *cx, jsval *vp, int argc, cocos2d::ValueVector* ret); +bool jsvals_variadic_to_ccvaluevector( JSContext *cx, jsval *vp, int argc, cocos2d::ValueVector* ret); -JSBool jsval_to_ccaffinetransform(JSContext* cx, jsval v, cocos2d::AffineTransform* ret); -JSBool jsval_to_FontDefinition( JSContext *cx, jsval vp, cocos2d::FontDefinition* ret ); +bool jsval_to_ccaffinetransform(JSContext* cx, jsval v, cocos2d::AffineTransform* ret); +bool jsval_to_FontDefinition( JSContext *cx, jsval vp, cocos2d::FontDefinition* ret ); template -JSBool jsval_to_ccvector(JSContext* cx, jsval v, cocos2d::Vector* ret) +bool jsval_to_ccvector(JSContext* cx, jsval v, cocos2d::Vector* ret) { - JSObject *jsobj; - JSBool ok = v.isObject() && JS_ValueToObject( cx, v, &jsobj ); - JSB_PRECONDITION3( ok, cx, JS_FALSE, "Error converting value to object"); - JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, JS_FALSE, "Object must be an array"); + JS::RootedObject jsobj(cx); + JS::RootedValue jsval(cx, v); + + bool ok = jsval.isObject() && JS_ValueToObject( cx, jsval, &jsobj ); + JSB_PRECONDITION3( ok, cx, false, "Error converting value to object"); + JSB_PRECONDITION3( jsobj && JS_IsArrayObject( cx, jsobj), cx, false, "Object must be an array"); uint32_t len = 0; JS_GetArrayLength(cx, jsobj, &len); for (uint32_t i=0; i < len; i++) { - jsval value; + JS::RootedValue value(cx); if (JS_GetElement(cx, jsobj, i, &value)) { CCASSERT(value.isObject(), "the element in Vector isn't a native object."); @@ -144,29 +148,29 @@ JSBool jsval_to_ccvector(JSContext* cx, jsval v, cocos2d::Vector* ret) } } - return JS_TRUE; + return true; } -JSBool jsval_to_ccvalue(JSContext* cx, jsval v, cocos2d::Value* ret); -JSBool jsval_to_ccvaluemap(JSContext* cx, jsval v, cocos2d::ValueMap* ret); -JSBool jsval_to_ccvaluemapintkey(JSContext* cx, jsval v, cocos2d::ValueMapIntKey* ret); -JSBool jsval_to_ccvaluevector(JSContext* cx, jsval v, cocos2d::ValueVector* ret); -JSBool jsval_to_ssize( JSContext *cx, jsval vp, ssize_t* ret); -JSBool jsval_to_std_vector_string( JSContext *cx, jsval vp, std::vector* ret); -JSBool jsval_to_std_vector_int( JSContext *cx, jsval vp, std::vector* ret); +bool jsval_to_ccvalue(JSContext* cx, jsval v, cocos2d::Value* ret); +bool jsval_to_ccvaluemap(JSContext* cx, jsval v, cocos2d::ValueMap* ret); +bool jsval_to_ccvaluemapintkey(JSContext* cx, jsval v, cocos2d::ValueMapIntKey* ret); +bool jsval_to_ccvaluevector(JSContext* cx, jsval v, cocos2d::ValueVector* ret); +bool jsval_to_ssize( JSContext *cx, jsval vp, ssize_t* ret); +bool jsval_to_std_vector_string( JSContext *cx, jsval vp, std::vector* ret); +bool jsval_to_std_vector_int( JSContext *cx, jsval vp, std::vector* ret); template -JSBool jsval_to_ccmap_string_key(JSContext *cx, jsval v, cocos2d::Map* ret) +bool jsval_to_ccmap_string_key(JSContext *cx, jsval v, cocos2d::Map* ret) { if (JSVAL_IS_NULL(v) || JSVAL_IS_VOID(v)) { - return JS_TRUE; + return true; } JSObject* tmp = JSVAL_TO_OBJECT(v); if (!tmp) { CCLOG("%s", "jsval_to_ccvaluemap: the jsval is not an object."); - return JS_FALSE; + return false; } JSObject* it = JS_NewPropertyIterator(cx, tmp); @@ -176,7 +180,7 @@ JSBool jsval_to_ccmap_string_key(JSContext *cx, jsval v, cocos2d::Map& v) int i = 0; for (const auto& obj : v) { - jsval arrElement; + JS::RootedValue arrElement(cx); //First, check whether object is associated with js object. js_proxy_t* jsproxy = js_get_or_create_proxy(cx, obj); diff --git a/cocos/scripting/javascript/bindings/jsb_helper.h b/cocos/scripting/javascript/bindings/jsb_helper.h index 664d7f4f28..26a67d63d0 100644 --- a/cocos/scripting/javascript/bindings/jsb_helper.h +++ b/cocos/scripting/javascript/bindings/jsb_helper.h @@ -1,10 +1,12 @@ #ifndef __XMLHTTPHELPER_H__ #define __XMLHTTPHELPER_H__ +#include "jsapi.h" +#include "jsfriendapi.h" + #include #include #include -#include "jsapi.h" //#pragma mark - Helpful Macros @@ -20,25 +22,25 @@ JSObject* klass::js_proto = NULL; \ JSObject* klass::js_parent = NULL; \ #define JS_BINDED_FUNC(klass, name) \ -JSBool name(JSContext *cx, unsigned argc, jsval *vp) +bool name(JSContext *cx, unsigned argc, jsval *vp) #define JS_BINDED_CONSTRUCTOR(klass) \ -static JSBool _js_constructor(JSContext *cx, unsigned argc, jsval *vp) +static bool _js_constructor(JSContext *cx, unsigned argc, jsval *vp) #define JS_BINDED_CONSTRUCTOR_IMPL(klass) \ -JSBool klass::_js_constructor(JSContext *cx, unsigned argc, jsval *vp) +bool klass::_js_constructor(JSContext *cx, unsigned argc, jsval *vp) #define JS_BINDED_FUNC_IMPL(klass, name) \ -static JSBool klass##_func_##name(JSContext *cx, unsigned argc, jsval *vp) { \ +static bool klass##_func_##name(JSContext *cx, unsigned argc, jsval *vp) { \ JSObject* thisObj = JS_THIS_OBJECT(cx, vp); \ klass* obj = (klass*)JS_GetPrivate(thisObj); \ if (obj) { \ return obj->name(cx, argc, vp); \ } \ JS_ReportError(cx, "Invalid object call for function %s", #name); \ -return JS_FALSE; \ +return false; \ } \ -JSBool klass::name(JSContext *cx, unsigned argc, jsval *vp) +bool klass::name(JSContext *cx, unsigned argc, jsval *vp) #define JS_WRAP_OBJECT_IN_VAL(klass, cobj, out) \ do { \ @@ -53,32 +55,32 @@ out = OBJECT_TO_JSVAL(obj); \ JS_FN(#name, klass##_func_##name, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT) #define JS_BINDED_PROP_GET(klass, propName) \ -JSBool _js_get_##propName(JSContext *cx, JS::HandleId id, JS::MutableHandleValue vp) +bool _js_get_##propName(JSContext *cx, JS::HandleId id, JS::MutableHandleValue vp) #define JS_BINDED_PROP_GET_IMPL(klass, propName) \ -static JSBool _js_get_##klass##_##propName(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp) { \ +static bool _js_get_##klass##_##propName(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp) { \ klass* cobj = (klass*)JS_GetPrivate(obj); \ if (cobj) { \ return cobj->_js_get_##propName(cx, id, vp); \ } \ JS_ReportError(cx, "Invalid getter call for property %s", #propName); \ -return JS_FALSE; \ +return false; \ } \ -JSBool klass::_js_get_##propName(JSContext *cx, JS::HandleId id, JS::MutableHandleValue vp) +bool klass::_js_get_##propName(JSContext *cx, JS::HandleId id, JS::MutableHandleValue vp) #define JS_BINDED_PROP_SET(klass, propName) \ -JSBool _js_set_##propName(JSContext *cx, JS::HandleId id, JSBool strict, JS::MutableHandleValue vp) +bool _js_set_##propName(JSContext *cx, JS::HandleId id, bool strict, JS::MutableHandleValue vp) #define JS_BINDED_PROP_SET_IMPL(klass, propName) \ -static JSBool _js_set_##klass##_##propName(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JSBool strict, JS::MutableHandleValue vp) { \ +static bool _js_set_##klass##_##propName(JSContext *cx, JS::HandleObject obj, JS::HandleId id, bool strict, JS::MutableHandleValue vp) { \ klass* cobj = (klass*)JS_GetPrivate(obj); \ if (cobj) { \ return cobj->_js_set_##propName(cx, id, strict, vp); \ } \ JS_ReportError(cx, "Invalid setter call for property %s", #propName); \ -return JS_FALSE; \ +return false; \ } \ -JSBool klass::_js_set_##propName(JSContext *cx, JS::HandleId id, JSBool strict, JS::MutableHandleValue vp) +bool klass::_js_set_##propName(JSContext *cx, JS::HandleId id, bool strict, JS::MutableHandleValue vp) #define JS_BINDED_PROP_ACCESSOR(klass, propName) \ JS_BINDED_PROP_GET(klass, propName); \ diff --git a/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp b/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp index 878191adfd..4ff1dcde2d 100644 --- a/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp +++ b/cocos/scripting/javascript/bindings/jsb_opengl_functions.cpp @@ -16,374 +16,374 @@ // Arguments: GLenum // Ret value: void -JSBool JSB_glActiveTexture(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glActiveTexture(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glActiveTexture((GLenum)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint, GLuint // Ret value: void -JSBool JSB_glAttachShader(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glAttachShader(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glAttachShader((GLuint)arg0 , (GLuint)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint, GLuint, char* // Ret value: void -JSBool JSB_glBindAttribLocation(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glBindAttribLocation(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; const char* arg2; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); ok &= jsval_to_charptr(cx, *argvp++, &arg2 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glBindAttribLocation((GLuint)arg0 , (GLuint)arg1 , (char*)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLuint // Ret value: void -JSBool JSB_glBindBuffer(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glBindBuffer(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glBindBuffer((GLenum)arg0 , (GLuint)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLuint // Ret value: void -JSBool JSB_glBindFramebuffer(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glBindFramebuffer(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glBindFramebuffer((GLenum)arg0 , (GLuint)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLuint // Ret value: void -JSBool JSB_glBindRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glBindRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glBindRenderbuffer((GLenum)arg0 , (GLuint)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLuint // Ret value: void -JSBool JSB_glBindTexture(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glBindTexture(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glBindTexture((GLenum)arg0 , (GLuint)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLclampf, GLclampf, GLclampf, GLclampf // Ret value: void -JSBool JSB_glBlendColor(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glBlendColor(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); ok &= jsval_to_int32( cx, *argvp++, &arg3 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glBlendColor((GLclampf)arg0 , (GLclampf)arg1 , (GLclampf)arg2 , (GLclampf)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum // Ret value: void -JSBool JSB_glBlendEquation(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glBlendEquation(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glBlendEquation((GLenum)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLenum // Ret value: void -JSBool JSB_glBlendEquationSeparate(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glBlendEquationSeparate(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glBlendEquationSeparate((GLenum)arg0 , (GLenum)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLenum // Ret value: void -JSBool JSB_glBlendFunc(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glBlendFunc(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glBlendFunc((GLenum)arg0 , (GLenum)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLenum, GLenum, GLenum // Ret value: void -JSBool JSB_glBlendFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glBlendFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glBlendFuncSeparate((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLenum)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, ArrayBufferView, GLenum // Ret value: void -JSBool JSB_glBufferData(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glBufferData(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; void* arg1; uint32_t arg2; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg1); ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glBufferData((GLenum)arg0 , count, (GLvoid*)arg1 , (GLenum)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLintptr, ArrayBufferView // Ret value: void -JSBool JSB_glBufferSubData(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glBufferSubData(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; void* arg2; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg2); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glBufferSubData((GLenum)arg0 , (GLintptr)arg1 , count, (GLvoid*)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum // Ret value: GLenum -JSBool JSB_glCheckFramebufferStatus(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glCheckFramebufferStatus(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLenum ret_val; ret_val = glCheckFramebufferStatus((GLenum)arg0 ); JS_SET_RVAL(cx, vp, UINT_TO_JSVAL((uint32_t)ret_val)); - return JS_TRUE; + return true; } // Arguments: GLbitfield // Ret value: void -JSBool JSB_glClear(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glClear(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glClear((GLbitfield)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLclampf, GLclampf, GLclampf, GLclampf // Ret value: void -JSBool JSB_glClearColor(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glClearColor(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); ok &= jsval_to_int32( cx, *argvp++, &arg3 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glClearColor((GLclampf)arg0 , (GLclampf)arg1 , (GLclampf)arg2 , (GLclampf)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLclampf // Ret value: void -JSBool JSB_glClearDepthf(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glClearDepthf(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glClearDepthf((GLclampf)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint // Ret value: void -JSBool JSB_glClearStencil(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glClearStencil(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glClearStencil((GLint)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLboolean, GLboolean, GLboolean, GLboolean // Ret value: void -JSBool JSB_glColorMask(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glColorMask(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint16_t arg0; uint16_t arg1; uint16_t arg2; uint16_t arg3; ok &= jsval_to_uint16( cx, *argvp++, &arg0 ); ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); ok &= jsval_to_uint16( cx, *argvp++, &arg2 ); ok &= jsval_to_uint16( cx, *argvp++, &arg3 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glColorMask((GLboolean)arg0 , (GLboolean)arg1 , (GLboolean)arg2 , (GLboolean)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: void -JSBool JSB_glCompileShader(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glCompileShader(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glCompileShader((GLuint)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, ArrayBufferView // Ret value: void -JSBool JSB_glCompressedTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 8, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glCompressedTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 8, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; uint32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; void* arg7; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); @@ -395,19 +395,19 @@ JSBool JSB_glCompressedTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { ok &= jsval_to_int32( cx, *argvp++, &arg6 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg7); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glCompressedTexImage2D((GLenum)arg0 , (GLint)arg1 , (GLenum)arg2 , (GLsizei)arg3 , (GLsizei)arg4 , (GLint)arg5 , (GLsizei)arg6 , (GLvoid*)arg7 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, ArrayBufferView // Ret value: void -JSBool JSB_glCompressedTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 9, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glCompressedTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 9, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; int32_t arg7; void* arg8; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); @@ -420,19 +420,19 @@ JSBool JSB_glCompressedTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { ok &= jsval_to_int32( cx, *argvp++, &arg7 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg8); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glCompressedTexSubImage2D((GLenum)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLsizei)arg4 , (GLsizei)arg5 , (GLenum)arg6 , (GLsizei)arg7 , (GLvoid*)arg8 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint // Ret value: void -JSBool JSB_glCopyTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 8, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glCopyTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 8, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; uint32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; int32_t arg7; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); @@ -443,19 +443,19 @@ JSBool JSB_glCopyTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { ok &= jsval_to_int32( cx, *argvp++, &arg5 ); ok &= jsval_to_int32( cx, *argvp++, &arg6 ); ok &= jsval_to_int32( cx, *argvp++, &arg7 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glCopyTexImage2D((GLenum)arg0 , (GLint)arg1 , (GLenum)arg2 , (GLint)arg3 , (GLint)arg4 , (GLsizei)arg5 , (GLsizei)arg6 , (GLint)arg7 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei // Ret value: void -JSBool JSB_glCopyTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 8, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glCopyTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 8, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; int32_t arg6; int32_t arg7; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); @@ -466,211 +466,211 @@ JSBool JSB_glCopyTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { ok &= jsval_to_int32( cx, *argvp++, &arg5 ); ok &= jsval_to_int32( cx, *argvp++, &arg6 ); ok &= jsval_to_int32( cx, *argvp++, &arg7 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glCopyTexSubImage2D((GLenum)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLint)arg4 , (GLint)arg5 , (GLsizei)arg6 , (GLsizei)arg7 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: // Ret value: GLuint -JSBool JSB_glCreateProgram(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 0, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glCreateProgram(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 0, cx, false, "Invalid number of arguments" ); GLuint ret_val; ret_val = glCreateProgram( ); JS_SET_RVAL(cx, vp, UINT_TO_JSVAL((uint32_t)ret_val)); - return JS_TRUE; + return true; } // Arguments: GLenum // Ret value: GLuint -JSBool JSB_glCreateShader(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glCreateShader(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLuint ret_val; ret_val = glCreateShader((GLenum)arg0 ); JS_SET_RVAL(cx, vp, UINT_TO_JSVAL((uint32_t)ret_val)); - return JS_TRUE; + return true; } // Arguments: GLenum // Ret value: void -JSBool JSB_glCullFace(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glCullFace(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glCullFace((GLenum)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: void -JSBool JSB_glDeleteProgram(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glDeleteProgram(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDeleteProgram((GLuint)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: void -JSBool JSB_glDeleteShader(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glDeleteShader(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDeleteShader((GLuint)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum // Ret value: void -JSBool JSB_glDepthFunc(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glDepthFunc(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDepthFunc((GLenum)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLboolean // Ret value: void -JSBool JSB_glDepthMask(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glDepthMask(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint16_t arg0; ok &= jsval_to_uint16( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDepthMask((GLboolean)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLclampf, GLclampf // Ret value: void -JSBool JSB_glDepthRangef(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glDepthRangef(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDepthRangef((GLclampf)arg0 , (GLclampf)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint, GLuint // Ret value: void -JSBool JSB_glDetachShader(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glDetachShader(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDetachShader((GLuint)arg0 , (GLuint)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum // Ret value: void -JSBool JSB_glDisable(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glDisable(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDisable((GLenum)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: void -JSBool JSB_glDisableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glDisableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDisableVertexAttribArray((GLuint)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLint, GLsizei // Ret value: void -JSBool JSB_glDrawArrays(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glDrawArrays(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; int32_t arg2; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDrawArrays((GLenum)arg0 , (GLint)arg1 , (GLsizei)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLsizei, GLenum, ArrayBufferView // Ret value: void -JSBool JSB_glDrawElements(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glDrawElements(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; uint32_t arg2; void* arg3; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); @@ -678,90 +678,90 @@ JSBool JSB_glDrawElements(JSContext *cx, uint32_t argc, jsval *vp) { ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg3); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDrawElements((GLenum)arg0 , (GLsizei)arg1 , (GLenum)arg2 , (GLvoid*)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum // Ret value: void -JSBool JSB_glEnable(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glEnable(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glEnable((GLenum)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: void -JSBool JSB_glEnableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glEnableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glEnableVertexAttribArray((GLuint)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: // Ret value: void -JSBool JSB_glFinish(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 0, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glFinish(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 0, cx, false, "Invalid number of arguments" ); glFinish( ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: // Ret value: void -JSBool JSB_glFlush(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 0, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glFlush(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 0, cx, false, "Invalid number of arguments" ); glFlush( ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLenum, GLenum, GLuint // Ret value: void -JSBool JSB_glFramebufferRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glFramebufferRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glFramebufferRenderbuffer((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLuint)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLenum, GLenum, GLuint, GLint // Ret value: void -JSBool JSB_glFramebufferTexture2D(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 5, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glFramebufferTexture2D(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 5, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; int32_t arg4; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); @@ -769,301 +769,301 @@ JSBool JSB_glFramebufferTexture2D(JSContext *cx, uint32_t argc, jsval *vp) { ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); ok &= jsval_to_int32( cx, *argvp++, &arg4 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glFramebufferTexture2D((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLuint)arg3 , (GLint)arg4 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum // Ret value: void -JSBool JSB_glFrontFace(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glFrontFace(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glFrontFace((GLenum)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum // Ret value: void -JSBool JSB_glGenerateMipmap(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glGenerateMipmap(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glGenerateMipmap((GLenum)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint, char* // Ret value: int -JSBool JSB_glGetAttribLocation(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glGetAttribLocation(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; const char* arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_charptr( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); int ret_val; ret_val = glGetAttribLocation((GLuint)arg0 , (char*)arg1 ); JS_SET_RVAL(cx, vp, INT_TO_JSVAL((int32_t)ret_val)); - return JS_TRUE; + return true; } // Arguments: // Ret value: GLenum -JSBool JSB_glGetError(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 0, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glGetError(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 0, cx, false, "Invalid number of arguments" ); GLenum ret_val; ret_val = glGetError( ); JS_SET_RVAL(cx, vp, UINT_TO_JSVAL((uint32_t)ret_val)); - return JS_TRUE; + return true; } // Arguments: GLuint, char* // Ret value: int -JSBool JSB_glGetUniformLocation(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glGetUniformLocation(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; const char* arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_charptr( cx, *argvp++, &arg1 ); printf("%s ", arg1); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); int ret_val; ret_val = glGetUniformLocation((GLuint)arg0 , (char*)arg1 ); JS_SET_RVAL(cx, vp, INT_TO_JSVAL((int32_t)ret_val)); - return JS_TRUE; + return true; } // Arguments: GLenum, GLenum // Ret value: void -JSBool JSB_glHint(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glHint(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glHint((GLenum)arg0 , (GLenum)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: GLboolean -JSBool JSB_glIsBuffer(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glIsBuffer(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLboolean ret_val; ret_val = glIsBuffer((GLuint)arg0 ); JS_SET_RVAL(cx, vp, INT_TO_JSVAL((int32_t)ret_val)); - return JS_TRUE; + return true; } // Arguments: GLenum // Ret value: GLboolean -JSBool JSB_glIsEnabled(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glIsEnabled(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLboolean ret_val; ret_val = glIsEnabled((GLenum)arg0 ); JS_SET_RVAL(cx, vp, INT_TO_JSVAL((int32_t)ret_val)); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: GLboolean -JSBool JSB_glIsFramebuffer(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glIsFramebuffer(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLboolean ret_val; ret_val = glIsFramebuffer((GLuint)arg0 ); JS_SET_RVAL(cx, vp, INT_TO_JSVAL((int32_t)ret_val)); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: GLboolean -JSBool JSB_glIsProgram(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glIsProgram(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLboolean ret_val; ret_val = glIsProgram((GLuint)arg0 ); JS_SET_RVAL(cx, vp, INT_TO_JSVAL((int32_t)ret_val)); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: GLboolean -JSBool JSB_glIsRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glIsRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLboolean ret_val; ret_val = glIsRenderbuffer((GLuint)arg0 ); JS_SET_RVAL(cx, vp, INT_TO_JSVAL((int32_t)ret_val)); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: GLboolean -JSBool JSB_glIsShader(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glIsShader(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLboolean ret_val; ret_val = glIsShader((GLuint)arg0 ); JS_SET_RVAL(cx, vp, INT_TO_JSVAL((int32_t)ret_val)); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: GLboolean -JSBool JSB_glIsTexture(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glIsTexture(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLboolean ret_val; ret_val = glIsTexture((GLuint)arg0 ); JS_SET_RVAL(cx, vp, INT_TO_JSVAL((int32_t)ret_val)); - return JS_TRUE; + return true; } // Arguments: GLfloat // Ret value: void -JSBool JSB_glLineWidth(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glLineWidth(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glLineWidth((GLfloat)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: void -JSBool JSB_glLinkProgram(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glLinkProgram(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glLinkProgram((GLuint)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLint // Ret value: void -JSBool JSB_glPixelStorei(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glPixelStorei(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glPixelStorei((GLenum)arg0 , (GLint)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLfloat, GLfloat // Ret value: void -JSBool JSB_glPolygonOffset(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glPolygonOffset(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glPolygonOffset((GLfloat)arg0 , (GLfloat)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, ArrayBufferView // Ret value: void -JSBool JSB_glReadPixels(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 7, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glReadPixels(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 7, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; uint32_t arg4; uint32_t arg5; void* arg6; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); @@ -1074,191 +1074,191 @@ JSBool JSB_glReadPixels(JSContext *cx, uint32_t argc, jsval *vp) { ok &= jsval_to_uint32( cx, *argvp++, &arg5 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg6); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glReadPixels((GLint)arg0 , (GLint)arg1 , (GLsizei)arg2 , (GLsizei)arg3 , (GLenum)arg4 , (GLenum)arg5 , (GLvoid*)arg6 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: // Ret value: void -JSBool JSB_glReleaseShaderCompiler(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 0, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glReleaseShaderCompiler(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 0, cx, false, "Invalid number of arguments" ); glReleaseShaderCompiler( ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLenum, GLsizei, GLsizei // Ret value: void -JSBool JSB_glRenderbufferStorage(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glRenderbufferStorage(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; int32_t arg2; int32_t arg3; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); ok &= jsval_to_int32( cx, *argvp++, &arg3 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glRenderbufferStorage((GLenum)arg0 , (GLenum)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLclampf, GLboolean // Ret value: void -JSBool JSB_glSampleCoverage(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glSampleCoverage(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; uint16_t arg1; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glSampleCoverage((GLclampf)arg0 , (GLboolean)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLint, GLsizei, GLsizei // Ret value: void -JSBool JSB_glScissor(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glScissor(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); ok &= jsval_to_int32( cx, *argvp++, &arg3 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glScissor((GLint)arg0 , (GLint)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLint, GLuint // Ret value: void -JSBool JSB_glStencilFunc(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glStencilFunc(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; uint32_t arg2; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glStencilFunc((GLenum)arg0 , (GLint)arg1 , (GLuint)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLenum, GLint, GLuint // Ret value: void -JSBool JSB_glStencilFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glStencilFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; int32_t arg2; uint32_t arg3; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glStencilFuncSeparate((GLenum)arg0 , (GLenum)arg1 , (GLint)arg2 , (GLuint)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: void -JSBool JSB_glStencilMask(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glStencilMask(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glStencilMask((GLuint)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLuint // Ret value: void -JSBool JSB_glStencilMaskSeparate(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glStencilMaskSeparate(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glStencilMaskSeparate((GLenum)arg0 , (GLuint)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLenum, GLenum // Ret value: void -JSBool JSB_glStencilOp(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glStencilOp(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; uint32_t arg2; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glStencilOp((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLenum, GLenum, GLenum // Ret value: void -JSBool JSB_glStencilOpSeparate(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glStencilOpSeparate(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; uint32_t arg2; uint32_t arg3; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); ok &= jsval_to_uint32( cx, *argvp++, &arg2 ); ok &= jsval_to_uint32( cx, *argvp++, &arg3 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glStencilOpSeparate((GLenum)arg0 , (GLenum)arg1 , (GLenum)arg2 , (GLenum)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, ArrayBufferView // Ret value: void -JSBool JSB_glTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 9, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 9, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; uint32_t arg7; void* arg8; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); @@ -1271,55 +1271,55 @@ JSBool JSB_glTexImage2D(JSContext *cx, uint32_t argc, jsval *vp) { ok &= jsval_to_uint32( cx, *argvp++, &arg7 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg8); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glTexImage2D((GLenum)arg0 , (GLint)arg1 , (GLint)arg2 , (GLsizei)arg3 , (GLsizei)arg4 , (GLint)arg5 , (GLenum)arg6 , (GLenum)arg7 , (GLvoid*)arg8 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLenum, GLfloat // Ret value: void -JSBool JSB_glTexParameterf(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glTexParameterf(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; int32_t arg2; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glTexParameterf((GLenum)arg0 , (GLenum)arg1 , (GLfloat)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLenum, GLint // Ret value: void -JSBool JSB_glTexParameteri(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glTexParameteri(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; uint32_t arg1; int32_t arg2; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glTexParameteri((GLenum)arg0 , (GLenum)arg1 , (GLint)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, ArrayBufferView // Ret value: void -JSBool JSB_glTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 9, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 9, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; int32_t arg5; uint32_t arg6; uint32_t arg7; void* arg8; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); @@ -1332,241 +1332,241 @@ JSBool JSB_glTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp) { ok &= jsval_to_uint32( cx, *argvp++, &arg7 ); GLsizei count; ok &= JSB_get_arraybufferview_dataptr( cx, *argvp++, &count, &arg8); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glTexSubImage2D((GLenum)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLsizei)arg4 , (GLsizei)arg5 , (GLenum)arg6 , (GLenum)arg7 , (GLvoid*)arg8 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLfloat // Ret value: void -JSBool JSB_glUniform1f(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform1f(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform1f((GLint)arg0 , (GLfloat)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLsizei, TypedArray/Sequence // Ret value: void -JSBool JSB_glUniform1fv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform1fv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; void* arg2; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform1fv((GLint)arg0 , (GLsizei)arg1 , (GLfloat*)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLint // Ret value: void -JSBool JSB_glUniform1i(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform1i(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform1i((GLint)arg0 , (GLint)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLsizei, TypedArray/Sequence // Ret value: void -JSBool JSB_glUniform1iv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform1iv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; void* arg2; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform1iv((GLint)arg0 , (GLsizei)arg1 , (GLint*)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLfloat, GLfloat // Ret value: void -JSBool JSB_glUniform2f(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform2f(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; int32_t arg2; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform2f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLsizei, TypedArray/Sequence // Ret value: void -JSBool JSB_glUniform2fv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform2fv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; void* arg2; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform2fv((GLint)arg0 , (GLsizei)arg1 , (GLfloat*)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLint, GLint // Ret value: void -JSBool JSB_glUniform2i(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform2i(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; int32_t arg2; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform2i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLsizei, TypedArray/Sequence // Ret value: void -JSBool JSB_glUniform2iv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform2iv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; void* arg2; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform2iv((GLint)arg0 , (GLsizei)arg1 , (GLint*)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLfloat, GLfloat, GLfloat // Ret value: void -JSBool JSB_glUniform3f(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform3f(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); ok &= jsval_to_int32( cx, *argvp++, &arg3 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform3f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLsizei, TypedArray/Sequence // Ret value: void -JSBool JSB_glUniform3fv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform3fv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; void* arg2; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform3fv((GLint)arg0 , (GLsizei)arg1 , (GLfloat*)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLint, GLint, GLint // Ret value: void -JSBool JSB_glUniform3i(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform3i(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); ok &= jsval_to_int32( cx, *argvp++, &arg3 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform3i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLsizei, TypedArray/Sequence // Ret value: void -JSBool JSB_glUniform3iv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform3iv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; void* arg2; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform3iv((GLint)arg0 , (GLsizei)arg1 , (GLint*)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLfloat, GLfloat, GLfloat, GLfloat // Ret value: void -JSBool JSB_glUniform4f(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 5, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform4f(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 5, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); @@ -1574,38 +1574,38 @@ JSBool JSB_glUniform4f(JSContext *cx, uint32_t argc, jsval *vp) { ok &= jsval_to_int32( cx, *argvp++, &arg2 ); ok &= jsval_to_int32( cx, *argvp++, &arg3 ); ok &= jsval_to_int32( cx, *argvp++, &arg4 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform4f((GLint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 , (GLfloat)arg4 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLsizei, TypedArray/Sequence // Ret value: void -JSBool JSB_glUniform4fv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform4fv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; void* arg2; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform4fv((GLint)arg0 , (GLsizei)arg1 , (GLfloat*)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLint, GLint, GLint, GLint // Ret value: void -JSBool JSB_glUniform4i(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 5, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform4i(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 5, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); @@ -1613,235 +1613,235 @@ JSBool JSB_glUniform4i(JSContext *cx, uint32_t argc, jsval *vp) { ok &= jsval_to_int32( cx, *argvp++, &arg2 ); ok &= jsval_to_int32( cx, *argvp++, &arg3 ); ok &= jsval_to_int32( cx, *argvp++, &arg4 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform4i((GLint)arg0 , (GLint)arg1 , (GLint)arg2 , (GLint)arg3 , (GLint)arg4 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLsizei, TypedArray/Sequence // Ret value: void -JSBool JSB_glUniform4iv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniform4iv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; void* arg2; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_INT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniform4iv((GLint)arg0 , (GLsizei)arg1 , (GLint*)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLboolean, TypedArray/Sequence // Ret value: void -JSBool JSB_glUniformMatrix2fv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniformMatrix2fv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; uint16_t arg1; void* arg2; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniformMatrix2fv(arg0, 1, (GLboolean)arg1 , (GLfloat*)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLboolean, TypedArray/Sequence // Ret value: void -JSBool JSB_glUniformMatrix3fv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniformMatrix3fv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; uint16_t arg1; void* arg2; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniformMatrix3fv(arg0, 1, (GLboolean)arg1 , (GLfloat*)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLboolean, TypedArray/Sequence // Ret value: void -JSBool JSB_glUniformMatrix4fv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUniformMatrix4fv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; uint16_t arg1; void* arg2; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_uint16( cx, *argvp++, &arg1 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg2, js::ArrayBufferView::TYPE_FLOAT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUniformMatrix4fv(arg0, 1, (GLboolean)arg1 , (GLfloat*)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: void -JSBool JSB_glUseProgram(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glUseProgram(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glUseProgram((GLuint)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint // Ret value: void -JSBool JSB_glValidateProgram(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glValidateProgram(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glValidateProgram((GLuint)arg0 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint, GLfloat // Ret value: void -JSBool JSB_glVertexAttrib1f(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glVertexAttrib1f(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glVertexAttrib1f((GLuint)arg0 , (GLfloat)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint, TypedArray/Sequence // Ret value: void -JSBool JSB_glVertexAttrib1fv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glVertexAttrib1fv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; void* arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glVertexAttrib1fv((GLuint)arg0 , (GLfloat*)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint, GLfloat, GLfloat // Ret value: void -JSBool JSB_glVertexAttrib2f(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 3, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glVertexAttrib2f(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 3, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; int32_t arg2; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glVertexAttrib2f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint, TypedArray/Sequence // Ret value: void -JSBool JSB_glVertexAttrib2fv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glVertexAttrib2fv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; void* arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glVertexAttrib2fv((GLuint)arg0 , (GLfloat*)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint, GLfloat, GLfloat, GLfloat // Ret value: void -JSBool JSB_glVertexAttrib3f(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glVertexAttrib3f(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); ok &= jsval_to_int32( cx, *argvp++, &arg3 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glVertexAttrib3f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint, TypedArray/Sequence // Ret value: void -JSBool JSB_glVertexAttrib3fv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glVertexAttrib3fv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; void* arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glVertexAttrib3fv((GLuint)arg0 , (GLfloat*)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint, GLfloat, GLfloat, GLfloat, GLfloat // Ret value: void -JSBool JSB_glVertexAttrib4f(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 5, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glVertexAttrib4f(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 5, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; int32_t arg4; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); @@ -1849,37 +1849,37 @@ JSBool JSB_glVertexAttrib4f(JSContext *cx, uint32_t argc, jsval *vp) { ok &= jsval_to_int32( cx, *argvp++, &arg2 ); ok &= jsval_to_int32( cx, *argvp++, &arg3 ); ok &= jsval_to_int32( cx, *argvp++, &arg4 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glVertexAttrib4f((GLuint)arg0 , (GLfloat)arg1 , (GLfloat)arg2 , (GLfloat)arg3 , (GLfloat)arg4 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint, TypedArray/Sequence // Ret value: void -JSBool JSB_glVertexAttrib4fv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glVertexAttrib4fv(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; void* arg1; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); GLsizei count; ok &= JSB_jsval_typedarray_to_dataptr( cx, *argvp++, &count, &arg1, js::ArrayBufferView::TYPE_FLOAT32); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glVertexAttrib4fv((GLuint)arg0 , (GLfloat*)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLuint, GLint, GLenum, GLboolean, GLsizei, GLvoid* // Ret value: void -JSBool JSB_glVertexAttribPointer(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 6, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glVertexAttribPointer(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 6, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; int32_t arg1; uint32_t arg2; uint16_t arg3; int32_t arg4; int32_t arg5; ok &= jsval_to_uint32( cx, *argvp++, &arg0 ); @@ -1888,30 +1888,30 @@ JSBool JSB_glVertexAttribPointer(JSContext *cx, uint32_t argc, jsval *vp) { ok &= jsval_to_uint16( cx, *argvp++, &arg3 ); ok &= jsval_to_int32( cx, *argvp++, &arg4 ); ok &= jsval_to_int32( cx, *argvp++, &arg5 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glVertexAttribPointer((GLuint)arg0 , (GLint)arg1 , (GLenum)arg2 , (GLboolean)arg3 , (GLsizei)arg4 , (GLvoid*)arg5 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: GLint, GLint, GLsizei, GLsizei // Ret value: void -JSBool JSB_glViewport(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 4, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_glViewport(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 4, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; int32_t arg0; int32_t arg1; int32_t arg2; int32_t arg3; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); ok &= jsval_to_int32( cx, *argvp++, &arg2 ); ok &= jsval_to_int32( cx, *argvp++, &arg3 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glViewport((GLint)arg0 , (GLint)arg1 , (GLsizei)arg2 , (GLsizei)arg3 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } diff --git a/cocos/scripting/javascript/bindings/jsb_opengl_functions.h b/cocos/scripting/javascript/bindings/jsb_opengl_functions.h index ab82b91518..9a4449a7bb 100644 --- a/cocos/scripting/javascript/bindings/jsb_opengl_functions.h +++ b/cocos/scripting/javascript/bindings/jsb_opengl_functions.h @@ -10,132 +10,132 @@ extern "C" { -JSBool JSB_glActiveTexture(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glAttachShader(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glBindAttribLocation(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glBindBuffer(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glBindFramebuffer(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glBindRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glBindTexture(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glBlendColor(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glBlendEquation(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glBlendEquationSeparate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glBlendFunc(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glBlendFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glBufferData(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glBufferSubData(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glCheckFramebufferStatus(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glClear(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glClearColor(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glClearDepthf(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glClearStencil(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glColorMask(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glCompileShader(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glCompressedTexImage2D(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glCompressedTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glCopyTexImage2D(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glCopyTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glCreateProgram(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glCreateShader(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glCullFace(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDeleteBuffers(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDeleteFramebuffers(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDeleteProgram(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDeleteRenderbuffers(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDeleteShader(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDeleteTextures(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDepthFunc(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDepthMask(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDepthRangef(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDetachShader(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDisable(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDisableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDrawArrays(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glDrawElements(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glEnable(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glEnableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glFinish(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glFlush(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glFramebufferRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glFramebufferTexture2D(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glFrontFace(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGenBuffers(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGenFramebuffers(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGenRenderbuffers(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGenTextures(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGenerateMipmap(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGetActiveAttrib(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGetActiveUniform(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGetAttachedShaders(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGetAttribLocation(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGetError(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGetProgramInfoLog(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGetProgramiv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGetShaderInfoLog(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGetShaderSource(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGetShaderiv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGetTexParameterfv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGetUniformLocation(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glGetUniformfv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glHint(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glIsBuffer(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glIsEnabled(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glIsFramebuffer(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glIsProgram(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glIsRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glIsShader(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glIsTexture(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glLineWidth(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glLinkProgram(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glPixelStorei(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glPolygonOffset(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glReadPixels(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glReleaseShaderCompiler(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glRenderbufferStorage(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glSampleCoverage(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glScissor(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glShaderSource(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glStencilFunc(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glStencilFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glStencilMask(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glStencilMaskSeparate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glStencilOp(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glStencilOpSeparate(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glTexImage2D(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glTexParameterf(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glTexParameteri(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform1f(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform1fv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform1i(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform1iv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform2f(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform2fv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform2i(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform2iv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform3f(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform3fv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform3i(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform3iv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform4f(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform4fv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform4i(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniform4iv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniformMatrix2fv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniformMatrix3fv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUniformMatrix4fv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glUseProgram(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glValidateProgram(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glVertexAttrib1f(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glVertexAttrib1fv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glVertexAttrib2f(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glVertexAttrib2fv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glVertexAttrib3f(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glVertexAttrib3fv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glVertexAttrib4f(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glVertexAttrib4fv(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glVertexAttribPointer(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_glViewport(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glActiveTexture(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glAttachShader(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glBindAttribLocation(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glBindBuffer(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glBindFramebuffer(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glBindRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glBindTexture(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glBlendColor(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glBlendEquation(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glBlendEquationSeparate(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glBlendFunc(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glBlendFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glBufferData(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glBufferSubData(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glCheckFramebufferStatus(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glClear(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glClearColor(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glClearDepthf(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glClearStencil(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glColorMask(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glCompileShader(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glCompressedTexImage2D(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glCompressedTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glCopyTexImage2D(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glCopyTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glCreateProgram(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glCreateShader(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glCullFace(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDeleteBuffers(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDeleteFramebuffers(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDeleteProgram(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDeleteRenderbuffers(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDeleteShader(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDeleteTextures(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDepthFunc(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDepthMask(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDepthRangef(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDetachShader(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDisable(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDisableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDrawArrays(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glDrawElements(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glEnable(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glEnableVertexAttribArray(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glFinish(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glFlush(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glFramebufferRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glFramebufferTexture2D(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glFrontFace(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGenBuffers(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGenFramebuffers(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGenRenderbuffers(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGenTextures(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGenerateMipmap(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetActiveAttrib(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetActiveUniform(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetAttachedShaders(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetAttribLocation(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetError(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetProgramInfoLog(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetProgramiv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetShaderInfoLog(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetShaderSource(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetShaderiv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetTexParameterfv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetUniformLocation(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetUniformfv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glHint(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glIsBuffer(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glIsEnabled(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glIsFramebuffer(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glIsProgram(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glIsRenderbuffer(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glIsShader(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glIsTexture(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glLineWidth(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glLinkProgram(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glPixelStorei(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glPolygonOffset(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glReadPixels(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glReleaseShaderCompiler(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glRenderbufferStorage(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glSampleCoverage(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glScissor(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glShaderSource(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glStencilFunc(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glStencilFuncSeparate(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glStencilMask(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glStencilMaskSeparate(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glStencilOp(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glStencilOpSeparate(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glTexImage2D(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glTexParameterf(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glTexParameteri(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glTexSubImage2D(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform1f(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform1fv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform1i(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform1iv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform2f(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform2fv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform2i(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform2iv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform3f(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform3fv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform3i(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform3iv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform4f(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform4fv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform4i(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniform4iv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniformMatrix2fv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniformMatrix3fv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUniformMatrix4fv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glUseProgram(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glValidateProgram(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glVertexAttrib1f(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glVertexAttrib1fv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glVertexAttrib2f(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glVertexAttrib2fv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glVertexAttrib3f(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glVertexAttrib3fv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glVertexAttrib4f(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glVertexAttrib4fv(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glVertexAttribPointer(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glViewport(JSContext *cx, uint32_t argc, jsval *vp); } diff --git a/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp b/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp index fa4e2d31c8..245b44ab3b 100644 --- a/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp +++ b/cocos/scripting/javascript/bindings/jsb_opengl_manual.cpp @@ -26,9 +26,6 @@ #include "js_bindings_config.h" #ifdef JSB_INCLUDE_OPENGL -#include "jsapi.h" -#include "jsfriendapi.h" - #include "jsb_opengl_manual.h" #include "js_manual_conversions.h" #include "js_bindings_core.h" @@ -36,165 +33,165 @@ // Helper functions that link "glGenXXXs" (OpenGL ES 2.0 spec), with "gl.createXXX" (WebGL spec) -JSBool JSB_glGenTextures(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGenTextures(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 0, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 0, cx, false, "Invalid number of arguments" ); GLuint texture; glGenTextures(1, &texture); JS_SET_RVAL(cx, vp, INT_TO_JSVAL(texture)); - return JS_TRUE; + return true; } -JSBool JSB_glGenBuffers(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGenBuffers(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 0, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 0, cx, false, "Invalid number of arguments" ); GLuint buffer; glGenBuffers(1, &buffer); JS_SET_RVAL(cx, vp, INT_TO_JSVAL(buffer)); - return JS_TRUE; + return true; } -JSBool JSB_glGenRenderbuffers(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGenRenderbuffers(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 0, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 0, cx, false, "Invalid number of arguments" ); GLuint renderbuffers; glGenRenderbuffers(1, &renderbuffers); JS_SET_RVAL(cx, vp, INT_TO_JSVAL(renderbuffers)); - return JS_TRUE; + return true; } -JSBool JSB_glGenFramebuffers(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGenFramebuffers(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 0, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 0, cx, false, "Invalid number of arguments" ); GLuint framebuffers; glGenFramebuffers(1, &framebuffers); JS_SET_RVAL(cx, vp, INT_TO_JSVAL(framebuffers)); - return JS_TRUE; + return true; } -JSBool JSB_glDeleteTextures(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glDeleteTextures(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDeleteTextures(1, &arg0); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } -JSBool JSB_glDeleteBuffers(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glDeleteBuffers(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDeleteBuffers(1, &arg0); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } -JSBool JSB_glDeleteRenderbuffers(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glDeleteRenderbuffers(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDeleteRenderbuffers(1, &arg0); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } -JSBool JSB_glDeleteFramebuffers(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glDeleteFramebuffers(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glDeleteFramebuffers(1, &arg0); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } -JSBool JSB_glShaderSource(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glShaderSource(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; const char *arg1; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); ok &= jsval_to_charptr(cx, *argvp++, &arg1); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); glShaderSource(arg0, 1, &arg1, NULL); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } -JSBool JSB_glGetShaderiv(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGetShaderiv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0, arg1; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); ok &= jsval_to_uint( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLint ret; glGetShaderiv(arg0, arg1, &ret); JS_SET_RVAL(cx, vp, INT_TO_JSVAL(ret)); - return JS_TRUE; + return true; } -JSBool JSB_glGetProgramiv(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGetProgramiv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0, arg1; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); ok &= jsval_to_uint( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLint ret; glGetProgramiv(arg0, arg1, &ret); JS_SET_RVAL(cx, vp, INT_TO_JSVAL(ret)); - return JS_TRUE; + return true; } -JSBool JSB_glGetProgramInfoLog(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGetProgramInfoLog(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLsizei length; glGetProgramiv(arg0, GL_INFO_LOG_LENGTH, &length); @@ -203,19 +200,19 @@ JSBool JSB_glGetProgramInfoLog(JSContext *cx, uint32_t argc, jsval *vp) JS_SET_RVAL(cx, vp, charptr_to_jsval(cx, src)); CC_SAFE_DELETE_ARRAY(src); - return JS_TRUE; + return true; } // DOMString? getShaderInfoLog(WebGLShader? shader); -JSBool JSB_glGetShaderInfoLog(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGetShaderInfoLog(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLsizei length; glGetShaderiv(arg0, GL_INFO_LOG_LENGTH, &length); @@ -224,19 +221,19 @@ JSBool JSB_glGetShaderInfoLog(JSContext *cx, uint32_t argc, jsval *vp) JS_SET_RVAL(cx, vp, charptr_to_jsval(cx, src)); CC_SAFE_DELETE_ARRAY(src); - return JS_TRUE; + return true; } // DOMString? getShaderSource(WebGLShader? shader); -JSBool JSB_glGetShaderSource(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGetShaderSource(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLsizei length; glGetShaderiv(arg0, GL_SHADER_SOURCE_LENGTH, &length); @@ -245,7 +242,7 @@ JSBool JSB_glGetShaderSource(JSContext *cx, uint32_t argc, jsval *vp) JS_SET_RVAL(cx, vp, charptr_to_jsval(cx, src)); CC_SAFE_DELETE_ARRAY(src); - return JS_TRUE; + return true; } // interface WebGLActiveInfo { @@ -253,16 +250,16 @@ JSBool JSB_glGetShaderSource(JSContext *cx, uint32_t argc, jsval *vp) // readonly attribute GLenum type; // readonly attribute DOMString name; // WebGLActiveInfo? getActiveAttrib(WebGLProgram? program, GLuint index); -JSBool JSB_glGetActiveAttrib(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGetActiveAttrib(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0, arg1; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); ok &= jsval_to_uint( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLsizei length; glGetProgramiv(arg0, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &length); @@ -275,18 +272,18 @@ JSBool JSB_glGetActiveAttrib(JSContext *cx, uint32_t argc, jsval *vp) jsval retval = JSVAL_VOID; JSObject *object = JS_NewObject(cx, NULL, NULL, NULL ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error creating JS Object"); + JSB_PRECONDITION2(ok, cx, false, "Error creating JS Object"); if (!JS_DefineProperty(cx, object, "size", INT_TO_JSVAL(size), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || !JS_DefineProperty(cx, object, "type", INT_TO_JSVAL(type), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || !JS_DefineProperty(cx, object, "name", charptr_to_jsval(cx, buffer), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) ) - return JS_FALSE; + return false; retval = OBJECT_TO_JSVAL(object); JS_SET_RVAL(cx, vp, retval); CC_SAFE_DELETE_ARRAY(buffer); - return JS_TRUE; + return true; } @@ -296,16 +293,16 @@ JSBool JSB_glGetActiveAttrib(JSContext *cx, uint32_t argc, jsval *vp) // readonly attribute DOMString name; // }; // WebGLActiveInfo? getActiveUniform(WebGLProgram? program, GLuint index); -JSBool JSB_glGetActiveUniform(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGetActiveUniform(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0, arg1; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); ok &= jsval_to_uint( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLsizei length; glGetProgramiv(arg0, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &length); @@ -319,30 +316,30 @@ JSBool JSB_glGetActiveUniform(JSContext *cx, uint32_t argc, jsval *vp) JSObject *object = JS_NewObject(cx, NULL, NULL, NULL ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error creating JS Object"); + JSB_PRECONDITION2(ok, cx, false, "Error creating JS Object"); if (!JS_DefineProperty(cx, object, "size", INT_TO_JSVAL(size), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || !JS_DefineProperty(cx, object, "type", INT_TO_JSVAL(type), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) || !JS_DefineProperty(cx, object, "name", charptr_to_jsval(cx, buffer), NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT) ) - return JS_FALSE; + return false; retval = OBJECT_TO_JSVAL(object); JS_SET_RVAL(cx, vp, retval); CC_SAFE_DELETE_ARRAY(buffer); - return JS_TRUE; + return true; } // sequence? getAttachedShaders(WebGLProgram? program); -JSBool JSB_glGetAttachedShaders(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGetAttachedShaders(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLsizei length; glGetProgramiv(arg0, GL_ATTACHED_SHADERS, &length); @@ -353,28 +350,28 @@ JSBool JSB_glGetAttachedShaders(JSContext *cx, uint32_t argc, jsval *vp) glGetAttachedShaders(arg0, length, &realShaderCount, buffer); JSObject *jsobj = JS_NewArrayObject(cx, length, NULL); - JSB_PRECONDITION2(jsobj, cx, JS_FALSE, "Error creating JS Object"); + JSB_PRECONDITION2(jsobj, cx, false, "Error creating JS Object"); for( int i=0; i? getSupportedExtensions(); -JSBool JSB_glGetSupportedExtensions(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGetSupportedExtensions(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 0, cx, JS_FALSE, "Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 0, cx, false, "Invalid number of arguments" ); const GLubyte *extensions = glGetString(GL_EXTENSIONS); JSObject *jsobj = JS_NewArrayObject(cx, 0, NULL); - JSB_PRECONDITION2(jsobj, cx, JS_FALSE, "Error creating JS Object"); + JSB_PRECONDITION2(jsobj, cx, false, "Error creating JS Object"); // copy, to be able to add '\0' size_t len = strlen((char*)extensions); @@ -387,7 +384,7 @@ JSBool JSB_glGetSupportedExtensions(JSContext *cx, uint32_t argc, jsval *vp) if( copy[i]==' ' || copy[i]==',' || i==len ) { copy[i] = 0; - jsval str = charptr_to_jsval(cx, (const char*)©[start_extension]); + JS::RootedValue str(cx, charptr_to_jsval(cx, (const char*)©[start_extension])); JS_SetElement(cx, jsobj, element++, &str ); start_extension = i+1; @@ -398,42 +395,42 @@ JSBool JSB_glGetSupportedExtensions(JSContext *cx, uint32_t argc, jsval *vp) JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(jsobj)); CC_SAFE_DELETE_ARRAY(copy); - return JS_TRUE; + return true; } // any getTexParameter(GLenum target, GLenum pname); -JSBool JSB_glGetTexParameterfv(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGetTexParameterfv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "JSB_glGetTexParameterfv: Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 2, cx, false, "JSB_glGetTexParameterfv: Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0, arg1; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); ok &= jsval_to_uint( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "JSB_glGetTexParameterfv: Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "JSB_glGetTexParameterfv: Error processing arguments"); GLfloat param; glGetTexParameterfv(arg0, arg1, ¶m); JS_SET_RVAL(cx, vp, DOUBLE_TO_JSVAL(param)); - return JS_TRUE; + return true; } // any getUniform(WebGLProgram? program, WebGLUniformLocation? location); -JSBool JSB_glGetUniformfv(JSContext *cx, uint32_t argc, jsval *vp) +bool JSB_glGetUniformfv(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "JSB_glGetUniformfv: Invalid number of arguments" ); + JSB_PRECONDITION2( argc == 2, cx, false, "JSB_glGetUniformfv: Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; + bool ok = true; uint32_t arg0, arg1; ok &= jsval_to_uint( cx, *argvp++, &arg0 ); ok &= jsval_to_uint( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "JSB_glGetUniformfv: Error processing arguments"); + JSB_PRECONDITION2(ok, cx, false, "JSB_glGetUniformfv: Error processing arguments"); GLsizei length; glGetProgramiv(arg0, GL_ACTIVE_UNIFORM_MAX_LENGTH, &length); @@ -497,7 +494,7 @@ JSBool JSB_glGetUniformfv(JSContext *cx, uint32_t argc, jsval *vp) break; default: - JSB_PRECONDITION2(false, cx, JS_FALSE, "JSB_glGetUniformfv: Uniform Type not supported"); + JSB_PRECONDITION2(false, cx, false, "JSB_glGetUniformfv: Uniform Type not supported"); } JSObject *typedArray = NULL; @@ -526,7 +523,7 @@ JSBool JSB_glGetUniformfv(JSContext *cx, uint32_t argc, jsval *vp) } JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(typedArray)); - return JS_TRUE; + return true; } diff --git a/cocos/scripting/javascript/bindings/jsb_opengl_manual.h b/cocos/scripting/javascript/bindings/jsb_opengl_manual.h index c00afd7dab..f28d8db3fd 100644 --- a/cocos/scripting/javascript/bindings/jsb_opengl_manual.h +++ b/cocos/scripting/javascript/bindings/jsb_opengl_manual.h @@ -31,6 +31,7 @@ //#include #include "jsapi.h" +#include "jsfriendapi.h" #ifdef __IPHONE_OS_VERSION_MAX_ALLOWED #elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED) @@ -43,7 +44,7 @@ #endif // __MAC_OS_X_VERSION_MAX_ALLOWED // forward declaration of new functions -JSBool JSB_glGetSupportedExtensions(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_glGetSupportedExtensions(JSContext *cx, uint32_t argc, jsval *vp); #endif // JSB_INCLUDE_OPENGL diff --git a/cocos/scripting/javascript/bindings/jsb_opengl_registration.cpp b/cocos/scripting/javascript/bindings/jsb_opengl_registration.cpp index ad3fee9a24..6ce3964665 100644 --- a/cocos/scripting/javascript/bindings/jsb_opengl_registration.cpp +++ b/cocos/scripting/javascript/bindings/jsb_opengl_registration.cpp @@ -45,7 +45,7 @@ void JSB_register_opengl(JSContext *_cx, JSObject *object) JS_SetProperty(_cx, object, "gl", openglVal); JS::RootedValue nsval(_cx); - JSObject *ccns; + JS::RootedObject ccns(_cx); JS_GetProperty(_cx, object, "cc", &nsval); if (nsval == JSVAL_VOID) { ccns = JS_NewObject(_cx, NULL, NULL, NULL); diff --git a/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.cpp b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.cpp index 7d1a819fc8..55cda7d5f5 100644 --- a/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.cpp +++ b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.cpp @@ -3,72 +3,66 @@ * Generated by "generate_js_bindings.py -c system_jsb.ini" on 2012-12-17 * Script version: v0.5 */ -#include "cocos2d.h" -#include "js_bindings_config.h" -//#ifdef JSB_INCLUDE_SYSTEM - -#include "local-storage/LocalStorage.h" - -#include "jsfriendapi.h" +#include "js_bindings_system_functions.h" #include "js_bindings_config.h" #include "js_bindings_core.h" #include "js_manual_conversions.h" -#include "js_bindings_system_functions.h" #include "ScriptingCore.h" +#include "local-storage/LocalStorage.h" USING_NS_CC; // Arguments: char* // Ret value: const char* -JSBool JSB_localStorageGetItem(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_localStorageGetItem(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - const char* arg0; + bool ok = true; + std::string arg0; - ok &= jsval_to_charptr( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - const char* ret_val; + ok &= jsval_to_std_string( cx, *argvp++, &arg0 ); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); + std::string ret_val; - ret_val = localStorageGetItem((char*)arg0 ); + ret_val = localStorageGetItem(arg0); - jsval ret_jsval = c_string_to_jsval(cx, ret_val ? ret_val : ""); + jsval ret_jsval = std_string_to_jsval(cx, ret_val); JS_SET_RVAL(cx, vp, ret_jsval ); - return JS_TRUE; + return true; } // Arguments: char* // Ret value: void -JSBool JSB_localStorageRemoveItem(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_localStorageRemoveItem(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 1, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - const char* arg0; + bool ok = true; + std::string arg0; - ok &= jsval_to_charptr( cx, *argvp++, &arg0 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + ok &= jsval_to_std_string( cx, *argvp++, &arg0 ); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); - localStorageRemoveItem((char*)arg0 ); + localStorageRemoveItem(arg0); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } // Arguments: char*, char* // Ret value: void -JSBool JSB_localStorageSetItem(JSContext *cx, uint32_t argc, jsval *vp) { - JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); +bool JSB_localStorageSetItem(JSContext *cx, uint32_t argc, jsval *vp) { + JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); - JSBool ok = JS_TRUE; - const char* arg0; const char* arg1; + bool ok = true; + std::string arg0; std::string arg1; - ok &= jsval_to_charptr( cx, *argvp++, &arg0 ); - ok &= jsval_to_charptr( cx, *argvp++, &arg1 ); - JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); + ok &= jsval_to_std_string( cx, *argvp++, &arg0 ); + ok &= jsval_to_std_string( cx, *argvp++, &arg1 ); + JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); - localStorageSetItem((char*)arg0 , (char*)arg1 ); + localStorageSetItem(arg0 , arg1); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } diff --git a/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.h b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.h index 26d4a97c99..85f9ea55c3 100644 --- a/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.h +++ b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.h @@ -4,16 +4,14 @@ * Script version: v0.5 */ #include "js_bindings_config.h" -//#ifdef JSB_INCLUDE_SYSTEM - -//#include "LocalStorage.h" +#include "jsapi.h" #ifdef __cplusplus extern "C" { #endif -JSBool JSB_localStorageGetItem(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_localStorageRemoveItem(JSContext *cx, uint32_t argc, jsval *vp); -JSBool JSB_localStorageSetItem(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_localStorageGetItem(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_localStorageRemoveItem(JSContext *cx, uint32_t argc, jsval *vp); +bool JSB_localStorageSetItem(JSContext *cx, uint32_t argc, jsval *vp); #ifdef __cplusplus } diff --git a/cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj b/cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj index 2f074d6c17..e19d2ebaa6 100644 --- a/cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj +++ b/cocos/scripting/javascript/bindings/localstorage/libJSBindingForLocalStorage.vcxproj @@ -71,7 +71,7 @@ Level3 Disabled - WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_WINDOWS;_DEBUG;_LIB;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\storage;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\spidermonkey\include\win32;%(AdditionalIncludeDirectories) 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) true diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp index 6581d93205..94e079de0e 100644 --- a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.cpp @@ -317,7 +317,7 @@ JS_BINDED_CONSTRUCTOR_IMPL(MinXmlHttpRequest) p =jsb_new_proxy(req, obj); JS_AddNamedObjectRoot(cx, &p->obj, "XMLHttpRequest"); - return JS_TRUE; + return true; } /** @@ -341,7 +341,7 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, onreadystatechange) { vp.set(JSVAL_NULL); } - return JS_TRUE; + return true; } /** @@ -357,7 +357,7 @@ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, onreadystatechange) _onreadystateCallback = JSVAL_TO_OBJECT(callback); JS_AddNamedObjectRoot(cx, &_onreadystateCallback, "onreadystateCallback"); } - return JS_TRUE; + return true; } /** @@ -368,7 +368,7 @@ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, onreadystatechange) JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, upload) { vp.set(JSVAL_NULL); - return JS_TRUE; + return true; } /** @@ -379,7 +379,7 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, upload) JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, upload) { vp.set(JSVAL_NULL); - return JS_TRUE; + return true; } /** @@ -390,7 +390,7 @@ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, upload) JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, timeout) { vp.set(INT_TO_JSVAL(_timeout)); - return JS_TRUE; + return true; } /** @@ -404,7 +404,7 @@ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, timeout) _timeout = JSVAL_TO_INT(timeout_ms); //curl_easy_setopt(curlHandle, CURLOPT_CONNECTTIMEOUT_MS, timeout); - return JS_TRUE; + return true; } @@ -417,7 +417,7 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseType) { JSString* str = JS_NewStringCopyN(cx, "", 0); vp.set(STRING_TO_JSVAL(str)); - return JS_TRUE; + return true; } /** @@ -428,7 +428,7 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseType) JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseXML) { vp.set(JSVAL_NULL); - return JS_TRUE; + return true; } /** @@ -441,33 +441,33 @@ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, responseType) jsval type = vp.get(); if (type.isString()) { JSString* str = type.toString(); - JSBool equal; + bool equal; JS_StringEqualsAscii(cx, str, "text", &equal); if (equal) { _responseType = ResponseType::STRING; - return JS_TRUE; + return true; } JS_StringEqualsAscii(cx, str, "arraybuffer", &equal); if (equal) { _responseType = ResponseType::ARRAY_BUFFER; - return JS_TRUE; + return true; } JS_StringEqualsAscii(cx, str, "json", &equal); if (equal) { _responseType = ResponseType::JSON; - return JS_TRUE; + return true; } // ignore the rest of the response types for now - return JS_TRUE; + return true; } JS_ReportError(cx, "Invalid response type"); - return JS_FALSE; + return false; } /** @@ -478,7 +478,7 @@ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, responseType) JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, readyState) { vp.set(INT_TO_JSVAL(_readyState)); - return JS_TRUE; + return true; } /** @@ -489,7 +489,7 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, readyState) JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, status) { vp.set(INT_TO_JSVAL(_status)); - return JS_TRUE; + return true; } /** @@ -504,12 +504,12 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, statusText) if (strVal != JSVAL_NULL) { vp.set(strVal); - return JS_TRUE; + return true; } else { JS_ReportError(cx, "Error trying to create JSString from data"); - return JS_FALSE; + return false; } } @@ -520,7 +520,7 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, statusText) JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, withCredentials) { vp.set(BOOLEAN_TO_JSVAL(_withCredentialsValue)); - return JS_TRUE; + return true; } /** @@ -535,7 +535,7 @@ JS_BINDED_PROP_SET_IMPL(MinXmlHttpRequest, withCredentials) _withCredentialsValue = JSVAL_TO_BOOLEAN(credential); } - return JS_TRUE; + return true; } /** @@ -551,7 +551,7 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseText) if (strVal != JSVAL_NULL) { vp.set(strVal); - return JS_TRUE; + return true; } } @@ -560,7 +560,7 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, responseText) // Return an empty string vp.set(std_string_to_jsval(cx, "")); - return JS_TRUE; + return true; } /** @@ -578,7 +578,7 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, response) if (JS_ParseJSON(cx, JS_GetStringCharsZ(cx, JSVAL_TO_STRING(strVal)), _dataSize, &outVal)) { vp.set(outVal); - return JS_TRUE; + return true; } } else if (_responseType == ResponseType::ARRAY_BUFFER) @@ -589,7 +589,7 @@ JS_BINDED_PROP_GET_IMPL(MinXmlHttpRequest, response) jsval outVal = OBJECT_TO_JSVAL(tmp); vp.set(outVal); - return JS_TRUE; + return true; } // by default, return text return _js_get_responseText(cx, id, vp); @@ -606,7 +606,7 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, open) jsval* argv = JS_ARGV(cx, vp); const char* method; const char* urlstr; - JSBool async = true; + bool async = true; JSString* jsMethod = JS_ValueToString(cx, argv[0]); JSString* jsURL = JS_ValueToString(cx, argv[1]); @@ -643,11 +643,11 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, open) _isNetwork = true; _readyState = OPENED; - return JS_TRUE; + return true; } JS_ReportError(cx, "invalid call: %s", __FUNCTION__); - return JS_FALSE; + return false; } @@ -667,7 +667,7 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, send) { if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &str)) { - return JS_FALSE; + return false; } JSStringWrapper strWrap(str); data = strWrap.get(); @@ -682,7 +682,7 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, send) _setHttpRequestHeader(); _sendRequest(cx); - return JS_TRUE; + return true; } /** @@ -691,7 +691,7 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, send) */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, abort) { - return JS_TRUE; + return true; } /** @@ -714,15 +714,15 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getAllResponseHeaders) if (strVal != JSVAL_NULL) { JS_SET_RVAL(cx, vp, strVal); - return JS_TRUE; + return true; } else { JS_ReportError(cx, "Error trying to create JSString from data"); - return JS_FALSE; + return false; } - return JS_TRUE; + return true; } /** @@ -734,7 +734,7 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getResponseHeader) JSString *header_value; if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &header_value)) { - return JS_FALSE; + return false; }; std::string data; @@ -752,11 +752,11 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, getResponseHeader) { jsval js_ret_val = std_string_to_jsval(cx, iter->second); JS_SET_RVAL(cx, vp, js_ret_val); - return JS_TRUE; + return true; } else { JS_SET_RVAL(cx, vp, JSVAL_NULL); - return JS_TRUE; + return true; } } @@ -784,10 +784,10 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, setRequestHeader) // Populate the request_header map. _setRequestHeader(field, value); - return JS_TRUE; + return true; } - return JS_FALSE; + return false; } @@ -798,7 +798,7 @@ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, setRequestHeader) */ JS_BINDED_FUNC_IMPL(MinXmlHttpRequest, overrideMimeType) { - return JS_TRUE; + return true; } /** diff --git a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h index b04633e842..c634ef481e 100644 --- a/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h +++ b/cocos/scripting/javascript/bindings/network/XMLHTTPRequest.h @@ -29,12 +29,11 @@ #ifndef __FAKE_XMLHTTPREQUEST_H__ #define __FAKE_XMLHTTPREQUEST_H__ +#include "jsapi.h" +#include "jsfriendapi.h" #include "network/HttpClient.h" #include "js_bindings_config.h" #include "ScriptingCore.h" -#include "jstypes.h" -#include "jsapi.h" -#include "jsfriendapi.h" #include "jsb_helper.h" class MinXmlHttpRequest : public cocos2d::Object diff --git a/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp b/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp index 4eb0c29ad1..2b9ade362c 100644 --- a/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp +++ b/cocos/scripting/javascript/bindings/network/jsb_websocket.cpp @@ -169,13 +169,13 @@ void js_cocos2dx_WebSocket_finalize(JSFreeOp *fop, JSObject *obj) { CCLOG("jsbindings: finalizing JS object %p (WebSocket)", obj); } -JSBool js_cocos2dx_extension_WebSocket_send(JSContext *cx, uint32_t argc, jsval *vp) +bool js_cocos2dx_extension_WebSocket_send(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); WebSocket* cobj = (WebSocket *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if(argc == 1){ do @@ -218,28 +218,28 @@ JSBool js_cocos2dx_extension_WebSocket_send(JSContext *cx, uint32_t argc, jsval JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); - return JS_TRUE; + return true; } -JSBool js_cocos2dx_extension_WebSocket_close(JSContext *cx, uint32_t argc, jsval *vp){ +bool js_cocos2dx_extension_WebSocket_close(JSContext *cx, uint32_t argc, jsval *vp){ JSObject *obj = JS_THIS_OBJECT(cx, vp); js_proxy_t *proxy = jsb_get_js_proxy(obj); WebSocket* cobj = (WebSocket *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if(argc == 0){ cobj->close(); JS_SET_RVAL(cx, vp, JSVAL_VOID); - return JS_TRUE; + return true; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); - return JS_FALSE; + return false; } -JSBool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, jsval *vp) +bool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, jsval *vp) { jsval *argv = JS_ARGV(cx, vp); @@ -249,8 +249,8 @@ JSBool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, std::string url; do { - JSBool ok = jsval_to_std_string(cx, argv[0], &url); - JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error processing arguments"); + bool ok = jsval_to_std_string(cx, argv[0], &url); + JSB_PRECONDITION2( ok, cx, false, "Error processing arguments"); } while (0); JSObject *obj = JS_NewObject(cx, js_cocos2dx_websocket_class, js_cocos2dx_websocket_prototype, NULL); @@ -268,14 +268,14 @@ JSBool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, { std::string protocol; do { - JSBool ok = jsval_to_std_string(cx, argv[1], &protocol); - JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error processing arguments"); + bool ok = jsval_to_std_string(cx, argv[1], &protocol); + JSB_PRECONDITION2( ok, cx, false, "Error processing arguments"); } while (0); protocols.push_back(protocol); } else if (argv[1].isObject()) { - JSBool ok = JS_TRUE; + bool ok = true; JSObject* arg2 = JSVAL_TO_OBJECT(argv[1]); JSB_PRECONDITION(JS_IsArrayObject( cx, arg2 ), "Object must be an array"); @@ -284,12 +284,12 @@ JSBool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, for( uint32_t i=0; i< len;i++ ) { - jsval valarg; + JS::RootedValue valarg(cx); JS_GetElement(cx, arg2, i, &valarg); std::string protocol; do { ok = jsval_to_std_string(cx, valarg, &protocol); - JSB_PRECONDITION2( ok, cx, JS_FALSE, "Error processing arguments"); + JSB_PRECONDITION2( ok, cx, false, "Error processing arguments"); } while (0); protocols.push_back(protocol); @@ -315,26 +315,26 @@ JSBool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, JS_AddNamedObjectRoot(cx, &p->obj, "WebSocket"); JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj)); - return JS_TRUE; + return true; } JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 0); - return JS_FALSE; + return false; } -static JSBool js_cocos2dx_extension_WebSocket_get_readyState(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp) +static bool js_cocos2dx_extension_WebSocket_get_readyState(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp) { JSObject* jsobj = obj.get(); js_proxy_t *proxy = jsb_get_js_proxy(jsobj); WebSocket* cobj = (WebSocket *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object"); + JSB_PRECONDITION2( cobj, cx, false, "Invalid Native Object"); if (cobj) { vp.set(INT_TO_JSVAL((int)cobj->getReadyState())); - return JS_TRUE; + return true; } else { JS_ReportError(cx, "Error: WebSocket instance is invalid."); - return JS_FALSE; + return false; } } @@ -389,8 +389,8 @@ void register_jsb_websocket(JSContext *cx, JSObject *global) { , NULL, NULL, JSPROP_ENUMERATE | JSPROP_PERMANENT | JSPROP_READONLY); // make the class enumerable in the registered namespace - JSBool found; - JS_SetPropertyAttributes(cx, global, "WebSocket", JSPROP_ENUMERATE | JSPROP_READONLY, &found); +//FIXME: bool found; +// JS_SetPropertyAttributes(cx, global, "WebSocket", JSPROP_ENUMERATE | JSPROP_READONLY, &found); } diff --git a/cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj b/cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj index e4ff3eed4b..93266c783f 100644 --- a/cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj +++ b/cocos/scripting/javascript/bindings/network/libJSBindingForNetwork.vcxproj @@ -70,7 +70,7 @@ Level3 Disabled - WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_WINDOWS;_DEBUG;_LIB;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\network;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)external\websockets\include\win32;%(AdditionalIncludeDirectories) 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) true diff --git a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj index a4cbbd4d50..dbe0c512c5 100644 --- a/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj +++ b/cocos/scripting/javascript/bindings/proj.win32/libJSBinding.vcxproj @@ -98,7 +98,7 @@ Level3 Disabled - WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_WINDOWS;_DEBUG;_LIB;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\storage;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) true diff --git a/cocos/scripting/javascript/bindings/spidermonkey_specifics.h b/cocos/scripting/javascript/bindings/spidermonkey_specifics.h index 94f83728d0..ee034b2e2b 100644 --- a/cocos/scripting/javascript/bindings/spidermonkey_specifics.h +++ b/cocos/scripting/javascript/bindings/spidermonkey_specifics.h @@ -2,6 +2,7 @@ #define __SPIDERMONKEY_SPECIFICS_H__ #include "jsapi.h" +#include "jsfriendapi.h" #include "uthash.h" #include @@ -75,7 +76,7 @@ do { \ #define TEST_NATIVE_OBJECT(cx, native_obj) \ if (!native_obj) { \ JS_ReportError(cx, "Invalid Native Object"); \ - return JS_FALSE; \ + return false; \ } #endif diff --git a/cocos/scripting/javascript/bindings/spine/libJSBindingForSpine.vcxproj b/cocos/scripting/javascript/bindings/spine/libJSBindingForSpine.vcxproj index 13f9b1c4c1..09e521c09d 100644 --- a/cocos/scripting/javascript/bindings/spine/libJSBindingForSpine.vcxproj +++ b/cocos/scripting/javascript/bindings/spine/libJSBindingForSpine.vcxproj @@ -71,7 +71,7 @@ Level3 Disabled - WIN32;_WINDOWS;_DEBUG;_LIB;DEBUG;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_WINDOWS;_DEBUG;_LIB;COCOS2D_DEBUG=1;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) $(ProjectDir)..;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\editor-support\spine;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)cocos\audio\include;%(AdditionalIncludeDirectories) 4068;4101;4800;4251;4244;%(DisableSpecificWarnings) true diff --git a/cocos/scripting/javascript/script/debugger/DevToolsUtils.js b/cocos/scripting/javascript/script/debugger/DevToolsUtils.js index 26d0597644..c3649c569a 100644 --- a/cocos/scripting/javascript/script/debugger/DevToolsUtils.js +++ b/cocos/scripting/javascript/script/debugger/DevToolsUtils.js @@ -69,25 +69,37 @@ var dump = function(msg) { /* General utilities used throughout devtools. */ -/* Turn the error e into a string, without fail. */ +/** + * Turn the error |aError| into a string, without fail. + */ this.safeErrorString = function safeErrorString(aError) { try { - var s = aError.toString(); - if (typeof s === "string") - return s; + 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) { } + + return errorString; + } } catch (ee) { } return ""; } + /** * Report that |aWho| threw an exception, |aException|. */ this.reportException = function reportException(aWho, aException) { let msg = aWho + " threw an exception: " + safeErrorString(aException); - if (aException.stack) { - msg += "\nCall stack:\n" + aException.stack; - } dump(msg + "\n"); @@ -131,3 +143,88 @@ this.makeInfallible = function makeInfallible(aHandler, aName) { } } } + +const executeSoon = aFn => { + Services.tm.mainThread.dispatch({ + run: this.makeInfallible(aFn) + }, Components.interfaces.nsIThread.DISPATCH_NORMAL); +} + +/** + * 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. + * @returns Promise + * A promise that is resolved once the whole array has been iterated + * over. + */ +this.yieldingEach = function yieldingEach(aArray, aFn) { + const deferred = promise.defer(); + + let i = 0; + let len = aArray.length; + + (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) { + executeSoon(loop); + return; + } + + try { + aFn(aArray[i++]); + } catch (e) { + deferred.reject(e); + return; + } + } + + deferred.resolve(); + }()); + + return deferred.promise; +} + + +/** + * 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. + */ +this.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; + } + }); +} + diff --git a/cocos/scripting/javascript/script/debugger/actors/root.js b/cocos/scripting/javascript/script/debugger/actors/root.js index 93fc857c0b..66b3814fd1 100644 --- a/cocos/scripting/javascript/script/debugger/actors/root.js +++ b/cocos/scripting/javascript/script/debugger/actors/root.js @@ -152,6 +152,7 @@ function RootActor(aConnection, aParameters) { this.conn = aConnection; this._parameters = aParameters; this._onTabListChanged = this.onTabListChanged.bind(this); + this._onAddonListChanged = this.onAddonListChanged.bind(this); this._extraActors = {}; } @@ -169,7 +170,8 @@ RootActor.prototype = { /* This is not in the spec, but it's used by tests. */ testConnectionPrefix: this.conn.prefix, traits: { - sources: true + sources: true, + editOuterHTML: true } }; }, @@ -192,6 +194,9 @@ RootActor.prototype = { if (this._parameters.tabList) { this._parameters.tabList.onListChanged = null; } + if (this._parameters.addonList) { + this._parameters.addonList.onListChanged = null; + } if (typeof this._parameters.onShutdown === 'function') { this._parameters.onShutdown(); } @@ -221,45 +226,47 @@ RootActor.prototype = { let newActorPool = new ActorPool(this.conn); let tabActorList = []; let selected; - for (let tabActor of tabList) { - if (tabActor.selected) { - selected = tabActorList.length; + 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); } - tabActor.parentID = this.actorID; - newActorPool.addActor(tabActor); - tabActorList.push(tabActor); - } - /* DebuggerServer.addGlobalActor support: create actors. */ - this._createExtraActors(this._parameters.globalActorFactories, newActorPool); + /* DebuggerServer.addGlobalActor support: create actors. */ + this._createExtraActors(this._parameters.globalActorFactories, newActorPool); - /* - * 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); + /* + * 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": [actor.grip() for (actor of tabActorList)], - }; + let reply = { + "from": this.actorID, + "selected": selected || 0, + "tabs": [actor.form() for (actor of tabActorList)], + }; - /* DebuggerServer.addGlobalActor support: name actors in 'listTabs' reply. */ - this._appendExtraActors(reply); + /* 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; + /* + * 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; + return reply; + }); }, onTabListChanged: function () { @@ -268,6 +275,39 @@ RootActor.prototype = { 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": [addonActor.form() for (addonActor of addonActors)] + }; + }); + }, + + onAddonListChanged: function () { + this.conn.send({ from: this.actorID, type: "addonListChanged" }); + this._parameters.addonList.onListChanged = null; + }, + /* This is not in the spec, but it's used by tests. */ onEcho: function (aRequest) { /* @@ -340,5 +380,6 @@ RootActor.prototype = { RootActor.prototype.requestTypes = { "listTabs": RootActor.prototype.onListTabs, + "listAddons": RootActor.prototype.onListAddons, "echo": RootActor.prototype.onEcho }; diff --git a/cocos/scripting/javascript/script/debugger/actors/script.js.REMOVED.git-id b/cocos/scripting/javascript/script/debugger/actors/script.js.REMOVED.git-id index 802edb4902..bfb23b9c5f 100644 --- a/cocos/scripting/javascript/script/debugger/actors/script.js.REMOVED.git-id +++ b/cocos/scripting/javascript/script/debugger/actors/script.js.REMOVED.git-id @@ -1 +1 @@ -85c713e3bdd74f54afb60036b9c11f754c55e267 \ No newline at end of file +ff368f19d84487b796f356122449d194b649bef4 \ No newline at end of file diff --git a/cocos/scripting/javascript/script/debugger/core/promise.js b/cocos/scripting/javascript/script/debugger/core/promise.js index a695f5a3ad..4be9d11588 100644 --- a/cocos/scripting/javascript/script/debugger/core/promise.js +++ b/cocos/scripting/javascript/script/debugger/core/promise.js @@ -1,7 +1,3 @@ -/* vim:set ts=2 sw=2 sts=2 expandtab */ -/*jshint undef: true es5: true node: true browser: true devel: true - forin: true latedef: false */ -/*global define: true, Cu: true, __URI__: true */ //;(function(id, factory) { // Module boilerplate :( // if (typeof(define) === 'function') { // RequireJS // define(factory); diff --git a/cocos/scripting/javascript/script/debugger/main.js b/cocos/scripting/javascript/script/debugger/main.js index 2c57735dbf..6ef7d671c1 100644 --- a/cocos/scripting/javascript/script/debugger/main.js +++ b/cocos/scripting/javascript/script/debugger/main.js @@ -34,6 +34,7 @@ loadSubScript.call(this, "resource://gre/modules/devtools/DevToolsUtils.js"); let wantLogging = true; let debuggerServer = null; +const promptConnections = true; function dumpn(str) { if (wantLogging) { @@ -153,6 +154,19 @@ var DebuggerServer = { */ chromeWindowType: null, + /** + * Set that to a function that will be called anytime a new connection + * is opened or one is closed. + */ + onConnectionChange: null, + + _fireConnectionChange: function(aWhat) { + if (this.onConnectionChange && + typeof this.onConnectionChange === "function") { + this.onConnectionChange(aWhat); + } + }, + /** * Prompt the user to accept or decline the incoming connection. This is the * default implementation that products embedding the debugger server may @@ -249,9 +263,12 @@ var DebuggerServer = { this.closeListener(); this.globalActorFactories = {}; this.tabActorFactories = {}; - delete this._allowConnection; + this._allowConnection = null; this._transportInitialized = false; this._initialized = false; + + this._fireConnectionChange("closed"); + dumpn("Debugger server is shut down."); }, @@ -309,8 +326,8 @@ var DebuggerServer = { /** * Install Firefox-specific actors. */ - addBrowserActors: function DS_addBrowserActors() { - this.chromeWindowType = "navigator:browser"; + addBrowserActors: function(aWindowType) { + this.chromeWindowType = aWindowType ? aWindowType : "navigator:browser"; this.addActors("resource://gre/modules/devtools/server/actors/webbrowser.js"); this.addActors("resource://gre/modules/devtools/server/actors/script.js"); this.addGlobalActor(this.ChromeDebuggerActor, "chromeDebugger"); @@ -322,7 +339,9 @@ var DebuggerServer = { this.addActors("resource://gre/modules/devtools/server/actors/styleeditor.js"); this.addActors("resource://gre/modules/devtools/server/actors/webapps.js"); this.registerModule("devtools/server/actors/inspector"); + this.registerModule("devtools/server/actors/webgl"); this.registerModule("devtools/server/actors/tracer"); + this.registerModule("devtools/server/actors/device"); }, /** @@ -339,19 +358,21 @@ var DebuggerServer = { this.addActors("resource://gre/modules/devtools/server/actors/gcli.js"); this.addActors("resource://gre/modules/devtools/server/actors/styleeditor.js"); this.registerModule("devtools/server/actors/inspector"); + this.registerModule("devtools/server/actors/webgl"); } - if (!("ContentTabActor" in DebuggerServer)) { + if (!("ContentAppActor" in DebuggerServer)) { this.addActors("resource://gre/modules/devtools/server/actors/childtab.js"); } }, /** - * Listens on the given port for remote debugger connections. + * Listens on the given port or socket file for remote debugger connections. * - * @param aPort int - * The port to listen on. + * @param aPortOrPath int, string + * If given an integer, the port to listen on. + * Otherwise, the path to the unix socket domain file to listen on. */ - openListener: function DS_openListener(aPort) { + openListener: function DS_openListener(aPortOrPath) { // if (!Services.prefs.getBoolPref("devtools.debugger.remote-enabled")) { // return false; // } @@ -370,11 +391,16 @@ var DebuggerServer = { let flags = 0; try { - let socket = new ServerSocket(aPort, flags, 4); - socket.asyncListen(this); - this._listener = socket; + let backlog = 4; + let socket; + let port = Number(aPortOrPath); + if (port) { + socket = new ServerSocket(port, flags, 4); + socket.asyncListen(this); + this._listener = socket; + } } catch (e) { - dumpn("Could not start debugging listener on port " + aPort + ": " + e); + dumpn("Could not start debugging listener on '" + aPortOrPath + "': " + e); throw "Cr.NS_ERROR_NOT_AVAILABLE"; } this._socketConnections++; @@ -465,7 +491,7 @@ var DebuggerServer = { onSocketAccepted: makeInfallible(function DS_onSocketAccepted(aSocket, aTransport) { - if (!this._allowConnection()) { + if (promptConnections && !this._allowConnection()) { return; } dumpn("New debugging connection on " + aTransport.host + ":" + aTransport.port); @@ -525,7 +551,7 @@ var DebuggerServer = { aTransport.send(conn.rootActor.sayHello()); } aTransport.ready(); - + this._fireConnectionChange("opened"); return conn; }, @@ -534,6 +560,7 @@ var DebuggerServer = { */ _connectionClosed: function DS_connectionClosed(aConnection) { delete this._connections[aConnection.prefix]; + this._fireConnectionChange("closed"); }, // DebuggerServer extension API. @@ -738,6 +765,15 @@ function DebuggerServerConnection(aPrefix, aTransport) this._actorPool = new ActorPool(this); this._extraPools = []; + // Responses to a given actor must be returned the the client + // in the same order as the requests that they're replying to, but + // Implementations might finish serving requests in a different + // order. To keep things in order we generate a promise for each + // request, chained to the promise for the request before it. + // This map stores the latest request promise in the chain, keyed + // by an actor ID string. + this._actorResponses = new Map; + /* * We can forward packets to other servers, if the actors on that server * all use a distinct prefix on their names. This is a map from prefixes @@ -847,13 +883,12 @@ DebuggerServerConnection.prototype = { }, _unknownError: function DSC__unknownError(aPrefix, aError) { - let errorString = safeErrorString(aError); - errorString += "\n" + aError.stack; + let errorString = aPrefix + ": " + safeErrorString(aError); // Cu.reportError(errorString); dumpn(errorString); return { error: "unknownError", - message: (aPrefix + "': " + errorString) + message: errorString }; }, @@ -916,7 +951,8 @@ DebuggerServerConnection.prototype = { let actor = this.getActor(aPacket.to); if (!actor) { this.transport.send({ from: aPacket.to ? aPacket.to : "root", - error: "noSuchActor" }); + error: "noSuchActor", + message: "No such actor for ID: " + aPacket.to }); return; } @@ -950,7 +986,7 @@ DebuggerServerConnection.prototype = { "error occurred while processing '" + aPacket.type, e)); } finally { - delete this.currentPacket; + this.currentPacket = undefined; } } else { ret = { error: "unrecognizedPacketType", @@ -965,19 +1001,23 @@ DebuggerServerConnection.prototype = { return; } - resolve(ret) - .then(function (aResponse) { - if (!aResponse.from) { - aResponse.from = aPacket.to; - } - return aResponse; - }) - .then(this.transport.send.bind(this.transport)) - .then(null, (e) => { - return this._unknownError( - "error occurred while processing '" + aPacket.type, - e); - }); + let pendingResponse = this._actorResponses.get(actor.actorID) || resolve(null); + let response = pendingResponse.then(() => { + return ret; + }).then(aResponse => { + if (!aResponse.from) { + aResponse.from = aPacket.to; + } + this.transport.send(aResponse); + }).then(null, (e) => { + let errorPacket = this._unknownError( + "error occurred while processing '" + aPacket.type, + e); + errorPacket.from = aPacket.to; + this.transport.send(errorPacket); + }); + + this._actorResponses.set(actor.actorID, response); }, /** diff --git a/cocos/scripting/javascript/script/debugger/transport.js b/cocos/scripting/javascript/script/debugger/transport.js index b5de443a06..e4a23989cf 100644 --- a/cocos/scripting/javascript/script/debugger/transport.js +++ b/cocos/scripting/javascript/script/debugger/transport.js @@ -6,7 +6,7 @@ "use strict"; // Components.utils.import("resource://gre/modules/NetUtil.jsm"); - +let wantLogging = true; /** * An adapter that handles data transfers between the debugger client and * server. It can work with both nsIPipe and nsIServerSocket transports so @@ -66,8 +66,7 @@ DebuggerTransport.prototype = { * they are passed to this method. */ send: function DT_send(aPacket) { - // TODO (bug 709088): remove pretty printing when the protocol is done. - let data = JSON.stringify(aPacket, null, 2); + let data = JSON.stringify(aPacket); // data = this._converter.ConvertFromUnicode(data); let data_for_len = utf16to8(data); @@ -157,10 +156,21 @@ DebuggerTransport.prototype = { // Well this is ugly. let sep = this._incoming.indexOf(':'); if (sep < 0) { + // Incoming packet length is too big anyway - drop the connection. + if (this._incoming.length > 20) { + this.close(); + } return false; } - let count = parseInt(this._incoming.substring(0, sep)); + let count = this._incoming.substring(0, sep); + // Check for a positive number with no garbage afterwards. + if (!/^[0-9]+$/.exec(count)) { + this.close(); + return false; + } + + count = +count; if (this._incoming.length - (sep + 1) < count) { // Don't have a complete request yet. return false; @@ -184,11 +194,18 @@ DebuggerTransport.prototype = { return true; } - dumpn("Got: " + packet); + if (wantLogging) { + dumpn("Got: " + JSON.stringify(parsed, null, 2)); + } + let self = this; // Services.tm.currentThread.dispatch(makeInfallible(function() { - self.hooks.onPacket(parsed); + // Ensure the hooks are still around by the time this runs (they will go + // away when the transport is closed). + if (self.hooks) { + self.hooks.onPacket(parsed); + } // }, "DebuggerTransport instance's this.hooks.onPacket"), 0); return true; @@ -258,7 +275,7 @@ LocalDebuggerTransport.prototype = { // Remove the reference to the other endpoint before calling close(), to // avoid infinite recursion. let other = this.other; - delete this.other; + this.other = null; other.close(); } if (this.hooks) { diff --git a/cocos/scripting/javascript/script/jsb_cocos2d.js b/cocos/scripting/javascript/script/jsb_cocos2d.js index 3237113d99..2ab020b08a 100644 --- a/cocos/scripting/javascript/script/jsb_cocos2d.js +++ b/cocos/scripting/javascript/script/jsb_cocos2d.js @@ -651,10 +651,13 @@ cc.Class.extend = function (prop) { function Class() { // All construction is actually done in the init method if (!initializing) { - if (!this.ctor) - cc.log("No ctor function found, please set `classes_need_extend` section at `ini` file as `tools/tojs/cocos2dx.ini`"); - else + if (!this.ctor) { + if (this.__nativeObj) + cc.log("No ctor function found! Please check whether `classes_need_extend` section in `ini` file like which in `tools/tojs/cocos2dx.ini`"); + } + else { this.ctor.apply(this, arguments); + } } } diff --git a/cocos/scripting/javascript/script/jsb_debugger.js b/cocos/scripting/javascript/script/jsb_debugger.js index f7ff5821ac..2e50643e79 100644 --- a/cocos/scripting/javascript/script/jsb_debugger.js +++ b/cocos/scripting/javascript/script/jsb_debugger.js @@ -1,12 +1,54 @@ -require('debugger/DevToolsUtils.js', "debug"); -require('debugger/core/promise.js', "debug"); -require('debugger/transport.js', "debug"); -require('debugger/actors/root.js', "debug"); -require('debugger/actors/script.js', "debug"); -require('debugger/main.js', "debug"); - +let promise = null; var globalDebuggee = null; +var gTestGlobals = []; + + +// 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); + 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([tabActor for (tabActor of this._tabActors)]); + } +}; + +function createRootActor(aConnection) +{ + let root = new RootActor(aConnection, + { tabList: new TestTabList(aConnection) }); + root.applicationType = "xpcshell-tests"; + return root; +} + function TestTabActor(aConnection, aGlobal) { this.conn = aConnection; @@ -14,19 +56,40 @@ function TestTabActor(aConnection, aGlobal) this._threadActor = new ThreadActor(this, this._global); this.conn.addActor(this._threadActor); this._attached = false; + this._extraActors = {}; } TestTabActor.prototype = { constructor: TestTabActor, actorPrefix: "TestTabActor", - grip: function() { - return { actor: this.actorID, title: "Hello Cocos2d-X JSB", url: "http://cocos2d-x.org" }; + get window() { + return { wrappedJSObject: this._global }; + }, + + form: function() { + let response = { actor: this.actorID, title: "Hello Cocos2d-X JSB", url: "http://cocos2d-x.org" }; + + // 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; - return { type: "tabAttached", threadActor: this._threadActor.actorID }; + + let response = { type: "tabAttached", threadActor: this._threadActor.actorID }; +// this._appendExtraActors(response); + + return response; }, onDetach: function(aRequest) { @@ -36,6 +99,10 @@ TestTabActor.prototype = { return { type: "detached" }; }, + /* Support for DebuggerServer.addTabActor. */ + // _createExtraActors: CommonCreateExtraActors, + // _appendExtraActors: CommonAppendExtraActors, + // Hooks for use by TestTabActors. addToParentPool: function(aActor) { this.conn.addActor(aActor); @@ -51,53 +118,22 @@ TestTabActor.prototype.requestTypes = { "detach": TestTabActor.prototype.onDetach }; -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, globalDebuggee); - 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, - iterator: function() { - for (let actor of this._tabActors) { - yield actor; - } - } -}; - this.processInput = function (inputstr) { - +cc.log("connected 001"); if (!inputstr) { return; } if (inputstr === "connected") { - + cc.log("connected 01"); DebuggerServer.createRootActor = (conn => { return new RootActor(conn, { tabList: new TestTabList(conn) }); }); + cc.log("connected 02"); DebuggerServer.init(() => true); DebuggerServer.openListener(5086); - + cc.log("connected 03"); if (debuggerServer && debuggerServer.onSocketAccepted) { var aTransport = { @@ -116,8 +152,9 @@ this.processInput = function (inputstr) { }; }, }; - + cc.log("connected 04"); debuggerServer.onSocketAccepted(null, aTransport); + cc.log("connected 05"); } return; } @@ -131,5 +168,20 @@ this.processInput = function (inputstr) { this._prepareDebugger = function (global) { globalDebuggee = global; + require = global.require; + cc = global.cc; + + require('debugger/DevToolsUtils.js', "debug"); + require('debugger/core/promise.js', "debug"); + require('debugger/transport.js', "debug"); + require('debugger/actors/root.js', "debug"); + require('debugger/actors/script.js', "debug"); + require('debugger/main.js', "debug"); + + promise = exports; + //DebuggerServer.addTestGlobal = function(aGlobal) { + gTestGlobals.push(global); + //}; + }; diff --git a/cocos/scripting/lua/bindings/Android.mk b/cocos/scripting/lua/bindings/Android.mk index fa92938dd4..5261274e43 100644 --- a/cocos/scripting/lua/bindings/Android.mk +++ b/cocos/scripting/lua/bindings/Android.mk @@ -37,7 +37,25 @@ LOCAL_SRC_FILES := CCLuaBridge.cpp \ ../../../../external/lua/tolua/tolua_map.c \ ../../../../external/lua/tolua/tolua_push.c \ ../../../../external/lua/tolua/tolua_to.c \ - tolua_fix.c + tolua_fix.c \ + socket/auxiliar.c \ + socket/luasocket_buffer.c \ + socket/except.c \ + socket/inet.c \ + socket/luasocket_io.c \ + socket/luasocket.c \ + socket/mime.c \ + socket/options.c \ + socket/select.c \ + socket/serial.c \ + socket/socket_scripts.c \ + socket/tcp.c \ + socket/timeout.c \ + socket/udp.c \ + socket/unix.c \ + socket/usocket.c \ + lua_extensions.c + LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../../../external/lua/tolua \ $(LOCAL_PATH)/../../auto-generated/lua-bindings \ diff --git a/cocos/scripting/lua/bindings/CCBProxy.cpp b/cocos/scripting/lua/bindings/CCBProxy.cpp index cab487b1d8..f0ba9f92f8 100644 --- a/cocos/scripting/lua/bindings/CCBProxy.cpp +++ b/cocos/scripting/lua/bindings/CCBProxy.cpp @@ -58,75 +58,75 @@ const char* CCBProxy::getNodeTypeName(Node* pNode) } if (NULL != dynamic_cast(pNode)) { - return "LabelTTF"; + return "cc.LabelTTF"; } if (NULL != dynamic_cast(pNode)) { - return "LabelBMFont"; + return "cc.LabelBMFont"; } if (NULL != dynamic_cast(pNode)) { - return "Sprite"; + return "cc.Sprite"; } if (NULL != dynamic_cast(pNode)) { - return "ControlButton"; + return "cc.ControlButton"; } if (NULL != dynamic_cast(pNode)) { - return "LayerGradient"; + return "cc.LayerGradient"; } if (NULL != dynamic_cast(pNode)) { - return "LayerColor"; + return "cc.LayerColor"; } if (NULL != dynamic_cast(pNode)) { - return "LayerGradient"; + return "cc.LayerGradient"; } if (NULL != dynamic_cast(pNode)) { - return "Menu"; + return "cc.Menu"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItemAtlasFont"; + return "cc.MenuItemAtlasFont"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItemFont"; + return "cc.MenuItemFont"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItemLabel"; + return "cc.MenuItemLabel"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItemImage"; + return "cc.MenuItemImage"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItemToggle"; + return "cc.MenuItemToggle"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItemSprite"; + return "cc.MenuItemSprite"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItem"; + return "cc.MenuItem"; } if (NULL != dynamic_cast(pNode)) { - return "Layer"; + return "cc.Layer"; } if (NULL != dynamic_cast(pNode)) { - return "String"; + return "cc.String"; } if (NULL != dynamic_cast(pNode)) { - return "ParticleSystemQuad"; + return "cc.ParticleSystemQuad"; } return "No Support"; diff --git a/cocos/scripting/lua/bindings/CCLuaEngine.cpp b/cocos/scripting/lua/bindings/CCLuaEngine.cpp index a05fa8f54d..502909695d 100644 --- a/cocos/scripting/lua/bindings/CCLuaEngine.cpp +++ b/cocos/scripting/lua/bindings/CCLuaEngine.cpp @@ -167,7 +167,7 @@ int LuaEngine::executeEvent(int nHandler, const char* pEventName, Object* pEvent _stack->pushString(pEventName); if (pEventSource) { - _stack->pushObject(pEventSource, pEventSourceClassName ? pEventSourceClassName : "CCObject"); + _stack->pushObject(pEventSource, pEventSourceClassName ? pEventSourceClassName : "cc.Object"); } int ret = _stack->executeFunctionByHandler(nHandler, pEventSource ? 2 : 1); _stack->clean(); @@ -329,7 +329,7 @@ int LuaEngine::handleMenuClickedEvent(void* data) return 0; _stack->pushInt(menuItem->getTag()); - _stack->pushObject(menuItem, "MenuItem"); + _stack->pushObject(menuItem, "cc.MenuItem"); int ret = _stack->executeFunctionByHandler(handler, 2); _stack->clean(); return ret; @@ -352,7 +352,7 @@ int LuaEngine::handleCallFuncActionEvent(void* data) Object* target = static_cast(basicScriptData->value); if (NULL != target) { - _stack->pushObject(target, "Node"); + _stack->pushObject(target, "cc.Node"); } int ret = _stack->executeFunctionByHandler(handler, target ? 1 : 0); _stack->clean(); @@ -447,7 +447,7 @@ int LuaEngine::handleCommonEvent(void* data) } else { - _stack->pushObject(commonInfo->eventSource, "Object"); + _stack->pushObject(commonInfo->eventSource, "cc.Object"); } } int ret = _stack->executeFunctionByHandler(commonInfo->handler, commonInfo->eventSource ? 2 : 1); @@ -585,7 +585,7 @@ int LuaEngine::handlerControlEvent(void* data) if (0 != handler) { - _stack->pushObject((Object*)basicScriptData->nativeObject, "Object"); + _stack->pushObject((Object*)basicScriptData->nativeObject, "cc.Object"); _stack->pushInt(controlEvents); ret = _stack->executeFunctionByHandler(handler, 2); _stack->clean(); @@ -612,7 +612,7 @@ int LuaEngine::handleEventAcc(void* data) lua_State* L = _stack->getLuaState(); LuaEventAccelerationData* eventListennerAcc = static_cast(basicScriptData->value); - toluafix_pushusertype_ccobject(L, eventListennerAcc->event->_ID, &(eventListennerAcc->event->_luaID), (void*)(eventListennerAcc->event),"Event"); + toluafix_pushusertype_ccobject(L, eventListennerAcc->event->_ID, &(eventListennerAcc->event->_luaID), (void*)(eventListennerAcc->event),"cc.Event"); Acceleration* accleration = static_cast(eventListennerAcc->acc); lua_pushnumber(L,accleration->x); lua_pushnumber(L,accleration->y); @@ -640,7 +640,7 @@ int LuaEngine::handleEventKeyboard(ScriptHandlerMgr::HandlerType type, void* dat lua_State* L = _stack->getLuaState(); lua_pushinteger(L, keyboardData->keyCode); - toluafix_pushusertype_ccobject(L, keyboardData->event->_ID, &(keyboardData->event->_luaID), (void*)(keyboardData->event),"Event"); + toluafix_pushusertype_ccobject(L, keyboardData->event->_ID, &(keyboardData->event->_luaID), (void*)(keyboardData->event),"cc.Event"); int ret = _stack->executeFunctionByHandler(handler, 2); _stack->clean(); return ret; @@ -667,8 +667,8 @@ int LuaEngine::handleEventTouch(ScriptHandlerMgr::HandlerType type, void* data) Touch* touch = touchData->touch; if (NULL != touch) { - _stack->pushObject(touchData->touch, "Touch"); - _stack->pushObject(touchData->event, "Event"); + _stack->pushObject(touchData->touch, "cc.Touch"); + _stack->pushObject(touchData->event, "cc.Event"); ret = _stack->executeFunctionByHandler(handler, 2); } _stack->clean(); @@ -702,11 +702,11 @@ int LuaEngine::handleEventTouches(ScriptHandlerMgr::HandlerType type,void* data) for (auto& touch : touchesData->touches) { _stack->pushInt(i); - _stack->pushObject(touch, "Touch"); + _stack->pushObject(touch, "cc.Touch"); lua_rawset(L, -3); ++i; } - _stack->pushObject(touchesData->event, "Event"); + _stack->pushObject(touchesData->event, "cc.Event"); ret = _stack->executeFunctionByHandler(handler, 2); _stack->clean(); @@ -731,7 +731,7 @@ int LuaEngine::handleEventMouse(ScriptHandlerMgr::HandlerType type, void* data) if (0 == handler) return 0; - _stack->pushObject(mouseData->event, "Event"); + _stack->pushObject(mouseData->event, "cc.Event"); int ret = _stack->executeFunctionByHandler(handler, 1); _stack->clean(); @@ -754,7 +754,7 @@ int LuaEngine::handleEvenCustom(void* data) return 0; lua_State* L = _stack->getLuaState(); - toluafix_pushusertype_ccobject(L, eventCustom->_ID, &(eventCustom->_luaID), (void*)(eventCustom),"EventCustom"); + toluafix_pushusertype_ccobject(L, eventCustom->_ID, &(eventCustom->_luaID), (void*)(eventCustom),"cc.EventCustom"); int ret = _stack->executeFunctionByHandler(handler, 1); _stack->clean(); @@ -859,14 +859,102 @@ int LuaEngine::handleEvent(ScriptHandlerMgr::HandlerType type, void* data, int n int LuaEngine::handleTableViewEvent(ScriptHandlerMgr::HandlerType type,void* data) { - CCASSERT(0, "TableView is not bound yet"); - return 0; + if (nullptr == data) + return 0; + + BasicScriptData* eventData = static_cast(data); + if (nullptr == eventData->nativeObject || nullptr == eventData->value) + return 0; + + LuaTableViewEventData* tableViewData = static_cast(eventData->value); + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)eventData->nativeObject, type); + + if (0 == handler) + return 0; + + Object* obj = static_cast(eventData->nativeObject); + if (nullptr == obj) + return 0; + + int ret = 0; + switch (type) + { + case ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL: + case ScriptHandlerMgr::HandlerType::SCROLLVIEW_ZOOM: + { + toluafix_pushusertype_ccobject(_stack->getLuaState(), obj->_ID, &(obj->_luaID), (void*)(obj),"cc.TableView"); + ret = _stack->executeFunctionByHandler(handler, 1); + } + break; + case ScriptHandlerMgr::HandlerType::TABLECELL_TOUCHED: + case ScriptHandlerMgr::HandlerType::TABLECELL_HIGHLIGHT: + case ScriptHandlerMgr::HandlerType::TABLECELL_UNHIGHLIGHT: + case ScriptHandlerMgr::HandlerType::TABLECELL_WILL_RECYCLE: + { + Object* cellObject = static_cast(tableViewData->value); + if (nullptr == cellObject) { + break; + } + toluafix_pushusertype_ccobject(_stack->getLuaState(), obj->_ID, &(obj->_luaID), (void*)(obj),"cc.TableView"); + toluafix_pushusertype_ccobject(_stack->getLuaState(), cellObject->_ID, &(cellObject->_luaID), (void*)(cellObject),"cc.TableViewCell"); + ret = _stack->executeFunctionByHandler(handler, 2); + } + break; + default: + break; + } + + return ret; + } int LuaEngine::handleTableViewEvent(ScriptHandlerMgr::HandlerType handlerType,void* data, int numResults, const std::function& func) { - CCASSERT(0, "TableView is not bound yet"); - return 0; + if (nullptr == data || numResults <= 0) + return 0; + + BasicScriptData* eventData = static_cast(data); + if (nullptr == eventData->nativeObject || nullptr == eventData->value) + return 0; + + LuaTableViewEventData* tableViewData = static_cast(eventData->value); + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)eventData->nativeObject, handlerType); + + if (0 == handler) + return 0; + + Object* obj = static_cast(eventData->nativeObject); + if (nullptr == obj) + return 0; + + int ret = 0; + switch (handlerType) + { + case ScriptHandlerMgr::HandlerType::TABLECELL_SIZE_FOR_INDEX: + { + toluafix_pushusertype_ccobject(_stack->getLuaState(), obj->_ID, &(obj->_luaID), (void*)(obj),"cc.TableView"); + _stack->pushLong(*((ssize_t*)tableViewData->value)); + ret = _stack->executeFunction(handler, 2, 2, func); + } + break; + case ScriptHandlerMgr::HandlerType::TABLECELL_AT_INDEX: + { + toluafix_pushusertype_ccobject(_stack->getLuaState(), obj->_ID, &(obj->_luaID), (void*)(obj),"cc.TableView"); + _stack->pushLong(*((ssize_t*)tableViewData->value)); + ret = _stack->executeFunction(handler, 2, 1, func); + } + break; + case ScriptHandlerMgr::HandlerType::TABLEVIEW_NUMS_OF_CELLS: + { + toluafix_pushusertype_ccobject(_stack->getLuaState(), obj->_ID, &(obj->_luaID), (void*)(obj),"cc.TableView"); + ret = _stack->executeFunction(handler, 1, 1, func); + } + break; + default: + break; + } + + return ret; } int LuaEngine::handleAssetsManagerEvent(ScriptHandlerMgr::HandlerType type,void* data) @@ -925,7 +1013,7 @@ int LuaEngine::handleStudioEventListener(ScriptHandlerMgr::HandlerType type,void if (0 == handler) return 0; - _stack->pushObject(listenerData->objTarget, "Object"); + _stack->pushObject(listenerData->objTarget, "cc.Object"); _stack->pushInt(listenerData->eventType); _stack->executeFunctionByHandler(handler, 2); @@ -956,7 +1044,7 @@ int LuaEngine::handleArmatureWrapper(ScriptHandlerMgr::HandlerType type,void* da { LuaArmatureMovementEventData* movementData = static_cast(wrapperData->eventData); - _stack->pushObject(movementData->objTarget, "Armature"); + _stack->pushObject(movementData->objTarget, "ccs.Armature"); _stack->pushInt(movementData->movementType); _stack->pushString(movementData->movementID.c_str()); _stack->executeFunctionByHandler(handler, 3); @@ -966,7 +1054,7 @@ int LuaEngine::handleArmatureWrapper(ScriptHandlerMgr::HandlerType type,void* da { LuaArmatureFrameEventData* frameData = static_cast(wrapperData->eventData); - _stack->pushObject(frameData->objTarget, "Bone"); + _stack->pushObject(frameData->objTarget, "ccs.Bone"); _stack->pushString(frameData->frameEventName.c_str()); _stack->pushInt(frameData->originFrameIndex); _stack->pushInt(frameData->currentFrameIndex); diff --git a/cocos/scripting/lua/bindings/CCLuaStack.cpp b/cocos/scripting/lua/bindings/CCLuaStack.cpp index 7215e6afac..b836f49853 100644 --- a/cocos/scripting/lua/bindings/CCLuaStack.cpp +++ b/cocos/scripting/lua/bindings/CCLuaStack.cpp @@ -31,6 +31,9 @@ extern "C" { #include "lualib.h" #include "lauxlib.h" #include "tolua_fix.h" +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) +#include "lua_extensions.h" +#endif } #include "Cocos2dxLuaLoader.h" @@ -146,12 +149,14 @@ bool LuaStack::init(void) {NULL, NULL} }; luaL_register(_state, "_G", global_functions); +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) + luaopen_lua_extensions(_state); +#endif g_luaType.clear(); register_all_cocos2dx(_state); register_all_cocos2dx_extension(_state); register_all_cocos2dx_deprecated(_state); register_cocos2dx_extension_CCBProxy(_state); - register_cocos2dx_event_releated(_state); tolua_opengl_open(_state); register_all_cocos2dx_gui(_state); register_all_cocos2dx_studio(_state); diff --git a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp index c04df69ce3..a2d97434c8 100644 --- a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp +++ b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp @@ -33,6 +33,7 @@ extern "C" { #endif std::unordered_map g_luaType; +std::unordered_map g_typeCast; #if COCOS2D_DEBUG >=1 void luaval_to_native_err(lua_State* L,const char* msg,tolua_Error* err) @@ -1070,7 +1071,7 @@ bool luavals_variadic_to_array(lua_State* L,int argc, Array** ret) else if (lua_isuserdata(L, i + 2)) { tolua_Error err; - if (!tolua_isusertype(L, i + 2, "Object", 0, &err)) + if (!tolua_isusertype(L, i + 2, "cc.Object", 0, &err)) { #if COCOS2D_DEBUG >=1 luaval_to_native_err(L,"#ferror:",&err); @@ -1614,7 +1615,7 @@ void physics_raycastinfo_to_luaval(lua_State* L, const PhysicsRayCastInfo& info) point_to_luaval(L, info.start); lua_rawset(L, -3); /* table[key] = value, L: table */ - lua_pushstring(L, "end"); /* L: table key */ + lua_pushstring(L, "ended"); /* L: table key */ point_to_luaval(L, info.end); lua_rawset(L, -3); /* table[key] = value, L: table */ @@ -1631,6 +1632,26 @@ void physics_raycastinfo_to_luaval(lua_State* L, const PhysicsRayCastInfo& info) lua_rawset(L, -3); /* table[key] = value, L: table */ } +void physics_contactdata_to_luaval(lua_State* L, const PhysicsContactData* data) +{ + if (nullptr == L || nullptr == data) + return; + + lua_newtable(L); /* L: table */ + + lua_pushstring(L, "points"); + points_to_luaval(L, data->points, data->count); + lua_rawset(L, -3); + + lua_pushstring(L, "normal"); + point_to_luaval(L, data->normal); + lua_rawset(L, -3); + + lua_pushstring(L, "POINT_MAX"); + lua_pushnumber(L, data->POINT_MAX); + lua_rawset(L, -3); +} + void size_to_luaval(lua_State* L,const Size& sz) { if (NULL == L) diff --git a/cocos/scripting/lua/bindings/LuaBasicConversions.h b/cocos/scripting/lua/bindings/LuaBasicConversions.h index 20e4f79d73..361f421b02 100644 --- a/cocos/scripting/lua/bindings/LuaBasicConversions.h +++ b/cocos/scripting/lua/bindings/LuaBasicConversions.h @@ -35,6 +35,7 @@ extern "C" { using namespace cocos2d; extern std::unordered_map g_luaType; +extern std::unordered_map g_typeCast; #if COCOS2D_DEBUG >=1 void luaval_to_native_err(lua_State* L,const char* msg,tolua_Error* err); @@ -87,7 +88,7 @@ bool luavals_variadic_to_ccvector( lua_State* L, int argc, cocos2d::Vector* r { tolua_Error err; //Undo check - if (!tolua_isusertype(L, i + 2, "Object", 0, &err)) + if (!tolua_isusertype(L, i + 2, "cc.Object", 0, &err)) { ok = false; break; @@ -204,6 +205,7 @@ extern void color4b_to_luaval(lua_State* L,const Color4B& cc); extern void color4f_to_luaval(lua_State* L,const Color4F& cc); extern void physics_material_to_luaval(lua_State* L,const PhysicsMaterial& pm); extern void physics_raycastinfo_to_luaval(lua_State* L, const PhysicsRayCastInfo& info); +extern void physics_contactdata_to_luaval(lua_State* L, const PhysicsContactData* data); extern void affinetransform_to_luaval(lua_State* L,const AffineTransform& inValue); extern void fontdefinition_to_luaval(lua_State* L,const FontDefinition& inValue); extern void array_to_luaval(lua_State* L,Array* inValue); diff --git a/cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id b/cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id index 42910a1d92..caaa6e32e0 100644 --- a/cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id +++ b/cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id @@ -1 +1 @@ -bcec27eb626dbcf63b810cce7f0f48b2d02c2158 \ No newline at end of file +bc70bac577759c95fbcf25da6937dbd9109da8d5 \ No newline at end of file diff --git a/cocos/scripting/lua/bindings/LuaOpengl.h b/cocos/scripting/lua/bindings/LuaOpengl.h index d4691677ae..9e04ea1322 100644 --- a/cocos/scripting/lua/bindings/LuaOpengl.h +++ b/cocos/scripting/lua/bindings/LuaOpengl.h @@ -36,7 +36,7 @@ extern "C" { class GLNode:public cocos2d::Node { - virtual void draw(); + virtual void draw() override; }; TOLUA_API int tolua_opengl_open(lua_State* tolua_S); diff --git a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp index 81317d65d7..c781d5b1ec 100644 --- a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp +++ b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp @@ -282,7 +282,7 @@ static int tolua_Cocos2d_ScriptHandlerMgr_registerScriptHandler00(lua_State* tol #ifndef TOLUA_RELEASE tolua_Error tolua_err; if (!tolua_isusertype(tolua_S,1,"ScriptHandlerMgr",0,&tolua_err) || - !tolua_isusertype(tolua_S, 2, "Object", 0, &tolua_err) || + !tolua_isusertype(tolua_S, 2, "cc.Object", 0, &tolua_err) || !toluafix_isfunction(tolua_S, 3, "LUA_FUNCTION", 0, &tolua_err) || !tolua_isnumber(tolua_S, 4, 0, &tolua_err) || !tolua_isnoobj(tolua_S,5,&tolua_err) ) @@ -316,7 +316,7 @@ static int tolua_Cocos2d_ScriptHandlerMgr_unregisterScriptHandler00(lua_State* t #ifndef TOLUA_RELEASE tolua_Error tolua_err; if (!tolua_isusertype(tolua_S,1,"ScriptHandlerMgr",0,&tolua_err) || - !tolua_isusertype(tolua_S, 2, "Object", 0, &tolua_err) || + !tolua_isusertype(tolua_S, 2, "cc.Object", 0, &tolua_err) || !tolua_isnumber(tolua_S, 3, 0, &tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) ) goto tolua_lerror; @@ -348,7 +348,7 @@ static int tolua_Cocos2d_ScriptHandlerMgr_removeObjectAllHandlers00(lua_State* t #ifndef TOLUA_RELEASE tolua_Error tolua_err; if (!tolua_isusertype(tolua_S,1,"ScriptHandlerMgr",0,&tolua_err) || - !tolua_isusertype(tolua_S, 2, "Object", 0, &tolua_err) || + !tolua_isusertype(tolua_S, 2, "cc.Object", 0, &tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else diff --git a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h index d1cb5d3a57..7cc980a37e 100644 --- a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h +++ b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.h @@ -155,6 +155,11 @@ public: EVENT_MOUSE_SCROLL, EVENT_SPINE, + + EVENT_PHYSICS_CONTACT_BEGIN, + EVENT_PHYSICS_CONTACT_PRESOLVE, + EVENT_PHYSICS_CONTACT_POSTSOLVE, + EVENT_PHYSICS_CONTACT_SEPERATE, }; typedef int Handler; diff --git a/cocos/scripting/lua/bindings/Lua_web_socket.cpp b/cocos/scripting/lua/bindings/Lua_web_socket.cpp index 4d3b8ae715..f508e720f6 100644 --- a/cocos/scripting/lua/bindings/Lua_web_socket.cpp +++ b/cocos/scripting/lua/bindings/Lua_web_socket.cpp @@ -164,7 +164,7 @@ static int tolua_collect_WebSocket (lua_State* tolua_S) /* function to release collected object via destructor */ static void tolua_reg_Web_Socket_type(lua_State* tolua_S) { - tolua_usertype(tolua_S, "WebSocket"); + tolua_usertype(tolua_S, "cc.WebSocket"); } /* method: create of class WebSocket */ @@ -174,7 +174,7 @@ static int tolua_Cocos2d_WebSocket_create00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertable(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertable(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !tolua_isstring(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -185,7 +185,7 @@ static int tolua_Cocos2d_WebSocket_create00(lua_State* tolua_S) const char* urlName = ((const char*) tolua_tostring(tolua_S,2,0)); LuaWebSocket *wSocket = new LuaWebSocket(); wSocket->init(*wSocket, urlName); - tolua_pushusertype(tolua_S,(void*)wSocket,"WebSocket"); + tolua_pushusertype(tolua_S,(void*)wSocket,"cc.WebSocket"); tolua_register_gc(tolua_S,lua_gettop(tolua_S)); } return 1; @@ -204,7 +204,7 @@ static int tolua_Cocos2d_WebSocket_createByAProtocol00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertable(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertable(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !tolua_isstring(tolua_S,2,0,&tolua_err) || !tolua_isstring(tolua_S,3,0,&tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) @@ -219,7 +219,7 @@ static int tolua_Cocos2d_WebSocket_createByAProtocol00(lua_State* tolua_S) protocols.push_back(protocol); LuaWebSocket *wSocket = new LuaWebSocket(); wSocket->init(*wSocket, urlName,&protocols); - tolua_pushusertype(tolua_S,(void*)wSocket,"WebSocket"); + tolua_pushusertype(tolua_S,(void*)wSocket,"cc.WebSocket"); tolua_register_gc(tolua_S,lua_gettop(tolua_S)); } return 1; @@ -238,7 +238,7 @@ static int tolua_Cocos2d_WebSocket_createByProtocolArray00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertable(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertable(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !tolua_isstring(tolua_S,2,0,&tolua_err) || !tolua_isusertable(tolua_S,3,"CCArray",0,&tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) @@ -262,7 +262,7 @@ static int tolua_Cocos2d_WebSocket_createByProtocolArray00(lua_State* tolua_S) } LuaWebSocket *wSocket = new LuaWebSocket(); wSocket->init(*wSocket, urlName,&protocols); - tolua_pushusertype(tolua_S,(void*)wSocket,"WebSocket"); + tolua_pushusertype(tolua_S,(void*)wSocket,"cc.WebSocket"); tolua_register_gc(tolua_S,lua_gettop(tolua_S)); } return 1; @@ -281,7 +281,7 @@ static int tolua_Cocos2d_WebSocket_getReadyState00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; @@ -312,7 +312,7 @@ static int tolua_Cocos2d_WebSocket_close00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; @@ -340,7 +340,7 @@ static int tolua_Cocos2d_WebSocket_sendString00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S, 1, "WebSocket", 0, &tolua_err) || + !tolua_isusertype(tolua_S, 1, "cc.WebSocket", 0, &tolua_err) || !tolua_isstring(tolua_S, 2, 0, &tolua_err) || !tolua_isnoobj(tolua_S, 3, &tolua_err) ) @@ -376,12 +376,12 @@ tolua_lerror: TOLUA_API int tolua_web_socket_open(lua_State* tolua_S){ tolua_open(tolua_S); tolua_reg_Web_Socket_type(tolua_S); - tolua_module(tolua_S,NULL,0); - tolua_beginmodule(tolua_S,NULL); + tolua_module(tolua_S,"cc",0); + tolua_beginmodule(tolua_S,"cc"); #ifdef __cplusplus - tolua_cclass(tolua_S,"WebSocket","WebSocket","",tolua_collect_WebSocket); + tolua_cclass(tolua_S,"WebSocket","cc.WebSocket","",tolua_collect_WebSocket); #else - tolua_cclass(tolua_S,"WebSocket","WebSocket","",NULL); + tolua_cclass(tolua_S,"WebSocket","cc.WebSocket","",NULL); #endif tolua_beginmodule(tolua_S,"WebSocket"); tolua_function(tolua_S, "create", tolua_Cocos2d_WebSocket_create00); @@ -400,7 +400,7 @@ int tolua_Cocos2d_WebSocket_registerScriptHandler00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !toluafix_isfunction(tolua_S,2,"LUA_FUNCTION",0,&tolua_err) || !tolua_isnumber(tolua_S,3,0,&tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) @@ -429,7 +429,7 @@ int tolua_Cocos2d_WebSocket_unregisterScriptHandler00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !tolua_isnumber(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -457,7 +457,7 @@ TOLUA_API int register_web_socket_manual(lua_State* tolua_S) if (nullptr == tolua_S) return 0 ; - lua_pushstring(tolua_S,"WebSocket"); + lua_pushstring(tolua_S,"cc.WebSocket"); lua_rawget(tolua_S,LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { diff --git a/cocos/scripting/lua/bindings/Lua_web_socket.h b/cocos/scripting/lua/bindings/Lua_web_socket.h index 5431209d12..d2463af3c2 100644 --- a/cocos/scripting/lua/bindings/Lua_web_socket.h +++ b/cocos/scripting/lua/bindings/Lua_web_socket.h @@ -39,10 +39,10 @@ class LuaWebSocket: public cocos2d::network::WebSocket,public cocos2d::network:: { public: virtual ~LuaWebSocket(); - virtual void onOpen(WebSocket* ws); - virtual void onMessage(WebSocket* ws, const WebSocket::Data& data); - virtual void onClose(WebSocket* ws); - virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error); + virtual void onOpen(WebSocket* ws) override; + virtual void onMessage(WebSocket* ws, const WebSocket::Data& data) override; + virtual void onClose(WebSocket* ws) override; + virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error) override; enum WebSocketScriptHandlerType { diff --git a/cocos/scripting/lua/bindings/liblua.vcxproj b/cocos/scripting/lua/bindings/liblua.vcxproj index c7fcc70043..f00dc2c19f 100644 --- a/cocos/scripting/lua/bindings/liblua.vcxproj +++ b/cocos/scripting/lua/bindings/liblua.vcxproj @@ -96,7 +96,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\lua\luajit\prebuilt\win32\*.*" "$ MaxSpeed true - $(ProjectDir);$(ProjectDir)..\..\..;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\editor-support\cocostudio;$(EngineRoot)cocos\editor-support\cocosbuilder;$(EngineRoot)cocos\audio\include;$(EngineRoot)extensions;$(EngineRoot)extensions\network;$(EngineRoot)external;$(EngineRoot)external\libwebsockets\win32\include;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\lua\luajit\include;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\gui;%(AdditionalIncludeDirectories) + $(ProjectDir);$(ProjectDir)..\..\..;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\editor-support\cocostudio;$(EngineRoot)cocos\editor-support\cocosbuilder;$(EngineRoot)cocos\editor-support\spine;$(EngineRoot)cocos\audio\include;$(EngineRoot)extensions;$(EngineRoot)extensions\network;$(EngineRoot)external;$(EngineRoot)external\libwebsockets\win32\include;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\lua\luajit\include;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\gui;%(AdditionalIncludeDirectories) WIN32;NDEBUG;_WINDOWS;LIBLUA_EXPORTS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) MultiThreadedDLL true @@ -152,8 +152,23 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\lua\luajit\prebuilt\win32\*.*" "$ + + + + + + + + + + + + + + + @@ -186,8 +201,24 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\lua\luajit\prebuilt\win32\*.*" "$ + + + + + + + + + + + + + + + + diff --git a/cocos/scripting/lua/bindings/liblua.vcxproj.filters b/cocos/scripting/lua/bindings/liblua.vcxproj.filters index 57c0335ab0..e7190e46e4 100644 --- a/cocos/scripting/lua/bindings/liblua.vcxproj.filters +++ b/cocos/scripting/lua/bindings/liblua.vcxproj.filters @@ -16,6 +16,9 @@ {19f563f0-e0ff-4500-890b-1755841d4ddb} + + {8815bb6e-fc9c-4cbf-b190-8b47169ed71f} + @@ -111,6 +114,51 @@ cocos2dx_support\generated + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support + @@ -209,6 +257,54 @@ cocos2dx_support\generated + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support\socket + + + cocos2dx_support + diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_coco_studio_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_coco_studio_manual.cpp index 5120f1d966..581279907d 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_coco_studio_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_coco_studio_manual.cpp @@ -83,7 +83,7 @@ static int lua_cocos2dx_ArmatureAnimation_setMovementEventCallFunc(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"ArmatureAnimation",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccs.ArmatureAnimation",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -153,7 +153,7 @@ static int lua_cocos2dx_ArmatureAnimation_setFrameEventCallFunc(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"ArmatureAnimation",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccs.ArmatureAnimation",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -217,7 +217,7 @@ tolua_lerror: static void extendArmatureAnimation(lua_State* L) { - lua_pushstring(L, "ArmatureAnimation"); + lua_pushstring(L, "ccs.ArmatureAnimation"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -237,7 +237,7 @@ static int lua_cocos2dx_ArmatureDataManager_addArmatureFileInfoAsyncCallFunc(lua #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"ArmatureDataManager",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccs.ArmatureDataManager",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -309,7 +309,7 @@ tolua_lerror: static void extendArmatureDataManager(lua_State* L) { - lua_pushstring(L, "ArmatureDataManager"); + lua_pushstring(L, "ccs.ArmatureDataManager"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -328,7 +328,7 @@ static int lua_cocos2dx_extension_Bone_setIgnoreMovementBoneData(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"Bone",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccs.Bone",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -373,7 +373,7 @@ static int lua_cocos2dx_extension_Bone_getIgnoreMovementBoneData(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"Bone",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccs.Bone",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -405,7 +405,7 @@ tolua_lerror: static void extendBone(lua_State* L) { - lua_pushstring(L, "Bone"); + lua_pushstring(L, "ccs.Bone"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_deprecated.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_deprecated.cpp index 0d6d053810..e907189be2 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_deprecated.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_deprecated.cpp @@ -2123,6 +2123,15 @@ static int tolua_bnd_cast_deprecated00(lua_State* tolua_S) } else { + std::string castName = tolua_tostring(tolua_S,2,NULL); + auto iter = g_typeCast.find(castName); + if (iter != g_typeCast.end() ) + { + CCLOG("Cast name %s doesn't include modular name which it belongs to,please add the modular name",iter->first.c_str()); + tolua_pushstring(tolua_S, iter->second.c_str()); + lua_insert(tolua_S, 2); + lua_pop(tolua_S, 1); + } return tolua_bnd_cast(tolua_S); } } diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp index 88b4693c01..739abb548c 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp @@ -42,6 +42,203 @@ USING_NS_CC; USING_NS_CC_EXT; using namespace cocostudio; +class LuaScrollViewDelegate:public Object, public ScrollViewDelegate +{ +public: + virtual ~LuaScrollViewDelegate() + {} + + virtual void scrollViewDidScroll(ScrollView* view) override + { + if (nullptr != view) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)view, ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL); + if (0 != handler) + { + CommonScriptData data(handler,""); + ScriptEvent event(kCommonEvent,(void*)&data); + LuaEngine::getInstance()->sendEvent(&event); + } + + } + } + + virtual void scrollViewDidZoom(ScrollView* view) override + { + if (nullptr != view) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)view, ScriptHandlerMgr::HandlerType::SCROLLVIEW_ZOOM); + if (0 != handler) + { + CommonScriptData data(handler,""); + ScriptEvent event(kCommonEvent,(void*)&data); + LuaEngine::getInstance()->sendEvent(&event); + } + } + } +}; + +static int tolua_cocos2dx_ScrollView_setDelegate(lua_State* tolua_S) +{ + if (nullptr == tolua_S) + return 0; + + int argc = 0; + ScrollView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(tolua_S,1,"cc.ScrollView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (ScrollView*) tolua_tousertype(tolua_S,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(tolua_S,"invalid 'self' in function 'tolua_cocos2dx_ScrollView_setDelegate'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S) - 1; + + if (0 == argc) + { + LuaScrollViewDelegate* delegate = new LuaScrollViewDelegate(); + if (nullptr == delegate) + return 0; + + self->setUserObject(delegate); + self->setDelegate(delegate); + + delegate->release(); + + return 0; + } + + CCLOG("'setDelegate' function of ScrollView wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'setDelegate'.",&tolua_err); + return 0; +#endif +} + +static int tolua_cocos2d_ScrollView_registerScriptHandler(lua_State* tolua_S) +{ + if (NULL == tolua_S) + return 0; + + int argc = 0; + ScrollView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(tolua_S,1,"cc.ScrollView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(tolua_S,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(tolua_S,"invalid 'self' in function 'tolua_cocos2d_ScrollView_registerScriptHandler'\n", NULL); + return 0; + } +#endif + argc = lua_gettop(tolua_S) - 1; + if (2 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!toluafix_isfunction(tolua_S,2,"LUA_FUNCTION",0,&tolua_err) || + !tolua_isnumber(tolua_S, 3, 0, &tolua_err) ) + { + goto tolua_lerror; + } +#endif + LUA_FUNCTION handler = ( toluafix_ref_function(tolua_S,2,0)); + ScriptHandlerMgr::HandlerType handlerType = (ScriptHandlerMgr::HandlerType) ((int)tolua_tonumber(tolua_S,3,0) + (int)ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL); + + ScriptHandlerMgr::getInstance()->addObjectHandler((void*)self, handler, handlerType); + return 0; + } + + CCLOG("'registerScriptHandler' function of ScrollView has wrong number of arguments: %d, was expecting %d\n", argc, 2); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'registerScriptHandler'.",&tolua_err); + return 0; +#endif +} + +static int tolua_cocos2d_ScrollView_unregisterScriptHandler(lua_State* tolua_S) +{ + if (NULL == tolua_S) + return 0; + + int argc = 0; + ScrollView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(tolua_S,1,"cc.ScrollView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(tolua_S,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(tolua_S,"invalid 'self' in function 'tolua_cocos2d_ScrollView_unregisterScriptHandler'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(tolua_S) - 1; + + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isnumber(tolua_S, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + ScriptHandlerMgr::HandlerType handlerType = (ScriptHandlerMgr::HandlerType) ((int)tolua_tonumber(tolua_S,2,0) + (int)ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL); + ScriptHandlerMgr::getInstance()->removeObjectHandler((void*)self, handlerType); + return 0; + } + + CCLOG("'unregisterScriptHandler' function of ScrollView has wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'unregisterScriptHandler'.",&tolua_err); + return 0; +#endif +} + +static void extendScrollView(lua_State* tolua_S) +{ + lua_pushstring(tolua_S, "cc.ScrollView"); + lua_rawget(tolua_S, LUA_REGISTRYINDEX); + if (lua_istable(tolua_S,-1)) + { + lua_pushstring(tolua_S,"setDelegate"); + lua_pushcfunction(tolua_S,tolua_cocos2dx_ScrollView_setDelegate ); + lua_rawset(tolua_S,-3); + lua_pushstring(tolua_S,"registerScriptHandler"); + lua_pushcfunction(tolua_S,tolua_cocos2d_ScrollView_registerScriptHandler ); + lua_rawset(tolua_S,-3); + lua_pushstring(tolua_S,"unregisterScriptHandler"); + lua_pushcfunction(tolua_S,tolua_cocos2d_ScrollView_unregisterScriptHandler ); + lua_rawset(tolua_S,-3); + } + lua_pop(tolua_S, 1); +} + + static int tolua_cocos2d_Control_registerControlEventHandler(lua_State* tolua_S) { if (NULL == tolua_S) @@ -52,7 +249,7 @@ static int tolua_cocos2d_Control_registerControlEventHandler(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"Control",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.Control",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -108,7 +305,7 @@ static int tolua_cocos2d_control_unregisterControlEventHandler(lua_State* tolua_ #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"Control",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.Control",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -153,7 +350,7 @@ tolua_lerror: static void extendControl(lua_State* tolua_S) { - lua_pushstring(tolua_S, "Control"); + lua_pushstring(tolua_S, "cc.Control"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -177,7 +374,7 @@ static int tolua_cocos2d_EditBox_registerScriptEditBoxHandler(lua_State* tolua_S #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"EditBox",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.EditBox",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -226,7 +423,7 @@ static int tolua_cocos2d_EditBox_unregisterScriptEditBoxHandler(lua_State* tolua #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"EditBox",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.EditBox",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -258,7 +455,7 @@ tolua_lerror: static void extendEditBox(lua_State* tolua_S) { - lua_pushstring(tolua_S, "EditBox"); + lua_pushstring(tolua_S, "cc.EditBox"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -281,7 +478,7 @@ static int tolua_cocos2d_CCBProxy_create(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertable(tolua_S,1,"CCBProxy",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(tolua_S,1,"cc.CCBProxy",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(tolua_S) - 1; @@ -291,7 +488,7 @@ static int tolua_cocos2d_CCBProxy_create(lua_State* tolua_S) CCBProxy* tolua_ret = (CCBProxy*)CCBProxy::create(); int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int *pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"CCBProxy"); + toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"cc.CCBProxy"); return 1; } @@ -316,7 +513,7 @@ static int tolua_cocos2d_CCBProxy_createCCBReader(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"CCBProxy",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.CCBProxy",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -335,7 +532,7 @@ static int tolua_cocos2d_CCBProxy_createCCBReader(lua_State* tolua_S) CCBReader* tolua_ret = (CCBReader*) self->createCCBReader(); int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"CCBReader"); + toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"cc.CCBReader"); return 1; } @@ -366,7 +563,7 @@ static int tolua_cocos2d_CCBProxy_readCCBFromFile(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"CCBProxy",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.CCBProxy",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -384,7 +581,7 @@ static int tolua_cocos2d_CCBProxy_readCCBFromFile(lua_State* tolua_S) { #if COCOS2D_DEBUG >= 1 if (!tolua_isstring(tolua_S, 2, 0, &tolua_err)|| - !tolua_isusertype(tolua_S,3,"CCBReader",0,&tolua_err)|| + !tolua_isusertype(tolua_S,3,"cc.CCBReader",0,&tolua_err)|| !tolua_isboolean(tolua_S,4,1,&tolua_err ) ) goto tolua_lerror; @@ -395,7 +592,7 @@ static int tolua_cocos2d_CCBProxy_readCCBFromFile(lua_State* tolua_S) tolua_ret = (Node*) self->readCCBFromFile(ccbFilePath, ccbReader, setOwner); ID = (tolua_ret) ? (int)tolua_ret->_ID : -1; luaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"Node"); + toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"cc.Node"); return 1; } @@ -420,7 +617,7 @@ static int tolua_cocos2d_CCBProxy_getNodeTypeName(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"CCBProxy",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.CCBProxy",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -437,7 +634,7 @@ static int tolua_cocos2d_CCBProxy_getNodeTypeName(lua_State* tolua_S) if (1 == argc) { #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"Node",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.Node",0,&tolua_err)) goto tolua_lerror; #endif Node* node = static_cast(tolua_tousertype(tolua_S,2,0)); @@ -466,7 +663,7 @@ static int tolua_cocos2d_CCBProxy_setCallback(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"CCBProxy",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.CCBProxy",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -482,7 +679,7 @@ static int tolua_cocos2d_CCBProxy_setCallback(lua_State* tolua_S) if ( argc >= 2 && argc <= 3 ) { #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,2,"Node",0,&tolua_err) || + if (!tolua_isusertype(tolua_S,2,"cc.Node",0,&tolua_err) || !toluafix_isfunction(tolua_S, 3, "LUA_FUNCTION", 0, &tolua_err) || !tolua_isnumber(tolua_S, 4, 1, &tolua_err) ) @@ -510,8 +707,8 @@ int register_cocos2dx_extension_CCBProxy(lua_State* tolua_S) { tolua_module(tolua_S,"cc",0); tolua_beginmodule(tolua_S,"cc"); - tolua_usertype(tolua_S,"CCBProxy"); - tolua_cclass(tolua_S,"CCBProxy","CCBProxy","Layer",NULL); + tolua_usertype(tolua_S,"cc.CCBProxy"); + tolua_cclass(tolua_S,"CCBProxy","cc.CCBProxy","cc.Layer",NULL); tolua_beginmodule(tolua_S,"CCBProxy"); tolua_function(tolua_S, "create", tolua_cocos2d_CCBProxy_create); tolua_function(tolua_S, "createCCBReader", tolua_cocos2d_CCBProxy_createCCBReader); @@ -522,7 +719,7 @@ int register_cocos2dx_extension_CCBProxy(lua_State* tolua_S) tolua_endmodule(tolua_S); std::string typeName = typeid(CCBProxy).name(); - g_luaType[typeName] = "CCBProxy"; + g_luaType[typeName] = "cc.CCBProxy"; return 1; } @@ -537,7 +734,7 @@ static int tolua_cocos2d_CCBReader_load(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"CCBReader",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.CCBReader",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -564,12 +761,12 @@ static int tolua_cocos2d_CCBReader_load(lua_State* tolua_S) Node* tolua_ret = (Node*) self->readNodeGraphFromFile(fileName); int ID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* luaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"Node"); + toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"cc.Node"); return 1; } #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S, 3, "Object", 0, &tolua_err)) + if (!tolua_isusertype(tolua_S, 3, "cc.Object", 0, &tolua_err)) goto tolua_lerror; #endif Object* owner = static_cast(tolua_tousertype(tolua_S, 3, 0)); @@ -579,7 +776,7 @@ static int tolua_cocos2d_CCBReader_load(lua_State* tolua_S) Node* tolua_ret = (Node*) self->readNodeGraphFromFile(fileName,owner); int ID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* luaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"Node"); + toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"cc.Node"); return 1; } @@ -591,7 +788,7 @@ static int tolua_cocos2d_CCBReader_load(lua_State* tolua_S) Node* tolua_ret = (Node*) self->readNodeGraphFromFile(fileName,owner,size); int ID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* luaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"Node"); + toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"cc.Node"); return 1; } @@ -608,7 +805,7 @@ tolua_lerror: static void extendCCBReader(lua_State* tolua_S) { - lua_pushstring(tolua_S, "CCBReader"); + lua_pushstring(tolua_S, "cc.CCBReader"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -630,7 +827,7 @@ static int tolua_cocos2d_CCBAnimationManager_setCallFuncForLuaCallbackNamed(lua_ #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"CCBAnimationManager",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.CCBAnimationManager",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -647,7 +844,7 @@ static int tolua_cocos2d_CCBAnimationManager_setCallFuncForLuaCallbackNamed(lua_ { #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,2, "CallFunc", 0, &tolua_err) || + if (!tolua_isusertype(tolua_S,2, "cc.CallFunc", 0, &tolua_err) || !tolua_isstring(tolua_S, 3, 0, &tolua_err) ) goto tolua_lerror; #endif @@ -675,7 +872,7 @@ tolua_lerror: static void extendCCBAnimationManager(lua_State* tolua_S) { - lua_pushstring(tolua_S, "CCBAnimationManager"); + lua_pushstring(tolua_S, "cc.CCBAnimationManager"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -692,7 +889,7 @@ public: virtual ~LuaAssetsManagerDelegateProtocol() {} - virtual void onProgress(int percent) + virtual void onProgress(int percent) override { int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this, ScriptHandlerMgr::HandlerType::ASSETSMANAGER_PROGRESS); if (0 != handler) @@ -703,7 +900,7 @@ public: } } - virtual void onSuccess() + virtual void onSuccess() override { int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this, ScriptHandlerMgr::HandlerType::ASSETSMANAGER_SUCCESS); if (0 != handler) @@ -714,7 +911,7 @@ public: } } - virtual void onError(AssetsManager::ErrorCode errorCode) + virtual void onError(AssetsManager::ErrorCode errorCode) override { int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this, ScriptHandlerMgr::HandlerType::ASSETSMANAGER_ERROR); if (0 != handler) @@ -736,7 +933,7 @@ static int lua_cocos2dx_AssetsManager_setDelegate(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"AssetsManager",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.AssetsManager",0,&tolua_err)) goto tolua_lerror; #endif self = (AssetsManager*) tolua_tousertype(L,1,0); @@ -791,7 +988,7 @@ tolua_lerror: static void extendAssetsManager(lua_State* L) { - lua_pushstring(L, "AssetsManager"); + lua_pushstring(L, "cc.AssetsManager"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -800,6 +997,473 @@ static void extendAssetsManager(lua_State* L) lua_pop(L, 1); } +#define KEY_TABLEVIEW_DATA_SOURCE "TableViewDataSource" +#define KEY_TABLEVIEW_DELEGATE "TableViewDelegate" + +class LUA_TableViewDelegate:public Object, public TableViewDelegate +{ +public: + LUA_TableViewDelegate(){} + + virtual ~LUA_TableViewDelegate(){} + + + virtual void scrollViewDidScroll(ScrollView* view) override + { + if (nullptr != view) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)view, ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL); + if (0 != handler) + { + LuaTableViewEventData eventData; + BasicScriptData data(view,&eventData); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL, (void*)&data); + } + } + } + + virtual void scrollViewDidZoom(ScrollView* view) override + { + if (nullptr != view) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)view, ScriptHandlerMgr::HandlerType::SCROLLVIEW_ZOOM); + if (0 != handler) + { + LuaTableViewEventData eventData; + BasicScriptData data(view,&eventData); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::SCROLLVIEW_ZOOM, (void*)&data); + } + } + } + + virtual void tableCellTouched(TableView* table, TableViewCell* cell) override + { + if (nullptr != table && nullptr != cell) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLECELL_TOUCHED); + if (0 != handler) + { + LuaTableViewEventData eventData(cell); + BasicScriptData data(table,&eventData); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLECELL_TOUCHED,(void*)&data); + } + } + } + + virtual void tableCellHighlight(TableView* table, TableViewCell* cell) override + { + if (nullptr != table && nullptr != cell) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLECELL_HIGHLIGHT); + if (0 != handler) + { + LuaTableViewEventData eventData(cell); + BasicScriptData data(table,&eventData); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLECELL_HIGHLIGHT,(void*)&data); + } + } + } + + virtual void tableCellUnhighlight(TableView* table, TableViewCell* cell) override + { + if (nullptr != table && nullptr != cell) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLECELL_UNHIGHLIGHT); + if (0 != handler) + { + LuaTableViewEventData eventData(cell); + BasicScriptData data(table,&eventData); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLECELL_UNHIGHLIGHT,(void*)&data); + } + } + } + + virtual void tableCellWillRecycle(TableView* table, TableViewCell* cell) override + { + if (nullptr != table && nullptr != cell) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLECELL_WILL_RECYCLE); + if (0 != handler) + { + LuaTableViewEventData eventData(cell); + BasicScriptData data(table,&eventData); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLECELL_WILL_RECYCLE,(void*)&data); + } + } + } +}; + +static int lua_cocos2dx_TableView_setDelegate(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + TableView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"cc.TableView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (TableView*) tolua_tousertype(L,1,0); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_TableView_setDelegate'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (0 == argc) + { + LUA_TableViewDelegate* delegate = new LUA_TableViewDelegate(); + if (nullptr == delegate) + return 0; + + Dictionary* userDict = static_cast(self->getUserObject()); + if (nullptr == userDict) + { + userDict = new Dictionary(); + if (NULL == userDict) + return 0; + + self->setUserObject(userDict); + userDict->release(); + } + + userDict->setObject(delegate, KEY_TABLEVIEW_DELEGATE); + self->setDelegate(delegate); + delegate->release(); + + return 0; + } + + CCLOG("'setDelegate' function of TableView wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'setDelegate'.",&tolua_err); + return 0; +#endif +} + +class LUA_TableViewDataSource:public Object,public TableViewDataSource +{ +public: + LUA_TableViewDataSource(){} + virtual ~LUA_TableViewDataSource(){} + + virtual Size tableCellSizeForIndex(TableView *table, ssize_t idx) override + { + if (nullptr != table ) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLECELL_SIZE_FOR_INDEX); + if (0 != handler) + { + LuaTableViewEventData eventData(&idx); + BasicScriptData data(table,&eventData); + float width = 0.0; + float height = 0.0; + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLECELL_SIZE_FOR_INDEX, (void*)&data,2,[&](lua_State* L,int numReturn){ + CCASSERT(numReturn == 2, "tableCellSizeForIndex return count error"); + ValueVector vec; + width = (float)tolua_tonumber(L, -1, 0); + lua_pop(L, 1); + height = (float)tolua_tonumber(L, -1, 0); + lua_pop(L, 1); + }); + + return Size(width, height); + } + } + + return Size::ZERO; + } + + virtual TableViewCell* tableCellAtIndex(TableView *table, ssize_t idx) override + { + if (nullptr != table ) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLECELL_AT_INDEX); + if (0 != handler) + { + LuaTableViewEventData eventData(&idx); + BasicScriptData data(table,&eventData); + TableViewCell* viewCell = nullptr; + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLECELL_AT_INDEX, (void*)&data, 1, [&](lua_State* L, int numReturn){ + CCASSERT(numReturn == 1, "tableCellAtIndex return count error"); + viewCell = static_cast(tolua_tousertype(L, -1, nullptr)); + lua_pop(L, 1); + }); + + return viewCell; + } + } + + return NULL; + } + + virtual ssize_t numberOfCellsInTableView(TableView *table) override + { + if (nullptr != table ) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLEVIEW_NUMS_OF_CELLS); + if (0 != handler) + { + LuaTableViewEventData eventData; + BasicScriptData data(table,&eventData); + ssize_t counts = 0; + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLEVIEW_NUMS_OF_CELLS, (void*)&data,1, [&](lua_State* L, int numReturn){ + CCASSERT(numReturn == 1, "numberOfCellsInTableView return count error"); + counts = (ssize_t)tolua_tonumber(L, -1, 0); + lua_pop(L, 1); + }); + return counts; + } + } + return 0; + } +}; + +static int lua_cocos2dx_TableView_setDataSource(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + TableView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"cc.TableView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (TableView*) tolua_tousertype(L,1,0); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_TableView_setDataSource'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (0 == argc) + { + LUA_TableViewDataSource* dataSource = new LUA_TableViewDataSource(); + if (nullptr == dataSource) + return 0; + + Dictionary* userDict = static_cast(self->getUserObject()); + if (nullptr == userDict) + { + userDict = new Dictionary(); + if (NULL == userDict) + return 0; + + self->setUserObject(userDict); + userDict->release(); + } + + userDict->setObject(dataSource, KEY_TABLEVIEW_DATA_SOURCE); + + self->setDataSource(dataSource); + + dataSource->release(); + + return 0; + } + + CCLOG("'setDataSource' function of TableView wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'setDataSource'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_TableView_create(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertable(L,1,"cc.TableView",0,&tolua_err)) goto tolua_lerror; +#endif + + argc = lua_gettop(L) - 1; + + if (2 == argc || 1 == argc) + { + LUA_TableViewDataSource* dataSource = new LUA_TableViewDataSource(); + Size size; + ok &= luaval_to_size(L, 2, &size); + + TableView* ret = nullptr; + + if (1 == argc) + { + ret = TableView::create(dataSource, size); + } + else + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(L,3,"cc.Node",0,&tolua_err)) goto tolua_lerror; +#endif + Node* node = static_cast(tolua_tousertype(L, 3, nullptr)); + ret = TableView::create(dataSource, size, node); + } + + if (nullptr == ret) + return 0; + + ret->reloadData(); + + Dictionary* userDict = new Dictionary(); + userDict->setObject(dataSource, KEY_TABLEVIEW_DATA_SOURCE); + ret->setUserObject(userDict); + userDict->release(); + + dataSource->release(); + + + int nID = (int)ret->_ID; + int* pLuaID = &ret->_luaID; + toluafix_pushusertype_ccobject(L, nID, pLuaID, (void*)ret,"cc.TableView"); + + return 1; + } + CCLOG("'create' function of TableView wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'create'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2d_TableView_registerScriptHandler(lua_State* L) +{ + if (NULL == L) + return 0; + + int argc = 0; + TableView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"cc.TableView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(L,"invalid 'self' in function 'tolua_cocos2d_TableView_registerScriptHandler'\n", NULL); + return 0; + } +#endif + argc = lua_gettop(L) - 1; + if (2 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!toluafix_isfunction(L,2,"LUA_FUNCTION",0,&tolua_err) || + !tolua_isnumber(L, 3, 0, &tolua_err) ) + { + goto tolua_lerror; + } +#endif + LUA_FUNCTION handler = ( toluafix_ref_function(L,2,0)); + ScriptHandlerMgr::HandlerType handlerType = (ScriptHandlerMgr::HandlerType) ((int)tolua_tonumber(L,3,0) + (int)ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL); + + ScriptHandlerMgr::getInstance()->addObjectHandler((void*)self, handler, handlerType); + return 0; + } + + CCLOG("'registerScriptHandler' function of TableView has wrong number of arguments: %d, was expecting %d\n", argc, 2); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'registerScriptHandler'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2d_TableView_unregisterScriptHandler(lua_State* L) +{ + if (NULL == L) + return 0; + + int argc = 0; + TableView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"cc.TableView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(L,"invalid 'self' in function 'lua_cocos2d_TableView_unregisterScriptHandler'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isnumber(L, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + ScriptHandlerMgr::HandlerType handlerType = (ScriptHandlerMgr::HandlerType) ((int)tolua_tonumber(L,2,0) + (int)ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL); + ScriptHandlerMgr::getInstance()->removeObjectHandler((void*)self, handlerType); + return 0; + } + + CCLOG("'unregisterScriptHandler' function of TableView has wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'unregisterScriptHandler'.",&tolua_err); + return 0; +#endif +} + +static void extendTableView(lua_State* L) +{ + lua_pushstring(L, "cc.TableView"); + lua_rawget(L, LUA_REGISTRYINDEX); + if (lua_istable(L,-1)) + { + tolua_function(L, "setDelegate", lua_cocos2dx_TableView_setDelegate); + tolua_function(L, "setDataSource", lua_cocos2dx_TableView_setDataSource); + tolua_function(L, "create", lua_cocos2dx_TableView_create); + tolua_function(L, "registerScriptHandler", lua_cocos2d_TableView_registerScriptHandler); + tolua_function(L, "unregisterScriptHandler", lua_cocos2d_TableView_unregisterScriptHandler); + } + lua_pop(L, 1); +} + int register_all_cocos2dx_extension_manual(lua_State* tolua_S) { extendControl(tolua_S); @@ -807,5 +1471,7 @@ int register_all_cocos2dx_extension_manual(lua_State* tolua_S) extendCCBReader(tolua_S); extendCCBAnimationManager(tolua_S); extendAssetsManager(tolua_S); + extendScrollView(tolua_S); + extendTableView(tolua_S); return 0; } diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h index 1a76eaf316..b150bf3cbd 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h @@ -46,5 +46,16 @@ struct LuaAssetsManagerEventData } }; +struct LuaTableViewEventData +{ + void* value; + + // Constructor + LuaTableViewEventData(void* _value = nullptr) + :value(_value) + { + } +}; + #endif // #ifndef COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_LUA_COCOS2DX_EXTENSION_MANUAL_H diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_gui_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_gui_manual.cpp index ec8a23ccd8..b51979ff53 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_gui_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_gui_manual.cpp @@ -94,7 +94,7 @@ static int lua_cocos2dx_Widget_addTouchEventListener(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"Widget",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.Widget",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -145,7 +145,7 @@ tolua_lerror: static void extendWidget(lua_State* L) { - lua_pushstring(L, "Widget"); + lua_pushstring(L, "ccui.Widget"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -164,7 +164,7 @@ static int lua_cocos2dx_CheckBox_addEventListenerCheckBox(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"CheckBox",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.CheckBox",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -214,7 +214,7 @@ tolua_lerror: static void extendCheckBox(lua_State* L) { - lua_pushstring(L, "CheckBox"); + lua_pushstring(L, "ccui.CheckBox"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -233,7 +233,7 @@ static int lua_cocos2dx_Slider_addEventListenerSlider(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"Slider",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.Slider",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -283,7 +283,7 @@ tolua_lerror: static void extendSlider(lua_State* L) { - lua_pushstring(L, "Slider"); + lua_pushstring(L, "ccui.Slider"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -302,7 +302,7 @@ static int lua_cocos2dx_TextField_addEventListenerTextField(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"TextField",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.TextField",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -352,7 +352,7 @@ tolua_lerror: static void extendTextField(lua_State* L) { - lua_pushstring(L, "TextField"); + lua_pushstring(L, "ccui.TextField"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -371,7 +371,7 @@ static int lua_cocos2dx_PageView_addEventListenerPageView(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"PageView",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.PageView",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -421,7 +421,7 @@ tolua_lerror: static void extendPageView(lua_State* L) { - lua_pushstring(L, "PageView"); + lua_pushstring(L, "ccui.PageView"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -440,7 +440,7 @@ static int lua_cocos2dx_ListView_addEventListenerListView(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"ListView",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.ListView",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -490,7 +490,7 @@ tolua_lerror: static void extendListView(lua_State* L) { - lua_pushstring(L, "ListView"); + lua_pushstring(L, "ccui.ListView"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -509,7 +509,7 @@ static int lua_cocos2dx_LayoutParameter_setMargin(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"LayoutParameter",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.LayoutParameter",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -577,7 +577,7 @@ static int lua_cocos2dx_LayoutParameter_getMargin(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"LayoutParameter",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.LayoutParameter",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -628,7 +628,7 @@ tolua_lerror: static void extendLayoutParameter(lua_State* L) { - lua_pushstring(L, "LayoutParameter"); + lua_pushstring(L, "ccui.LayoutParameter"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id index e3c65441d6..ee22cb131d 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id @@ -1 +1 @@ -f916840e52bdfd7e7283cb9c70ebfaf1c23b9301 \ No newline at end of file +c5f8d4a3ea721a2ecb36fe381430b7ac6fad1740 \ No newline at end of file diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_physics_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_physics_manual.cpp index 0d11f0f9b4..884ba8d75d 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_physics_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_physics_manual.cpp @@ -29,7 +29,7 @@ int lua_cocos2dx_physics_PhysicsBody_getJoints(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsBody",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsBody",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsBody*)tolua_tousertype(tolua_S,1,0); @@ -69,7 +69,7 @@ int lua_cocos2dx_physics_PhysicsBody_getJoints(lua_State* tolua_S) if(name != g_luaType.end()){ className = name->second.c_str(); } else { - className = "PhysicsJoint"; + className = "cc.PhysicsJoint"; } lua_pushnumber(tolua_S, (lua_Number)indexTable); @@ -102,7 +102,7 @@ int lua_cocos2dx_physics_PhysicsWorld_getScene(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsWorld",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsWorld",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsWorld*)tolua_tousertype(tolua_S,1,0); @@ -129,7 +129,7 @@ int lua_cocos2dx_physics_PhysicsWorld_getScene(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "Scene"; + className = "cc.Scene"; } int ID = (int)(ret._ID); @@ -162,7 +162,7 @@ int lua_cocos2dx_physics_PhysicsWorld_rayCast(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsWorld",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsWorld",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsWorld*)tolua_tousertype(tolua_S,1,0); @@ -191,7 +191,7 @@ int lua_cocos2dx_physics_PhysicsWorld_rayCast(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsWorld"; + className = "cc.PhysicsWorld"; } tolua_pushusertype(tolua_S, (void*)(&world), className.c_str()); @@ -229,7 +229,7 @@ int lua_cocos2dx_physics_PhysicsWorld_queryRect(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsWorld",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsWorld",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsWorld*)tolua_tousertype(tolua_S,1,0); @@ -257,7 +257,7 @@ int lua_cocos2dx_physics_PhysicsWorld_queryRect(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsWorld"; + className = "cc.PhysicsWorld"; } tolua_pushusertype(tolua_S, (void*)(&world), className.c_str()); @@ -268,7 +268,7 @@ int lua_cocos2dx_physics_PhysicsWorld_queryRect(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsShape"; + className = "cc.PhysicsShape"; } toluafix_pushusertype_ccobject(tolua_S, shape._ID, &shape._luaID, (void*)(&shape), className.c_str()); return LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); @@ -305,7 +305,7 @@ int lua_cocos2dx_physics_PhysicsWorld_queryPoint(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsWorld",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsWorld",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsWorld*)tolua_tousertype(tolua_S,1,0); @@ -333,7 +333,7 @@ int lua_cocos2dx_physics_PhysicsWorld_queryPoint(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsWorld"; + className = "cc.PhysicsWorld"; } tolua_pushusertype(tolua_S, (void*)(&world), className.c_str()); @@ -344,7 +344,7 @@ int lua_cocos2dx_physics_PhysicsWorld_queryPoint(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsShape"; + className = "cc.PhysicsShape"; } toluafix_pushusertype_ccobject(tolua_S, shape._ID, &shape._luaID, (void*)(&shape), className.c_str()); return LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); @@ -380,7 +380,7 @@ int lua_cocos2dx_physics_PhysicsBody_createPolygon(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertable(tolua_S,1,"PhysicsBody",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(tolua_S,1,"cc.PhysicsBody",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(tolua_S) - 1; @@ -409,7 +409,7 @@ int lua_cocos2dx_physics_PhysicsBody_createPolygon(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -450,7 +450,7 @@ int lua_cocos2dx_physics_PhysicsBody_createPolygon(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -493,7 +493,7 @@ int lua_cocos2dx_physics_PhysicsBody_createPolygon(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -527,7 +527,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgePolygon(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertable(tolua_S,1,"PhysicsBody",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(tolua_S,1,"cc.PhysicsBody",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(tolua_S) - 1; @@ -556,7 +556,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgePolygon(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -597,7 +597,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgePolygon(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -640,7 +640,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgePolygon(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -674,7 +674,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeChain(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertable(tolua_S,1,"PhysicsBody",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(tolua_S,1,"cc.PhysicsBody",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(tolua_S) - 1; @@ -703,7 +703,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeChain(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -744,7 +744,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeChain(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -787,7 +787,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeChain(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -821,7 +821,7 @@ int lua_cocos2dx_physics_PhysicsShape_recenterPoints(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertable(tolua_S,1,"PhysicsShape",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(tolua_S,1,"cc.PhysicsShape",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(tolua_S) - 1; @@ -886,7 +886,7 @@ int lua_cocos2dx_physics_PhysicsShape_getPolyonCenter(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertable(tolua_S,1,"PhysicsShape",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(tolua_S,1,"cc.PhysicsShape",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(tolua_S) - 1; @@ -900,7 +900,6 @@ int lua_cocos2dx_physics_PhysicsShape_getPolyonCenter(lua_State* tolua_S) if (nullptr == arg0){ LUA_PRECONDITION( arg0, "Invalid Native Object"); }} while (0); - ok &= luaval_to_int32(tolua_S, 3,(int *)&arg1); if(!ok) { CC_SAFE_FREE(arg0); @@ -924,14 +923,13 @@ int lua_cocos2dx_physics_PhysicsShapeBox_getPoints(lua_State* tolua_S) { int argc = 0; cocos2d::PhysicsShapeBox* cobj = nullptr; - bool ok = true; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsShapeBox",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsShapeBox",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsShapeBox*)tolua_tousertype(tolua_S,1,0); @@ -967,14 +965,13 @@ int lua_cocos2dx_physics_PhysicsShapePolygon_getPoints(lua_State* tolua_S) { int argc = 0; cocos2d::PhysicsShapePolygon* cobj = nullptr; - bool ok = true; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsShapePolygon",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsShapePolygon",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsShapePolygon*)tolua_tousertype(tolua_S,1,0); @@ -1012,14 +1009,13 @@ int lua_cocos2dx_physics_PhysicsShapeEdgeBox_getPoints(lua_State* tolua_S) { int argc = 0; cocos2d::PhysicsShapeEdgeBox* cobj = nullptr; - bool ok = true; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsShapeEdgeBox",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsShapeEdgeBox",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsShapeEdgeBox*)tolua_tousertype(tolua_S,1,0); @@ -1057,14 +1053,13 @@ int lua_cocos2dx_physics_PhysicsShapeEdgePolygon_getPoints(lua_State* tolua_S) { int argc = 0; cocos2d::PhysicsShapeEdgePolygon* cobj = nullptr; - bool ok = true; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsShapeEdgePolygon",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsShapeEdgePolygon",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsShapeEdgePolygon*)tolua_tousertype(tolua_S,1,0); @@ -1102,14 +1097,13 @@ int lua_cocos2dx_physics_PhysicsShapeEdgeChain_getPoints(lua_State* tolua_S) { int argc = 0; cocos2d::PhysicsShapeEdgeChain* cobj = nullptr; - bool ok = true; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsShapeEdgeChain",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsShapeEdgeChain",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsShapeEdgeChain*)tolua_tousertype(tolua_S,1,0); @@ -1143,9 +1137,117 @@ tolua_lerror: return 0; } +static int tolua_cocos2dx_EventListenerPhysicsContact_registerScriptHandler(lua_State* tolua_S) +{ + if (nullptr == tolua_S) + return 0; + + int argc = 0; + EventListenerPhysicsContact* self = nullptr; +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(tolua_S, 1, "cc.EventListenerPhysicsContact", 0, &tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(tolua_S,1,0)); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(tolua_S,"invalid 'self' in function 'tolua_cocos2dx_EventListenerPhysicsContact_registerScriptHandler'\n", nullptr); + return 0; + } +#endif + argc = lua_gettop(tolua_S) - 1; + + if (argc == 2) + { +#if COCOS2D_DEBUG >= 1 + if (!toluafix_isfunction(tolua_S,2,"LUA_FUNCTION",0,&tolua_err) || + !tolua_isnumber(tolua_S, 3, 0, &tolua_err)) + { + goto tolua_lerror; + } +#endif + LUA_FUNCTION handler = toluafix_ref_function(tolua_S,2,0); + ScriptHandlerMgr::HandlerType type = static_cast((int)tolua_tonumber(tolua_S, 3, 0)); + switch (type) + { + case ScriptHandlerMgr::HandlerType::EVENT_PHYSICS_CONTACT_BEGIN: + { + ScriptHandlerMgr::getInstance()->addObjectHandler((void*)self, handler, type); + + self->onContactBegin = [handler](EventCustom* event, const PhysicsContact& contact) -> bool{ + LuaStack* stack = LuaEngine::getInstance()->getLuaStack(); + stack->pushObject(event, "cc.EventCustom"); + stack->pushObject(const_cast(&contact), "cc.PhysicsContact"); + bool ret = stack->executeFunctionByHandler(handler, 2); + stack->clean(); + + return ret; + }; + } + break; + case ScriptHandlerMgr::HandlerType::EVENT_PHYSICS_CONTACT_PRESOLVE: + { + ScriptHandlerMgr::getInstance()->addObjectHandler((void*)self, handler, type); + + self->onContactPreSolve = [handler](EventCustom* event, const PhysicsContact& contact, const PhysicsContactPreSolve& solve) -> bool{ + LuaStack* stack = LuaEngine::getInstance()->getLuaStack(); + stack->pushObject(event, "cc.EventCustom"); + stack->pushObject(const_cast(&contact), "cc.PhysicsContact"); + tolua_pushusertype(stack->getLuaState(), const_cast(&solve), "cc.PhysicsContactPreSolve"); + bool ret = stack->executeFunctionByHandler(handler, 3); + stack->clean(); + + return ret; + }; + } + break; + case ScriptHandlerMgr::HandlerType::EVENT_PHYSICS_CONTACT_POSTSOLVE: + { + ScriptHandlerMgr::getInstance()->addObjectHandler((void*)self, handler, type); + + self->onContactPostSolve = [handler](EventCustom* event, const PhysicsContact& contact, const PhysicsContactPostSolve& solve){ + LuaStack* stack = LuaEngine::getInstance()->getLuaStack(); + stack->pushObject(event, "cc.EventCustom"); + stack->pushObject(const_cast(&contact), "cc.PhysicsContact"); + tolua_pushusertype(stack->getLuaState(), const_cast(&solve), "cc.PhysicsContactPostSolve"); + stack->executeFunctionByHandler(handler, 3); + stack->clean(); + }; + } + break; + case ScriptHandlerMgr::HandlerType::EVENT_PHYSICS_CONTACT_SEPERATE: + { + ScriptHandlerMgr::getInstance()->addObjectHandler((void*)self, handler, type); + + self->onContactSeperate = [handler](EventCustom* event, const PhysicsContact& contact){ + LuaStack* stack = LuaEngine::getInstance()->getLuaStack(); + stack->pushObject(event, "cc.EventCustom"); + stack->pushObject(const_cast(&contact), "cc.PhysicsContact"); + stack->executeFunctionByHandler(handler, 2); + stack->clean(); + }; + } + break; + default: + break; + } + return 0; + } + + CCLOG("'registerScriptHandler' has wrong number of arguments: %d, was expecting %d\n", argc, 2); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'registerScriptHandler'.",&tolua_err); + return 0; +#endif +} + int register_all_cocos2dx_physics_manual(lua_State* tolua_S) { - lua_pushstring(tolua_S, "PhysicsBody"); + lua_pushstring(tolua_S, "cc.PhysicsBody"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1164,7 +1266,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsShape"); + lua_pushstring(tolua_S, "cc.PhysicsShape"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1177,7 +1279,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsShapeBox"); + lua_pushstring(tolua_S, "cc.PhysicsShapeBox"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1187,7 +1289,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsShapeEdgeBox"); + lua_pushstring(tolua_S, "cc.PhysicsShapeEdgeBox"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1197,7 +1299,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsShapePolygon"); + lua_pushstring(tolua_S, "cc.PhysicsShapePolygon"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1207,7 +1309,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsShapeEdgePolygon"); + lua_pushstring(tolua_S, "cc.PhysicsShapeEdgePolygon"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1217,7 +1319,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsShapeEdgeChain"); + lua_pushstring(tolua_S, "cc.PhysicsShapeEdgeChain"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1227,7 +1329,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsWorld"); + lua_pushstring(tolua_S, "cc.PhysicsWorld"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1259,9 +1361,16 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) lua_pushnumber(tolua_S, PhysicsWorld::DEBUGDRAW_ALL); lua_rawset(tolua_S,-3); } - lua_pop(tolua_S, 1); + lua_pushstring(tolua_S, "cc.EventListenerPhysicsContact"); + lua_rawget(tolua_S, LUA_REGISTRYINDEX); + if (lua_istable(tolua_S,-1)) + { + tolua_function(tolua_S, "registerScriptHandler", tolua_cocos2dx_EventListenerPhysicsContact_registerScriptHandler); + } + lua_pop(tolua_S, 1); + tolua_constant(tolua_S, "PHYSICS_INFINITY", PHYSICS_INFINITY); return 0; diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_spine_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_spine_manual.cpp index 593dd3f0a3..78c6e2b340 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_spine_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_spine_manual.cpp @@ -94,7 +94,7 @@ static int lua_cocos2dx_CCSkeletonAnimation_createWithFile(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertable(L,1,"SkeletonAnimation",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(L,1,"sp.SkeletonAnimation",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(L) - 1; @@ -115,7 +115,7 @@ static int lua_cocos2dx_CCSkeletonAnimation_createWithFile(lua_State* L) int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(L, nID, pLuaID, (void*)tolua_ret,"SkeletonAnimation"); + toluafix_pushusertype_ccobject(L, nID, pLuaID, (void*)tolua_ret,"sp.SkeletonAnimation"); return 1; } else if (3 == argc) { @@ -135,7 +135,7 @@ static int lua_cocos2dx_CCSkeletonAnimation_createWithFile(lua_State* L) int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(L, nID, pLuaID, (void*)tolua_ret,"SkeletonAnimation"); + toluafix_pushusertype_ccobject(L, nID, pLuaID, (void*)tolua_ret,"sp.SkeletonAnimation"); return 1; } @@ -148,12 +148,12 @@ tolua_lerror: #endif } -int tolua_Cocos2d_CCSkeletonAnimation_registerScriptHandler00(lua_State* tolua_S) +int tolua_Cocos2d_CCSkeletonAnimation_registerSpineEventHandler00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"SkeletonAnimation",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"sp.SkeletonAnimation",0,&tolua_err) || !toluafix_isfunction(tolua_S,2,"LUA_FUNCTION",0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -170,17 +170,17 @@ int tolua_Cocos2d_CCSkeletonAnimation_registerScriptHandler00(lua_State* tolua_S return 0; #ifndef TOLUA_RELEASE tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'registerScriptHandler'.",&tolua_err); + tolua_error(tolua_S,"#ferror in function 'registerSpineEventHandler'.",&tolua_err); return 0; #endif } -int tolua_Cocos2d_CCSkeletonAnimation_unregisterScriptHandler00(lua_State* tolua_S) +int tolua_Cocos2d_CCSkeletonAnimation_unregisterSpineEventHandler00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"SkeletonAnimation",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"sp.SkeletonAnimation",0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; @@ -205,7 +205,7 @@ static int tolua_Cocos2d_CCSkeletonAnimation_setTimeScale00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"SkeletonAnimation",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"sp.SkeletonAnimation",0,&tolua_err) || !tolua_isnumber(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -232,7 +232,7 @@ static int tolua_Cocos2d_CCSkeletonAnimation_setDebugSlots00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"SkeletonAnimation",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"sp.SkeletonAnimation",0,&tolua_err) || !tolua_isboolean(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -259,7 +259,7 @@ static int tolua_Cocos2d_CCSkeletonAnimation_setDebugBones00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"SkeletonAnimation",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"sp.SkeletonAnimation",0,&tolua_err) || !tolua_isboolean(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -286,7 +286,7 @@ static int tolua_Cocos2d_CCSkeletonAnimation_setPremultipliedAlpha00(lua_State* #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"SkeletonAnimation",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"sp.SkeletonAnimation",0,&tolua_err) || !tolua_isboolean(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -311,19 +311,19 @@ tolua_lerror: static int tolua_spine_SkeletoneAnimation_setBlendFunc(lua_State* tolua_S) { - return tolua_cocos2dx_setBlendFunc(tolua_S,"SkeletonAnimation"); + return tolua_cocos2dx_setBlendFunc(tolua_S,"sp.SkeletonAnimation"); } static void extendCCSkeletonAnimation(lua_State* L) { - lua_pushstring(L, "SkeletonAnimation"); + lua_pushstring(L, "sp.SkeletonAnimation"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { tolua_function(L, "create", lua_cocos2dx_CCSkeletonAnimation_createWithFile); - tolua_function(L, "registerScriptHandler", tolua_Cocos2d_CCSkeletonAnimation_registerScriptHandler00); - tolua_function(L, "unregisterScriptHandler", tolua_Cocos2d_CCSkeletonAnimation_unregisterScriptHandler00); + tolua_function(L, "registerSpineEventHandler", tolua_Cocos2d_CCSkeletonAnimation_registerSpineEventHandler00); + tolua_function(L, "unregisterSpineEventHandler", tolua_Cocos2d_CCSkeletonAnimation_unregisterSpineEventHandler00); tolua_function(L, "setBlendFunc", tolua_spine_SkeletoneAnimation_setBlendFunc); tolua_function(L, "setTimeScale", tolua_Cocos2d_CCSkeletonAnimation_setTimeScale00); tolua_function(L, "setDebugSlots", tolua_Cocos2d_CCSkeletonAnimation_setDebugSlots00); diff --git a/cocos/scripting/lua/bindings/lua_extensions.c b/cocos/scripting/lua/bindings/lua_extensions.c new file mode 100644 index 0000000000..e3f62e42cd --- /dev/null +++ b/cocos/scripting/lua/bindings/lua_extensions.c @@ -0,0 +1,37 @@ + +#include "lua_extensions.h" + +#if __cplusplus +extern "C" { +#endif +// socket +#include "socket/luasocket.h" +#include "socket/mime.h" +#include "socket/socket_scripts.h" + +static luaL_Reg luax_exts[] = { + {"socket.core", luaopen_socket_core}, + {"mime.core", luaopen_mime_core}, + {NULL, NULL} +}; + +void luaopen_lua_extensions(lua_State *L) +{ + // load extensions + luaL_Reg* lib = luax_exts; + lua_getglobal(L, "package"); + lua_getfield(L, -1, "preload"); + for (; lib->func; lib++) + { + lua_pushcfunction(L, lib->func); + lua_setfield(L, -2, lib->name); + } + lua_pop(L, 2); + + // load extensions script + luaopen_socket_scripts(L); +} + +#if __cplusplus +} // extern "C" +#endif diff --git a/cocos/scripting/lua/bindings/lua_extensions.h b/cocos/scripting/lua/bindings/lua_extensions.h new file mode 100644 index 0000000000..67727f057f --- /dev/null +++ b/cocos/scripting/lua/bindings/lua_extensions.h @@ -0,0 +1,23 @@ + +#ifndef __LUA_EXTRA_H_ +#define __LUA_EXTRA_H_ + +#if defined(_USRDLL) + #define LUA_EXTENSIONS_DLL __declspec(dllexport) +#else /* use a DLL library */ + #define LUA_EXTENSIONS_DLL +#endif + +#if __cplusplus +extern "C" { +#endif + +#include "lauxlib.h" + +void LUA_EXTENSIONS_DLL luaopen_lua_extensions(lua_State *L); + +#if __cplusplus +} +#endif + +#endif /* __LUA_EXTRA_H_ */ diff --git a/cocos/scripting/lua/bindings/lua_xml_http_request.cpp b/cocos/scripting/lua/bindings/lua_xml_http_request.cpp index 9a7b124ee9..9470afffb1 100644 --- a/cocos/scripting/lua/bindings/lua_xml_http_request.cpp +++ b/cocos/scripting/lua/bindings/lua_xml_http_request.cpp @@ -270,7 +270,7 @@ void LuaMinXmlHttpRequest::getByteData(unsigned char* byteData) /* function to regType */ static void lua_reg_xml_http_request(lua_State* L) { - tolua_usertype(L, "XMLHttpRequest"); + tolua_usertype(L, "cc.XMLHttpRequest"); } static int lua_collect_xml_http_request (lua_State* L) @@ -296,7 +296,7 @@ static int lua_cocos2dx_XMLHttpRequest_constructor(lua_State* L) self->autorelease(); int ID = self? (int)self->_ID : -1; int* luaID = self? &self->_luaID : NULL; - toluafix_pushusertype_ccobject(L, ID, luaID, (void*)self, "XMLHttpRequest"); + toluafix_pushusertype_ccobject(L, ID, luaID, (void*)self, "cc.XMLHttpRequest"); return 1; } @@ -316,7 +316,7 @@ static int lua_get_XMLHttpRequest_responseType(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -345,7 +345,7 @@ static int lua_set_XMLHttpRequest_responseType(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -388,7 +388,7 @@ static int lua_get_XMLHttpRequest_withCredentials(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -417,7 +417,7 @@ static int lua_set_XMLHttpRequest_withCredentials(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -457,7 +457,7 @@ static int lua_get_XMLHttpRequest_timeout(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -486,7 +486,7 @@ static int lua_set_XMLHttpRequest_timeout(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -526,7 +526,7 @@ static int lua_get_XMLHttpRequest_readyState(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -555,7 +555,7 @@ static int lua_get_XMLHttpRequest_status(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -584,7 +584,7 @@ static int lua_get_XMLHttpRequest_statusText(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -613,7 +613,7 @@ static int lua_get_XMLHttpRequest_responseText(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -640,7 +640,7 @@ static int lua_get_XMLHttpRequest_response(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -711,7 +711,7 @@ static int lua_cocos2dx_XMLHttpRequest_open(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -796,7 +796,7 @@ static int lua_cocos2dx_XMLHttpRequest_send(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -855,7 +855,7 @@ static int lua_cocos2dx_XMLHttpRequest_setRequestHeader(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -902,7 +902,7 @@ static int lua_cocos2dx_XMLHttpRequest_getAllResponseHeaders(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -948,7 +948,7 @@ static int lua_cocos2dx_XMLHttpRequest_getResponseHeader(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -1002,7 +1002,7 @@ static int lua_cocos2dx_XMLHttpRequest_registerScriptHandler(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -1046,7 +1046,7 @@ static int lua_cocos2dx_XMLHttpRequest_unregisterScriptHandler(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -1082,9 +1082,9 @@ TOLUA_API int register_xml_http_request(lua_State* L) { tolua_open(L); lua_reg_xml_http_request(L); - tolua_module(L,NULL,0); - tolua_beginmodule(L,NULL); - tolua_cclass(L,"XMLHttpRequest","XMLHttpRequest","Object",lua_collect_xml_http_request); + tolua_module(L,"cc",0); + tolua_beginmodule(L,"cc"); + tolua_cclass(L,"XMLHttpRequest","cc.XMLHttpRequest","cc.Object",lua_collect_xml_http_request); tolua_beginmodule(L,"XMLHttpRequest"); tolua_variable(L, "responseType", lua_get_XMLHttpRequest_responseType, lua_set_XMLHttpRequest_responseType); tolua_variable(L, "withCredentials", lua_get_XMLHttpRequest_withCredentials, lua_set_XMLHttpRequest_withCredentials); diff --git a/cocos/scripting/lua/bindings/lua_xml_http_request.h b/cocos/scripting/lua/bindings/lua_xml_http_request.h index 8d0ae45394..c76f1ba383 100644 --- a/cocos/scripting/lua/bindings/lua_xml_http_request.h +++ b/cocos/scripting/lua/bindings/lua_xml_http_request.h @@ -32,6 +32,8 @@ extern "C" { } #endif +#include +#include #include "network/HttpClient.h" diff --git a/cocos/scripting/lua/bindings/socket/auxiliar.c b/cocos/scripting/lua/bindings/socket/auxiliar.c new file mode 100644 index 0000000000..de625e9d74 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/auxiliar.c @@ -0,0 +1,158 @@ +/*=========================================================================*\ +* Auxiliar routines for class hierarchy manipulation +* LuaSocket toolkit +\*=========================================================================*/ +#include +#include + +#include "auxiliar.h" + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initializes the module +\*-------------------------------------------------------------------------*/ +int auxiliar_open(lua_State *L) { + (void) L; + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Creates a new class with given methods +* Methods whose names start with __ are passed directly to the metatable. +\*-------------------------------------------------------------------------*/ +void auxiliar_newclass(lua_State *L, const char *classname, luaL_Reg *func) { + luaL_newmetatable(L, classname); /* mt */ + /* create __index table to place methods */ + lua_pushstring(L, "__index"); /* mt,"__index" */ + lua_newtable(L); /* mt,"__index",it */ + /* put class name into class metatable */ + lua_pushstring(L, "class"); /* mt,"__index",it,"class" */ + lua_pushstring(L, classname); /* mt,"__index",it,"class",classname */ + lua_rawset(L, -3); /* mt,"__index",it */ + /* pass all methods that start with _ to the metatable, and all others + * to the index table */ + for (; func->name; func++) { /* mt,"__index",it */ + lua_pushstring(L, func->name); + lua_pushcfunction(L, func->func); + lua_rawset(L, func->name[0] == '_' ? -5: -3); + } + lua_rawset(L, -3); /* mt */ + lua_pop(L, 1); +} + +/*-------------------------------------------------------------------------*\ +* Prints the value of a class in a nice way +\*-------------------------------------------------------------------------*/ +int auxiliar_tostring(lua_State *L) { + char buf[32]; + if (!lua_getmetatable(L, 1)) goto error; + lua_pushstring(L, "__index"); + lua_gettable(L, -2); + if (!lua_istable(L, -1)) goto error; + lua_pushstring(L, "class"); + lua_gettable(L, -2); + if (!lua_isstring(L, -1)) goto error; + sprintf(buf, "%p", lua_touserdata(L, 1)); + lua_pushfstring(L, "%s: %s", lua_tostring(L, -1), buf); + return 1; +error: + lua_pushstring(L, "invalid object passed to 'auxiliar.c:__tostring'"); + lua_error(L); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Insert class into group +\*-------------------------------------------------------------------------*/ +void auxiliar_add2group(lua_State *L, const char *classname, const char *groupname) { + luaL_getmetatable(L, classname); + lua_pushstring(L, groupname); + lua_pushboolean(L, 1); + lua_rawset(L, -3); + lua_pop(L, 1); +} + +/*-------------------------------------------------------------------------*\ +* Make sure argument is a boolean +\*-------------------------------------------------------------------------*/ +int auxiliar_checkboolean(lua_State *L, int objidx) { + if (!lua_isboolean(L, objidx)) + auxiliar_typeerror(L, objidx, lua_typename(L, LUA_TBOOLEAN)); + return lua_toboolean(L, objidx); +} + +/*-------------------------------------------------------------------------*\ +* Return userdata pointer if object belongs to a given class, abort with +* error otherwise +\*-------------------------------------------------------------------------*/ +void *auxiliar_checkclass(lua_State *L, const char *classname, int objidx) { + void *data = auxiliar_getclassudata(L, classname, objidx); + if (!data) { + char msg[45]; + sprintf(msg, "%.35s expected", classname); + luaL_argerror(L, objidx, msg); + } + return data; +} + +/*-------------------------------------------------------------------------*\ +* Return userdata pointer if object belongs to a given group, abort with +* error otherwise +\*-------------------------------------------------------------------------*/ +void *auxiliar_checkgroup(lua_State *L, const char *groupname, int objidx) { + void *data = auxiliar_getgroupudata(L, groupname, objidx); + if (!data) { + char msg[45]; + sprintf(msg, "%.35s expected", groupname); + luaL_argerror(L, objidx, msg); + } + return data; +} + +/*-------------------------------------------------------------------------*\ +* Set object class +\*-------------------------------------------------------------------------*/ +void auxiliar_setclass(lua_State *L, const char *classname, int objidx) { + luaL_getmetatable(L, classname); + if (objidx < 0) objidx--; + lua_setmetatable(L, objidx); +} + +/*-------------------------------------------------------------------------*\ +* Get a userdata pointer if object belongs to a given group. Return NULL +* otherwise +\*-------------------------------------------------------------------------*/ +void *auxiliar_getgroupudata(lua_State *L, const char *groupname, int objidx) { + if (!lua_getmetatable(L, objidx)) + return NULL; + lua_pushstring(L, groupname); + lua_rawget(L, -2); + if (lua_isnil(L, -1)) { + lua_pop(L, 2); + return NULL; + } else { + lua_pop(L, 2); + return lua_touserdata(L, objidx); + } +} + +/*-------------------------------------------------------------------------*\ +* Get a userdata pointer if object belongs to a given class. Return NULL +* otherwise +\*-------------------------------------------------------------------------*/ +void *auxiliar_getclassudata(lua_State *L, const char *classname, int objidx) { + return luaL_checkudata(L, objidx, classname); +} + +/*-------------------------------------------------------------------------*\ +* Throws error when argument does not have correct type. +* Used to be part of lauxlib in Lua 5.1, was dropped from 5.2. +\*-------------------------------------------------------------------------*/ +int auxiliar_typeerror (lua_State *L, int narg, const char *tname) { + const char *msg = lua_pushfstring(L, "%s expected, got %s", tname, + luaL_typename(L, narg)); + return luaL_argerror(L, narg, msg); +} + diff --git a/cocos/scripting/lua/bindings/socket/auxiliar.h b/cocos/scripting/lua/bindings/socket/auxiliar.h new file mode 100644 index 0000000000..ea9901333d --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/auxiliar.h @@ -0,0 +1,47 @@ +#ifndef AUXILIAR_H +#define AUXILIAR_H +/*=========================================================================*\ +* Auxiliar routines for class hierarchy manipulation +* LuaSocket toolkit (but completely independent of other LuaSocket modules) +* +* A LuaSocket class is a name associated with Lua metatables. A LuaSocket +* group is a name associated with a class. A class can belong to any number +* of groups. This module provides the functionality to: +* +* - create new classes +* - add classes to groups +* - set the class of objects +* - check if an object belongs to a given class or group +* - get the userdata associated to objects +* - print objects in a pretty way +* +* LuaSocket class names follow the convention {}. Modules +* can define any number of classes and groups. The module tcp.c, for +* example, defines the classes tcp{master}, tcp{client} and tcp{server} and +* the groups tcp{client,server} and tcp{any}. Module functions can then +* perform type-checking on their arguments by either class or group. +* +* LuaSocket metatables define the __index metamethod as being a table. This +* table has one field for each method supported by the class, and a field +* "class" with the class name. +* +* The mapping from class name to the corresponding metatable and the +* reverse mapping are done using lauxlib. +\*=========================================================================*/ + +#include "lua.h" +#include "lauxlib.h" + +int auxiliar_open(lua_State *L); +void auxiliar_newclass(lua_State *L, const char *classname, luaL_Reg *func); +void auxiliar_add2group(lua_State *L, const char *classname, const char *group); +void auxiliar_setclass(lua_State *L, const char *classname, int objidx); +void *auxiliar_checkclass(lua_State *L, const char *classname, int objidx); +void *auxiliar_checkgroup(lua_State *L, const char *groupname, int objidx); +void *auxiliar_getclassudata(lua_State *L, const char *groupname, int objidx); +void *auxiliar_getgroupudata(lua_State *L, const char *groupname, int objidx); +int auxiliar_checkboolean(lua_State *L, int objidx); +int auxiliar_tostring(lua_State *L); +int auxiliar_typeerror(lua_State *L, int narg, const char *tname); + +#endif /* AUXILIAR_H */ diff --git a/cocos/scripting/lua/bindings/socket/except.c b/cocos/scripting/lua/bindings/socket/except.c new file mode 100644 index 0000000000..1d1ade0ee0 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/except.c @@ -0,0 +1,97 @@ +/*=========================================================================*\ +* Simple exception support +* LuaSocket toolkit +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "except.h" + +/*=========================================================================*\ +* Internal function prototypes. +\*=========================================================================*/ +static int global_protect(lua_State *L); +static int global_newtry(lua_State *L); +static int protected_(lua_State *L); +static int finalize(lua_State *L); +static int do_nothing(lua_State *L); + +/* except functions */ +static luaL_Reg func[] = { + {"newtry", global_newtry}, + {"protect", global_protect}, + {NULL, NULL} +}; + +/*-------------------------------------------------------------------------*\ +* Try factory +\*-------------------------------------------------------------------------*/ +static void wrap(lua_State *L) { + lua_newtable(L); + lua_pushnumber(L, 1); + lua_pushvalue(L, -3); + lua_settable(L, -3); + lua_insert(L, -2); + lua_pop(L, 1); +} + +static int finalize(lua_State *L) { + if (!lua_toboolean(L, 1)) { + lua_pushvalue(L, lua_upvalueindex(1)); + lua_pcall(L, 0, 0, 0); + lua_settop(L, 2); + wrap(L); + lua_error(L); + return 0; + } else return lua_gettop(L); +} + +static int do_nothing(lua_State *L) { + (void) L; + return 0; +} + +static int global_newtry(lua_State *L) { + lua_settop(L, 1); + if (lua_isnil(L, 1)) lua_pushcfunction(L, do_nothing); + lua_pushcclosure(L, finalize, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Protect factory +\*-------------------------------------------------------------------------*/ +static int unwrap(lua_State *L) { + if (lua_istable(L, -1)) { + lua_pushnumber(L, 1); + lua_gettable(L, -2); + lua_pushnil(L); + lua_insert(L, -2); + return 1; + } else return 0; +} + +static int protected_(lua_State *L) { + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + if (lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0) != 0) { + if (unwrap(L)) return 2; + else lua_error(L); + return 0; + } else return lua_gettop(L); +} + +static int global_protect(lua_State *L) { + lua_pushcclosure(L, protected_, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Init module +\*-------------------------------------------------------------------------*/ +int except_open(lua_State *L) { + luaL_openlib(L, NULL, func, 0); + return 0; +} diff --git a/cocos/scripting/lua/bindings/socket/except.h b/cocos/scripting/lua/bindings/socket/except.h new file mode 100644 index 0000000000..1e7a2455e7 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/except.h @@ -0,0 +1,33 @@ +#ifndef EXCEPT_H +#define EXCEPT_H +/*=========================================================================*\ +* Exception control +* LuaSocket toolkit (but completely independent from other modules) +* +* This provides support for simple exceptions in Lua. During the +* development of the HTTP/FTP/SMTP support, it became aparent that +* error checking was taking a substantial amount of the coding. These +* function greatly simplify the task of checking errors. +* +* The main idea is that functions should return nil as its first return +* value when it finds an error, and return an error message (or value) +* following nil. In case of success, as long as the first value is not nil, +* the other values don't matter. +* +* The idea is to nest function calls with the "try" function. This function +* checks the first value, and calls "error" on the second if the first is +* nil. Otherwise, it returns all values it received. +* +* The protect function returns a new function that behaves exactly like the +* function it receives, but the new function doesn't throw exceptions: it +* returns nil followed by the error message instead. +* +* With these two function, it's easy to write functions that throw +* exceptions on error, but that don't interrupt the user script. +\*=========================================================================*/ + +#include "lua.h" + +int except_open(lua_State *L); + +#endif diff --git a/cocos/scripting/lua/bindings/socket/inet.c b/cocos/scripting/lua/bindings/socket/inet.c new file mode 100644 index 0000000000..16f709387c --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/inet.c @@ -0,0 +1,528 @@ +/*=========================================================================*\ +* Internet domain functions +* LuaSocket toolkit +\*=========================================================================*/ +#include +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "inet.h" + +/*=========================================================================*\ +* Internal function prototypes. +\*=========================================================================*/ +static int inet_global_toip(lua_State *L); +static int inet_global_getaddrinfo(lua_State *L); +static int inet_global_tohostname(lua_State *L); +static int inet_global_getnameinfo(lua_State *L); +static void inet_pushresolved(lua_State *L, struct hostent *hp); +static int inet_global_gethostname(lua_State *L); + +/* DNS functions */ +static luaL_Reg func[] = { + { "toip", inet_global_toip}, + { "getaddrinfo", inet_global_getaddrinfo}, + { "tohostname", inet_global_tohostname}, + { "getnameinfo", inet_global_getnameinfo}, + { "gethostname", inet_global_gethostname}, + { NULL, NULL} +}; + +#ifdef _WINDOWS_ +/****luodx patch for windows xp start**/ +char* win32xp_inet_ntop(int family, PVOID src, char* dest, size_t length) +{ + char* result = inet_ntoa(*(IN_ADDR*)src); + if (result != NULL){ + strcpy(dest, result); + } + return result; +} + +int win32xp_inet_pton(int family, const char* string, PVOID dest) { + return inet_aton(string, (IN_ADDR*)dest); +} +/****luodx patch for windows xp end**/ +#endif + + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int inet_open(lua_State *L) +{ + lua_pushstring(L, "dns"); + lua_newtable(L); + luaL_openlib(L, NULL, func, 0); + lua_settable(L, -3); + return 0; +} + +/*=========================================================================*\ +* Global Lua functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Returns all information provided by the resolver given a host name +* or ip address +\*-------------------------------------------------------------------------*/ +static int inet_gethost(const char *address, struct hostent **hp) { + struct in_addr addr; + if (inet_aton(address, &addr)) + return socket_gethostbyaddr((char *) &addr, sizeof(addr), hp); + else + return socket_gethostbyname(address, hp); +} + +/*-------------------------------------------------------------------------*\ +* Returns all information provided by the resolver given a host name +* or ip address +\*-------------------------------------------------------------------------*/ +static int inet_global_tohostname(lua_State *L) { + const char *address = luaL_checkstring(L, 1); + struct hostent *hp = NULL; + int err = inet_gethost(address, &hp); + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, socket_hoststrerror(err)); + return 2; + } + lua_pushstring(L, hp->h_name); + inet_pushresolved(L, hp); + return 2; +} + +static int inet_global_getnameinfo(lua_State *L) { + int i, ret; + char host[1024]; + char serv[32]; + struct addrinfo hints; + struct addrinfo *resolved, *iter; + const char *node = luaL_optstring(L, 1, NULL); + const char *service = luaL_optstring(L, 2, NULL); + + if (!(node || service)) + luaL_error(L, "You have to specify a hostname, a service, or both"); + + memset(&hints, 0, sizeof(hints)); + hints.ai_socktype = SOCK_STREAM; + hints.ai_family = PF_UNSPEC; + + /* getaddrinfo must get a node and a service argument */ + ret = getaddrinfo(node ? node : "127.0.0.1", service ? service : "7", + &hints, &resolved); + if (ret != 0) { + lua_pushnil(L); + lua_pushstring(L, socket_gaistrerror(ret)); + return 2; + } + + lua_newtable(L); + for (i = 1, iter = resolved; iter; i++, iter = iter->ai_next) { + getnameinfo(iter->ai_addr, (socklen_t) iter->ai_addrlen, host, + node ? (socklen_t) sizeof(host) : 0, serv, service ? (socklen_t) sizeof(serv) : 0, 0); + + if (node) { + lua_pushnumber(L, i); + lua_pushstring(L, host); + lua_settable(L, -3); + } + } + freeaddrinfo(resolved); + + if (service) { + lua_pushstring(L, serv); + return 2; + } else { + return 1; + } +} + +/*-------------------------------------------------------------------------*\ +* Returns all information provided by the resolver given a host name +* or ip address +\*-------------------------------------------------------------------------*/ +static int inet_global_toip(lua_State *L) +{ + const char *address = luaL_checkstring(L, 1); + struct hostent *hp = NULL; + int err = inet_gethost(address, &hp); + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, socket_hoststrerror(err)); + return 2; + } + lua_pushstring(L, inet_ntoa(*((struct in_addr *) hp->h_addr))); + inet_pushresolved(L, hp); + return 2; +} + +int inet_optfamily(lua_State* L, int narg, const char* def) +{ + static const char* optname[] = { "unspec", "inet", "inet6", NULL }; + static int optvalue[] = { PF_UNSPEC, PF_INET, PF_INET6, 0 }; + + return optvalue[luaL_checkoption(L, narg, def, optname)]; +} + +int inet_optsocktype(lua_State* L, int narg, const char* def) +{ + static const char* optname[] = { "stream", "dgram", NULL }; + static int optvalue[] = { SOCK_STREAM, SOCK_DGRAM, 0 }; + + return optvalue[luaL_checkoption(L, narg, def, optname)]; +} + +static int inet_global_getaddrinfo(lua_State *L) +{ + const char *hostname = luaL_checkstring(L, 1); + struct addrinfo *iterator = NULL, *resolved = NULL; + struct addrinfo hints; + int i = 1, ret = 0; + memset(&hints, 0, sizeof(hints)); + hints.ai_socktype = SOCK_STREAM; + hints.ai_family = PF_UNSPEC; + ret = getaddrinfo(hostname, NULL, &hints, &resolved); + if (ret != 0) { + lua_pushnil(L); + lua_pushstring(L, socket_gaistrerror(ret)); + return 2; + } + lua_newtable(L); + for (iterator = resolved; iterator; iterator = iterator->ai_next) { + char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV]; + getnameinfo(iterator->ai_addr, (socklen_t) iterator->ai_addrlen, hbuf, + (socklen_t) sizeof(hbuf), sbuf, 0, NI_NUMERICHOST); + lua_pushnumber(L, i); + lua_newtable(L); + switch (iterator->ai_family) { + case AF_INET: + lua_pushliteral(L, "family"); + lua_pushliteral(L, "inet"); + lua_settable(L, -3); + break; + case AF_INET6: + lua_pushliteral(L, "family"); + lua_pushliteral(L, "inet6"); + lua_settable(L, -3); + break;; + } + lua_pushliteral(L, "addr"); + lua_pushstring(L, hbuf); + lua_settable(L, -3); + lua_settable(L, -3); + i++; + } + freeaddrinfo(resolved); + return 1; +} + + +/*-------------------------------------------------------------------------*\ +* Gets the host name +\*-------------------------------------------------------------------------*/ +static int inet_global_gethostname(lua_State *L) +{ + char name[257]; + name[256] = '\0'; + if (gethostname(name, 256) < 0) { + lua_pushnil(L); + lua_pushstring(L, socket_strerror(errno)); + return 2; + } else { + lua_pushstring(L, name); + return 1; + } +} + + + +/*=========================================================================*\ +* Lua methods +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Retrieves socket peer name +\*-------------------------------------------------------------------------*/ +int inet_meth_getpeername(lua_State *L, p_socket ps, int family) +{ + switch (family) { + case PF_INET: { + struct sockaddr_in peer; + socklen_t peer_len = sizeof(peer); + char name[INET_ADDRSTRLEN]; + if (getpeername(*ps, (SA *) &peer, &peer_len) < 0) { + lua_pushnil(L); + lua_pushstring(L, socket_strerror(errno)); + return 2; + } else { + my_inet_ntop(family, &peer.sin_addr, name, sizeof(name)); + lua_pushstring(L, name); + lua_pushnumber(L, ntohs(peer.sin_port)); + lua_pushliteral(L, "inet"); + return 3; + } + } + case PF_INET6: { + struct sockaddr_in6 peer; + socklen_t peer_len = sizeof(peer); + char name[INET6_ADDRSTRLEN]; + if (getpeername(*ps, (SA *) &peer, &peer_len) < 0) { + lua_pushnil(L); + lua_pushstring(L, socket_strerror(errno)); + return 2; + } else { + my_inet_ntop(family, &peer.sin6_addr, name, sizeof(name)); + lua_pushstring(L, name); + lua_pushnumber(L, ntohs(peer.sin6_port)); + lua_pushliteral(L, "inet6"); + return 3; + } + } + default: + lua_pushnil(L); + lua_pushfstring(L, "unknown family %d", family); + return 2; + } +} + +/*-------------------------------------------------------------------------*\ +* Retrieves socket local name +\*-------------------------------------------------------------------------*/ +int inet_meth_getsockname(lua_State *L, p_socket ps, int family) +{ + switch (family) { + case PF_INET: { + struct sockaddr_in local; + socklen_t local_len = sizeof(local); + char name[INET_ADDRSTRLEN]; + if (getsockname(*ps, (SA *) &local, &local_len) < 0) { + lua_pushnil(L); + lua_pushstring(L, socket_strerror(errno)); + return 2; + } else { + my_inet_ntop(family, &local.sin_addr, name, sizeof(name)); + lua_pushstring(L, name); + lua_pushnumber(L, ntohs(local.sin_port)); + lua_pushliteral(L, "inet"); + return 3; + } + } + case PF_INET6: { + struct sockaddr_in6 local; + socklen_t local_len = sizeof(local); + char name[INET6_ADDRSTRLEN]; + if (getsockname(*ps, (SA *) &local, &local_len) < 0) { + lua_pushnil(L); + lua_pushstring(L, socket_strerror(errno)); + return 2; + } else { + my_inet_ntop(family, &local.sin6_addr, name, sizeof(name)); + lua_pushstring(L, name); + lua_pushnumber(L, ntohs(local.sin6_port)); + lua_pushliteral(L, "inet6"); + return 3; + } + } + default: + lua_pushnil(L); + lua_pushfstring(L, "unknown family %d", family); + return 2; + } +} + +/*=========================================================================*\ +* Internal functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Passes all resolver information to Lua as a table +\*-------------------------------------------------------------------------*/ +static void inet_pushresolved(lua_State *L, struct hostent *hp) +{ + char **alias; + struct in_addr **addr; + int i, resolved; + lua_newtable(L); resolved = lua_gettop(L); + lua_pushstring(L, "name"); + lua_pushstring(L, hp->h_name); + lua_settable(L, resolved); + lua_pushstring(L, "ip"); + lua_pushstring(L, "alias"); + i = 1; + alias = hp->h_aliases; + lua_newtable(L); + if (alias) { + while (*alias) { + lua_pushnumber(L, i); + lua_pushstring(L, *alias); + lua_settable(L, -3); + i++; alias++; + } + } + lua_settable(L, resolved); + i = 1; + lua_newtable(L); + addr = (struct in_addr **) hp->h_addr_list; + if (addr) { + while (*addr) { + lua_pushnumber(L, i); + lua_pushstring(L, inet_ntoa(**addr)); + lua_settable(L, -3); + i++; addr++; + } + } + lua_settable(L, resolved); +} + +/*-------------------------------------------------------------------------*\ +* Tries to create a new inet socket +\*-------------------------------------------------------------------------*/ +const char *inet_trycreate(p_socket ps, int family, int type) { + return socket_strerror(socket_create(ps, family, type, 0)); +} + +/*-------------------------------------------------------------------------*\ +* "Disconnects" a DGRAM socket +\*-------------------------------------------------------------------------*/ +const char *inet_trydisconnect(p_socket ps, int family, p_timeout tm) +{ + switch (family) { + case PF_INET: { + struct sockaddr_in sin; + memset((char *) &sin, 0, sizeof(sin)); + sin.sin_family = AF_UNSPEC; + sin.sin_addr.s_addr = INADDR_ANY; + return socket_strerror(socket_connect(ps, (SA *) &sin, + sizeof(sin), tm)); + } + case PF_INET6: { + struct sockaddr_in6 sin6; + struct in6_addr addrany = IN6ADDR_ANY_INIT; + memset((char *) &sin6, 0, sizeof(sin6)); + sin6.sin6_family = AF_UNSPEC; +fprintf(stderr, "disconnecting\n"); + sin6.sin6_addr = addrany; + return socket_strerror(socket_connect(ps, (SA *) &sin6, + sizeof(sin6), tm)); + } + } + return NULL; +} + +/*-------------------------------------------------------------------------*\ +* Tries to connect to remote address (address, port) +\*-------------------------------------------------------------------------*/ +const char *inet_tryconnect(p_socket ps, const char *address, + const char *serv, p_timeout tm, struct addrinfo *connecthints) +{ + struct addrinfo *iterator = NULL, *resolved = NULL; + const char *err = NULL; + /* try resolving */ + err = socket_gaistrerror(getaddrinfo(address, serv, + connecthints, &resolved)); + if (err != NULL) { + if (resolved) freeaddrinfo(resolved); + return err; + } + for (iterator = resolved; iterator; iterator = iterator->ai_next) { + timeout_markstart(tm); + /* try connecting to remote address */ + err = socket_strerror(socket_connect(ps, (SA *) iterator->ai_addr, + (socklen_t) iterator->ai_addrlen, tm)); + /* if success, break out of loop */ + if (err == NULL) break; + } + freeaddrinfo(resolved); + /* here, if err is set, we failed */ + return err; +} + +/*-------------------------------------------------------------------------*\ +* Tries to accept a socket +\*-------------------------------------------------------------------------*/ +const char *inet_tryaccept(p_socket server, int family, p_socket client, p_timeout tm) +{ + socklen_t len; + t_sockaddr_storage addr; + if (family == PF_INET6) { + len = sizeof(struct sockaddr_in6); + } else { + len = sizeof(struct sockaddr_in); + } + return socket_strerror(socket_accept(server, client, (SA *) &addr, &len, tm)); +} + +/*-------------------------------------------------------------------------*\ +* Tries to bind socket to (address, port) +\*-------------------------------------------------------------------------*/ +const char *inet_trybind(p_socket ps, const char *address, const char *serv, + struct addrinfo *bindhints) +{ + struct addrinfo *iterator = NULL, *resolved = NULL; + const char *err = NULL; + t_socket sock = *ps; + /* try resolving */ + err = socket_gaistrerror(getaddrinfo(address, serv, bindhints, &resolved)); + if (err) { + if (resolved) freeaddrinfo(resolved); + return err; + } + /* iterate over resolved addresses until one is good */ + for (iterator = resolved; iterator; iterator = iterator->ai_next) { + if(sock == SOCKET_INVALID) { + err = socket_strerror(socket_create(&sock, iterator->ai_family, + iterator->ai_socktype, iterator->ai_protocol)); + if(err) + continue; + } + /* try binding to local address */ + err = socket_strerror(socket_bind(&sock, + (SA *) iterator->ai_addr, + (socklen_t) iterator->ai_addrlen)); + + /* keep trying unless bind succeeded */ + if (err) { + if(sock != *ps) + socket_destroy(&sock); + } else { + /* remember what we connected to, particularly the family */ + *bindhints = *iterator; + break; + } + } + /* cleanup and return error */ + freeaddrinfo(resolved); + *ps = sock; + return err; +} + +/*-------------------------------------------------------------------------*\ +* Some systems do not provide this so that we provide our own. It's not +* marvelously fast, but it works just fine. +\*-------------------------------------------------------------------------*/ +#ifdef INET_ATON +int inet_aton(const char *cp, struct in_addr *inp) +{ + unsigned int a = 0, b = 0, c = 0, d = 0; + int n = 0, r; + unsigned long int addr = 0; + r = sscanf(cp, "%u.%u.%u.%u%n", &a, &b, &c, &d, &n); + if (r == 0 || n == 0) return 0; + cp += n; + if (*cp) return 0; + if (a > 255 || b > 255 || c > 255 || d > 255) return 0; + if (inp) { + addr += a; addr <<= 8; + addr += b; addr <<= 8; + addr += c; addr <<= 8; + addr += d; + inp->s_addr = htonl(addr); + } + return 1; +} +#endif + + diff --git a/cocos/scripting/lua/bindings/socket/inet.h b/cocos/scripting/lua/bindings/socket/inet.h new file mode 100644 index 0000000000..9971002103 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/inet.h @@ -0,0 +1,56 @@ +#ifndef INET_H +#define INET_H +/*=========================================================================*\ +* Internet domain functions +* LuaSocket toolkit +* +* This module implements the creation and connection of internet domain +* sockets, on top of the socket.h interface, and the interface of with the +* resolver. +* +* The function inet_aton is provided for the platforms where it is not +* available. The module also implements the interface of the internet +* getpeername and getsockname functions as seen by Lua programs. +* +* The Lua functions toip and tohostname are also implemented here. +\*=========================================================================*/ +#include "lua.h" +#include "socket.h" +#include "timeout.h" + +#ifdef _WIN32 +#define INET_ATON +#endif + +int inet_open(lua_State *L); + +const char *inet_trycreate(p_socket ps, int family, int type); +const char *inet_tryconnect(p_socket ps, const char *address, + const char *serv, p_timeout tm, struct addrinfo *connecthints); +const char *inet_trybind(p_socket ps, const char *address, const char *serv, + struct addrinfo *bindhints); +const char *inet_trydisconnect(p_socket ps, int family, p_timeout tm); +const char *inet_tryaccept(p_socket server, int family, p_socket client, p_timeout tm); + +int inet_meth_getpeername(lua_State *L, p_socket ps, int family); +int inet_meth_getsockname(lua_State *L, p_socket ps, int family); + +int inet_optfamily(lua_State* L, int narg, const char* def); +int inet_optsocktype(lua_State* L, int narg, const char* def); + +#ifdef INET_ATON +int inet_aton(const char *cp, struct in_addr *inp); +#endif + +#ifndef _WINDOWS_ +#define my_inet_ntop(a,b,c,d) inet_ntop(a,b,c,d) +#define my_inet_pton(a,b,c) inet_pton(a,b,c) +#else +int win32xp_inet_pton(int family, const char* string, PVOID dest); +char* win32xp_inet_ntop(int family, PVOID src, char* dest, size_t length); +#define my_inet_ntop(a,b,c,d) win32xp_inet_ntop(a,b,c,d) +#define my_inet_pton(a,b,c) win32xp_inet_pton(a,b,c) +#endif + + +#endif /* INET_H */ diff --git a/cocos/scripting/lua/bindings/socket/luasocket.c b/cocos/scripting/lua/bindings/socket/luasocket.c new file mode 100644 index 0000000000..c86a3e86b0 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/luasocket.c @@ -0,0 +1,116 @@ +/*=========================================================================*\ +* LuaSocket toolkit +* Networking support for the Lua language +* Diego Nehab +* 26/11/1999 +* +* This library is part of an effort to progressively increase the network +* connectivity of the Lua language. The Lua interface to networking +* functions follows the Sockets API closely, trying to simplify all tasks +* involved in setting up both client and server connections. The provided +* IO routines, however, follow the Lua style, being very similar to the +* standard Lua read and write functions. +\*=========================================================================*/ + +/*=========================================================================*\ +* Standard include files +\*=========================================================================*/ +#include "lua.h" +#include "lauxlib.h" + +#if !defined(LUA_VERSION_NUM) || (LUA_VERSION_NUM < 501) +#include "compat-5.1.h" +#endif + +/*=========================================================================*\ +* LuaSocket includes +\*=========================================================================*/ +#include "luasocket.h" +#include "auxiliar.h" +#include "except.h" +#include "timeout.h" +#include "luasocket_buffer.h" +#include "inet.h" +#include "tcp.h" +#include "udp.h" +#include "select.h" + +/*-------------------------------------------------------------------------*\ +* Internal function prototypes +\*-------------------------------------------------------------------------*/ +static int global_skip(lua_State *L); +static int global_unload(lua_State *L); +static int base_open(lua_State *L); + +/*-------------------------------------------------------------------------*\ +* Modules and functions +\*-------------------------------------------------------------------------*/ +static const luaL_Reg mod[] = { + {"auxiliar", auxiliar_open}, + {"except", except_open}, + {"timeout", timeout_open}, + {"buffer", buffer_open}, + {"inet", inet_open}, + {"tcp", tcp_open}, + {"udp", udp_open}, + {"select", select_open}, + {NULL, NULL} +}; + +static luaL_Reg func[] = { + {"skip", global_skip}, + {"__unload", global_unload}, + {NULL, NULL} +}; + +/*-------------------------------------------------------------------------*\ +* Skip a few arguments +\*-------------------------------------------------------------------------*/ +static int global_skip(lua_State *L) { + int amount = luaL_checkint(L, 1); + int ret = lua_gettop(L) - amount - 1; + return ret >= 0 ? ret : 0; +} + +/*-------------------------------------------------------------------------*\ +* Unloads the library +\*-------------------------------------------------------------------------*/ +static int global_unload(lua_State *L) { + (void) L; + socket_close(); + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Setup basic stuff. +\*-------------------------------------------------------------------------*/ +static int base_open(lua_State *L) { + if (socket_open()) { + /* export functions (and leave namespace table on top of stack) */ + luaL_openlib(L, "socket", func, 0); +#ifdef LUASOCKET_DEBUG + lua_pushstring(L, "_DEBUG"); + lua_pushboolean(L, 1); + lua_rawset(L, -3); +#endif + /* make version string available to scripts */ + lua_pushstring(L, "_VERSION"); + lua_pushstring(L, LUASOCKET_VERSION); + lua_rawset(L, -3); + return 1; + } else { + lua_pushstring(L, "unable to initialize library"); + lua_error(L); + return 0; + } +} + +/*-------------------------------------------------------------------------*\ +* Initializes all library modules. +\*-------------------------------------------------------------------------*/ +LUASOCKET_API int luaopen_socket_core(lua_State *L) { + int i; + base_open(L); + for (i = 0; mod[i].name; i++) mod[i].func(L); + return 1; +} diff --git a/cocos/scripting/lua/bindings/socket/luasocket.h b/cocos/scripting/lua/bindings/socket/luasocket.h new file mode 100644 index 0000000000..f2ca3c159e --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/luasocket.h @@ -0,0 +1,34 @@ +#ifndef LUASOCKET_H +#define LUASOCKET_H +/*=========================================================================*\ +* LuaSocket toolkit +* Networking support for the Lua language +* Diego Nehab +* 9/11/1999 +\*=========================================================================*/ +#include "lua.h" + +/*-------------------------------------------------------------------------*\ +* Current socket library version +\*-------------------------------------------------------------------------*/ +#define LUASOCKET_VERSION "LuaSocket 2.1-rc1" +#define LUASOCKET_COPYRIGHT "Copyright (C) 1999-2012 Diego Nehab" +#define LUASOCKET_AUTHORS "Diego Nehab" + +/*-------------------------------------------------------------------------*\ +* This macro prefixes all exported API functions +\*-------------------------------------------------------------------------*/ +#ifndef LUASOCKET_API +#define LUASOCKET_API extern +#endif + +#if LUA_VERSION_NUM > 501 & !( defined LUA_COMPAT_MODULE) +# error Lua 5.2 requires LUA_COMPAT_MODULE defined for luaL_openlib +#endif + +/*-------------------------------------------------------------------------*\ +* Initializes the library. +\*-------------------------------------------------------------------------*/ +LUASOCKET_API int luaopen_socket_core(lua_State *L); + +#endif /* LUASOCKET_H */ diff --git a/cocos/scripting/lua/bindings/socket/luasocket_buffer.c b/cocos/scripting/lua/bindings/socket/luasocket_buffer.c new file mode 100644 index 0000000000..13140bccc0 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/luasocket_buffer.c @@ -0,0 +1,276 @@ +/*=========================================================================*\ +* Input/Output interface for Lua programs +* LuaSocket toolkit +\*=========================================================================*/ +#include "lua.h" +#include "lauxlib.h" + +#include "luasocket_buffer.h" + +/*=========================================================================*\ +* Internal function prototypes +\*=========================================================================*/ +static int recvraw(p_buffer buf, size_t wanted, luaL_Buffer *b); +static int recvline(p_buffer buf, luaL_Buffer *b); +static int recvall(p_buffer buf, luaL_Buffer *b); +static int buffer_get(p_buffer buf, const char **data, size_t *count); +static void buffer_skip(p_buffer buf, size_t count); +static int sendraw(p_buffer buf, const char *data, size_t count, size_t *sent); + +/* min and max macros */ +#ifndef MIN +#define MIN(x, y) ((x) < (y) ? x : y) +#endif +#ifndef MAX +#define MAX(x, y) ((x) > (y) ? x : y) +#endif + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int buffer_open(lua_State *L) { + (void) L; + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Initializes C structure +\*-------------------------------------------------------------------------*/ +void buffer_init(p_buffer buf, p_io io, p_timeout tm) { + buf->first = buf->last = 0; + buf->io = io; + buf->tm = tm; + buf->received = buf->sent = 0; + buf->birthday = timeout_gettime(); +} + +/*-------------------------------------------------------------------------*\ +* object:getstats() interface +\*-------------------------------------------------------------------------*/ +int buffer_meth_getstats(lua_State *L, p_buffer buf) { + lua_pushnumber(L, (lua_Number) buf->received); + lua_pushnumber(L, (lua_Number) buf->sent); + lua_pushnumber(L, timeout_gettime() - buf->birthday); + return 3; +} + +/*-------------------------------------------------------------------------*\ +* object:setstats() interface +\*-------------------------------------------------------------------------*/ +int buffer_meth_setstats(lua_State *L, p_buffer buf) { + buf->received = (long) luaL_optnumber(L, 2, (lua_Number) buf->received); + buf->sent = (long) luaL_optnumber(L, 3, (lua_Number) buf->sent); + if (lua_isnumber(L, 4)) buf->birthday = timeout_gettime() - lua_tonumber(L, 4); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* object:send() interface +\*-------------------------------------------------------------------------*/ +int buffer_meth_send(lua_State *L, p_buffer buf) { + int top = lua_gettop(L); + int err = IO_DONE; + size_t size = 0, sent = 0; + const char *data = luaL_checklstring(L, 2, &size); + long start = (long) luaL_optnumber(L, 3, 1); + long end = (long) luaL_optnumber(L, 4, -1); +#ifdef LUASOCKET_DEBUG + p_timeout tm = timeout_markstart(buf->tm); +#endif + if (start < 0) start = (long) (size+start+1); + if (end < 0) end = (long) (size+end+1); + if (start < 1) start = (long) 1; + if (end > (long) size) end = (long) size; + if (start <= end) err = sendraw(buf, data+start-1, end-start+1, &sent); + /* check if there was an error */ + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, buf->io->error(buf->io->ctx, err)); + lua_pushnumber(L, (lua_Number) (sent+start-1)); + } else { + lua_pushnumber(L, (lua_Number) (sent+start-1)); + lua_pushnil(L); + lua_pushnil(L); + } +#ifdef LUASOCKET_DEBUG + /* push time elapsed during operation as the last return value */ + lua_pushnumber(L, timeout_gettime() - timeout_getstart(tm)); +#endif + return lua_gettop(L) - top; +} + +/*-------------------------------------------------------------------------*\ +* object:receive() interface +\*-------------------------------------------------------------------------*/ +int buffer_meth_receive(lua_State *L, p_buffer buf) { + int err = IO_DONE, top = lua_gettop(L); + luaL_Buffer b; + size_t size; + const char *part = luaL_optlstring(L, 3, "", &size); +#ifdef LUASOCKET_DEBUG + p_timeout tm = timeout_markstart(buf->tm); +#endif + /* initialize buffer with optional extra prefix + * (useful for concatenating previous partial results) */ + luaL_buffinit(L, &b); + luaL_addlstring(&b, part, size); + /* receive new patterns */ + if (!lua_isnumber(L, 2)) { + const char *p= luaL_optstring(L, 2, "*l"); + if (p[0] == '*' && p[1] == 'l') err = recvline(buf, &b); + else if (p[0] == '*' && p[1] == 'a') err = recvall(buf, &b); + else luaL_argcheck(L, 0, 2, "invalid receive pattern"); + /* get a fixed number of bytes (minus what was already partially + * received) */ + } else { + double n = lua_tonumber(L, 2); + size_t wanted = (size_t) n; + luaL_argcheck(L, n >= 0, 2, "invalid receive pattern"); + if (size == 0 || wanted > size) + err = recvraw(buf, wanted-size, &b); + } + /* check if there was an error */ + if (err != IO_DONE) { + /* we can't push anyting in the stack before pushing the + * contents of the buffer. this is the reason for the complication */ + luaL_pushresult(&b); + lua_pushstring(L, buf->io->error(buf->io->ctx, err)); + lua_pushvalue(L, -2); + lua_pushnil(L); + lua_replace(L, -4); + } else { + luaL_pushresult(&b); + lua_pushnil(L); + lua_pushnil(L); + } +#ifdef LUASOCKET_DEBUG + /* push time elapsed during operation as the last return value */ + lua_pushnumber(L, timeout_gettime() - timeout_getstart(tm)); +#endif + return lua_gettop(L) - top; +} + +/*-------------------------------------------------------------------------*\ +* Determines if there is any data in the read buffer +\*-------------------------------------------------------------------------*/ +int buffer_isempty(p_buffer buf) { + return buf->first >= buf->last; +} + +/*=========================================================================*\ +* Internal functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Sends a block of data (unbuffered) +\*-------------------------------------------------------------------------*/ +#define STEPSIZE 8192 +static int sendraw(p_buffer buf, const char *data, size_t count, size_t *sent) { + p_io io = buf->io; + p_timeout tm = buf->tm; + size_t total = 0; + int err = IO_DONE; + while (total < count && err == IO_DONE) { + size_t done = 0; + size_t step = (count-total <= STEPSIZE)? count-total: STEPSIZE; + err = io->send(io->ctx, data+total, step, &done, tm); + total += done; + } + *sent = total; + buf->sent += total; + return err; +} + +/*-------------------------------------------------------------------------*\ +* Reads a fixed number of bytes (buffered) +\*-------------------------------------------------------------------------*/ +static int recvraw(p_buffer buf, size_t wanted, luaL_Buffer *b) { + int err = IO_DONE; + size_t total = 0; + while (err == IO_DONE) { + size_t count; const char *data; + err = buffer_get(buf, &data, &count); + count = MIN(count, wanted - total); + luaL_addlstring(b, data, count); + buffer_skip(buf, count); + total += count; + if (total >= wanted) break; + } + return err; +} + +/*-------------------------------------------------------------------------*\ +* Reads everything until the connection is closed (buffered) +\*-------------------------------------------------------------------------*/ +static int recvall(p_buffer buf, luaL_Buffer *b) { + int err = IO_DONE; + size_t total = 0; + while (err == IO_DONE) { + const char *data; size_t count; + err = buffer_get(buf, &data, &count); + total += count; + luaL_addlstring(b, data, count); + buffer_skip(buf, count); + } + if (err == IO_CLOSED) { + if (total > 0) return IO_DONE; + else return IO_CLOSED; + } else return err; +} + +/*-------------------------------------------------------------------------*\ +* Reads a line terminated by a CR LF pair or just by a LF. The CR and LF +* are not returned by the function and are discarded from the buffer +\*-------------------------------------------------------------------------*/ +static int recvline(p_buffer buf, luaL_Buffer *b) { + int err = IO_DONE; + while (err == IO_DONE) { + size_t count, pos; const char *data; + err = buffer_get(buf, &data, &count); + pos = 0; + while (pos < count && data[pos] != '\n') { + /* we ignore all \r's */ + if (data[pos] != '\r') luaL_addchar(b, data[pos]); + pos++; + } + if (pos < count) { /* found '\n' */ + buffer_skip(buf, pos+1); /* skip '\n' too */ + break; /* we are done */ + } else /* reached the end of the buffer */ + buffer_skip(buf, pos); + } + return err; +} + +/*-------------------------------------------------------------------------*\ +* Skips a given number of bytes from read buffer. No data is read from the +* transport layer +\*-------------------------------------------------------------------------*/ +static void buffer_skip(p_buffer buf, size_t count) { + buf->received += count; + buf->first += count; + if (buffer_isempty(buf)) + buf->first = buf->last = 0; +} + +/*-------------------------------------------------------------------------*\ +* Return any data available in buffer, or get more data from transport layer +* if buffer is empty +\*-------------------------------------------------------------------------*/ +static int buffer_get(p_buffer buf, const char **data, size_t *count) { + int err = IO_DONE; + p_io io = buf->io; + p_timeout tm = buf->tm; + if (buffer_isempty(buf)) { + size_t got; + err = io->recv(io->ctx, buf->data, BUF_SIZE, &got, tm); + buf->first = 0; + buf->last = got; + } + *count = buf->last - buf->first; + *data = buf->data + buf->first; + return err; +} diff --git a/cocos/scripting/lua/bindings/socket/luasocket_buffer.h b/cocos/scripting/lua/bindings/socket/luasocket_buffer.h new file mode 100644 index 0000000000..2456cd386b --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/luasocket_buffer.h @@ -0,0 +1,45 @@ +#ifndef BUF_H +#define BUF_H +/*=========================================================================*\ +* Input/Output interface for Lua programs +* LuaSocket toolkit +* +* Line patterns require buffering. Reading one character at a time involves +* too many system calls and is very slow. This module implements the +* LuaSocket interface for input/output on connected objects, as seen by +* Lua programs. +* +* Input is buffered. Output is *not* buffered because there was no simple +* way of making sure the buffered output data would ever be sent. +* +* The module is built on top of the I/O abstraction defined in io.h and the +* timeout management is done with the timeout.h interface. +\*=========================================================================*/ +#include "lua.h" + +#include "luasocket_io.h" +#include "timeout.h" + +/* buffer size in bytes */ +#define BUF_SIZE 8192 + +/* buffer control structure */ +typedef struct t_buffer_ { + double birthday; /* throttle support info: creation time, */ + size_t sent, received; /* bytes sent, and bytes received */ + p_io io; /* IO driver used for this buffer */ + p_timeout tm; /* timeout management for this buffer */ + size_t first, last; /* index of first and last bytes of stored data */ + char data[BUF_SIZE]; /* storage space for buffer data */ +} t_buffer; +typedef t_buffer *p_buffer; + +int buffer_open(lua_State *L); +void buffer_init(p_buffer buf, p_io io, p_timeout tm); +int buffer_meth_send(lua_State *L, p_buffer buf); +int buffer_meth_receive(lua_State *L, p_buffer buf); +int buffer_meth_getstats(lua_State *L, p_buffer buf); +int buffer_meth_setstats(lua_State *L, p_buffer buf); +int buffer_isempty(p_buffer buf); + +#endif /* BUF_H */ diff --git a/cocos/scripting/lua/bindings/socket/luasocket_io.c b/cocos/scripting/lua/bindings/socket/luasocket_io.c new file mode 100644 index 0000000000..74722a5abf --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/luasocket_io.c @@ -0,0 +1,30 @@ +/*=========================================================================*\ +* Input/Output abstraction +* LuaSocket toolkit +\*=========================================================================*/ +#include "luasocket_io.h" + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initializes C structure +\*-------------------------------------------------------------------------*/ +void io_init(p_io io, p_send send, p_recv recv, p_error error, void *ctx) { + io->send = send; + io->recv = recv; + io->error = error; + io->ctx = ctx; +} + +/*-------------------------------------------------------------------------*\ +* I/O error strings +\*-------------------------------------------------------------------------*/ +const char *io_strerror(int err) { + switch (err) { + case IO_DONE: return NULL; + case IO_CLOSED: return "closed"; + case IO_TIMEOUT: return "timeout"; + default: return "unknown error"; + } +} diff --git a/cocos/scripting/lua/bindings/socket/luasocket_io.h b/cocos/scripting/lua/bindings/socket/luasocket_io.h new file mode 100644 index 0000000000..8cca08a860 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/luasocket_io.h @@ -0,0 +1,65 @@ +#ifndef IO_H +#define IO_H +/*=========================================================================*\ +* Input/Output abstraction +* LuaSocket toolkit +* +* This module defines the interface that LuaSocket expects from the +* transport layer for streamed input/output. The idea is that if any +* transport implements this interface, then the buffer.c functions +* automatically work on it. +* +* The module socket.h implements this interface, and thus the module tcp.h +* is very simple. +\*=========================================================================*/ +#include +#include "lua.h" + +#include "timeout.h" + +/* IO error codes */ +enum { + IO_DONE = 0, /* operation completed successfully */ + IO_TIMEOUT = -1, /* operation timed out */ + IO_CLOSED = -2, /* the connection has been closed */ + IO_UNKNOWN = -3 +}; + +/* interface to error message function */ +typedef const char *(*p_error) ( + void *ctx, /* context needed by send */ + int err /* error code */ +); + +/* interface to send function */ +typedef int (*p_send) ( + void *ctx, /* context needed by send */ + const char *data, /* pointer to buffer with data to send */ + size_t count, /* number of bytes to send from buffer */ + size_t *sent, /* number of bytes sent uppon return */ + p_timeout tm /* timeout control */ +); + +/* interface to recv function */ +typedef int (*p_recv) ( + void *ctx, /* context needed by recv */ + char *data, /* pointer to buffer where data will be writen */ + size_t count, /* number of bytes to receive into buffer */ + size_t *got, /* number of bytes received uppon return */ + p_timeout tm /* timeout control */ +); + +/* IO driver definition */ +typedef struct t_io_ { + void *ctx; /* context needed by send/recv */ + p_send send; /* send function pointer */ + p_recv recv; /* receive function pointer */ + p_error error; /* strerror function */ +} t_io; +typedef t_io *p_io; + +void io_init(p_io io, p_send send, p_recv recv, p_error error, void *ctx); +const char *io_strerror(int err); + +#endif /* IO_H */ + diff --git a/cocos/scripting/lua/bindings/socket/mime.c b/cocos/scripting/lua/bindings/socket/mime.c new file mode 100644 index 0000000000..dddd3d66ea --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/mime.c @@ -0,0 +1,723 @@ +/*=========================================================================*\ +* MIME support functions +* LuaSocket toolkit +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#if !defined(LUA_VERSION_NUM) || (LUA_VERSION_NUM < 501) +#include "compat-5.1.h" +#endif + +#include "mime.h" + +/*=========================================================================*\ +* Don't want to trust escape character constants +\*=========================================================================*/ +typedef unsigned char UC; +static const char CRLF[] = "\r\n"; +static const char EQCRLF[] = "=\r\n"; + +/*=========================================================================*\ +* Internal function prototypes. +\*=========================================================================*/ +static int mime_global_wrp(lua_State *L); +static int mime_global_b64(lua_State *L); +static int mime_global_unb64(lua_State *L); +static int mime_global_qp(lua_State *L); +static int mime_global_unqp(lua_State *L); +static int mime_global_qpwrp(lua_State *L); +static int mime_global_eol(lua_State *L); +static int mime_global_dot(lua_State *L); + +static size_t dot(int c, size_t state, luaL_Buffer *buffer); +static void b64setup(UC *base); +static size_t b64encode(UC c, UC *input, size_t size, luaL_Buffer *buffer); +static size_t b64pad(const UC *input, size_t size, luaL_Buffer *buffer); +static size_t b64decode(UC c, UC *input, size_t size, luaL_Buffer *buffer); + +static void qpsetup(UC *class, UC *unbase); +static void qpquote(UC c, luaL_Buffer *buffer); +static size_t qpdecode(UC c, UC *input, size_t size, luaL_Buffer *buffer); +static size_t qpencode(UC c, UC *input, size_t size, + const char *marker, luaL_Buffer *buffer); +static size_t qppad(UC *input, size_t size, luaL_Buffer *buffer); + +/* code support functions */ +static luaL_Reg func[] = { + { "dot", mime_global_dot }, + { "b64", mime_global_b64 }, + { "eol", mime_global_eol }, + { "qp", mime_global_qp }, + { "qpwrp", mime_global_qpwrp }, + { "unb64", mime_global_unb64 }, + { "unqp", mime_global_unqp }, + { "wrp", mime_global_wrp }, + { NULL, NULL } +}; + +/*-------------------------------------------------------------------------*\ +* Quoted-printable globals +\*-------------------------------------------------------------------------*/ +static UC qpclass[256]; +static UC qpbase[] = "0123456789ABCDEF"; +static UC qpunbase[256]; +enum {QP_PLAIN, QP_QUOTED, QP_CR, QP_IF_LAST}; + +/*-------------------------------------------------------------------------*\ +* Base64 globals +\*-------------------------------------------------------------------------*/ +static const UC b64base[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static UC b64unbase[256]; + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +MIME_API int luaopen_mime_core(lua_State *L) +{ + luaL_openlib(L, "mime", func, 0); + /* make version string available to scripts */ + lua_pushstring(L, "_VERSION"); + lua_pushstring(L, MIME_VERSION); + lua_rawset(L, -3); + /* initialize lookup tables */ + qpsetup(qpclass, qpunbase); + b64setup(b64unbase); + return 1; +} + +/*=========================================================================*\ +* Global Lua functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Incrementaly breaks a string into lines. The string can have CRLF breaks. +* A, n = wrp(l, B, length) +* A is a copy of B, broken into lines of at most 'length' bytes. +* 'l' is how many bytes are left for the first line of B. +* 'n' is the number of bytes left in the last line of A. +\*-------------------------------------------------------------------------*/ +static int mime_global_wrp(lua_State *L) +{ + size_t size = 0; + int left = (int) luaL_checknumber(L, 1); + const UC *input = (UC *) luaL_optlstring(L, 2, NULL, &size); + const UC *last = input + size; + int length = (int) luaL_optnumber(L, 3, 76); + luaL_Buffer buffer; + /* end of input black-hole */ + if (!input) { + /* if last line has not been terminated, add a line break */ + if (left < length) lua_pushstring(L, CRLF); + /* otherwise, we are done */ + else lua_pushnil(L); + lua_pushnumber(L, length); + return 2; + } + luaL_buffinit(L, &buffer); + while (input < last) { + switch (*input) { + case '\r': + break; + case '\n': + luaL_addstring(&buffer, CRLF); + left = length; + break; + default: + if (left <= 0) { + left = length; + luaL_addstring(&buffer, CRLF); + } + luaL_addchar(&buffer, *input); + left--; + break; + } + input++; + } + luaL_pushresult(&buffer); + lua_pushnumber(L, left); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Fill base64 decode map. +\*-------------------------------------------------------------------------*/ +static void b64setup(UC *unbase) +{ + int i; + for (i = 0; i <= 255; i++) unbase[i] = (UC) 255; + for (i = 0; i < 64; i++) unbase[b64base[i]] = (UC) i; + unbase['='] = 0; +} + +/*-------------------------------------------------------------------------*\ +* Acumulates bytes in input buffer until 3 bytes are available. +* Translate the 3 bytes into Base64 form and append to buffer. +* Returns new number of bytes in buffer. +\*-------------------------------------------------------------------------*/ +static size_t b64encode(UC c, UC *input, size_t size, + luaL_Buffer *buffer) +{ + input[size++] = c; + if (size == 3) { + UC code[4]; + unsigned long value = 0; + value += input[0]; value <<= 8; + value += input[1]; value <<= 8; + value += input[2]; + code[3] = b64base[value & 0x3f]; value >>= 6; + code[2] = b64base[value & 0x3f]; value >>= 6; + code[1] = b64base[value & 0x3f]; value >>= 6; + code[0] = b64base[value]; + luaL_addlstring(buffer, (char *) code, 4); + size = 0; + } + return size; +} + +/*-------------------------------------------------------------------------*\ +* Encodes the Base64 last 1 or 2 bytes and adds padding '=' +* Result, if any, is appended to buffer. +* Returns 0. +\*-------------------------------------------------------------------------*/ +static size_t b64pad(const UC *input, size_t size, + luaL_Buffer *buffer) +{ + unsigned long value = 0; + UC code[4] = {'=', '=', '=', '='}; + switch (size) { + case 1: + value = input[0] << 4; + code[1] = b64base[value & 0x3f]; value >>= 6; + code[0] = b64base[value]; + luaL_addlstring(buffer, (char *) code, 4); + break; + case 2: + value = input[0]; value <<= 8; + value |= input[1]; value <<= 2; + code[2] = b64base[value & 0x3f]; value >>= 6; + code[1] = b64base[value & 0x3f]; value >>= 6; + code[0] = b64base[value]; + luaL_addlstring(buffer, (char *) code, 4); + break; + default: + break; + } + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Acumulates bytes in input buffer until 4 bytes are available. +* Translate the 4 bytes from Base64 form and append to buffer. +* Returns new number of bytes in buffer. +\*-------------------------------------------------------------------------*/ +static size_t b64decode(UC c, UC *input, size_t size, + luaL_Buffer *buffer) +{ + /* ignore invalid characters */ + if (b64unbase[c] > 64) return size; + input[size++] = c; + /* decode atom */ + if (size == 4) { + UC decoded[3]; + int valid, value = 0; + value = b64unbase[input[0]]; value <<= 6; + value |= b64unbase[input[1]]; value <<= 6; + value |= b64unbase[input[2]]; value <<= 6; + value |= b64unbase[input[3]]; + decoded[2] = (UC) (value & 0xff); value >>= 8; + decoded[1] = (UC) (value & 0xff); value >>= 8; + decoded[0] = (UC) value; + /* take care of paddding */ + valid = (input[2] == '=') ? 1 : (input[3] == '=') ? 2 : 3; + luaL_addlstring(buffer, (char *) decoded, valid); + return 0; + /* need more data */ + } else return size; +} + +/*-------------------------------------------------------------------------*\ +* Incrementally applies the Base64 transfer content encoding to a string +* A, B = b64(C, D) +* A is the encoded version of the largest prefix of C .. D that is +* divisible by 3. B has the remaining bytes of C .. D, *without* encoding. +* The easiest thing would be to concatenate the two strings and +* encode the result, but we can't afford that or Lua would dupplicate +* every chunk we received. +\*-------------------------------------------------------------------------*/ +static int mime_global_b64(lua_State *L) +{ + UC atom[3]; + size_t isize = 0, asize = 0; + const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize); + const UC *last = input + isize; + luaL_Buffer buffer; + /* end-of-input blackhole */ + if (!input) { + lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* make sure we don't confuse buffer stuff with arguments */ + lua_settop(L, 2); + /* process first part of the input */ + luaL_buffinit(L, &buffer); + while (input < last) + asize = b64encode(*input++, atom, asize, &buffer); + input = (UC *) luaL_optlstring(L, 2, NULL, &isize); + /* if second part is nil, we are done */ + if (!input) { + size_t osize = 0; + asize = b64pad(atom, asize, &buffer); + luaL_pushresult(&buffer); + /* if the output is empty and the input is nil, return nil */ + lua_tolstring(L, -1, &osize); + if (osize == 0) lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* otherwise process the second part */ + last = input + isize; + while (input < last) + asize = b64encode(*input++, atom, asize, &buffer); + luaL_pushresult(&buffer); + lua_pushlstring(L, (char *) atom, asize); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Incrementally removes the Base64 transfer content encoding from a string +* A, B = b64(C, D) +* A is the encoded version of the largest prefix of C .. D that is +* divisible by 4. B has the remaining bytes of C .. D, *without* encoding. +\*-------------------------------------------------------------------------*/ +static int mime_global_unb64(lua_State *L) +{ + UC atom[4]; + size_t isize = 0, asize = 0; + const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize); + const UC *last = input + isize; + luaL_Buffer buffer; + /* end-of-input blackhole */ + if (!input) { + lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* make sure we don't confuse buffer stuff with arguments */ + lua_settop(L, 2); + /* process first part of the input */ + luaL_buffinit(L, &buffer); + while (input < last) + asize = b64decode(*input++, atom, asize, &buffer); + input = (UC *) luaL_optlstring(L, 2, NULL, &isize); + /* if second is nil, we are done */ + if (!input) { + size_t osize = 0; + luaL_pushresult(&buffer); + /* if the output is empty and the input is nil, return nil */ + lua_tolstring(L, -1, &osize); + if (osize == 0) lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* otherwise, process the rest of the input */ + last = input + isize; + while (input < last) + asize = b64decode(*input++, atom, asize, &buffer); + luaL_pushresult(&buffer); + lua_pushlstring(L, (char *) atom, asize); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Quoted-printable encoding scheme +* all (except CRLF in text) can be =XX +* CLRL in not text must be =XX=XX +* 33 through 60 inclusive can be plain +* 62 through 126 inclusive can be plain +* 9 and 32 can be plain, unless in the end of a line, where must be =XX +* encoded lines must be no longer than 76 not counting CRLF +* soft line-break are =CRLF +* To encode one byte, we need to see the next two. +* Worst case is when we see a space, and wonder if a CRLF is comming +\*-------------------------------------------------------------------------*/ +/*-------------------------------------------------------------------------*\ +* Split quoted-printable characters into classes +* Precompute reverse map for encoding +\*-------------------------------------------------------------------------*/ +static void qpsetup(UC *cl, UC *unbase) +{ + int i; + for (i = 0; i < 256; i++) cl[i] = QP_QUOTED; + for (i = 33; i <= 60; i++) cl[i] = QP_PLAIN; + for (i = 62; i <= 126; i++) cl[i] = QP_PLAIN; + cl['\t'] = QP_IF_LAST; + cl[' '] = QP_IF_LAST; + cl['\r'] = QP_CR; + for (i = 0; i < 256; i++) unbase[i] = 255; + unbase['0'] = 0; unbase['1'] = 1; unbase['2'] = 2; + unbase['3'] = 3; unbase['4'] = 4; unbase['5'] = 5; + unbase['6'] = 6; unbase['7'] = 7; unbase['8'] = 8; + unbase['9'] = 9; unbase['A'] = 10; unbase['a'] = 10; + unbase['B'] = 11; unbase['b'] = 11; unbase['C'] = 12; + unbase['c'] = 12; unbase['D'] = 13; unbase['d'] = 13; + unbase['E'] = 14; unbase['e'] = 14; unbase['F'] = 15; + unbase['f'] = 15; +} + +/*-------------------------------------------------------------------------*\ +* Output one character in form =XX +\*-------------------------------------------------------------------------*/ +static void qpquote(UC c, luaL_Buffer *buffer) +{ + luaL_addchar(buffer, '='); + luaL_addchar(buffer, qpbase[c >> 4]); + luaL_addchar(buffer, qpbase[c & 0x0F]); +} + +/*-------------------------------------------------------------------------*\ +* Accumulate characters until we are sure about how to deal with them. +* Once we are sure, output to the buffer, in the correct form. +\*-------------------------------------------------------------------------*/ +static size_t qpencode(UC c, UC *input, size_t size, + const char *marker, luaL_Buffer *buffer) +{ + input[size++] = c; + /* deal with all characters we can have */ + while (size > 0) { + switch (qpclass[input[0]]) { + /* might be the CR of a CRLF sequence */ + case QP_CR: + if (size < 2) return size; + if (input[1] == '\n') { + luaL_addstring(buffer, marker); + return 0; + } else qpquote(input[0], buffer); + break; + /* might be a space and that has to be quoted if last in line */ + case QP_IF_LAST: + if (size < 3) return size; + /* if it is the last, quote it and we are done */ + if (input[1] == '\r' && input[2] == '\n') { + qpquote(input[0], buffer); + luaL_addstring(buffer, marker); + return 0; + } else luaL_addchar(buffer, input[0]); + break; + /* might have to be quoted always */ + case QP_QUOTED: + qpquote(input[0], buffer); + break; + /* might never have to be quoted */ + default: + luaL_addchar(buffer, input[0]); + break; + } + input[0] = input[1]; input[1] = input[2]; + size--; + } + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Deal with the final characters +\*-------------------------------------------------------------------------*/ +static size_t qppad(UC *input, size_t size, luaL_Buffer *buffer) +{ + size_t i; + for (i = 0; i < size; i++) { + if (qpclass[input[i]] == QP_PLAIN) luaL_addchar(buffer, input[i]); + else qpquote(input[i], buffer); + } + if (size > 0) luaL_addstring(buffer, EQCRLF); + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Incrementally converts a string to quoted-printable +* A, B = qp(C, D, marker) +* Marker is the text to be used to replace CRLF sequences found in A. +* A is the encoded version of the largest prefix of C .. D that +* can be encoded without doubts. +* B has the remaining bytes of C .. D, *without* encoding. +\*-------------------------------------------------------------------------*/ +static int mime_global_qp(lua_State *L) +{ + + size_t asize = 0, isize = 0; + UC atom[3]; + const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize); + const UC *last = input + isize; + const char *marker = luaL_optstring(L, 3, CRLF); + luaL_Buffer buffer; + /* end-of-input blackhole */ + if (!input) { + lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* make sure we don't confuse buffer stuff with arguments */ + lua_settop(L, 3); + /* process first part of input */ + luaL_buffinit(L, &buffer); + while (input < last) + asize = qpencode(*input++, atom, asize, marker, &buffer); + input = (UC *) luaL_optlstring(L, 2, NULL, &isize); + /* if second part is nil, we are done */ + if (!input) { + asize = qppad(atom, asize, &buffer); + luaL_pushresult(&buffer); + if (!(*lua_tostring(L, -1))) lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* otherwise process rest of input */ + last = input + isize; + while (input < last) + asize = qpencode(*input++, atom, asize, marker, &buffer); + luaL_pushresult(&buffer); + lua_pushlstring(L, (char *) atom, asize); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Accumulate characters until we are sure about how to deal with them. +* Once we are sure, output the to the buffer, in the correct form. +\*-------------------------------------------------------------------------*/ +static size_t qpdecode(UC c, UC *input, size_t size, luaL_Buffer *buffer) { + int d; + input[size++] = c; + /* deal with all characters we can deal */ + switch (input[0]) { + /* if we have an escape character */ + case '=': + if (size < 3) return size; + /* eliminate soft line break */ + if (input[1] == '\r' && input[2] == '\n') return 0; + /* decode quoted representation */ + c = qpunbase[input[1]]; d = qpunbase[input[2]]; + /* if it is an invalid, do not decode */ + if (c > 15 || d > 15) luaL_addlstring(buffer, (char *)input, 3); + else luaL_addchar(buffer, (char) ((c << 4) + d)); + return 0; + case '\r': + if (size < 2) return size; + if (input[1] == '\n') luaL_addlstring(buffer, (char *)input, 2); + return 0; + default: + if (input[0] == '\t' || (input[0] > 31 && input[0] < 127)) + luaL_addchar(buffer, input[0]); + return 0; + } +} + +/*-------------------------------------------------------------------------*\ +* Incrementally decodes a string in quoted-printable +* A, B = qp(C, D) +* A is the decoded version of the largest prefix of C .. D that +* can be decoded without doubts. +* B has the remaining bytes of C .. D, *without* decoding. +\*-------------------------------------------------------------------------*/ +static int mime_global_unqp(lua_State *L) +{ + size_t asize = 0, isize = 0; + UC atom[3]; + const UC *input = (UC *) luaL_optlstring(L, 1, NULL, &isize); + const UC *last = input + isize; + luaL_Buffer buffer; + /* end-of-input blackhole */ + if (!input) { + lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* make sure we don't confuse buffer stuff with arguments */ + lua_settop(L, 2); + /* process first part of input */ + luaL_buffinit(L, &buffer); + while (input < last) + asize = qpdecode(*input++, atom, asize, &buffer); + input = (UC *) luaL_optlstring(L, 2, NULL, &isize); + /* if second part is nil, we are done */ + if (!input) { + luaL_pushresult(&buffer); + if (!(*lua_tostring(L, -1))) lua_pushnil(L); + lua_pushnil(L); + return 2; + } + /* otherwise process rest of input */ + last = input + isize; + while (input < last) + asize = qpdecode(*input++, atom, asize, &buffer); + luaL_pushresult(&buffer); + lua_pushlstring(L, (char *) atom, asize); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Incrementally breaks a quoted-printed string into lines +* A, n = qpwrp(l, B, length) +* A is a copy of B, broken into lines of at most 'length' bytes. +* 'l' is how many bytes are left for the first line of B. +* 'n' is the number of bytes left in the last line of A. +* There are two complications: lines can't be broken in the middle +* of an encoded =XX, and there might be line breaks already +\*-------------------------------------------------------------------------*/ +static int mime_global_qpwrp(lua_State *L) +{ + size_t size = 0; + int left = (int) luaL_checknumber(L, 1); + const UC *input = (UC *) luaL_optlstring(L, 2, NULL, &size); + const UC *last = input + size; + int length = (int) luaL_optnumber(L, 3, 76); + luaL_Buffer buffer; + /* end-of-input blackhole */ + if (!input) { + if (left < length) lua_pushstring(L, EQCRLF); + else lua_pushnil(L); + lua_pushnumber(L, length); + return 2; + } + /* process all input */ + luaL_buffinit(L, &buffer); + while (input < last) { + switch (*input) { + case '\r': + break; + case '\n': + left = length; + luaL_addstring(&buffer, CRLF); + break; + case '=': + if (left <= 3) { + left = length; + luaL_addstring(&buffer, EQCRLF); + } + luaL_addchar(&buffer, *input); + left--; + break; + default: + if (left <= 1) { + left = length; + luaL_addstring(&buffer, EQCRLF); + } + luaL_addchar(&buffer, *input); + left--; + break; + } + input++; + } + luaL_pushresult(&buffer); + lua_pushnumber(L, left); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Here is what we do: \n, and \r are considered candidates for line +* break. We issue *one* new line marker if any of them is seen alone, or +* followed by a different one. That is, \n\n and \r\r will issue two +* end of line markers each, but \r\n, \n\r etc will only issue *one* +* marker. This covers Mac OS, Mac OS X, VMS, Unix and DOS, as well as +* probably other more obscure conventions. +* +* c is the current character being processed +* last is the previous character +\*-------------------------------------------------------------------------*/ +#define eolcandidate(c) (c == '\r' || c == '\n') +static int eolprocess(int c, int last, const char *marker, + luaL_Buffer *buffer) +{ + if (eolcandidate(c)) { + if (eolcandidate(last)) { + if (c == last) luaL_addstring(buffer, marker); + return 0; + } else { + luaL_addstring(buffer, marker); + return c; + } + } else { + luaL_addchar(buffer, (char) c); + return 0; + } +} + +/*-------------------------------------------------------------------------*\ +* Converts a string to uniform EOL convention. +* A, n = eol(o, B, marker) +* A is the converted version of the largest prefix of B that can be +* converted unambiguously. 'o' is the context returned by the previous +* call. 'n' is the new context. +\*-------------------------------------------------------------------------*/ +static int mime_global_eol(lua_State *L) +{ + int ctx = luaL_checkint(L, 1); + size_t isize = 0; + const char *input = luaL_optlstring(L, 2, NULL, &isize); + const char *last = input + isize; + const char *marker = luaL_optstring(L, 3, CRLF); + luaL_Buffer buffer; + luaL_buffinit(L, &buffer); + /* end of input blackhole */ + if (!input) { + lua_pushnil(L); + lua_pushnumber(L, 0); + return 2; + } + /* process all input */ + while (input < last) + ctx = eolprocess(*input++, ctx, marker, &buffer); + luaL_pushresult(&buffer); + lua_pushnumber(L, ctx); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Takes one byte and stuff it if needed. +\*-------------------------------------------------------------------------*/ +static size_t dot(int c, size_t state, luaL_Buffer *buffer) +{ + luaL_addchar(buffer, (char) c); + switch (c) { + case '\r': + return 1; + case '\n': + return (state == 1)? 2: 0; + case '.': + if (state == 2) + luaL_addchar(buffer, '.'); + default: + return 0; + } +} + +/*-------------------------------------------------------------------------*\ +* Incrementally applies smtp stuffing to a string +* A, n = dot(l, D) +\*-------------------------------------------------------------------------*/ +static int mime_global_dot(lua_State *L) +{ + size_t isize = 0, state = (size_t) luaL_checknumber(L, 1); + const char *input = luaL_optlstring(L, 2, NULL, &isize); + const char *last = input + isize; + luaL_Buffer buffer; + /* end-of-input blackhole */ + if (!input) { + lua_pushnil(L); + lua_pushnumber(L, 2); + return 2; + } + /* process all input */ + luaL_buffinit(L, &buffer); + while (input < last) + state = dot(*input++, state, &buffer); + luaL_pushresult(&buffer); + lua_pushnumber(L, (lua_Number) state); + return 2; +} + diff --git a/cocos/scripting/lua/bindings/socket/mime.h b/cocos/scripting/lua/bindings/socket/mime.h new file mode 100644 index 0000000000..150e7adf91 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/mime.h @@ -0,0 +1,29 @@ +#ifndef MIME_H +#define MIME_H +/*=========================================================================*\ +* Core MIME support +* LuaSocket toolkit +* +* This module provides functions to implement transfer content encodings +* and formatting conforming to RFC 2045. It is used by mime.lua, which +* provide a higher level interface to this functionality. +\*=========================================================================*/ +#include "lua.h" + +/*-------------------------------------------------------------------------*\ +* Current MIME library version +\*-------------------------------------------------------------------------*/ +#define MIME_VERSION "MIME 1.0.3-rc1" +#define MIME_COPYRIGHT "Copyright (C) 2004-2012 Diego Nehab" +#define MIME_AUTHORS "Diego Nehab" + +/*-------------------------------------------------------------------------*\ +* This macro prefixes all exported API functions +\*-------------------------------------------------------------------------*/ +#ifndef MIME_API +#define MIME_API extern +#endif + +MIME_API int luaopen_mime_core(lua_State *L); + +#endif /* MIME_H */ diff --git a/cocos/scripting/lua/bindings/socket/options.c b/cocos/scripting/lua/bindings/socket/options.c new file mode 100644 index 0000000000..6cae7eeb92 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/options.c @@ -0,0 +1,262 @@ +/*=========================================================================*\ +* Common option interface +* LuaSocket toolkit +\*=========================================================================*/ +#include + +#include "lauxlib.h" + +#include "auxiliar.h" +#include "options.h" +#include "inet.h" + +/*=========================================================================*\ +* Internal functions prototypes +\*=========================================================================*/ +static int opt_setmembership(lua_State *L, p_socket ps, int level, int name); +static int opt_setboolean(lua_State *L, p_socket ps, int level, int name); +static int opt_getboolean(lua_State *L, p_socket ps, int level, int name); +static int opt_set(lua_State *L, p_socket ps, int level, int name, + void *val, int len); +static int opt_get(lua_State *L, p_socket ps, int level, int name, + void *val, int* len); + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Calls appropriate option handler +\*-------------------------------------------------------------------------*/ +int opt_meth_setoption(lua_State *L, p_opt opt, p_socket ps) +{ + const char *name = luaL_checkstring(L, 2); /* obj, name, ... */ + while (opt->name && strcmp(name, opt->name)) + opt++; + if (!opt->func) { + char msg[45]; + sprintf(msg, "unsupported option `%.35s'", name); + luaL_argerror(L, 2, msg); + } + return opt->func(L, ps); +} + +int opt_meth_getoption(lua_State *L, p_opt opt, p_socket ps) +{ + const char *name = luaL_checkstring(L, 2); /* obj, name, ... */ + while (opt->name && strcmp(name, opt->name)) + opt++; + if (!opt->func) { + char msg[45]; + sprintf(msg, "unsupported option `%.35s'", name); + luaL_argerror(L, 2, msg); + } + return opt->func(L, ps); +} + +/* enables reuse of local address */ +int opt_set_reuseaddr(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, SOL_SOCKET, SO_REUSEADDR); +} + +int opt_get_reuseaddr(lua_State *L, p_socket ps) +{ + return opt_getboolean(L, ps, SOL_SOCKET, SO_REUSEADDR); +} + +/* enables reuse of local port */ +int opt_set_reuseport(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, SOL_SOCKET, SO_REUSEPORT); +} + +int opt_get_reuseport(lua_State *L, p_socket ps) +{ + return opt_getboolean(L, ps, SOL_SOCKET, SO_REUSEPORT); +} + +/* disables the Naggle algorithm */ +int opt_set_tcp_nodelay(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, IPPROTO_TCP, TCP_NODELAY); +} + +int opt_get_tcp_nodelay(lua_State *L, p_socket ps) +{ + return opt_getboolean(L, ps, IPPROTO_TCP, TCP_NODELAY); +} + +int opt_set_keepalive(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, SOL_SOCKET, SO_KEEPALIVE); +} + +int opt_get_keepalive(lua_State *L, p_socket ps) +{ + return opt_getboolean(L, ps, SOL_SOCKET, SO_KEEPALIVE); +} + +int opt_set_dontroute(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, SOL_SOCKET, SO_DONTROUTE); +} + +int opt_set_broadcast(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, SOL_SOCKET, SO_BROADCAST); +} + +int opt_set_ip_multicast_loop(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, IPPROTO_IP, IP_MULTICAST_LOOP); +} + +int opt_get_ip_multicast_loop(lua_State *L, p_socket ps) +{ + return opt_getboolean(L, ps, IPPROTO_IP, IP_MULTICAST_LOOP); +} + +int opt_set_linger(lua_State *L, p_socket ps) +{ + struct linger li; /* obj, name, table */ + if (!lua_istable(L, 3)) auxiliar_typeerror(L,3,lua_typename(L, LUA_TTABLE)); + lua_pushstring(L, "on"); + lua_gettable(L, 3); + if (!lua_isboolean(L, -1)) + luaL_argerror(L, 3, "boolean 'on' field expected"); + li.l_onoff = (u_short) lua_toboolean(L, -1); + lua_pushstring(L, "timeout"); + lua_gettable(L, 3); + if (!lua_isnumber(L, -1)) + luaL_argerror(L, 3, "number 'timeout' field expected"); + li.l_linger = (u_short) lua_tonumber(L, -1); + return opt_set(L, ps, SOL_SOCKET, SO_LINGER, (char *) &li, sizeof(li)); +} + +int opt_get_linger(lua_State *L, p_socket ps) +{ + struct linger li; /* obj, name */ + int len = sizeof(li); + int err = opt_get(L, ps, SOL_SOCKET, SO_LINGER, (char *) &li, &len); + if (err) + return err; + lua_newtable(L); + lua_pushboolean(L, li.l_onoff); + lua_setfield(L, -2, "on"); + lua_pushinteger(L, li.l_linger); + lua_setfield(L, -2, "timeout"); + return 1; +} + +int opt_set_ip_multicast_ttl(lua_State *L, p_socket ps) +{ + int val = (int) luaL_checknumber(L, 3); /* obj, name, int */ + return opt_set(L, ps, IPPROTO_IP, IP_MULTICAST_TTL, + (char *) &val, sizeof(val)); +} + +int opt_set_ip_multicast_if(lua_State *L, p_socket ps) +{ + const char *address = luaL_checkstring(L, 3); /* obj, name, ip */ + struct in_addr val; + val.s_addr = htonl(INADDR_ANY); + if (strcmp(address, "*") && !inet_aton(address, &val)) + luaL_argerror(L, 3, "ip expected"); + return opt_set(L, ps, IPPROTO_IP, IP_MULTICAST_IF, + (char *) &val, sizeof(val)); +} + +int opt_get_ip_multicast_if(lua_State *L, p_socket ps) +{ + struct in_addr val; + socklen_t len = sizeof(val); + if (getsockopt(*ps, IPPROTO_IP, IP_MULTICAST_IF, (char *) &val, &len) < 0) { + lua_pushnil(L); + lua_pushstring(L, "getsockopt failed"); + return 2; + } + lua_pushstring(L, inet_ntoa(val)); + return 1; +} + +int opt_set_ip_add_membership(lua_State *L, p_socket ps) +{ + return opt_setmembership(L, ps, IPPROTO_IP, IP_ADD_MEMBERSHIP); +} + +int opt_set_ip_drop_membersip(lua_State *L, p_socket ps) +{ + return opt_setmembership(L, ps, IPPROTO_IP, IP_DROP_MEMBERSHIP); +} + +int opt_set_ip6_v6only(lua_State *L, p_socket ps) +{ + return opt_setboolean(L, ps, IPPROTO_IPV6, IPV6_V6ONLY); +} + +/*=========================================================================*\ +* Auxiliar functions +\*=========================================================================*/ +static int opt_setmembership(lua_State *L, p_socket ps, int level, int name) +{ + struct ip_mreq val; /* obj, name, table */ + if (!lua_istable(L, 3)) auxiliar_typeerror(L,3,lua_typename(L, LUA_TTABLE)); + lua_pushstring(L, "multiaddr"); + lua_gettable(L, 3); + if (!lua_isstring(L, -1)) + luaL_argerror(L, 3, "string 'multiaddr' field expected"); + if (!inet_aton(lua_tostring(L, -1), &val.imr_multiaddr)) + luaL_argerror(L, 3, "invalid 'multiaddr' ip address"); + lua_pushstring(L, "interface"); + lua_gettable(L, 3); + if (!lua_isstring(L, -1)) + luaL_argerror(L, 3, "string 'interface' field expected"); + val.imr_interface.s_addr = htonl(INADDR_ANY); + if (strcmp(lua_tostring(L, -1), "*") && + !inet_aton(lua_tostring(L, -1), &val.imr_interface)) + luaL_argerror(L, 3, "invalid 'interface' ip address"); + return opt_set(L, ps, level, name, (char *) &val, sizeof(val)); +} + +static +int opt_get(lua_State *L, p_socket ps, int level, int name, void *val, int* len) +{ + socklen_t socklen = *len; + if (getsockopt(*ps, level, name, (char *) val, &socklen) < 0) { + lua_pushnil(L); + lua_pushstring(L, "getsockopt failed"); + return 2; + } + *len = socklen; + return 0; +} + +static +int opt_set(lua_State *L, p_socket ps, int level, int name, void *val, int len) +{ + if (setsockopt(*ps, level, name, (char *) val, len) < 0) { + lua_pushnil(L); + lua_pushstring(L, "setsockopt failed"); + return 2; + } + lua_pushnumber(L, 1); + return 1; +} + +static int opt_getboolean(lua_State *L, p_socket ps, int level, int name) +{ + int val = 0; + int len = sizeof(val); + int err = opt_get(L, ps, level, name, (char *) &val, &len); + if (err) + return err; + lua_pushboolean(L, val); + return 1; +} + +static int opt_setboolean(lua_State *L, p_socket ps, int level, int name) +{ + int val = auxiliar_checkboolean(L, 3); /* obj, name, bool */ + return opt_set(L, ps, level, name, (char *) &val, sizeof(val)); +} + diff --git a/cocos/scripting/lua/bindings/socket/options.h b/cocos/scripting/lua/bindings/socket/options.h new file mode 100644 index 0000000000..55447f78f4 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/options.h @@ -0,0 +1,50 @@ +#ifndef OPTIONS_H +#define OPTIONS_H +/*=========================================================================*\ +* Common option interface +* LuaSocket toolkit +* +* This module provides a common interface to socket options, used mainly by +* modules UDP and TCP. +\*=========================================================================*/ + +#include "lua.h" +#include "socket.h" + +/* option registry */ +typedef struct t_opt { + const char *name; + int (*func)(lua_State *L, p_socket ps); +} t_opt; +typedef t_opt *p_opt; + +/* supported options for setoption */ +int opt_set_dontroute(lua_State *L, p_socket ps); +int opt_set_broadcast(lua_State *L, p_socket ps); +int opt_set_reuseaddr(lua_State *L, p_socket ps); +int opt_set_tcp_nodelay(lua_State *L, p_socket ps); +int opt_set_keepalive(lua_State *L, p_socket ps); +int opt_set_linger(lua_State *L, p_socket ps); +int opt_set_reuseaddr(lua_State *L, p_socket ps); +int opt_set_reuseport(lua_State *L, p_socket ps); +int opt_set_ip_multicast_if(lua_State *L, p_socket ps); +int opt_set_ip_multicast_ttl(lua_State *L, p_socket ps); +int opt_set_ip_multicast_loop(lua_State *L, p_socket ps); +int opt_set_ip_add_membership(lua_State *L, p_socket ps); +int opt_set_ip_drop_membersip(lua_State *L, p_socket ps); +int opt_set_ip6_v6only(lua_State *L, p_socket ps); + +/* supported options for getoption */ +int opt_get_reuseaddr(lua_State *L, p_socket ps); +int opt_get_tcp_nodelay(lua_State *L, p_socket ps); +int opt_get_keepalive(lua_State *L, p_socket ps); +int opt_get_linger(lua_State *L, p_socket ps); +int opt_get_reuseaddr(lua_State *L, p_socket ps); +int opt_get_ip_multicast_loop(lua_State *L, p_socket ps); +int opt_get_ip_multicast_if(lua_State *L, p_socket ps); + +/* invokes the appropriate option handler */ +int opt_meth_setoption(lua_State *L, p_opt opt, p_socket ps); +int opt_meth_getoption(lua_State *L, p_opt opt, p_socket ps); + +#endif diff --git a/cocos/scripting/lua/bindings/socket/select.c b/cocos/scripting/lua/bindings/socket/select.c new file mode 100644 index 0000000000..51fb198611 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/select.c @@ -0,0 +1,216 @@ +/*=========================================================================*\ +* Select implementation +* LuaSocket toolkit +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "socket.h" +#include "timeout.h" +#include "select.h" + +/*=========================================================================*\ +* Internal function prototypes. +\*=========================================================================*/ +static t_socket getfd(lua_State *L); +static int dirty(lua_State *L); +static void collect_fd(lua_State *L, int tab, int itab, + fd_set *set, t_socket *max_fd); +static int check_dirty(lua_State *L, int tab, int dtab, fd_set *set); +static void return_fd(lua_State *L, fd_set *set, t_socket max_fd, + int itab, int tab, int start); +static void make_assoc(lua_State *L, int tab); +static int global_select(lua_State *L); + +/* functions in library namespace */ +static luaL_Reg func[] = { + {"select", global_select}, + {NULL, NULL} +}; + +/*=========================================================================*\ +* Exported functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int select_open(lua_State *L) { + lua_pushstring(L, "_SETSIZE"); + lua_pushnumber(L, FD_SETSIZE); + lua_rawset(L, -3); + luaL_openlib(L, NULL, func, 0); + return 0; +} + +/*=========================================================================*\ +* Global Lua functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Waits for a set of sockets until a condition is met or timeout. +\*-------------------------------------------------------------------------*/ +static int global_select(lua_State *L) { + int rtab, wtab, itab, ret, ndirty; + t_socket max_fd = SOCKET_INVALID; + fd_set rset, wset; + t_timeout tm; + double t = luaL_optnumber(L, 3, -1); + FD_ZERO(&rset); FD_ZERO(&wset); + lua_settop(L, 3); + lua_newtable(L); itab = lua_gettop(L); + lua_newtable(L); rtab = lua_gettop(L); + lua_newtable(L); wtab = lua_gettop(L); + collect_fd(L, 1, itab, &rset, &max_fd); + collect_fd(L, 2, itab, &wset, &max_fd); + ndirty = check_dirty(L, 1, rtab, &rset); + t = ndirty > 0? 0.0: t; + timeout_init(&tm, t, -1); + timeout_markstart(&tm); + ret = socket_select(max_fd+1, &rset, &wset, NULL, &tm); + if (ret > 0 || ndirty > 0) { + return_fd(L, &rset, max_fd+1, itab, rtab, ndirty); + return_fd(L, &wset, max_fd+1, itab, wtab, 0); + make_assoc(L, rtab); + make_assoc(L, wtab); + return 2; + } else if (ret == 0) { + lua_pushstring(L, "timeout"); + return 3; + } else { + luaL_error(L, "select failed"); + return 3; + } +} + +/*=========================================================================*\ +* Internal functions +\*=========================================================================*/ +static t_socket getfd(lua_State *L) { + t_socket fd = SOCKET_INVALID; + lua_pushstring(L, "getfd"); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + lua_pushvalue(L, -2); + lua_call(L, 1, 1); + if (lua_isnumber(L, -1)) { + double numfd = lua_tonumber(L, -1); + fd = (numfd >= 0.0)? (t_socket) numfd: SOCKET_INVALID; + } + } + lua_pop(L, 1); + return fd; +} + +static int dirty(lua_State *L) { + int is = 0; + lua_pushstring(L, "dirty"); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + lua_pushvalue(L, -2); + lua_call(L, 1, 1); + is = lua_toboolean(L, -1); + } + lua_pop(L, 1); + return is; +} + +static void collect_fd(lua_State *L, int tab, int itab, + fd_set *set, t_socket *max_fd) { + int i = 1, n = 0; + /* nil is the same as an empty table */ + if (lua_isnil(L, tab)) return; + /* otherwise we need it to be a table */ + luaL_checktype(L, tab, LUA_TTABLE); + for ( ;; ) { + t_socket fd; + lua_pushnumber(L, i); + lua_gettable(L, tab); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + break; + } + /* getfd figures out if this is a socket */ + fd = getfd(L); + if (fd != SOCKET_INVALID) { + /* make sure we don't overflow the fd_set */ +#ifdef _WIN32 + if (n >= FD_SETSIZE) + luaL_argerror(L, tab, "too many sockets"); +#else + if (fd >= FD_SETSIZE) + luaL_argerror(L, tab, "descriptor too large for set size"); +#endif + FD_SET(fd, set); + n++; + /* keep track of the largest descriptor so far */ + if (*max_fd == SOCKET_INVALID || *max_fd < fd) + *max_fd = fd; + /* make sure we can map back from descriptor to the object */ + lua_pushnumber(L, (lua_Number) fd); + lua_pushvalue(L, -2); + lua_settable(L, itab); + } + lua_pop(L, 1); + i = i + 1; + } +} + +static int check_dirty(lua_State *L, int tab, int dtab, fd_set *set) { + int ndirty = 0, i = 1; + if (lua_isnil(L, tab)) + return 0; + for ( ;; ) { + t_socket fd; + lua_pushnumber(L, i); + lua_gettable(L, tab); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + break; + } + fd = getfd(L); + if (fd != SOCKET_INVALID && dirty(L)) { + lua_pushnumber(L, ++ndirty); + lua_pushvalue(L, -2); + lua_settable(L, dtab); + FD_CLR(fd, set); + } + lua_pop(L, 1); + i = i + 1; + } + return ndirty; +} + +static void return_fd(lua_State *L, fd_set *set, t_socket max_fd, + int itab, int tab, int start) { + t_socket fd; + for (fd = 0; fd < max_fd; fd++) { + if (FD_ISSET(fd, set)) { + lua_pushnumber(L, ++start); + lua_pushnumber(L, (lua_Number) fd); + lua_gettable(L, itab); + lua_settable(L, tab); + } + } +} + +static void make_assoc(lua_State *L, int tab) { + int i = 1, atab; + lua_newtable(L); atab = lua_gettop(L); + for ( ;; ) { + lua_pushnumber(L, i); + lua_gettable(L, tab); + if (!lua_isnil(L, -1)) { + lua_pushnumber(L, i); + lua_pushvalue(L, -2); + lua_settable(L, atab); + lua_pushnumber(L, i); + lua_settable(L, atab); + } else { + lua_pop(L, 1); + break; + } + i = i+1; + } +} + diff --git a/cocos/scripting/lua/bindings/socket/select.h b/cocos/scripting/lua/bindings/socket/select.h new file mode 100644 index 0000000000..8750200395 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/select.h @@ -0,0 +1,15 @@ +#ifndef SELECT_H +#define SELECT_H +/*=========================================================================*\ +* Select implementation +* LuaSocket toolkit +* +* Each object that can be passed to the select function has to export +* method getfd() which returns the descriptor to be passed to the +* underlying select function. Another method, dirty(), should return +* true if there is data ready for reading (required for buffered input). +\*=========================================================================*/ + +int select_open(lua_State *L); + +#endif /* SELECT_H */ diff --git a/cocos/scripting/lua/bindings/socket/serial.c b/cocos/scripting/lua/bindings/socket/serial.c new file mode 100644 index 0000000000..5b09e76830 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/serial.c @@ -0,0 +1,183 @@ +/*=========================================================================*\ +* Serial stream +* LuaSocket toolkit +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "auxiliar.h" +#include "socket.h" +#include "options.h" +#include "unix.h" +#include + +/* +Reuses userdata definition from unix.h, since it is useful for all +stream-like objects. + +If we stored the serial path for use in error messages or userdata +printing, we might need our own userdata definition. + +Group usage is semi-inherited from unix.c, but unnecessary since we +have only one object type. +*/ + +/*=========================================================================*\ +* Internal function prototypes +\*=========================================================================*/ +static int global_create(lua_State *L); +static int meth_send(lua_State *L); +static int meth_receive(lua_State *L); +static int meth_close(lua_State *L); +static int meth_settimeout(lua_State *L); +static int meth_getfd(lua_State *L); +static int meth_setfd(lua_State *L); +static int meth_dirty(lua_State *L); +static int meth_getstats(lua_State *L); +static int meth_setstats(lua_State *L); + +/* serial object methods */ +static luaL_Reg serial_methods[] = { + {"__gc", meth_close}, + {"__tostring", auxiliar_tostring}, + {"close", meth_close}, + {"dirty", meth_dirty}, + {"getfd", meth_getfd}, + {"getstats", meth_getstats}, + {"setstats", meth_setstats}, + {"receive", meth_receive}, + {"send", meth_send}, + {"setfd", meth_setfd}, + {"settimeout", meth_settimeout}, + {NULL, NULL} +}; + +/* our socket creation function */ +static luaL_Reg func[] = { + {"serial", global_create}, + {NULL, NULL} +}; + + +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +LUASOCKET_API int luaopen_socket_serial(lua_State *L) { + /* create classes */ + auxiliar_newclass(L, "serial{client}", serial_methods); + /* create class groups */ + auxiliar_add2group(L, "serial{client}", "serial{any}"); + /* make sure the function ends up in the package table */ + luaL_openlib(L, "socket", func, 0); + /* return the function instead of the 'socket' table */ + lua_pushstring(L, "serial"); + lua_gettable(L, -2); + return 1; +} + +/*=========================================================================*\ +* Lua methods +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Just call buffered IO methods +\*-------------------------------------------------------------------------*/ +static int meth_send(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkclass(L, "serial{client}", 1); + return buffer_meth_send(L, &un->buf); +} + +static int meth_receive(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkclass(L, "serial{client}", 1); + return buffer_meth_receive(L, &un->buf); +} + +static int meth_getstats(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkclass(L, "serial{client}", 1); + return buffer_meth_getstats(L, &un->buf); +} + +static int meth_setstats(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkclass(L, "serial{client}", 1); + return buffer_meth_setstats(L, &un->buf); +} + +/*-------------------------------------------------------------------------*\ +* Select support methods +\*-------------------------------------------------------------------------*/ +static int meth_getfd(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkgroup(L, "serial{any}", 1); + lua_pushnumber(L, (int) un->sock); + return 1; +} + +/* this is very dangerous, but can be handy for those that are brave enough */ +static int meth_setfd(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkgroup(L, "serial{any}", 1); + un->sock = (t_socket) luaL_checknumber(L, 2); + return 0; +} + +static int meth_dirty(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkgroup(L, "serial{any}", 1); + lua_pushboolean(L, !buffer_isempty(&un->buf)); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Closes socket used by object +\*-------------------------------------------------------------------------*/ +static int meth_close(lua_State *L) +{ + p_unix un = (p_unix) auxiliar_checkgroup(L, "serial{any}", 1); + socket_destroy(&un->sock); + lua_pushnumber(L, 1); + return 1; +} + + +/*-------------------------------------------------------------------------*\ +* Just call tm methods +\*-------------------------------------------------------------------------*/ +static int meth_settimeout(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkgroup(L, "serial{any}", 1); + return timeout_meth_settimeout(L, &un->tm); +} + +/*=========================================================================*\ +* Library functions +\*=========================================================================*/ + + +/*-------------------------------------------------------------------------*\ +* Creates a serial object +\*-------------------------------------------------------------------------*/ +static int global_create(lua_State *L) { + const char* path = luaL_checkstring(L, 1); + + /* allocate unix object */ + p_unix un = (p_unix) lua_newuserdata(L, sizeof(t_unix)); + + /* open serial device */ + t_socket sock = open(path, O_NOCTTY|O_RDWR); + + /*printf("open %s on %d\n", path, sock);*/ + + if (sock < 0) { + lua_pushnil(L); + lua_pushstring(L, socket_strerror(errno)); + lua_pushnumber(L, errno); + return 3; + } + /* set its type as client object */ + auxiliar_setclass(L, "serial{client}", -1); + /* initialize remaining structure fields */ + socket_setnonblocking(&sock); + un->sock = sock; + io_init(&un->io, (p_send) socket_write, (p_recv) socket_read, + (p_error) socket_ioerror, &un->sock); + timeout_init(&un->tm, -1, -1); + buffer_init(&un->buf, &un->io, &un->tm); + return 1; +} diff --git a/cocos/scripting/lua/bindings/socket/socket.h b/cocos/scripting/lua/bindings/socket/socket.h new file mode 100644 index 0000000000..03fa186b8a --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/socket.h @@ -0,0 +1,78 @@ +#ifndef SOCKET_H +#define SOCKET_H +/*=========================================================================*\ +* Socket compatibilization module +* LuaSocket toolkit +* +* BSD Sockets and WinSock are similar, but there are a few irritating +* differences. Also, not all *nix platforms behave the same. This module +* (and the associated usocket.h and wsocket.h) factor these differences and +* creates a interface compatible with the io.h module. +\*=========================================================================*/ +#include "luasocket_io.h" + +/*=========================================================================*\ +* Platform specific compatibilization +\*=========================================================================*/ +#ifdef _WIN32 +#include "wsocket.h" +#else +#include "usocket.h" +#endif + +/*=========================================================================*\ +* The connect and accept functions accept a timeout and their +* implementations are somewhat complicated. We chose to move +* the timeout control into this module for these functions in +* order to simplify the modules that use them. +\*=========================================================================*/ +#include "timeout.h" + +/* we are lazy... */ +typedef struct sockaddr SA; + +/*=========================================================================*\ +* Functions bellow implement a comfortable platform independent +* interface to sockets +\*=========================================================================*/ +int socket_open(void); +int socket_close(void); +void socket_destroy(p_socket ps); +void socket_shutdown(p_socket ps, int how); +int socket_sendto(p_socket ps, const char *data, size_t count, + size_t *sent, SA *addr, socklen_t addr_len, p_timeout tm); +int socket_recvfrom(p_socket ps, char *data, size_t count, + size_t *got, SA *addr, socklen_t *addr_len, p_timeout tm); + +void socket_setnonblocking(p_socket ps); +void socket_setblocking(p_socket ps); + +int socket_waitfd(p_socket ps, int sw, p_timeout tm); +int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds, + p_timeout tm); + +int socket_connect(p_socket ps, SA *addr, socklen_t addr_len, p_timeout tm); +int socket_create(p_socket ps, int domain, int type, int protocol); +int socket_bind(p_socket ps, SA *addr, socklen_t addr_len); +int socket_listen(p_socket ps, int backlog); +int socket_accept(p_socket ps, p_socket pa, SA *addr, + socklen_t *addr_len, p_timeout tm); + +const char *socket_hoststrerror(int err); +const char *socket_gaistrerror(int err); +const char *socket_strerror(int err); + +/* these are perfect to use with the io abstraction module + and the buffered input module */ +int socket_send(p_socket ps, const char *data, size_t count, + size_t *sent, p_timeout tm); +int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm); +int socket_write(p_socket ps, const char *data, size_t count, + size_t *sent, p_timeout tm); +int socket_read(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm); +const char *socket_ioerror(p_socket ps, int err); + +int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp); +int socket_gethostbyname(const char *addr, struct hostent **hp); + +#endif /* SOCKET_H */ diff --git a/cocos/scripting/lua/bindings/socket/socket_scripts.c.REMOVED.git-id b/cocos/scripting/lua/bindings/socket/socket_scripts.c.REMOVED.git-id new file mode 100644 index 0000000000..f8ab743b49 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/socket_scripts.c.REMOVED.git-id @@ -0,0 +1 @@ +e79358cdf4b02c66a50e684543e505002bdbcc91 \ No newline at end of file diff --git a/cocos/scripting/lua/bindings/socket/socket_scripts.h b/cocos/scripting/lua/bindings/socket/socket_scripts.h new file mode 100644 index 0000000000..939fcb2d03 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/socket_scripts.h @@ -0,0 +1,32 @@ + +/* socket_scripts.h */ + +#ifndef __LUA_MODULES_E58C07CB2FBAF5B178B7E1836DC22849_H_ +#define __LUA_MODULES_E58C07CB2FBAF5B178B7E1836DC22849_H_ + +#if __cplusplus +extern "C" { +#endif + +#include "lua.h" + +void luaopen_socket_scripts(lua_State* L); + +/* +int luaopen_lua_m_ltn12(lua_State* L); +int luaopen_lua_m_mime(lua_State* L); +int luaopen_lua_m_socket_ftp(lua_State* L); +int luaopen_lua_m_socket_headers(lua_State* L); +int luaopen_lua_m_socket_http(lua_State* L); +int luaopen_lua_m_socket_mbox(lua_State* L); +int luaopen_lua_m_socket_smtp(lua_State* L); +int luaopen_lua_m_socket_tp(lua_State* L); +int luaopen_lua_m_socket_url(lua_State* L); +int luaopen_lua_m_socket(lua_State* L); +*/ + +#if __cplusplus +} +#endif + +#endif /* __LUA_MODULES_E58C07CB2FBAF5B178B7E1836DC22849_H_ */ diff --git a/cocos/scripting/lua/bindings/socket/tcp.c b/cocos/scripting/lua/bindings/socket/tcp.c new file mode 100644 index 0000000000..6734dc0b49 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/tcp.c @@ -0,0 +1,475 @@ +/*=========================================================================*\ +* TCP object +* LuaSocket toolkit +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "auxiliar.h" +#include "socket.h" +#include "inet.h" +#include "options.h" +#include "tcp.h" + +/*=========================================================================*\ +* Internal function prototypes +\*=========================================================================*/ +static int global_create(lua_State *L); +static int global_create6(lua_State *L); +static int global_connect(lua_State *L); +static int meth_connect(lua_State *L); +static int meth_listen(lua_State *L); +static int meth_getfamily(lua_State *L); +static int meth_bind(lua_State *L); +static int meth_send(lua_State *L); +static int meth_getstats(lua_State *L); +static int meth_setstats(lua_State *L); +static int meth_getsockname(lua_State *L); +static int meth_getpeername(lua_State *L); +static int meth_shutdown(lua_State *L); +static int meth_receive(lua_State *L); +static int meth_accept(lua_State *L); +static int meth_close(lua_State *L); +static int meth_getoption(lua_State *L); +static int meth_setoption(lua_State *L); +static int meth_settimeout(lua_State *L); +static int meth_getfd(lua_State *L); +static int meth_setfd(lua_State *L); +static int meth_dirty(lua_State *L); + +/* tcp object methods */ +static luaL_Reg tcp_methods[] = { + {"__gc", meth_close}, + {"__tostring", auxiliar_tostring}, + {"accept", meth_accept}, + {"bind", meth_bind}, + {"close", meth_close}, + {"connect", meth_connect}, + {"dirty", meth_dirty}, + {"getfamily", meth_getfamily}, + {"getfd", meth_getfd}, + {"getoption", meth_getoption}, + {"getpeername", meth_getpeername}, + {"getsockname", meth_getsockname}, + {"getstats", meth_getstats}, + {"setstats", meth_setstats}, + {"listen", meth_listen}, + {"receive", meth_receive}, + {"send", meth_send}, + {"setfd", meth_setfd}, + {"setoption", meth_setoption}, + {"setpeername", meth_connect}, + {"setsockname", meth_bind}, + {"settimeout", meth_settimeout}, + {"shutdown", meth_shutdown}, + {NULL, NULL} +}; + +/* socket option handlers */ +static t_opt optget[] = { + {"keepalive", opt_get_keepalive}, + {"reuseaddr", opt_get_reuseaddr}, + {"tcp-nodelay", opt_get_tcp_nodelay}, + {"linger", opt_get_linger}, + {NULL, NULL} +}; + +static t_opt optset[] = { + {"keepalive", opt_set_keepalive}, + {"reuseaddr", opt_set_reuseaddr}, + {"tcp-nodelay", opt_set_tcp_nodelay}, + {"ipv6-v6only", opt_set_ip6_v6only}, + {"linger", opt_set_linger}, + {NULL, NULL} +}; + +/* functions in library namespace */ +static luaL_Reg func[] = { + {"tcp", global_create}, + {"tcp6", global_create6}, + {"connect", global_connect}, + {NULL, NULL} +}; + +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int tcp_open(lua_State *L) +{ + /* create classes */ + auxiliar_newclass(L, "tcp{master}", tcp_methods); + auxiliar_newclass(L, "tcp{client}", tcp_methods); + auxiliar_newclass(L, "tcp{server}", tcp_methods); + /* create class groups */ + auxiliar_add2group(L, "tcp{master}", "tcp{any}"); + auxiliar_add2group(L, "tcp{client}", "tcp{any}"); + auxiliar_add2group(L, "tcp{server}", "tcp{any}"); + /* define library functions */ + luaL_openlib(L, NULL, func, 0); + return 0; +} + +/*=========================================================================*\ +* Lua methods +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Just call buffered IO methods +\*-------------------------------------------------------------------------*/ +static int meth_send(lua_State *L) { + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1); + return buffer_meth_send(L, &tcp->buf); +} + +static int meth_receive(lua_State *L) { + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1); + return buffer_meth_receive(L, &tcp->buf); +} + +static int meth_getstats(lua_State *L) { + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1); + return buffer_meth_getstats(L, &tcp->buf); +} + +static int meth_setstats(lua_State *L) { + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1); + return buffer_meth_setstats(L, &tcp->buf); +} + +/*-------------------------------------------------------------------------*\ +* Just call option handler +\*-------------------------------------------------------------------------*/ +static int meth_getoption(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + return opt_meth_getoption(L, optget, &tcp->sock); +} + +static int meth_setoption(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + return opt_meth_setoption(L, optset, &tcp->sock); +} + +/*-------------------------------------------------------------------------*\ +* Select support methods +\*-------------------------------------------------------------------------*/ +static int meth_getfd(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + lua_pushnumber(L, (int) tcp->sock); + return 1; +} + +/* this is very dangerous, but can be handy for those that are brave enough */ +static int meth_setfd(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + tcp->sock = (t_socket) luaL_checknumber(L, 2); + return 0; +} + +static int meth_dirty(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + lua_pushboolean(L, !buffer_isempty(&tcp->buf)); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Waits for and returns a client object attempting connection to the +* server object +\*-------------------------------------------------------------------------*/ +static int meth_accept(lua_State *L) +{ + p_tcp server = (p_tcp) auxiliar_checkclass(L, "tcp{server}", 1); + p_timeout tm = timeout_markstart(&server->tm); + t_socket sock; + const char *err = inet_tryaccept(&server->sock, server->family, &sock, tm); + /* if successful, push client socket */ + if (err == NULL) { + p_tcp clnt = (p_tcp) lua_newuserdata(L, sizeof(t_tcp)); + auxiliar_setclass(L, "tcp{client}", -1); + /* initialize structure fields */ + memset(clnt, 0, sizeof(t_tcp)); + socket_setnonblocking(&sock); + clnt->sock = sock; + io_init(&clnt->io, (p_send) socket_send, (p_recv) socket_recv, + (p_error) socket_ioerror, &clnt->sock); + timeout_init(&clnt->tm, -1, -1); + buffer_init(&clnt->buf, &clnt->io, &clnt->tm); + clnt->family = server->family; + return 1; + } else { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } +} + +/*-------------------------------------------------------------------------*\ +* Binds an object to an address +\*-------------------------------------------------------------------------*/ +static int meth_bind(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{master}", 1); + const char *address = luaL_checkstring(L, 2); + const char *port = luaL_checkstring(L, 3); + const char *err; + struct addrinfo bindhints; + memset(&bindhints, 0, sizeof(bindhints)); + bindhints.ai_socktype = SOCK_STREAM; + bindhints.ai_family = tcp->family; + bindhints.ai_flags = AI_PASSIVE; + address = strcmp(address, "*")? address: NULL; + err = inet_trybind(&tcp->sock, address, port, &bindhints); + if (err) { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Turns a master tcp object into a client object. +\*-------------------------------------------------------------------------*/ +static int meth_connect(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + const char *address = luaL_checkstring(L, 2); + const char *port = luaL_checkstring(L, 3); + struct addrinfo connecthints; + const char *err; + memset(&connecthints, 0, sizeof(connecthints)); + connecthints.ai_socktype = SOCK_STREAM; + /* make sure we try to connect only to the same family */ + connecthints.ai_family = tcp->family; + timeout_markstart(&tcp->tm); + err = inet_tryconnect(&tcp->sock, address, port, &tcp->tm, &connecthints); + /* have to set the class even if it failed due to non-blocking connects */ + auxiliar_setclass(L, "tcp{client}", 1); + if (err) { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Closes socket used by object +\*-------------------------------------------------------------------------*/ +static int meth_close(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + socket_destroy(&tcp->sock); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Returns family as string +\*-------------------------------------------------------------------------*/ +static int meth_getfamily(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + if (tcp->family == PF_INET6) { + lua_pushliteral(L, "inet6"); + return 1; + } else { + lua_pushliteral(L, "inet4"); + return 1; + } +} + +/*-------------------------------------------------------------------------*\ +* Puts the sockt in listen mode +\*-------------------------------------------------------------------------*/ +static int meth_listen(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{master}", 1); + int backlog = (int) luaL_optnumber(L, 2, 32); + int err = socket_listen(&tcp->sock, backlog); + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, socket_strerror(err)); + return 2; + } + /* turn master object into a server object */ + auxiliar_setclass(L, "tcp{server}", 1); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Shuts the connection down partially +\*-------------------------------------------------------------------------*/ +static int meth_shutdown(lua_State *L) +{ + /* SHUT_RD, SHUT_WR, SHUT_RDWR have the value 0, 1, 2, so we can use method index directly */ + static const char* methods[] = { "receive", "send", "both", NULL }; + p_tcp tcp = (p_tcp) auxiliar_checkclass(L, "tcp{client}", 1); + int how = luaL_checkoption(L, 2, "both", methods); + socket_shutdown(&tcp->sock, how); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Just call inet methods +\*-------------------------------------------------------------------------*/ +static int meth_getpeername(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + return inet_meth_getpeername(L, &tcp->sock, tcp->family); +} + +static int meth_getsockname(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + return inet_meth_getsockname(L, &tcp->sock, tcp->family); +} + +/*-------------------------------------------------------------------------*\ +* Just call tm methods +\*-------------------------------------------------------------------------*/ +static int meth_settimeout(lua_State *L) +{ + p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1); + return timeout_meth_settimeout(L, &tcp->tm); +} + +/*=========================================================================*\ +* Library functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Creates a master tcp object +\*-------------------------------------------------------------------------*/ +static int tcp_create(lua_State *L, int family) { + t_socket sock; + const char *err = inet_trycreate(&sock, family, SOCK_STREAM); + /* try to allocate a system socket */ + if (!err) { + /* allocate tcp object */ + p_tcp tcp = (p_tcp) lua_newuserdata(L, sizeof(t_tcp)); + memset(tcp, 0, sizeof(t_tcp)); + /* set its type as master object */ + auxiliar_setclass(L, "tcp{master}", -1); + /* initialize remaining structure fields */ + socket_setnonblocking(&sock); + if (family == PF_INET6) { + int yes = 1; + setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, + (void *)&yes, sizeof(yes)); + } + tcp->sock = sock; + io_init(&tcp->io, (p_send) socket_send, (p_recv) socket_recv, + (p_error) socket_ioerror, &tcp->sock); + timeout_init(&tcp->tm, -1, -1); + buffer_init(&tcp->buf, &tcp->io, &tcp->tm); + tcp->family = family; + return 1; + } else { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } +} + +static int global_create(lua_State *L) { + return tcp_create(L, AF_INET); +} + +static int global_create6(lua_State *L) { + return tcp_create(L, AF_INET6); +} + +static const char *tryconnect6(const char *remoteaddr, const char *remoteserv, + struct addrinfo *connecthints, p_tcp tcp) { + struct addrinfo *iterator = NULL, *resolved = NULL; + const char *err = NULL; + /* try resolving */ + err = socket_gaistrerror(getaddrinfo(remoteaddr, remoteserv, + connecthints, &resolved)); + if (err != NULL) { + if (resolved) freeaddrinfo(resolved); + return err; + } + /* iterate over all returned addresses trying to connect */ + for (iterator = resolved; iterator; iterator = iterator->ai_next) { + p_timeout tm = timeout_markstart(&tcp->tm); + /* create new socket if one wasn't created by the bind stage */ + if (tcp->sock == SOCKET_INVALID) { + err = socket_strerror(socket_create(&tcp->sock, + iterator->ai_family, iterator->ai_socktype, + iterator->ai_protocol)); + if (err != NULL) { + freeaddrinfo(resolved); + return err; + } + tcp->family = iterator->ai_family; + /* all sockets initially non-blocking */ + socket_setnonblocking(&tcp->sock); + } + /* finally try connecting to remote address */ + err = socket_strerror(socket_connect(&tcp->sock, + (SA *) iterator->ai_addr, + (socklen_t) iterator->ai_addrlen, tm)); + /* if success, break out of loop */ + if (err == NULL) break; + } + + freeaddrinfo(resolved); + /* here, if err is set, we failed */ + return err; +} + +static int global_connect(lua_State *L) { + const char *remoteaddr = luaL_checkstring(L, 1); + const char *remoteserv = luaL_checkstring(L, 2); + const char *localaddr = luaL_optstring(L, 3, NULL); + const char *localserv = luaL_optstring(L, 4, "0"); + int family = inet_optfamily(L, 5, "unspec"); + p_tcp tcp = (p_tcp) lua_newuserdata(L, sizeof(t_tcp)); + struct addrinfo bindhints, connecthints; + const char *err = NULL; + /* initialize tcp structure */ + memset(tcp, 0, sizeof(t_tcp)); + io_init(&tcp->io, (p_send) socket_send, (p_recv) socket_recv, + (p_error) socket_ioerror, &tcp->sock); + timeout_init(&tcp->tm, -1, -1); + buffer_init(&tcp->buf, &tcp->io, &tcp->tm); + tcp->sock = SOCKET_INVALID; + /* allow user to pick local address and port */ + memset(&bindhints, 0, sizeof(bindhints)); + bindhints.ai_socktype = SOCK_STREAM; + bindhints.ai_family = family; + bindhints.ai_flags = AI_PASSIVE; + if (localaddr) { + err = inet_trybind(&tcp->sock, localaddr, localserv, &bindhints); + if (err) { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + tcp->family = bindhints.ai_family; + } + /* try to connect to remote address and port */ + memset(&connecthints, 0, sizeof(connecthints)); + connecthints.ai_socktype = SOCK_STREAM; + /* make sure we try to connect only to the same family */ + connecthints.ai_family = bindhints.ai_family; + err = tryconnect6(remoteaddr, remoteserv, &connecthints, tcp); + if (err) { + socket_destroy(&tcp->sock); + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + auxiliar_setclass(L, "tcp{client}", -1); + return 1; +} diff --git a/cocos/scripting/lua/bindings/socket/tcp.h b/cocos/scripting/lua/bindings/socket/tcp.h new file mode 100644 index 0000000000..a8b9b6f2cf --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/tcp.h @@ -0,0 +1,35 @@ +#ifndef TCP_H +#define TCP_H +/*=========================================================================*\ +* TCP object +* LuaSocket toolkit +* +* The tcp.h module is basicly a glue that puts together modules buffer.h, +* timeout.h socket.h and inet.h to provide the LuaSocket TCP (AF_INET, +* SOCK_STREAM) support. +* +* Three classes are defined: master, client and server. The master class is +* a newly created tcp object, that has not been bound or connected. Server +* objects are tcp objects bound to some local address. Client objects are +* tcp objects either connected to some address or returned by the accept +* method of a server object. +\*=========================================================================*/ +#include "lua.h" + +#include "luasocket_buffer.h" +#include "timeout.h" +#include "socket.h" + +typedef struct t_tcp_ { + t_socket sock; + t_io io; + t_buffer buf; + t_timeout tm; + int family; +} t_tcp; + +typedef t_tcp *p_tcp; + +int tcp_open(lua_State *L); + +#endif /* TCP_H */ diff --git a/cocos/scripting/lua/bindings/socket/timeout.c b/cocos/scripting/lua/bindings/socket/timeout.c new file mode 100644 index 0000000000..c7354b52f3 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/timeout.c @@ -0,0 +1,217 @@ +/*=========================================================================*\ +* Timeout management functions +* LuaSocket toolkit +\*=========================================================================*/ +#include +#include +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "auxiliar.h" +#include "timeout.h" + +#ifdef _WIN32 +#include +#else +#include +#include +#endif + +/* min and max macros */ +#ifndef MIN +#define MIN(x, y) ((x) < (y) ? x : y) +#endif +#ifndef MAX +#define MAX(x, y) ((x) > (y) ? x : y) +#endif + +/*=========================================================================*\ +* Internal function prototypes +\*=========================================================================*/ +static int timeout_lua_gettime(lua_State *L); +static int timeout_lua_sleep(lua_State *L); + +static luaL_Reg func[] = { + { "gettime", timeout_lua_gettime }, + { "sleep", timeout_lua_sleep }, + { NULL, NULL } +}; + +/*=========================================================================*\ +* Exported functions. +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Initialize structure +\*-------------------------------------------------------------------------*/ +void timeout_init(p_timeout tm, double block, double total) { + tm->block = block; + tm->total = total; +} + +/*-------------------------------------------------------------------------*\ +* Determines how much time we have left for the next system call, +* if the previous call was successful +* Input +* tm: timeout control structure +* Returns +* the number of ms left or -1 if there is no time limit +\*-------------------------------------------------------------------------*/ +double timeout_get(p_timeout tm) { + if (tm->block < 0.0 && tm->total < 0.0) { + return -1; + } else if (tm->block < 0.0) { + double t = tm->total - timeout_gettime() + tm->start; + return MAX(t, 0.0); + } else if (tm->total < 0.0) { + return tm->block; + } else { + double t = tm->total - timeout_gettime() + tm->start; + return MIN(tm->block, MAX(t, 0.0)); + } +} + +/*-------------------------------------------------------------------------*\ +* Returns time since start of operation +* Input +* tm: timeout control structure +* Returns +* start field of structure +\*-------------------------------------------------------------------------*/ +double timeout_getstart(p_timeout tm) { + return tm->start; +} + +/*-------------------------------------------------------------------------*\ +* Determines how much time we have left for the next system call, +* if the previous call was a failure +* Input +* tm: timeout control structure +* Returns +* the number of ms left or -1 if there is no time limit +\*-------------------------------------------------------------------------*/ +double timeout_getretry(p_timeout tm) { + if (tm->block < 0.0 && tm->total < 0.0) { + return -1; + } else if (tm->block < 0.0) { + double t = tm->total - timeout_gettime() + tm->start; + return MAX(t, 0.0); + } else if (tm->total < 0.0) { + double t = tm->block - timeout_gettime() + tm->start; + return MAX(t, 0.0); + } else { + double t = tm->total - timeout_gettime() + tm->start; + return MIN(tm->block, MAX(t, 0.0)); + } +} + +/*-------------------------------------------------------------------------*\ +* Marks the operation start time in structure +* Input +* tm: timeout control structure +\*-------------------------------------------------------------------------*/ +p_timeout timeout_markstart(p_timeout tm) { + tm->start = timeout_gettime(); + return tm; +} + +/*-------------------------------------------------------------------------*\ +* Gets time in s, relative to January 1, 1970 (UTC) +* Returns +* time in s. +\*-------------------------------------------------------------------------*/ +#ifdef _WIN32 +double timeout_gettime(void) { + FILETIME ft; + double t; + GetSystemTimeAsFileTime(&ft); + /* Windows file time (time since January 1, 1601 (UTC)) */ + t = ft.dwLowDateTime/1.0e7 + ft.dwHighDateTime*(4294967296.0/1.0e7); + /* convert to Unix Epoch time (time since January 1, 1970 (UTC)) */ + return (t - 11644473600.0); +} +#else +double timeout_gettime(void) { + struct timeval v; + gettimeofday(&v, (struct timezone *) NULL); + /* Unix Epoch time (time since January 1, 1970 (UTC)) */ + return v.tv_sec + v.tv_usec/1.0e6; +} +#endif + +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int timeout_open(lua_State *L) { + luaL_openlib(L, NULL, func, 0); + return 0; +} + +/*-------------------------------------------------------------------------*\ +* Sets timeout values for IO operations +* Lua Input: base, time [, mode] +* time: time out value in seconds +* mode: "b" for block timeout, "t" for total timeout. (default: b) +\*-------------------------------------------------------------------------*/ +int timeout_meth_settimeout(lua_State *L, p_timeout tm) { + double t = luaL_optnumber(L, 2, -1); + const char *mode = luaL_optstring(L, 3, "b"); + switch (*mode) { + case 'b': + tm->block = t; + break; + case 'r': case 't': + tm->total = t; + break; + default: + luaL_argcheck(L, 0, 3, "invalid timeout mode"); + break; + } + lua_pushnumber(L, 1); + return 1; +} + +/*=========================================================================*\ +* Test support functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Returns the time the system has been up, in secconds. +\*-------------------------------------------------------------------------*/ +static int timeout_lua_gettime(lua_State *L) +{ + lua_pushnumber(L, timeout_gettime()); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Sleep for n seconds. +\*-------------------------------------------------------------------------*/ +#ifdef _WIN32 +int timeout_lua_sleep(lua_State *L) +{ + double n = luaL_checknumber(L, 1); + if (n < 0.0) n = 0.0; + if (n < DBL_MAX/1000.0) n *= 1000.0; + if (n > INT_MAX) n = INT_MAX; + Sleep((int)n); + return 0; +} +#else +int timeout_lua_sleep(lua_State *L) +{ + double n = luaL_checknumber(L, 1); + struct timespec t, r; + if (n < 0.0) n = 0.0; + if (n > INT_MAX) n = INT_MAX; + t.tv_sec = (int) n; + n -= t.tv_sec; + t.tv_nsec = (int) (n * 1000000000); + if (t.tv_nsec >= 1000000000) t.tv_nsec = 999999999; + while (nanosleep(&t, &r) != 0) { + t.tv_sec = r.tv_sec; + t.tv_nsec = r.tv_nsec; + } + return 0; +} +#endif diff --git a/cocos/scripting/lua/bindings/socket/timeout.h b/cocos/scripting/lua/bindings/socket/timeout.h new file mode 100644 index 0000000000..6715ca70a1 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/timeout.h @@ -0,0 +1,28 @@ +#ifndef TIMEOUT_H +#define TIMEOUT_H +/*=========================================================================*\ +* Timeout management functions +* LuaSocket toolkit +\*=========================================================================*/ +#include "lua.h" + +/* timeout control structure */ +typedef struct t_timeout_ { + double block; /* maximum time for blocking calls */ + double total; /* total number of miliseconds for operation */ + double start; /* time of start of operation */ +} t_timeout; +typedef t_timeout *p_timeout; + +int timeout_open(lua_State *L); +void timeout_init(p_timeout tm, double block, double total); +double timeout_get(p_timeout tm); +double timeout_getretry(p_timeout tm); +p_timeout timeout_markstart(p_timeout tm); +double timeout_getstart(p_timeout tm); +double timeout_gettime(void); +int timeout_meth_settimeout(lua_State *L, p_timeout tm); + +#define timeout_iszero(tm) ((tm)->block == 0.0) + +#endif /* TIMEOUT_H */ diff --git a/cocos/scripting/lua/bindings/socket/udp.c b/cocos/scripting/lua/bindings/socket/udp.c new file mode 100644 index 0000000000..c51bd9ddd2 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/udp.c @@ -0,0 +1,468 @@ +/*=========================================================================*\ +* UDP object +* LuaSocket toolkit +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "auxiliar.h" +#include "socket.h" +#include "inet.h" +#include "options.h" +#include "udp.h" + +/* min and max macros */ +#ifndef MIN +#define MIN(x, y) ((x) < (y) ? x : y) +#endif +#ifndef MAX +#define MAX(x, y) ((x) > (y) ? x : y) +#endif + +/*=========================================================================*\ +* Internal function prototypes +\*=========================================================================*/ +static int global_create(lua_State *L); +static int global_create6(lua_State *L); +static int meth_send(lua_State *L); +static int meth_sendto(lua_State *L); +static int meth_receive(lua_State *L); +static int meth_receivefrom(lua_State *L); +static int meth_getfamily(lua_State *L); +static int meth_getsockname(lua_State *L); +static int meth_getpeername(lua_State *L); +static int meth_setsockname(lua_State *L); +static int meth_setpeername(lua_State *L); +static int meth_close(lua_State *L); +static int meth_setoption(lua_State *L); +static int meth_getoption(lua_State *L); +static int meth_settimeout(lua_State *L); +static int meth_getfd(lua_State *L); +static int meth_setfd(lua_State *L); +static int meth_dirty(lua_State *L); + +/* udp object methods */ +static luaL_Reg udp_methods[] = { + {"__gc", meth_close}, + {"__tostring", auxiliar_tostring}, + {"close", meth_close}, + {"dirty", meth_dirty}, + {"getfamily", meth_getfamily}, + {"getfd", meth_getfd}, + {"getpeername", meth_getpeername}, + {"getsockname", meth_getsockname}, + {"receive", meth_receive}, + {"receivefrom", meth_receivefrom}, + {"send", meth_send}, + {"sendto", meth_sendto}, + {"setfd", meth_setfd}, + {"setoption", meth_setoption}, + {"getoption", meth_getoption}, + {"setpeername", meth_setpeername}, + {"setsockname", meth_setsockname}, + {"settimeout", meth_settimeout}, + {NULL, NULL} +}; + +/* socket options for setoption */ +static t_opt optset[] = { + {"dontroute", opt_set_dontroute}, + {"broadcast", opt_set_broadcast}, + {"reuseaddr", opt_set_reuseaddr}, + {"reuseport", opt_set_reuseport}, + {"ip-multicast-if", opt_set_ip_multicast_if}, + {"ip-multicast-ttl", opt_set_ip_multicast_ttl}, + {"ip-multicast-loop", opt_set_ip_multicast_loop}, + {"ip-add-membership", opt_set_ip_add_membership}, + {"ip-drop-membership", opt_set_ip_drop_membersip}, + {"ipv6-v6only", opt_set_ip6_v6only}, + {NULL, NULL} +}; + +/* socket options for getoption */ +static t_opt optget[] = { + {"ip-multicast-if", opt_get_ip_multicast_if}, + {"ip-multicast-loop", opt_get_ip_multicast_loop}, + {NULL, NULL} +}; + +/* functions in library namespace */ +static luaL_Reg func[] = { + {"udp", global_create}, + {"udp6", global_create6}, + {NULL, NULL} +}; + +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int udp_open(lua_State *L) +{ + /* create classes */ + auxiliar_newclass(L, "udp{connected}", udp_methods); + auxiliar_newclass(L, "udp{unconnected}", udp_methods); + /* create class groups */ + auxiliar_add2group(L, "udp{connected}", "udp{any}"); + auxiliar_add2group(L, "udp{unconnected}", "udp{any}"); + auxiliar_add2group(L, "udp{connected}", "select{able}"); + auxiliar_add2group(L, "udp{unconnected}", "select{able}"); + /* define library functions */ + luaL_openlib(L, NULL, func, 0); + return 0; +} + +/*=========================================================================*\ +* Lua methods +\*=========================================================================*/ +const char *udp_strerror(int err) { + /* a 'closed' error on an unconnected means the target address was not + * accepted by the transport layer */ + if (err == IO_CLOSED) return "refused"; + else return socket_strerror(err); +} + +/*-------------------------------------------------------------------------*\ +* Send data through connected udp socket +\*-------------------------------------------------------------------------*/ +static int meth_send(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{connected}", 1); + p_timeout tm = &udp->tm; + size_t count, sent = 0; + int err; + const char *data = luaL_checklstring(L, 2, &count); + timeout_markstart(tm); + err = socket_send(&udp->sock, data, count, &sent, tm); + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, udp_strerror(err)); + return 2; + } + lua_pushnumber(L, (lua_Number) sent); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Send data through unconnected udp socket +\*-------------------------------------------------------------------------*/ +static int meth_sendto(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{unconnected}", 1); + size_t count, sent = 0; + const char *data = luaL_checklstring(L, 2, &count); + const char *ip = luaL_checkstring(L, 3); + unsigned short port = (unsigned short) luaL_checknumber(L, 4); + p_timeout tm = &udp->tm; + int err; + switch (udp->family) { + case PF_INET: { + struct sockaddr_in addr; + memset(&addr, 0, sizeof(addr)); + if (!my_inet_pton(AF_INET, ip, &addr.sin_addr)) + luaL_argerror(L, 3, "invalid ip address"); + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + timeout_markstart(tm); + err = socket_sendto(&udp->sock, data, count, &sent, + (SA *) &addr, sizeof(addr), tm); + break; + } + case PF_INET6: { + struct sockaddr_in6 addr; + memset(&addr, 0, sizeof(addr)); + if (!my_inet_pton(AF_INET6, ip, &addr.sin6_addr)) + luaL_argerror(L, 3, "invalid ip address"); + addr.sin6_family = AF_INET6; + addr.sin6_port = htons(port); + timeout_markstart(tm); + err = socket_sendto(&udp->sock, data, count, &sent, + (SA *) &addr, sizeof(addr), tm); + break; + } + default: + lua_pushnil(L); + lua_pushfstring(L, "unknown family %d", udp->family); + return 2; + } + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, udp_strerror(err)); + return 2; + } + lua_pushnumber(L, (lua_Number) sent); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Receives data from a UDP socket +\*-------------------------------------------------------------------------*/ +static int meth_receive(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + char buffer[UDP_DATAGRAMSIZE]; + size_t got, count = (size_t) luaL_optnumber(L, 2, sizeof(buffer)); + int err; + p_timeout tm = &udp->tm; + count = MIN(count, sizeof(buffer)); + timeout_markstart(tm); + err = socket_recv(&udp->sock, buffer, count, &got, tm); + /* Unlike TCP, recv() of zero is not closed, but a zero-length packet. */ + if (err == IO_CLOSED) + err = IO_DONE; + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, udp_strerror(err)); + return 2; + } + lua_pushlstring(L, buffer, got); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Receives data and sender from a UDP socket +\*-------------------------------------------------------------------------*/ +static int meth_receivefrom(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{unconnected}", 1); + char buffer[UDP_DATAGRAMSIZE]; + size_t got, count = (size_t) luaL_optnumber(L, 2, sizeof(buffer)); + int err; + p_timeout tm = &udp->tm; + timeout_markstart(tm); + count = MIN(count, sizeof(buffer)); + switch (udp->family) { + case PF_INET: { + struct sockaddr_in addr; + socklen_t addr_len = sizeof(addr); + err = socket_recvfrom(&udp->sock, buffer, count, &got, + (SA *) &addr, &addr_len, tm); + /* Unlike TCP, recv() of zero is not closed, but a zero-length packet. */ + if (err == IO_CLOSED) + err = IO_DONE; + if (err == IO_DONE) { + char addrstr[INET_ADDRSTRLEN]; + lua_pushlstring(L, buffer, got); + if (!my_inet_ntop(AF_INET, &addr.sin_addr, + addrstr, sizeof(addrstr))) { + lua_pushnil(L); + lua_pushstring(L, "invalid source address"); + return 2; + } + lua_pushstring(L, addrstr); + lua_pushnumber(L, ntohs(addr.sin_port)); + return 3; + } + break; + } + case PF_INET6: { + struct sockaddr_in6 addr; + socklen_t addr_len = sizeof(addr); + err = socket_recvfrom(&udp->sock, buffer, count, &got, + (SA *) &addr, &addr_len, tm); + /* Unlike TCP, recv() of zero is not closed, but a zero-length packet. */ + if (err == IO_CLOSED) + err = IO_DONE; + if (err == IO_DONE) { + char addrstr[INET6_ADDRSTRLEN]; + lua_pushlstring(L, buffer, got); + if (!my_inet_ntop(AF_INET6, &addr.sin6_addr, + addrstr, sizeof(addrstr))) { + lua_pushnil(L); + lua_pushstring(L, "invalid source address"); + return 2; + } + lua_pushstring(L, addrstr); + lua_pushnumber(L, ntohs(addr.sin6_port)); + return 3; + } + break; + } + default: + lua_pushnil(L); + lua_pushfstring(L, "unknown family %d", udp->family); + return 2; + } + lua_pushnil(L); + lua_pushstring(L, udp_strerror(err)); + return 2; +} + +/*-------------------------------------------------------------------------*\ +* Returns family as string +\*-------------------------------------------------------------------------*/ +static int meth_getfamily(lua_State *L) +{ + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + if (udp->family == PF_INET6) { + lua_pushliteral(L, "inet6"); + return 1; + } else { + lua_pushliteral(L, "inet4"); + return 1; + } +} + +/*-------------------------------------------------------------------------*\ +* Select support methods +\*-------------------------------------------------------------------------*/ +static int meth_getfd(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + lua_pushnumber(L, (int) udp->sock); + return 1; +} + +/* this is very dangerous, but can be handy for those that are brave enough */ +static int meth_setfd(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + udp->sock = (t_socket) luaL_checknumber(L, 2); + return 0; +} + +static int meth_dirty(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + (void) udp; + lua_pushboolean(L, 0); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Just call inet methods +\*-------------------------------------------------------------------------*/ +static int meth_getpeername(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{connected}", 1); + return inet_meth_getpeername(L, &udp->sock, udp->family); +} + +static int meth_getsockname(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + return inet_meth_getsockname(L, &udp->sock, udp->family); +} + +/*-------------------------------------------------------------------------*\ +* Just call option handler +\*-------------------------------------------------------------------------*/ +static int meth_setoption(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + return opt_meth_setoption(L, optset, &udp->sock); +} + +/*-------------------------------------------------------------------------*\ +* Just call option handler +\*-------------------------------------------------------------------------*/ +static int meth_getoption(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + return opt_meth_getoption(L, optget, &udp->sock); +} + +/*-------------------------------------------------------------------------*\ +* Just call tm methods +\*-------------------------------------------------------------------------*/ +static int meth_settimeout(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + return timeout_meth_settimeout(L, &udp->tm); +} + +/*-------------------------------------------------------------------------*\ +* Turns a master udp object into a client object. +\*-------------------------------------------------------------------------*/ +static int meth_setpeername(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + p_timeout tm = &udp->tm; + const char *address = luaL_checkstring(L, 2); + int connecting = strcmp(address, "*"); + const char *port = connecting? luaL_checkstring(L, 3): "0"; + struct addrinfo connecthints; + const char *err; + memset(&connecthints, 0, sizeof(connecthints)); + connecthints.ai_socktype = SOCK_DGRAM; + /* make sure we try to connect only to the same family */ + connecthints.ai_family = udp->family; + if (connecting) { + err = inet_tryconnect(&udp->sock, address, port, tm, &connecthints); + if (err) { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + auxiliar_setclass(L, "udp{connected}", 1); + } else { + /* we ignore possible errors because Mac OS X always + * returns EAFNOSUPPORT */ + inet_trydisconnect(&udp->sock, udp->family, tm); + auxiliar_setclass(L, "udp{unconnected}", 1); + } + /* change class to connected or unconnected depending on address */ + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Closes socket used by object +\*-------------------------------------------------------------------------*/ +static int meth_close(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1); + socket_destroy(&udp->sock); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Turns a master object into a server object +\*-------------------------------------------------------------------------*/ +static int meth_setsockname(lua_State *L) { + p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{unconnected}", 1); + const char *address = luaL_checkstring(L, 2); + const char *port = luaL_checkstring(L, 3); + const char *err; + struct addrinfo bindhints; + memset(&bindhints, 0, sizeof(bindhints)); + bindhints.ai_socktype = SOCK_DGRAM; + bindhints.ai_family = udp->family; + bindhints.ai_flags = AI_PASSIVE; + err = inet_trybind(&udp->sock, address, port, &bindhints); + if (err) { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + lua_pushnumber(L, 1); + return 1; +} + +/*=========================================================================*\ +* Library functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Creates a master udp object +\*-------------------------------------------------------------------------*/ +static int udp_create(lua_State *L, int family) { + t_socket sock; + const char *err = inet_trycreate(&sock, family, SOCK_DGRAM); + /* try to allocate a system socket */ + if (!err) { + /* allocate udp object */ + p_udp udp = (p_udp) lua_newuserdata(L, sizeof(t_udp)); + auxiliar_setclass(L, "udp{unconnected}", -1); + /* initialize remaining structure fields */ + socket_setnonblocking(&sock); + if (family == PF_INET6) { + int yes = 1; + setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, + (void *)&yes, sizeof(yes)); + } + udp->sock = sock; + timeout_init(&udp->tm, -1, -1); + udp->family = family; + return 1; + } else { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } +} + +static int global_create(lua_State *L) { + return udp_create(L, AF_INET); +} + +static int global_create6(lua_State *L) { + return udp_create(L, AF_INET6); +} diff --git a/cocos/scripting/lua/bindings/socket/udp.h b/cocos/scripting/lua/bindings/socket/udp.h new file mode 100644 index 0000000000..2b831a5371 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/udp.h @@ -0,0 +1,32 @@ +#ifndef UDP_H +#define UDP_H +/*=========================================================================*\ +* UDP object +* LuaSocket toolkit +* +* The udp.h module provides LuaSocket with support for UDP protocol +* (AF_INET, SOCK_DGRAM). +* +* Two classes are defined: connected and unconnected. UDP objects are +* originally unconnected. They can be "connected" to a given address +* with a call to the setpeername function. The same function can be used to +* break the connection. +\*=========================================================================*/ +#include "lua.h" + +#include "timeout.h" +#include "socket.h" + +/* can't be larger than wsocket.c MAXCHUNK!!! */ +#define UDP_DATAGRAMSIZE 8192 + +typedef struct t_udp_ { + t_socket sock; + t_timeout tm; + int family; +} t_udp; +typedef t_udp *p_udp; + +int udp_open(lua_State *L); + +#endif /* UDP_H */ diff --git a/cocos/scripting/lua/bindings/socket/unix.c b/cocos/scripting/lua/bindings/socket/unix.c new file mode 100644 index 0000000000..28d4cc7b84 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/unix.c @@ -0,0 +1,340 @@ +/*=========================================================================*\ +* Unix domain socket +* LuaSocket toolkit +\*=========================================================================*/ +#include + +#include "lua.h" +#include "lauxlib.h" + +#include "auxiliar.h" +#include "socket.h" +#include "options.h" +#include "unix.h" +#include + +/*=========================================================================*\ +* Internal function prototypes +\*=========================================================================*/ +static int global_create(lua_State *L); +static int meth_connect(lua_State *L); +static int meth_listen(lua_State *L); +static int meth_bind(lua_State *L); +static int meth_send(lua_State *L); +static int meth_shutdown(lua_State *L); +static int meth_receive(lua_State *L); +static int meth_accept(lua_State *L); +static int meth_close(lua_State *L); +static int meth_setoption(lua_State *L); +static int meth_settimeout(lua_State *L); +static int meth_getfd(lua_State *L); +static int meth_setfd(lua_State *L); +static int meth_dirty(lua_State *L); +static int meth_getstats(lua_State *L); +static int meth_setstats(lua_State *L); + +static const char *unix_tryconnect(p_unix un, const char *path); +static const char *unix_trybind(p_unix un, const char *path); + +/* unix object methods */ +static luaL_Reg unix_methods[] = { + {"__gc", meth_close}, + {"__tostring", auxiliar_tostring}, + {"accept", meth_accept}, + {"bind", meth_bind}, + {"close", meth_close}, + {"connect", meth_connect}, + {"dirty", meth_dirty}, + {"getfd", meth_getfd}, + {"getstats", meth_getstats}, + {"setstats", meth_setstats}, + {"listen", meth_listen}, + {"receive", meth_receive}, + {"send", meth_send}, + {"setfd", meth_setfd}, + {"setoption", meth_setoption}, + {"setpeername", meth_connect}, + {"setsockname", meth_bind}, + {"settimeout", meth_settimeout}, + {"shutdown", meth_shutdown}, + {NULL, NULL} +}; + +/* socket option handlers */ +static t_opt optset[] = { + {"keepalive", opt_set_keepalive}, + {"reuseaddr", opt_set_reuseaddr}, + {"linger", opt_set_linger}, + {NULL, NULL} +}; + +/* our socket creation function */ +static luaL_Reg func[] = { + {"unix", global_create}, + {NULL, NULL} +}; + + +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int luaopen_socket_unix(lua_State *L) { + /* create classes */ + auxiliar_newclass(L, "unix{master}", unix_methods); + auxiliar_newclass(L, "unix{client}", unix_methods); + auxiliar_newclass(L, "unix{server}", unix_methods); + /* create class groups */ + auxiliar_add2group(L, "unix{master}", "unix{any}"); + auxiliar_add2group(L, "unix{client}", "unix{any}"); + auxiliar_add2group(L, "unix{server}", "unix{any}"); + /* make sure the function ends up in the package table */ + luaL_openlib(L, "socket", func, 0); + /* return the function instead of the 'socket' table */ + lua_pushstring(L, "unix"); + lua_gettable(L, -2); + return 1; +} + +/*=========================================================================*\ +* Lua methods +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Just call buffered IO methods +\*-------------------------------------------------------------------------*/ +static int meth_send(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkclass(L, "unix{client}", 1); + return buffer_meth_send(L, &un->buf); +} + +static int meth_receive(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkclass(L, "unix{client}", 1); + return buffer_meth_receive(L, &un->buf); +} + +static int meth_getstats(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkclass(L, "unix{client}", 1); + return buffer_meth_getstats(L, &un->buf); +} + +static int meth_setstats(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkclass(L, "unix{client}", 1); + return buffer_meth_setstats(L, &un->buf); +} + +/*-------------------------------------------------------------------------*\ +* Just call option handler +\*-------------------------------------------------------------------------*/ +static int meth_setoption(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkgroup(L, "unix{any}", 1); + return opt_meth_setoption(L, optset, &un->sock); +} + +/*-------------------------------------------------------------------------*\ +* Select support methods +\*-------------------------------------------------------------------------*/ +static int meth_getfd(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkgroup(L, "unix{any}", 1); + lua_pushnumber(L, (int) un->sock); + return 1; +} + +/* this is very dangerous, but can be handy for those that are brave enough */ +static int meth_setfd(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkgroup(L, "unix{any}", 1); + un->sock = (t_socket) luaL_checknumber(L, 2); + return 0; +} + +static int meth_dirty(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkgroup(L, "unix{any}", 1); + lua_pushboolean(L, !buffer_isempty(&un->buf)); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Waits for and returns a client object attempting connection to the +* server object +\*-------------------------------------------------------------------------*/ +static int meth_accept(lua_State *L) { + p_unix server = (p_unix) auxiliar_checkclass(L, "unix{server}", 1); + p_timeout tm = timeout_markstart(&server->tm); + t_socket sock; + int err = socket_accept(&server->sock, &sock, NULL, NULL, tm); + /* if successful, push client socket */ + if (err == IO_DONE) { + p_unix clnt = (p_unix) lua_newuserdata(L, sizeof(t_unix)); + auxiliar_setclass(L, "unix{client}", -1); + /* initialize structure fields */ + socket_setnonblocking(&sock); + clnt->sock = sock; + io_init(&clnt->io, (p_send)socket_send, (p_recv)socket_recv, + (p_error) socket_ioerror, &clnt->sock); + timeout_init(&clnt->tm, -1, -1); + buffer_init(&clnt->buf, &clnt->io, &clnt->tm); + return 1; + } else { + lua_pushnil(L); + lua_pushstring(L, socket_strerror(err)); + return 2; + } +} + +/*-------------------------------------------------------------------------*\ +* Binds an object to an address +\*-------------------------------------------------------------------------*/ +static const char *unix_trybind(p_unix un, const char *path) { + struct sockaddr_un local; + size_t len = strlen(path); + int err; + if (len >= sizeof(local.sun_path)) return "path too long"; + memset(&local, 0, sizeof(local)); + strcpy(local.sun_path, path); + local.sun_family = AF_UNIX; +#ifdef UNIX_HAS_SUN_LEN + local.sun_len = sizeof(local.sun_family) + sizeof(local.sun_len) + + len + 1; + err = socket_bind(&un->sock, (SA *) &local, local.sun_len); + +#else + err = socket_bind(&un->sock, (SA *) &local, + (socklen_t)(sizeof(local.sun_family) + len)); +#endif + if (err != IO_DONE) socket_destroy(&un->sock); + return socket_strerror(err); +} + +static int meth_bind(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkclass(L, "unix{master}", 1); + const char *path = luaL_checkstring(L, 2); + const char *err = unix_trybind(un, path); + if (err) { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Turns a master unix object into a client object. +\*-------------------------------------------------------------------------*/ +static const char *unix_tryconnect(p_unix un, const char *path) +{ + struct sockaddr_un remote; + int err; + size_t len = strlen(path); + if (len >= sizeof(remote.sun_path)) return "path too long"; + memset(&remote, 0, sizeof(remote)); + strcpy(remote.sun_path, path); + remote.sun_family = AF_UNIX; + timeout_markstart(&un->tm); +#ifdef UNIX_HAS_SUN_LEN + remote.sun_len = sizeof(remote.sun_family) + sizeof(remote.sun_len) + + len + 1; + err = socket_connect(&un->sock, (SA *) &remote, remote.sun_len, &un->tm); +#else + err = socket_connect(&un->sock, (SA *) &remote, + (socklen_t)(sizeof(remote.sun_family) + len), &un->tm); +#endif + if (err != IO_DONE) socket_destroy(&un->sock); + return socket_strerror(err); +} + +static int meth_connect(lua_State *L) +{ + p_unix un = (p_unix) auxiliar_checkclass(L, "unix{master}", 1); + const char *path = luaL_checkstring(L, 2); + const char *err = unix_tryconnect(un, path); + if (err) { + lua_pushnil(L); + lua_pushstring(L, err); + return 2; + } + /* turn master object into a client object */ + auxiliar_setclass(L, "unix{client}", 1); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Closes socket used by object +\*-------------------------------------------------------------------------*/ +static int meth_close(lua_State *L) +{ + p_unix un = (p_unix) auxiliar_checkgroup(L, "unix{any}", 1); + socket_destroy(&un->sock); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Puts the sockt in listen mode +\*-------------------------------------------------------------------------*/ +static int meth_listen(lua_State *L) +{ + p_unix un = (p_unix) auxiliar_checkclass(L, "unix{master}", 1); + int backlog = (int) luaL_optnumber(L, 2, 32); + int err = socket_listen(&un->sock, backlog); + if (err != IO_DONE) { + lua_pushnil(L); + lua_pushstring(L, socket_strerror(err)); + return 2; + } + /* turn master object into a server object */ + auxiliar_setclass(L, "unix{server}", 1); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Shuts the connection down partially +\*-------------------------------------------------------------------------*/ +static int meth_shutdown(lua_State *L) +{ + /* SHUT_RD, SHUT_WR, SHUT_RDWR have the value 0, 1, 2, so we can use method index directly */ + static const char* methods[] = { "receive", "send", "both", NULL }; + p_unix tcp = (p_unix) auxiliar_checkclass(L, "unix{client}", 1); + int how = luaL_checkoption(L, 2, "both", methods); + socket_shutdown(&tcp->sock, how); + lua_pushnumber(L, 1); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Just call tm methods +\*-------------------------------------------------------------------------*/ +static int meth_settimeout(lua_State *L) { + p_unix un = (p_unix) auxiliar_checkgroup(L, "unix{any}", 1); + return timeout_meth_settimeout(L, &un->tm); +} + +/*=========================================================================*\ +* Library functions +\*=========================================================================*/ +/*-------------------------------------------------------------------------*\ +* Creates a master unix object +\*-------------------------------------------------------------------------*/ +static int global_create(lua_State *L) { + t_socket sock; + int err = socket_create(&sock, AF_UNIX, SOCK_STREAM, 0); + /* try to allocate a system socket */ + if (err == IO_DONE) { + /* allocate unix object */ + p_unix un = (p_unix) lua_newuserdata(L, sizeof(t_unix)); + /* set its type as master object */ + auxiliar_setclass(L, "unix{master}", -1); + /* initialize remaining structure fields */ + socket_setnonblocking(&sock); + un->sock = sock; + io_init(&un->io, (p_send) socket_send, (p_recv) socket_recv, + (p_error) socket_ioerror, &un->sock); + timeout_init(&un->tm, -1, -1); + buffer_init(&un->buf, &un->io, &un->tm); + return 1; + } else { + lua_pushnil(L); + lua_pushstring(L, socket_strerror(err)); + return 2; + } +} diff --git a/cocos/scripting/lua/bindings/socket/unix.h b/cocos/scripting/lua/bindings/socket/unix.h new file mode 100644 index 0000000000..86a961b747 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/unix.h @@ -0,0 +1,26 @@ +#ifndef UNIX_H +#define UNIX_H +/*=========================================================================*\ +* Unix domain object +* LuaSocket toolkit +* +* This module is just an example of how to extend LuaSocket with a new +* domain. +\*=========================================================================*/ +#include "lua.h" +#include "luasocket.h" +#include "luasocket_buffer.h" +#include "timeout.h" +#include "socket.h" + +typedef struct t_unix_ { + t_socket sock; + t_io io; + t_buffer buf; + t_timeout tm; +} t_unix; +typedef t_unix *p_unix; + +LUASOCKET_API int luaopen_socket_unix(lua_State *L); + +#endif /* UNIX_H */ diff --git a/cocos/scripting/lua/bindings/socket/usocket.c b/cocos/scripting/lua/bindings/socket/usocket.c new file mode 100644 index 0000000000..096ecd00b6 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/usocket.c @@ -0,0 +1,449 @@ +/*=========================================================================*\ +* Socket compatibilization module for Unix +* LuaSocket toolkit +* +* The code is now interrupt-safe. +* The penalty of calling select to avoid busy-wait is only paid when +* the I/O call fail in the first place. +\*=========================================================================*/ +#include +#include + +#include "socket.h" + +/*-------------------------------------------------------------------------*\ +* Wait for readable/writable/connected socket with timeout +\*-------------------------------------------------------------------------*/ +#ifndef SOCKET_SELECT +#include + +#define WAITFD_R POLLIN +#define WAITFD_W POLLOUT +#define WAITFD_C (POLLIN|POLLOUT) +int socket_waitfd(p_socket ps, int sw, p_timeout tm) { + int ret; + struct pollfd pfd; + pfd.fd = *ps; + pfd.events = sw; + pfd.revents = 0; + if (timeout_iszero(tm)) return IO_TIMEOUT; /* optimize timeout == 0 case */ + do { + int t = (int)(timeout_getretry(tm)*1e3); + ret = poll(&pfd, 1, t >= 0? t: -1); + } while (ret == -1 && errno == EINTR); + if (ret == -1) return errno; + if (ret == 0) return IO_TIMEOUT; + if (sw == WAITFD_C && (pfd.revents & (POLLIN|POLLERR))) return IO_CLOSED; + return IO_DONE; +} +#else + +#define WAITFD_R 1 +#define WAITFD_W 2 +#define WAITFD_C (WAITFD_R|WAITFD_W) + +int socket_waitfd(p_socket ps, int sw, p_timeout tm) { + int ret; + fd_set rfds, wfds, *rp, *wp; + struct timeval tv, *tp; + double t; + if (*ps >= FD_SETSIZE) return EINVAL; + if (timeout_iszero(tm)) return IO_TIMEOUT; /* optimize timeout == 0 case */ + do { + /* must set bits within loop, because select may have modifed them */ + rp = wp = NULL; + if (sw & WAITFD_R) { FD_ZERO(&rfds); FD_SET(*ps, &rfds); rp = &rfds; } + if (sw & WAITFD_W) { FD_ZERO(&wfds); FD_SET(*ps, &wfds); wp = &wfds; } + t = timeout_getretry(tm); + tp = NULL; + if (t >= 0.0) { + tv.tv_sec = (int)t; + tv.tv_usec = (int)((t-tv.tv_sec)*1.0e6); + tp = &tv; + } + ret = select(*ps+1, rp, wp, NULL, tp); + } while (ret == -1 && errno == EINTR); + if (ret == -1) return errno; + if (ret == 0) return IO_TIMEOUT; + if (sw == WAITFD_C && FD_ISSET(*ps, &rfds)) return IO_CLOSED; + return IO_DONE; +} +#endif + + +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int socket_open(void) { + /* instals a handler to ignore sigpipe or it will crash us */ + signal(SIGPIPE, SIG_IGN); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Close module +\*-------------------------------------------------------------------------*/ +int socket_close(void) { + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Close and inutilize socket +\*-------------------------------------------------------------------------*/ +void socket_destroy(p_socket ps) { + if (*ps != SOCKET_INVALID) { + socket_setblocking(ps); + close(*ps); + *ps = SOCKET_INVALID; + } +} + +/*-------------------------------------------------------------------------*\ +* Select with timeout control +\*-------------------------------------------------------------------------*/ +int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds, + p_timeout tm) { + int ret; + do { + struct timeval tv; + double t = timeout_getretry(tm); + tv.tv_sec = (int) t; + tv.tv_usec = (int) ((t - tv.tv_sec) * 1.0e6); + /* timeout = 0 means no wait */ + ret = select(n, rfds, wfds, efds, t >= 0.0 ? &tv: NULL); + } while (ret < 0 && errno == EINTR); + return ret; +} + +/*-------------------------------------------------------------------------*\ +* Creates and sets up a socket +\*-------------------------------------------------------------------------*/ +int socket_create(p_socket ps, int domain, int type, int protocol) { + *ps = socket(domain, type, protocol); + if (*ps != SOCKET_INVALID) return IO_DONE; + else return errno; +} + +/*-------------------------------------------------------------------------*\ +* Binds or returns error message +\*-------------------------------------------------------------------------*/ +int socket_bind(p_socket ps, SA *addr, socklen_t len) { + int err = IO_DONE; + socket_setblocking(ps); + if (bind(*ps, addr, len) < 0) err = errno; + socket_setnonblocking(ps); + return err; +} + +/*-------------------------------------------------------------------------*\ +* +\*-------------------------------------------------------------------------*/ +int socket_listen(p_socket ps, int backlog) { + int err = IO_DONE; + socket_setblocking(ps); + if (listen(*ps, backlog)) err = errno; + socket_setnonblocking(ps); + return err; +} + +/*-------------------------------------------------------------------------*\ +* +\*-------------------------------------------------------------------------*/ +void socket_shutdown(p_socket ps, int how) { + socket_setblocking(ps); + shutdown(*ps, how); + socket_setnonblocking(ps); +} + +/*-------------------------------------------------------------------------*\ +* Connects or returns error message +\*-------------------------------------------------------------------------*/ +int socket_connect(p_socket ps, SA *addr, socklen_t len, p_timeout tm) { + int err; + /* avoid calling on closed sockets */ + if (*ps == SOCKET_INVALID) return IO_CLOSED; + /* call connect until done or failed without being interrupted */ + do if (connect(*ps, addr, len) == 0) return IO_DONE; + while ((err = errno) == EINTR); + /* if connection failed immediately, return error code */ + if (err != EINPROGRESS && err != EAGAIN) return err; + /* zero timeout case optimization */ + if (timeout_iszero(tm)) return IO_TIMEOUT; + /* wait until we have the result of the connection attempt or timeout */ + err = socket_waitfd(ps, WAITFD_C, tm); + if (err == IO_CLOSED) { + if (recv(*ps, (char *) &err, 0, 0) == 0) return IO_DONE; + else return errno; + } else return err; +} + +/*-------------------------------------------------------------------------*\ +* Accept with timeout +\*-------------------------------------------------------------------------*/ +int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *len, p_timeout tm) { + if (*ps == SOCKET_INVALID) return IO_CLOSED; + for ( ;; ) { + int err; + if ((*pa = accept(*ps, addr, len)) != SOCKET_INVALID) return IO_DONE; + err = errno; + if (err == EINTR) continue; + if (err != EAGAIN && err != ECONNABORTED) return err; + if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; + } + /* can't reach here */ + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Send with timeout +\*-------------------------------------------------------------------------*/ +int socket_send(p_socket ps, const char *data, size_t count, + size_t *sent, p_timeout tm) +{ + int err; + *sent = 0; + /* avoid making system calls on closed sockets */ + if (*ps == SOCKET_INVALID) return IO_CLOSED; + /* loop until we send something or we give up on error */ + for ( ;; ) { + long put = (long) send(*ps, data, count, 0); + /* if we sent anything, we are done */ + if (put >= 0) { + *sent = put; + return IO_DONE; + } + err = errno; + /* EPIPE means the connection was closed */ + if (err == EPIPE) return IO_CLOSED; + /* we call was interrupted, just try again */ + if (err == EINTR) continue; + /* if failed fatal reason, report error */ + if (err != EAGAIN) return err; + /* wait until we can send something or we timeout */ + if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err; + } + /* can't reach here */ + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Sendto with timeout +\*-------------------------------------------------------------------------*/ +int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent, + SA *addr, socklen_t len, p_timeout tm) +{ + int err; + *sent = 0; + if (*ps == SOCKET_INVALID) return IO_CLOSED; + for ( ;; ) { + long put = (long) sendto(*ps, data, count, 0, addr, len); + if (put >= 0) { + *sent = put; + return IO_DONE; + } + err = errno; + if (err == EPIPE) return IO_CLOSED; + if (err == EINTR) continue; + if (err != EAGAIN) return err; + if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err; + } + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Receive with timeout +\*-------------------------------------------------------------------------*/ +int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm) { + int err; + *got = 0; + if (*ps == SOCKET_INVALID) return IO_CLOSED; + for ( ;; ) { + long taken = (long) recv(*ps, data, count, 0); + if (taken > 0) { + *got = taken; + return IO_DONE; + } + err = errno; + if (taken == 0) return IO_CLOSED; + if (err == EINTR) continue; + if (err != EAGAIN) return err; + if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; + } + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Recvfrom with timeout +\*-------------------------------------------------------------------------*/ +int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got, + SA *addr, socklen_t *len, p_timeout tm) { + int err; + *got = 0; + if (*ps == SOCKET_INVALID) return IO_CLOSED; + for ( ;; ) { + long taken = (long) recvfrom(*ps, data, count, 0, addr, len); + if (taken > 0) { + *got = taken; + return IO_DONE; + } + err = errno; + if (taken == 0) return IO_CLOSED; + if (err == EINTR) continue; + if (err != EAGAIN) return err; + if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; + } + return IO_UNKNOWN; +} + + +/*-------------------------------------------------------------------------*\ +* Write with timeout +* +* socket_read and socket_write are cut-n-paste of socket_send and socket_recv, +* with send/recv replaced with write/read. We can't just use write/read +* in the socket version, because behaviour when size is zero is different. +\*-------------------------------------------------------------------------*/ +int socket_write(p_socket ps, const char *data, size_t count, + size_t *sent, p_timeout tm) +{ + int err; + *sent = 0; + /* avoid making system calls on closed sockets */ + if (*ps == SOCKET_INVALID) return IO_CLOSED; + /* loop until we send something or we give up on error */ + for ( ;; ) { + long put = (long) write(*ps, data, count); + /* if we sent anything, we are done */ + if (put >= 0) { + *sent = put; + return IO_DONE; + } + err = errno; + /* EPIPE means the connection was closed */ + if (err == EPIPE) return IO_CLOSED; + /* we call was interrupted, just try again */ + if (err == EINTR) continue; + /* if failed fatal reason, report error */ + if (err != EAGAIN) return err; + /* wait until we can send something or we timeout */ + if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err; + } + /* can't reach here */ + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Read with timeout +* See note for socket_write +\*-------------------------------------------------------------------------*/ +int socket_read(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm) { + int err; + *got = 0; + if (*ps == SOCKET_INVALID) return IO_CLOSED; + for ( ;; ) { + long taken = (long) read(*ps, data, count); + if (taken > 0) { + *got = taken; + return IO_DONE; + } + err = errno; + if (taken == 0) return IO_CLOSED; + if (err == EINTR) continue; + if (err != EAGAIN) return err; + if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; + } + return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Put socket into blocking mode +\*-------------------------------------------------------------------------*/ +void socket_setblocking(p_socket ps) { + int flags = fcntl(*ps, F_GETFL, 0); + flags &= (~(O_NONBLOCK)); + fcntl(*ps, F_SETFL, flags); +} + +/*-------------------------------------------------------------------------*\ +* Put socket into non-blocking mode +\*-------------------------------------------------------------------------*/ +void socket_setnonblocking(p_socket ps) { + int flags = fcntl(*ps, F_GETFL, 0); + flags |= O_NONBLOCK; + fcntl(*ps, F_SETFL, flags); +} + +/*-------------------------------------------------------------------------*\ +* DNS helpers +\*-------------------------------------------------------------------------*/ +int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp) { + *hp = gethostbyaddr(addr, len, AF_INET); + if (*hp) return IO_DONE; + else if (h_errno) return h_errno; + else if (errno) return errno; + else return IO_UNKNOWN; +} + +int socket_gethostbyname(const char *addr, struct hostent **hp) { + *hp = gethostbyname(addr); + if (*hp) return IO_DONE; + else if (h_errno) return h_errno; + else if (errno) return errno; + else return IO_UNKNOWN; +} + +/*-------------------------------------------------------------------------*\ +* Error translation functions +* Make sure important error messages are standard +\*-------------------------------------------------------------------------*/ +const char *socket_hoststrerror(int err) { + if (err <= 0) return io_strerror(err); + switch (err) { + case HOST_NOT_FOUND: return "host not found"; + default: return hstrerror(err); + } +} + +const char *socket_strerror(int err) { + if (err <= 0) return io_strerror(err); + switch (err) { + case EADDRINUSE: return "address already in use"; + case EISCONN: return "already connected"; + case EACCES: return "permission denied"; + case ECONNREFUSED: return "connection refused"; + case ECONNABORTED: return "closed"; + case ECONNRESET: return "closed"; + case ETIMEDOUT: return "timeout"; + default: return strerror(err); + } +} + +const char *socket_ioerror(p_socket ps, int err) { + (void) ps; + return socket_strerror(err); +} + +const char *socket_gaistrerror(int err) { + if (err == 0) return NULL; + switch (err) { + case EAI_AGAIN: return "temporary failure in name resolution"; + case EAI_BADFLAGS: return "invalid value for ai_flags"; +#ifdef EAI_BADHINTS + case EAI_BADHINTS: return "invalid value for hints"; +#endif + case EAI_FAIL: return "non-recoverable failure in name resolution"; + case EAI_FAMILY: return "ai_family not supported"; + case EAI_MEMORY: return "memory allocation failure"; + case EAI_NONAME: + return "host or service not provided, or not known"; + case EAI_OVERFLOW: return "argument buffer overflow"; +#ifdef EAI_PROTOCOL + case EAI_PROTOCOL: return "resolved protocol is unknown"; +#endif + case EAI_SERVICE: return "service not supported for socket type"; + case EAI_SOCKTYPE: return "ai_socktype not supported"; + case EAI_SYSTEM: return strerror(errno); + default: return gai_strerror(err); + } +} + diff --git a/cocos/scripting/lua/bindings/socket/usocket.h b/cocos/scripting/lua/bindings/socket/usocket.h new file mode 100644 index 0000000000..8b3241bf3c --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/usocket.h @@ -0,0 +1,43 @@ +#ifndef USOCKET_H +#define USOCKET_H +/*=========================================================================*\ +* Socket compatibilization module for Unix +* LuaSocket toolkit +\*=========================================================================*/ + +/*=========================================================================*\ +* BSD include files +\*=========================================================================*/ +/* error codes */ +#include +/* close function */ +#include +/* fnctnl function and associated constants */ +#include +/* struct sockaddr */ +#include +/* socket function */ +#include +/* struct timeval */ +#include +/* gethostbyname and gethostbyaddr functions */ +#include +/* sigpipe handling */ +#include +/* IP stuff*/ +#include +#include +/* TCP options (nagle algorithm disable) */ +#include + +#ifndef SO_REUSEPORT +#define SO_REUSEPORT SO_REUSEADDR +#endif + +typedef int t_socket; +typedef t_socket *p_socket; +typedef struct sockaddr_storage t_sockaddr_storage; + +#define SOCKET_INVALID (-1) + +#endif /* USOCKET_H */ diff --git a/cocos/scripting/lua/bindings/socket/wsocket.c b/cocos/scripting/lua/bindings/socket/wsocket.c new file mode 100644 index 0000000000..19b3f11b37 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/wsocket.c @@ -0,0 +1,413 @@ +/*=========================================================================*\ +* Socket compatibilization module for Win32 +* LuaSocket toolkit +* +* The penalty of calling select to avoid busy-wait is only paid when +* the I/O call fail in the first place. +\*=========================================================================*/ +#include + +#include "socket.h" + +/* WinSock doesn't have a strerror... */ +static const char *wstrerror(int err); + +/*-------------------------------------------------------------------------*\ +* Initializes module +\*-------------------------------------------------------------------------*/ +int socket_open(void) { + WSADATA wsaData; + WORD wVersionRequested = MAKEWORD(2, 0); + int err = WSAStartup(wVersionRequested, &wsaData ); + if (err != 0) return 0; + if ((LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 0) && + (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)) { + WSACleanup(); + return 0; + } + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Close module +\*-------------------------------------------------------------------------*/ +int socket_close(void) { + WSACleanup(); + return 1; +} + +/*-------------------------------------------------------------------------*\ +* Wait for readable/writable/connected socket with timeout +\*-------------------------------------------------------------------------*/ +#define WAITFD_R 1 +#define WAITFD_W 2 +#define WAITFD_E 4 +#define WAITFD_C (WAITFD_E|WAITFD_W) + +int socket_waitfd(p_socket ps, int sw, p_timeout tm) { + int ret; + fd_set rfds, wfds, efds, *rp = NULL, *wp = NULL, *ep = NULL; + struct timeval tv, *tp = NULL; + double t; + if (timeout_iszero(tm)) return IO_TIMEOUT; /* optimize timeout == 0 case */ + if (sw & WAITFD_R) { + FD_ZERO(&rfds); + FD_SET(*ps, &rfds); + rp = &rfds; + } + if (sw & WAITFD_W) { FD_ZERO(&wfds); FD_SET(*ps, &wfds); wp = &wfds; } + if (sw & WAITFD_C) { FD_ZERO(&efds); FD_SET(*ps, &efds); ep = &efds; } + if ((t = timeout_get(tm)) >= 0.0) { + tv.tv_sec = (int) t; + tv.tv_usec = (int) ((t-tv.tv_sec)*1.0e6); + tp = &tv; + } + ret = select(0, rp, wp, ep, tp); + if (ret == -1) return WSAGetLastError(); + if (ret == 0) return IO_TIMEOUT; + if (sw == WAITFD_C && FD_ISSET(*ps, &efds)) return IO_CLOSED; + return IO_DONE; +} + +/*-------------------------------------------------------------------------*\ +* Select with int timeout in ms +\*-------------------------------------------------------------------------*/ +int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds, + p_timeout tm) { + struct timeval tv; + double t = timeout_get(tm); + tv.tv_sec = (int) t; + tv.tv_usec = (int) ((t - tv.tv_sec) * 1.0e6); + if (n <= 0) { + Sleep((DWORD) (1000*t)); + return 0; + } else return select(0, rfds, wfds, efds, t >= 0.0? &tv: NULL); +} + +/*-------------------------------------------------------------------------*\ +* Close and inutilize socket +\*-------------------------------------------------------------------------*/ +void socket_destroy(p_socket ps) { + if (*ps != SOCKET_INVALID) { + socket_setblocking(ps); /* close can take a long time on WIN32 */ + closesocket(*ps); + *ps = SOCKET_INVALID; + } +} + +/*-------------------------------------------------------------------------*\ +* +\*-------------------------------------------------------------------------*/ +void socket_shutdown(p_socket ps, int how) { + socket_setblocking(ps); + shutdown(*ps, how); + socket_setnonblocking(ps); +} + +/*-------------------------------------------------------------------------*\ +* Creates and sets up a socket +\*-------------------------------------------------------------------------*/ +int socket_create(p_socket ps, int domain, int type, int protocol) { + *ps = socket(domain, type, protocol); + if (*ps != SOCKET_INVALID) return IO_DONE; + else return WSAGetLastError(); +} + +/*-------------------------------------------------------------------------*\ +* Connects or returns error message +\*-------------------------------------------------------------------------*/ +int socket_connect(p_socket ps, SA *addr, socklen_t len, p_timeout tm) { + int err; + /* don't call on closed socket */ + if (*ps == SOCKET_INVALID) return IO_CLOSED; + /* ask system to connect */ + if (connect(*ps, addr, len) == 0) return IO_DONE; + /* make sure the system is trying to connect */ + err = WSAGetLastError(); + if (err != WSAEWOULDBLOCK && err != WSAEINPROGRESS) return err; + /* zero timeout case optimization */ + if (timeout_iszero(tm)) return IO_TIMEOUT; + /* we wait until something happens */ + err = socket_waitfd(ps, WAITFD_C, tm); + if (err == IO_CLOSED) { + int len = sizeof(err); + /* give windows time to set the error (yes, disgusting) */ + Sleep(10); + /* find out why we failed */ + getsockopt(*ps, SOL_SOCKET, SO_ERROR, (char *)&err, &len); + /* we KNOW there was an error. if 'why' is 0, we will return + * "unknown error", but it's not really our fault */ + return err > 0? err: IO_UNKNOWN; + } else return err; + +} + +/*-------------------------------------------------------------------------*\ +* Binds or returns error message +\*-------------------------------------------------------------------------*/ +int socket_bind(p_socket ps, SA *addr, socklen_t len) { + int err = IO_DONE; + socket_setblocking(ps); + if (bind(*ps, addr, len) < 0) err = WSAGetLastError(); + socket_setnonblocking(ps); + return err; +} + +/*-------------------------------------------------------------------------*\ +* +\*-------------------------------------------------------------------------*/ +int socket_listen(p_socket ps, int backlog) { + int err = IO_DONE; + socket_setblocking(ps); + if (listen(*ps, backlog) < 0) err = WSAGetLastError(); + socket_setnonblocking(ps); + return err; +} + +/*-------------------------------------------------------------------------*\ +* Accept with timeout +\*-------------------------------------------------------------------------*/ +int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *len, + p_timeout tm) { + if (*ps == SOCKET_INVALID) return IO_CLOSED; + for ( ;; ) { + int err; + /* try to get client socket */ + if ((*pa = accept(*ps, addr, len)) != SOCKET_INVALID) return IO_DONE; + /* find out why we failed */ + err = WSAGetLastError(); + /* if we failed because there was no connectoin, keep trying */ + if (err != WSAEWOULDBLOCK && err != WSAECONNABORTED) return err; + /* call select to avoid busy wait */ + if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; + } +} + +/*-------------------------------------------------------------------------*\ +* Send with timeout +* On windows, if you try to send 10MB, the OS will buffer EVERYTHING +* this can take an awful lot of time and we will end up blocked. +* Therefore, whoever calls this function should not pass a huge buffer. +\*-------------------------------------------------------------------------*/ +int socket_send(p_socket ps, const char *data, size_t count, + size_t *sent, p_timeout tm) +{ + int err; + *sent = 0; + /* avoid making system calls on closed sockets */ + if (*ps == SOCKET_INVALID) return IO_CLOSED; + /* loop until we send something or we give up on error */ + for ( ;; ) { + /* try to send something */ + int put = send(*ps, data, (int) count, 0); + /* if we sent something, we are done */ + if (put > 0) { + *sent = put; + return IO_DONE; + } + /* deal with failure */ + err = WSAGetLastError(); + /* we can only proceed if there was no serious error */ + if (err != WSAEWOULDBLOCK) return err; + /* avoid busy wait */ + if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err; + } +} + +/*-------------------------------------------------------------------------*\ +* Sendto with timeout +\*-------------------------------------------------------------------------*/ +int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent, + SA *addr, socklen_t len, p_timeout tm) +{ + int err; + *sent = 0; + if (*ps == SOCKET_INVALID) return IO_CLOSED; + for ( ;; ) { + int put = sendto(*ps, data, (int) count, 0, addr, len); + if (put > 0) { + *sent = put; + return IO_DONE; + } + err = WSAGetLastError(); + if (err != WSAEWOULDBLOCK) return err; + if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err; + } +} + +/*-------------------------------------------------------------------------*\ +* Receive with timeout +\*-------------------------------------------------------------------------*/ +int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm) { + int err; + *got = 0; + if (*ps == SOCKET_INVALID) return IO_CLOSED; + for ( ;; ) { + int taken = recv(*ps, data, (int) count, 0); + if (taken > 0) { + *got = taken; + return IO_DONE; + } + if (taken == 0) return IO_CLOSED; + err = WSAGetLastError(); + if (err != WSAEWOULDBLOCK) return err; + if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; + } +} + +/*-------------------------------------------------------------------------*\ +* Recvfrom with timeout +\*-------------------------------------------------------------------------*/ +int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got, + SA *addr, socklen_t *len, p_timeout tm) { + int err; + *got = 0; + if (*ps == SOCKET_INVALID) return IO_CLOSED; + for ( ;; ) { + int taken = recvfrom(*ps, data, (int) count, 0, addr, len); + if (taken > 0) { + *got = taken; + return IO_DONE; + } + if (taken == 0) return IO_CLOSED; + err = WSAGetLastError(); + if (err != WSAEWOULDBLOCK) return err; + if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err; + } +} + +/*-------------------------------------------------------------------------*\ +* Put socket into blocking mode +\*-------------------------------------------------------------------------*/ +void socket_setblocking(p_socket ps) { + u_long argp = 0; + ioctlsocket(*ps, FIONBIO, &argp); +} + +/*-------------------------------------------------------------------------*\ +* Put socket into non-blocking mode +\*-------------------------------------------------------------------------*/ +void socket_setnonblocking(p_socket ps) { + u_long argp = 1; + ioctlsocket(*ps, FIONBIO, &argp); +} + +/*-------------------------------------------------------------------------*\ +* DNS helpers +\*-------------------------------------------------------------------------*/ +int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp) { + *hp = gethostbyaddr(addr, len, AF_INET); + if (*hp) return IO_DONE; + else return WSAGetLastError(); +} + +int socket_gethostbyname(const char *addr, struct hostent **hp) { + *hp = gethostbyname(addr); + if (*hp) return IO_DONE; + else return WSAGetLastError(); +} + +/*-------------------------------------------------------------------------*\ +* Error translation functions +\*-------------------------------------------------------------------------*/ +const char *socket_hoststrerror(int err) { + if (err <= 0) return io_strerror(err); + switch (err) { + case WSAHOST_NOT_FOUND: return "host not found"; + default: return wstrerror(err); + } +} + +const char *socket_strerror(int err) { + if (err <= 0) return io_strerror(err); + switch (err) { + case WSAEADDRINUSE: return "address already in use"; + case WSAECONNREFUSED: return "connection refused"; + case WSAEISCONN: return "already connected"; + case WSAEACCES: return "permission denied"; + case WSAECONNABORTED: return "closed"; + case WSAECONNRESET: return "closed"; + case WSAETIMEDOUT: return "timeout"; + default: return wstrerror(err); + } +} + +const char *socket_ioerror(p_socket ps, int err) { + (void) ps; + return socket_strerror(err); +} + +static const char *wstrerror(int err) { + switch (err) { + case WSAEINTR: return "Interrupted function call"; + case WSAEACCES: return "Permission denied"; + case WSAEFAULT: return "Bad address"; + case WSAEINVAL: return "Invalid argument"; + case WSAEMFILE: return "Too many open files"; + case WSAEWOULDBLOCK: return "Resource temporarily unavailable"; + case WSAEINPROGRESS: return "Operation now in progress"; + case WSAEALREADY: return "Operation already in progress"; + case WSAENOTSOCK: return "Socket operation on nonsocket"; + case WSAEDESTADDRREQ: return "Destination address required"; + case WSAEMSGSIZE: return "Message too long"; + case WSAEPROTOTYPE: return "Protocol wrong type for socket"; + case WSAENOPROTOOPT: return "Bad protocol option"; + case WSAEPROTONOSUPPORT: return "Protocol not supported"; + case WSAESOCKTNOSUPPORT: return "Socket type not supported"; + case WSAEOPNOTSUPP: return "Operation not supported"; + case WSAEPFNOSUPPORT: return "Protocol family not supported"; + case WSAEAFNOSUPPORT: + return "Address family not supported by protocol family"; + case WSAEADDRINUSE: return "Address already in use"; + case WSAEADDRNOTAVAIL: return "Cannot assign requested address"; + case WSAENETDOWN: return "Network is down"; + case WSAENETUNREACH: return "Network is unreachable"; + case WSAENETRESET: return "Network dropped connection on reset"; + case WSAECONNABORTED: return "Software caused connection abort"; + case WSAECONNRESET: return "Connection reset by peer"; + case WSAENOBUFS: return "No buffer space available"; + case WSAEISCONN: return "Socket is already connected"; + case WSAENOTCONN: return "Socket is not connected"; + case WSAESHUTDOWN: return "Cannot send after socket shutdown"; + case WSAETIMEDOUT: return "Connection timed out"; + case WSAECONNREFUSED: return "Connection refused"; + case WSAEHOSTDOWN: return "Host is down"; + case WSAEHOSTUNREACH: return "No route to host"; + case WSAEPROCLIM: return "Too many processes"; + case WSASYSNOTREADY: return "Network subsystem is unavailable"; + case WSAVERNOTSUPPORTED: return "Winsock.dll version out of range"; + case WSANOTINITIALISED: + return "Successful WSAStartup not yet performed"; + case WSAEDISCON: return "Graceful shutdown in progress"; + case WSAHOST_NOT_FOUND: return "Host not found"; + case WSATRY_AGAIN: return "Nonauthoritative host not found"; + case WSANO_RECOVERY: return "Nonrecoverable name lookup error"; + case WSANO_DATA: return "Valid name, no data record of requested type"; + default: return "Unknown error"; + } +} + +const char *socket_gaistrerror(int err) { + if (err == 0) return NULL; + switch (err) { + case EAI_AGAIN: return "temporary failure in name resolution"; + case EAI_BADFLAGS: return "invalid value for ai_flags"; +#ifdef EAI_BADHINTS + case EAI_BADHINTS: return "invalid value for hints"; +#endif + case EAI_FAIL: return "non-recoverable failure in name resolution"; + case EAI_FAMILY: return "ai_family not supported"; + case EAI_MEMORY: return "memory allocation failure"; + case EAI_NONAME: + return "host or service not provided, or not known"; +// case EAI_OVERFLOW: return "argument buffer overflow"; +#ifdef EAI_PROTOCOL + case EAI_PROTOCOL: return "resolved protocol is unknown"; +#endif + case EAI_SERVICE: return "service not supported for socket type"; + case EAI_SOCKTYPE: return "ai_socktype not supported"; +// case EAI_SYSTEM: return strerror(errno); + default: return gai_strerrorA(err); + } +} + diff --git a/cocos/scripting/lua/bindings/socket/wsocket.h b/cocos/scripting/lua/bindings/socket/wsocket.h new file mode 100644 index 0000000000..0783b00d84 --- /dev/null +++ b/cocos/scripting/lua/bindings/socket/wsocket.h @@ -0,0 +1,25 @@ +#ifndef WSOCKET_H +#define WSOCKET_H +/*=========================================================================*\ +* Socket compatibilization module for Win32 +* LuaSocket toolkit +\*=========================================================================*/ + +/*=========================================================================*\ +* WinSock include files +\*=========================================================================*/ +#include +#include + +typedef int socklen_t; +typedef SOCKADDR_STORAGE t_sockaddr_storage; +typedef SOCKET t_socket; +typedef t_socket *p_socket; + +#define SOCKET_INVALID (INVALID_SOCKET) + +#ifndef SO_REUSEPORT +#define SO_REUSEPORT SO_REUSEADDR +#endif + +#endif /* WSOCKET_H */ diff --git a/cocos/scripting/lua/script/CCBReaderLoad.lua b/cocos/scripting/lua/script/CCBReaderLoad.lua index 733a432317..141a4e5df5 100644 --- a/cocos/scripting/lua/script/CCBReaderLoad.lua +++ b/cocos/scripting/lua/script/CCBReaderLoad.lua @@ -17,7 +17,7 @@ function CCBReaderLoad(strFilePath,proxy,owner) local i = 1 for i = 1,table.getn(ownerCallbackNames) do local callbackName = ownerCallbackNames[i] - local callbackNode = tolua.cast(ownerCallbackNodes[i],"Node") + local callbackNode = tolua.cast(ownerCallbackNodes[i],"cc.Node") if "function" == type(owner[callbackName]) then proxy:setCallback(callbackNode, owner[callbackName], ownerCallbackControlEvents[i]) @@ -33,7 +33,7 @@ function CCBReaderLoad(strFilePath,proxy,owner) for i = 1, table.getn(ownerOutletNames) do local outletName = ownerOutletNames[i] - local outletNode = tolua.cast(ownerOutletNodes[i],"Node") + local outletNode = tolua.cast(ownerOutletNodes[i],"cc.Node") owner[outletName] = outletNode end end @@ -42,8 +42,8 @@ function CCBReaderLoad(strFilePath,proxy,owner) local animationManagersForNodes = ccbReader:getAnimationManagersForNodes() for i = 1 , table.getn(nodesWithAnimationManagers) do - local innerNode = tolua.cast(nodesWithAnimationManagers[i], "Node") - local animationManager = tolua.cast(animationManagersForNodes[i], "CCBAnimationManager") + local innerNode = tolua.cast(nodesWithAnimationManagers[i], "cc.Node") + local animationManager = tolua.cast(animationManagersForNodes[i], "cc.CCBAnimationManager") local documentControllerName = animationManager:getDocumentControllerName() if "" == documentControllerName then @@ -59,7 +59,7 @@ function CCBReaderLoad(strFilePath,proxy,owner) for i = 1,table.getn(documentCallbackNames) do local callbackName = documentCallbackNames[i] - local callbackNode = tolua.cast(documentCallbackNodes[i],"Node") + local callbackNode = tolua.cast(documentCallbackNodes[i],"cc.Node") if "" ~= documentControllerName and nil ~= ccb[documentControllerName] then if "function" == type(ccb[documentControllerName][callbackName]) then proxy:setCallback(callbackNode, ccb[documentControllerName][callbackName], documentCallbackControlEvents[i]) @@ -75,7 +75,7 @@ function CCBReaderLoad(strFilePath,proxy,owner) for i = 1, table.getn(documentOutletNames) do local outletName = documentOutletNames[i] - local outletNode = tolua.cast(documentOutletNodes[i],"Node") + local outletNode = tolua.cast(documentOutletNodes[i],"cc.Node") if nil ~= ccb[documentControllerName] then ccb[documentControllerName][outletName] = tolua.cast(outletNode, proxy:getNodeTypeName(outletNode)) diff --git a/cocos/scripting/lua/script/Cocos2dConstants.lua b/cocos/scripting/lua/script/Cocos2dConstants.lua index 9e12b80b6a..55f405a78b 100644 --- a/cocos/scripting/lua/script/Cocos2dConstants.lua +++ b/cocos/scripting/lua/script/Cocos2dConstants.lua @@ -343,6 +343,10 @@ cc.Handler.EVENT_MOUSE_UP = 49 cc.Handler.EVENT_MOUSE_MOVE = 50 cc.Handler.EVENT_MOUSE_SCROLL = 51 cc.Handler.EVENT_SPINE = 52 +cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN = 53 +cc.Handler.EVENT_PHYSICS_CONTACT_PRESOLVE = 54 +cc.Handler.EVENT_PHYSICS_CONTACT_POSTSOLVE = 55 +cc.Handler.EVENT_PHYSICS_CONTACT_SEPERATE = 56 cc.EVENT_UNKNOWN = 0 cc.EVENT_TOUCH_ONE_BY_ONE = 1 @@ -352,10 +356,180 @@ cc.EVENT_MOUSE = 4 cc.EVENT_ACCELERATION = 5 cc.EVENT_CUSTOM = 6 -cc.PHYSICSSHAPE_MATERIAL_DEFAULT = {0.0, 0.5, 0.5} -cc.PHYSICSBODY_MATERIAL_DEFAULT = {0.1, 0.5, 0.5} +cc.PHYSICSSHAPE_MATERIAL_DEFAULT = {density = 0.0, restitution = 0.5, friction = 0.5} +cc.PHYSICSBODY_MATERIAL_DEFAULT = {density = 0.1, restitution = 0.5, friction = 0.5} cc.GLYPHCOLLECTION_DYNAMIC = 0 cc.GLYPHCOLLECTION_NEHE = 1 cc.GLYPHCOLLECTION_ASCII = 2 cc.GLYPHCOLLECTION_CUSTOM = 3 +cc.LabelEffect = +{ + NORMAL = 0, + OUTLINE = 1, + SHADOW = 2, + GLOW = 3, +} + +cc.KeyCode = +{ + KEY_NONE = 0, + KEY_PAUSE = 0x0013, + KEY_SCROLL_LOCK = 0x1014, + KEY_PRINT = 0x1061, + KEY_SYSREQ = 0x106A, + KEY_BREAK = 0x106B, + KEY_ESCAPE = 0x001B, + KEY_BACKSPACE = 0x0008, + KEY_TAB = 0x0009, + KEY_BACK_TAB = 0x0089, + KEY_RETURN = 0x000D, + KEY_CAPS_LOCK = 0x00E5, + KEY_SHIFT = 0x00E1, + KEY_CTRL = 0x00E3, + KEY_ALT = 0x00E9, + KEY_MENU = 0x1067, + KEY_HYPER = 0x10ED, + KEY_INSERT = 0x1063, + KEY_HOME = 0x1050, + KEY_PG_UP = 0x1055, + KEY_DELETE = 0x10FF, + KEY_END = 0x1057, + KEY_PG_DOWN = 0x1056, + KEY_LEFT_ARROW = 0x1051, + KEY_RIGHT_ARROW = 0x1053, + KEY_UP_ARROW = 0x1052, + KEY_DOWN_ARROW = 0x1054, + KEY_NUM_LOCK = 0x107F, + KEY_KP_PLUS = 0x10AB, + KEY_KP_MINUS = 0x10AD, + KEY_KP_MULTIPLY = 0x10AA, + KEY_KP_DIVIDE = 0x10AF, + KEY_KP_ENTER = 0x108D, + KEY_KP_HOME = 0x10B7, + KEY_KP_UP = 0x10B8, + KEY_KP_PG_UP = 0x10B9, + KEY_KP_LEFT = 0x10B4, + KEY_KP_FIVE = 0x10B5, + KEY_KP_RIGHT = 0x10B6, + KEY_KP_END = 0x10B1, + KEY_KP_DOWN = 0x10B2, + KEY_KP_PG_DOWN = 0x10B3, + KEY_KP_INSERT = 0x10B0, + KEY_KP_DELETE = 0x10AE, + KEY_F1 = 0x00BE, + KEY_F2 = 0x00BF, + KEY_F3 = 0x00C0, + KEY_F4 = 0x00C1, + KEY_F5 = 0x00C2, + KEY_F6 = 0x00C3, + KEY_F7 = 0x00C4, + KEY_F8 = 0x00C5, + KEY_F9 = 0x00C6, + KEY_F10 = 0x00C7, + KEY_F11 = 0x00C8, + KEY_F12 = 0x00C9, + KEY_SPACE = ' ', + KEY_EXCLAM = '!', + KEY_QUOTE = '"', + KEY_NUMBER = '#', + KEY_DOLLAR = '$', + KEY_PERCENT = '%', + KEY_CIRCUMFLEX = '^', + KEY_AMPERSAND = '&', + KEY_APOSTROPHE = '\'', + KEY_LEFT_PARENTHESIS = '(', + KEY_RIGHT_PARENTHESIS = ')', + KEY_ASTERISK = '*', + KEY_PLUS = '+', + KEY_COMMA = ',', + KEY_MINUS = '-', + KEY_PERIOD = '.', + KEY_SLASH = '/', + KEY_0 = '0', + KEY_1 = '1', + KEY_2 = '2', + KEY_3 = '3', + KEY_4 = '4', + KEY_5 = '5', + KEY_6 = '6', + KEY_7 = '7', + KEY_8 = '8', + KEY_9 = '9', + KEY_COLON = ':', + KEY_SEMICOLON = ';', + KEY_LESS_THAN = '<', + KEY_EQUAL = '=', + KEY_GREATER_THAN = '>', + KEY_QUESTION = '?', + KEY_AT = '@', + KEY_CAPITAL_A = 'A', + KEY_CAPITAL_B = 'B', + KEY_CAPITAL_C = 'C', + KEY_CAPITAL_D = 'D', + KEY_CAPITAL_E = 'E', + KEY_CAPITAL_F = 'F', + KEY_CAPITAL_G = 'G', + KEY_CAPITAL_H = 'H', + KEY_CAPITAL_I = 'I', + KEY_CAPITAL_J = 'J', + KEY_CAPITAL_K = 'K', + KEY_CAPITAL_L = 'L', + KEY_CAPITAL_M = 'M', + KEY_CAPITAL_N = 'N', + KEY_CAPITAL_O = 'O', + KEY_CAPITAL_P = 'P', + KEY_CAPITAL_Q = 'Q', + KEY_CAPITAL_R = 'R', + KEY_CAPITAL_S = 'S', + KEY_CAPITAL_T = 'T', + KEY_CAPITAL_U = 'U', + KEY_CAPITAL_V = 'V', + KEY_CAPITAL_W = 'W', + KEY_CAPITAL_X = 'X', + KEY_CAPITAL_Y = 'Y', + KEY_CAPITAL_Z = 'Z', + KEY_LEFT_BRACKET = '[', + KEY_BACK_SLASH = '\\', + KEY_RIGHT_BRACKET = ']', + KEY_UNDERSCORE = '_', + KEY_GRAVE = '`', + KEY_A = 'a', + KEY_B = 'b', + KEY_C = 'c', + KEY_D = 'd', + KEY_E = 'e', + KEY_F = 'f', + KEY_G = 'g', + KEY_H = 'h', + KEY_I = 'i', + KEY_J = 'j', + KEY_K = 'k', + KEY_L = 'l', + KEY_M = 'm', + KEY_N = 'n', + KEY_O = 'o', + KEY_P = 'p', + KEY_Q = 'q', + KEY_R = 'r', + KEY_S = 's', + KEY_T = 't', + KEY_U = 'u', + KEY_V = 'v', + KEY_W = 'w', + KEY_X = 'x', + KEY_Y = 'y', + KEY_Z = 'z', + KEY_LEFT_BRACE = '{', + KEY_BAR = '|', + KEY_RIGHT_BRACE = '}', + KEY_TILDE = '~', + KEY_EURO = 0x20AC, + KEY_POUND = 0x00A3, + KEY_YEN = 0x00A5, + KEY_MIDDLE_DOT = 0x0095, + KEY_SEARCH = 0xFFAA, +}; + + + diff --git a/cocos/scripting/lua/script/Deprecated.lua b/cocos/scripting/lua/script/Deprecated.lua index e48ba122e9..de1ea419fb 100644 --- a/cocos/scripting/lua/script/Deprecated.lua +++ b/cocos/scripting/lua/script/Deprecated.lua @@ -29,6 +29,12 @@ function TextureCacheDeprecated.destroyInstance(self) end rawset(cc.TextureCache,"destroyInstance",TextureCacheDeprecated.destroyInstance) +function TextureCacheDeprecated.dumpCachedTextureInfo(self) + deprecatedTip("self:dumpCachedTextureInfo","self:getCachedTextureInfo") + return print(self:getCachedTextureInfo()) +end +rawset(cc.TextureCache,"dumpCachedTextureInfo",TextureCacheDeprecated.dumpCachedTextureInfo) + local CCTextureCacheDeprecated = { } function CCTextureCacheDeprecated.sharedTextureCache() deprecatedTip("CCTextureCache:sharedTextureCache","CCTextureCache:getInstance") @@ -706,6 +712,21 @@ end rawset(CCEGLView,"sharedOpenGLView",CCEGLViewDeprecated.sharedOpenGLView) --functions of CCFileUtils will be deprecated end +--Enums of CCTableView will be deprecated begin +rawset(CCTableView, "kTableViewScroll",cc.SCROLLVIEW_SCRIPT_SCROLL) +rawset(CCTableView,"kTableViewZoom",cc.SCROLLVIEW_SCRIPT_ZOOM) +rawset(CCTableView,"kTableCellTouched",cc.TABLECELL_TOUCHED) +rawset(CCTableView,"kTableCellSizeForIndex",cc.TABLECELL_SIZE_FOR_INDEX) +rawset(CCTableView,"kTableCellSizeAtIndex",cc.TABLECELL_SIZE_AT_INDEX) +rawset(CCTableView,"kNumberOfCellsInTableView",cc.NUMBER_OF_CELLS_IN_TABLEVIEW) +--Enums of CCTableView will be deprecated end + +--Enums of CCScrollView will be deprecated begin +rawset(CCScrollView, "kScrollViewScroll",cc.SCROLLVIEW_SCRIPT_SCROLL) +rawset(CCScrollView,"kScrollViewZoom",cc.SCROLLVIEW_SCRIPT_ZOOM) +--Enums of CCScrollView will be deprecated end + + --functions of CCApplication will be deprecated end local CCApplicationDeprecated = { } @@ -1097,3 +1118,19 @@ end rawset(CCEGLView,"sharedOpenGLView",CCEGLViewDeprecated.sharedOpenGLView) --functions of CCEGLView will be deprecated end +--functions of cc.Node will be deprecated begin +local NodeDeprecated = { } +function NodeDeprecated.setZOrder(self,zOrder) + deprecatedTip("cc.Node:setZOrder","cc.Node:setLocalZOrder") + return self:setLocalZOrder(zOrder) +end +rawset(cc.Node,"setZOrder",NodeDeprecated.setZOrder) + +function NodeDeprecated.getZOrder(self) + deprecatedTip("cc.Node:getZOrder","cc.Node:getLocalZOrder") + return self:getLocalZOrder() +end +rawset(cc.Node,"getZOrder",NodeDeprecated.getZOrder) +--functions of cc.Node will be deprecated end + + diff --git a/cocos/scripting/lua/script/DeprecatedClass.lua b/cocos/scripting/lua/script/DeprecatedClass.lua index c899d0a0dc..05e476a6fe 100644 --- a/cocos/scripting/lua/script/DeprecatedClass.lua +++ b/cocos/scripting/lua/script/DeprecatedClass.lua @@ -175,6 +175,15 @@ end _G["CCEaseElasticOut"] = DeprecatedClass.CCEaseElasticOut() --CCEaseElasticOut class will be Deprecated,end +--CCTableViewCell class will be Deprecated,begin +function DeprecatedClass.CCTableViewCell() + deprecatedTip("CCTableViewCell","cc.TableViewCell") + return cc.TableViewCell +end +_G["CCTableViewCell"] = DeprecatedClass.CCTableViewCell() +--CCTableViewCell class will be Deprecated,end + + --CCEaseBackOut class will be Deprecated,begin function DeprecatedClass.CCEaseBackOut() deprecatedTip("CCEaseBackOut","cc.EaseBackOut") @@ -719,6 +728,15 @@ end _G["CCPlace"] = DeprecatedClass.CCPlace() --CCPlace class will be Deprecated,end +--CCScrollView class will be Deprecated,begin +function DeprecatedClass.CCScrollView() + deprecatedTip("CCScrollView","cc.ScrollView") + return cc.ScrollView +end +_G["CCScrollView"] = DeprecatedClass.CCScrollView() +--CCScrollView class will be Deprecated,end + + --CCGLProgram class will be Deprecated,begin function DeprecatedClass.CCGLProgram() deprecatedTip("CCGLProgram","cc.GLProgram") @@ -799,6 +817,15 @@ end _G["CCParticleFlower"] = DeprecatedClass.CCParticleFlower() --CCParticleFlower class will be Deprecated,end +--CCTableView class will be Deprecated,begin +function DeprecatedClass.CCTableView() + deprecatedTip("CCTableView","cc.TableView") + return cc.TableView +end +_G["CCTableView"] = DeprecatedClass.CCTableView() +--CCTableView class will be Deprecated,end + + --CCParticleSmoke class will be Deprecated,begin function DeprecatedClass.CCParticleSmoke() deprecatedTip("CCParticleSmoke","cc.ParticleSmoke") @@ -2127,4 +2154,20 @@ end _G["CCBProxy"] = DeprecatedClass.CCBProxy() --CCBProxy class will be Deprecated,end +--WebSocket class will be Deprecated,begin +function DeprecatedClass.WebSocket() + deprecatedTip("WebSocket","cc.WebSocket") + return cc.WebSocket +end +_G["WebSocket"] = DeprecatedClass.WebSocket() +--WebSocket class will be Deprecated,end + +--XMLHttpRequest class will be Deprecated,begin +function DeprecatedClass.XMLHttpRequest() + deprecatedTip("XMLHttpRequest","cc.XMLHttpRequest") + return cc.XMLHttpRequest +end +_G["XMLHttpRequest"] = DeprecatedClass.XMLHttpRequest() +--XMLHttpRequest class will be Deprecated,end + diff --git a/cocos/storage/local-storage/LocalStorage.cpp b/cocos/storage/local-storage/LocalStorage.cpp index 436432abce..a3ca1c70ad 100644 --- a/cocos/storage/local-storage/LocalStorage.cpp +++ b/cocos/storage/local-storage/LocalStorage.cpp @@ -27,7 +27,8 @@ Works on cocos2d-iphone and cocos2d-x. */ -#include "cocos2d.h" +#include "LocalStorage.h" +#include "CCPlatformMacros.h" #if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) @@ -55,16 +56,16 @@ static void localStorageCreateTable() printf("Error in CREATE TABLE\n"); } -void localStorageInit( const char *fullpath) +void localStorageInit( const std::string& fullpath/* = "" */) { if( ! _initialized ) { int ret = 0; - if (!fullpath) + if (fullpath.empty()) ret = sqlite3_open(":memory:",&_db); else - ret = sqlite3_open(fullpath, &_db); + ret = sqlite3_open(fullpath.c_str(), &_db); localStorageCreateTable(); @@ -103,12 +104,12 @@ void localStorageFree() } /** sets an item in the LS */ -void localStorageSetItem( const char *key, const char *value) +void localStorageSetItem( const std::string& key, const std::string& value) { assert( _initialized ); - int ok = sqlite3_bind_text(_stmt_update, 1, key, -1, SQLITE_TRANSIENT); - ok |= sqlite3_bind_text(_stmt_update, 2, value, -1, SQLITE_TRANSIENT); + int ok = sqlite3_bind_text(_stmt_update, 1, key.c_str(), -1, SQLITE_TRANSIENT); + ok |= sqlite3_bind_text(_stmt_update, 2, value.c_str(), -1, SQLITE_TRANSIENT); ok |= sqlite3_step(_stmt_update); @@ -119,29 +120,31 @@ void localStorageSetItem( const char *key, const char *value) } /** gets an item from the LS */ -const char* localStorageGetItem( const char *key ) +std::string localStorageGetItem( const std::string& key ) { assert( _initialized ); + std::string ret; int ok = sqlite3_reset(_stmt_select); - ok |= sqlite3_bind_text(_stmt_select, 1, key, -1, SQLITE_TRANSIENT); + ok |= sqlite3_bind_text(_stmt_select, 1, key.c_str(), -1, SQLITE_TRANSIENT); ok |= sqlite3_step(_stmt_select); - const unsigned char *ret = sqlite3_column_text(_stmt_select, 0); - + const unsigned char *text = sqlite3_column_text(_stmt_select, 0); + if (text) + ret = (const char*)text; if( ok != SQLITE_OK && ok != SQLITE_DONE && ok != SQLITE_ROW) printf("Error in localStorage.getItem()\n"); - return (const char*)ret; + return ret; } /** removes an item from the LS */ -void localStorageRemoveItem( const char *key ) +void localStorageRemoveItem( const std::string& key ) { assert( _initialized ); - int ok = sqlite3_bind_text(_stmt_remove, 1, key, -1, SQLITE_TRANSIENT); + int ok = sqlite3_bind_text(_stmt_remove, 1, key.c_str(), -1, SQLITE_TRANSIENT); ok |= sqlite3_step(_stmt_remove); diff --git a/cocos/storage/local-storage/LocalStorage.h b/cocos/storage/local-storage/LocalStorage.h index c38704616d..c79d46b1ee 100644 --- a/cocos/storage/local-storage/LocalStorage.h +++ b/cocos/storage/local-storage/LocalStorage.h @@ -30,22 +30,21 @@ THE SOFTWARE. #ifndef __JSB_LOCALSTORAGE_H #define __JSB_LOCALSTORAGE_H -#include -#include +#include /** Initializes the database. If path is null, it will create an in-memory DB */ -void localStorageInit( const char *fullpath); +void localStorageInit( const std::string& fullpath = ""); /** Frees the allocated resources */ void localStorageFree(); /** sets an item in the LS */ -void localStorageSetItem( const char *key, const char *value); +void localStorageSetItem( const std::string& key, const std::string& value); /** gets an item from the LS */ -const char* localStorageGetItem( const char *key ); +std::string localStorageGetItem( const std::string& key ); /** removes an item from the LS */ -void localStorageRemoveItem( const char *key ); +void localStorageRemoveItem( const std::string& key ); #endif // __JSB_LOCALSTORAGE_H diff --git a/cocos/storage/local-storage/LocalStorageAndroid.cpp b/cocos/storage/local-storage/LocalStorageAndroid.cpp index 93de8f5dc2..e95d40cf71 100644 --- a/cocos/storage/local-storage/LocalStorageAndroid.cpp +++ b/cocos/storage/local-storage/LocalStorageAndroid.cpp @@ -28,14 +28,14 @@ Works on cocos2d-iphone and cocos2d-x. */ -#include "cocos2d.h" +#include "LocalStorage.h" +#include "CCPlatformMacros.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include #include #include -#include #include "jni.h" #include "jni/JniHelper.h" @@ -52,27 +52,28 @@ static void splitFilename (std::string& str) } } -void localStorageInit( const char *fullpath) +void localStorageInit( const std::string& fullpath) { - if (fullpath == NULL || strlen(fullpath) == 0) return; + if (fullpath.empty()) + return; - if( ! _initialized ) { - JniMethodInfo t; + if( ! _initialized ) + { + JniMethodInfo t; - if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxLocalStorage", "init", "(Ljava/lang/String;Ljava/lang/String;)Z")) { - std::string strDBFilename = fullpath; - splitFilename(strDBFilename); - jstring jdbName = t.env->NewStringUTF(strDBFilename.c_str()); - jstring jtableName = t.env->NewStringUTF("data"); - jboolean ret = t.env->CallStaticBooleanMethod(t.classID, t.methodID, jdbName, jtableName); - t.env->DeleteLocalRef(jdbName); - t.env->DeleteLocalRef(jtableName); - t.env->DeleteLocalRef(t.classID); - if (ret) { - _initialized = 1; - } - } - + if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxLocalStorage", "init", "(Ljava/lang/String;Ljava/lang/String;)Z")) { + std::string strDBFilename = fullpath; + splitFilename(strDBFilename); + jstring jdbName = t.env->NewStringUTF(strDBFilename.c_str()); + jstring jtableName = t.env->NewStringUTF("data"); + jboolean ret = t.env->CallStaticBooleanMethod(t.classID, t.methodID, jdbName, jtableName); + t.env->DeleteLocalRef(jdbName); + t.env->DeleteLocalRef(jtableName); + t.env->DeleteLocalRef(t.classID); + if (ret) { + _initialized = 1; + } + } } } @@ -93,15 +94,15 @@ void localStorageFree() } /** sets an item in the LS */ -void localStorageSetItem( const char *key, const char *value) +void localStorageSetItem( const std::string& key, const std::string& value) { assert( _initialized ); JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxLocalStorage", "setItem", "(Ljava/lang/String;Ljava/lang/String;)V")) { - jstring jkey = t.env->NewStringUTF(key); - jstring jvalue = t.env->NewStringUTF(value); + jstring jkey = t.env->NewStringUTF(key.c_str()); + jstring jvalue = t.env->NewStringUTF(value.c_str()); t.env->CallStaticVoidMethod(t.classID, t.methodID, jkey, jvalue); t.env->DeleteLocalRef(jkey); t.env->DeleteLocalRef(jvalue); @@ -110,30 +111,31 @@ void localStorageSetItem( const char *key, const char *value) } /** gets an item from the LS */ -const char* localStorageGetItem( const char *key ) +std::string localStorageGetItem( const std::string& key ) { assert( _initialized ); JniMethodInfo t; - String* pStr = NULL; + + std::string ret; if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxLocalStorage", "getItem", "(Ljava/lang/String;)Ljava/lang/String;")) { - jstring jkey = t.env->NewStringUTF(key); - jstring ret = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID, jkey); - pStr = String::create(JniHelper::jstring2string(ret)); - t.env->DeleteLocalRef(ret); + jstring jkey = t.env->NewStringUTF(key.c_str()); + jstring jret = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID, jkey); + ret = JniHelper::jstring2string(jret); + t.env->DeleteLocalRef(jret); t.env->DeleteLocalRef(jkey); t.env->DeleteLocalRef(t.classID); } - return pStr ? pStr->getCString() : NULL; + return ret; } /** removes an item from the LS */ -void localStorageRemoveItem( const char *key ) +void localStorageRemoveItem( const std::string& key ) { assert( _initialized ); JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxLocalStorage", "removeItem", "(Ljava/lang/String;)V")) { - jstring jkey = t.env->NewStringUTF(key); + jstring jkey = t.env->NewStringUTF(key.c_str()); t.env->CallStaticVoidMethod(t.classID, t.methodID, jkey); t.env->DeleteLocalRef(jkey); t.env->DeleteLocalRef(t.classID); diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md index c9e5c61dcd..73409beae2 100644 --- a/docs/RELEASE_NOTES.md +++ b/docs/RELEASE_NOTES.md @@ -45,11 +45,13 @@ - [`ccTypes.h`](#cctypesh) - [deprecated functions and global variables](#deprecated-functions-and--global-variables) - [Changes in the Lua bindings](#changes-in-the-lua-bindings) - - [Use bindings-generator tool for Lua binding](#use-bindings-generator-tool-for-lua-binding) + - [Use bindings-generator tool for lua binding](#use-bindings-generator-tool-for-lua-binding) + - [Bind the classes with namespace to lua](#bind-the-classes-with-namespace-to-lua) - [Use ScriptHandlerMgr to manage the register and unregister of lua function](#use-scripthandlermgr-to-manage-the-register-and-unregister-of-lua-function) - [Use "cc" and "ccs" as module name](#use-cc-and-ccs-as-module-name) - [Deprecated funtions, tables and classes](#deprecated-funtions-tables-and-classes) - [Use the lua table instead of the some structs and classes binding](#use-the-lua-table-instead-of-the-some-structs-and-classes-binding) + - [Integrate more modules into lua](#integrate-more-modules-into-lua) - [Known issues](#known-issues) # Misc Information @@ -305,13 +307,43 @@ void setTexParameters(const ccTexParams& texParams); ## New Renderer -_Feature added in v3.0-beta_ +_Feature added in v3.0-beta and improved in v3.0-beta2_ The renderer functionality has been decoupled from the Scene graph / Node logic. A new object called `Renderer` is responsible for rendering the object. -Auto-batching and auto-culling support has been added. +Auto-batching ~~and auto-culling~~ support has been added. + +Please, see this document for detail information about its internal funcitonality: [Renderer Specification document](https://docs.google.com/document/d/17zjC55vbP_PYTftTZEuvqXuMb9PbYNxRFu0EGTULPK8/edit) + +### Renderer features + +#### Auto-batching + +TODO + +#### Auto-culling + +TODO + +#### Global Z order + +A new method called `setGlobalZOrder()` / `getGlobalZOrder()` was added to `Node`, and the old methods `setZOrder()` / `getZOrder()` were renamed to `setLocalZOrder()` / `getLocalZOrder()`. + +`globalZOrder` receives a `float` (and not an `int`) as argument. And this value is used to sort the Nodes in the Renderer. Lower values have higher priority over higher values. That means that a Node with a `globalZOrder` of `-10` is going to be drawn BEFORE a Node with `globalZOrder` of `10`. + +Nodes that have a `globalZOrder` of `0` (default value) will be drawn according to the Scene Graph order. + +So, if the `globalZOrder` is not changed, cocos2d-x v3.0 will behave exaclty as cocos2d-x v2.2. + +__`globalZOrder()` vs. `localZOrder()`__: + +* `globalZOrder` is used to sort the "draw commands" in the Renderer +* `localZOrder` is used to sort the Node in its parent's children Array + +__Exceptions__: + +TODO -Please, see this document for detail information about its internal funcitonality: https://docs.google.com/document/d/17zjC55vbP_PYTftTZEuvqXuMb9PbYNxRFu0EGTULPK8/edit ## Improved LabelTTF / LabelBMFont @@ -599,7 +631,7 @@ color3B = Color3B::WHITE; | Director::sharedDirector() | Director::getInstance() | | FileUtils::sharedFileUtils | FileUtils::getInstance | | FileUtils::purgeFileUtils | FileUtils::destroyInstance | - | EGLView::sharedOpenGLView | EGLView::getInstance | + | GLView::sharedOpenGLView | GLView::getInstance | | ShaderCache::sharedShaderCache | ShaderCache::getInstance | | ShaderCache::purgeSharedShaderCache | ShaderCache::destroyInstance | | AnimationCache::sharedAnimationCache | AnimationCache::getInstance | @@ -633,9 +665,21 @@ color3B = Color3B::WHITE; ## Changes in the Lua bindings -### Use bindings-generator tool for Lua binding +### Use bindings-generator tool for lua binding -Only configurating the *.ini files in the tools/tolua folder,not to write a lot of *.pkg files +Only have to write an ini file for a module, don't have to write a lot of .pkg files + +### Bind the classes with namespace to lua + +In previous, the lua binding can not bind classes that have the same class name but different namespaces. In order to resolve this issue, now the metatable name of a class is changed. For example, `CCNode` will be changed to `cc.Node`. This modification will affect some APIs as follows: + + | v2.x | v3.0 | + | tolua_usertype(tolua_S,"CCNode") | tolua_usertype(tolua_S,"cc.Node") | + | tolua_isusertable(tolua_S,1,"CCNode",0,&tolua_err | tolua_isusertable(tolua_S,1,"cc.Node",0,&tolua_err | + | tolua_isusertype(tolua_S,1,"CCNode",0,&tolua_err) | tolua_isusertype(tolua_S,1,"cc.Node",0,&tolua_err) | + | toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"CCNode") | toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"cc.Node") | + | tolua_pushusertype(tolua_S,(void*)tolua_ret,"CCFileUtils") | tolua_pushusertype(tolua_S,(void*)tolua_ret,"cc.FileUtils") | + | tolua.cast(pChildren[i + 1], "CCNode") | tolua.cast(pChildren[i + 1], "cc.Node") | ### Use ScriptHandlerMgr to manage the register and unregister of Lua function @@ -656,20 +700,29 @@ In v3.0 version, we only need to add the `HandlerType` enum in the `ScriptHandle ScriptHandlerMgr:getInstance():registerScriptHandler(menuItem, luafunction,cc.HANDLERTYPE_MENU_CLICKED) ``` -### Use "cc" and "ccs" as module name +### Use "cc"、"ccs"、"ccui" and "sp" as module name +The classes in the `cocos2d`、`cocos2d::extension`、`CocosDenshion` and `cocosbuilder` namespace were bound to lua in the `cc` module; +The classes in the `cocos2d::gui` namespace were bound to lua in the `ccui` module; +The classes in the `spine` namespace were bound to lua in the `sp` module; +The classes in the `cocostudio` namespace were bound to lua in the `ccs` module. +The main differences in the script are as follows: ```lua // v2.x CCSprite:create(s_pPathGrossini) CCEaseIn:create(createSimpleMoveBy(), 2.5) -UILayout:create() +CCArmature:create("bear") + +ImageView:create() // v3.0 cc.Director:getInstance():getWinSize() cc.EaseIn:create(createSimpleMoveBy(), 2.5) -ccs.UILayer:create() +ccs.Armature:create("bear") + +ccui.ImageView:create() ``` ### Deprecated funtions, tables and classes @@ -705,6 +758,24 @@ local color4B = cc.c4b(0,0,0,0) Through the funtions of the LuaBasicConversion file,they can be converted the Lua table when they are as a parameter in the bindings generator. +### Integrate more modules into lua +In the version 3.0,more modules were bound to lua,specific as follows: + +``` +1.physics +2.spine +3.XMLHttpRequest +``` +The XMLHttpRequest and physics are in the "cc" module,and the spine is in the "sp" module. +The related test cases located in: + +``` +physics ---> TestLua/PhysicsTest +spine ---> TestLua/SpineTest +XMLHttpRequest ---> TestLua/XMLHttpRequestTest +``` + + ## Known issues diff --git a/extensions/Android.mk b/extensions/Android.mk index a06c09bc47..638161b4af 100644 --- a/extensions/Android.mk +++ b/extensions/Android.mk @@ -38,9 +38,6 @@ LOCAL_WHOLE_STATIC_LIBRARIES += libwebsockets_static LOCAL_CXXFLAGS += -fexceptions -LOCAL_CFLAGS += -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -LOCAL_EXPORT_CFLAGS += -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 - LOCAL_C_INCLUDES := $(LOCAL_PATH)/.. LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. \ diff --git a/extensions/GUI/CCControlExtension/CCControl.h b/extensions/GUI/CCControlExtension/CCControl.h index 4e36bbe753..5c1815291f 100644 --- a/extensions/GUI/CCControlExtension/CCControl.h +++ b/extensions/GUI/CCControlExtension/CCControl.h @@ -31,12 +31,11 @@ #define __CCCONTROL_H__ #include "CCControlUtils.h" -#include "cocos2d.h" +#include "CCLayer.h" NS_CC_EXT_BEGIN - class Invocation; /** diff --git a/extensions/GUI/CCControlExtension/CCControlButton.h b/extensions/GUI/CCControlExtension/CCControlButton.h index d4208c0566..35202c6cec 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.h +++ b/extensions/GUI/CCControlExtension/CCControlButton.h @@ -33,6 +33,7 @@ #include "CCControl.h" #include "CCInvocation.h" #include "CCScale9Sprite.h" +#include "CCMap.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCControlPotentiometer.cpp b/extensions/GUI/CCControlExtension/CCControlPotentiometer.cpp index ab3fccdb74..b813750887 100644 --- a/extensions/GUI/CCControlExtension/CCControlPotentiometer.cpp +++ b/extensions/GUI/CCControlExtension/CCControlPotentiometer.cpp @@ -26,7 +26,6 @@ */ #include "CCControlPotentiometer.h" -#include "cocos2d.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCControlPotentiometer.h b/extensions/GUI/CCControlExtension/CCControlPotentiometer.h index bebe39b382..74d0219bc9 100644 --- a/extensions/GUI/CCControlExtension/CCControlPotentiometer.h +++ b/extensions/GUI/CCControlExtension/CCControlPotentiometer.h @@ -28,6 +28,7 @@ #define __CCCONTROLPOTENTIOMETER_H__ #include "CCControl.h" +#include "CCProgressTimer.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCControlStepper.h b/extensions/GUI/CCControlExtension/CCControlStepper.h index 1741e8c8a8..2376db9c99 100644 --- a/extensions/GUI/CCControlExtension/CCControlStepper.h +++ b/extensions/GUI/CCControlExtension/CCControlStepper.h @@ -29,6 +29,7 @@ #define __CCCONTROLSTEPPER_H__ #include "CCControl.h" +#include "CCLabelTTF.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp index f583398f06..e37c76735f 100644 --- a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp @@ -26,7 +26,12 @@ */ #include "CCControlSwitch.h" -#include "cocos2d.h" +#include "CCSprite.h" +#include "CCActionTween.h" +#include "CCLabelTTF.h" +#include "CCClippingNode.h" +#include "ccShaders.h" +#include "CCRenderTexture.h" NS_CC_EXT_BEGIN // ControlSwitchSprite diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp index 532c7fcf06..9f1a19e813 100644 --- a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp +++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp @@ -26,6 +26,9 @@ THE SOFTWARE. ****************************************************************************/ #include "CCScale9Sprite.h" +#include "CCPlatformMacros.h" +#include "CCSprite.h" +#include "CCSpriteFrameCache.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.h b/extensions/GUI/CCControlExtension/CCScale9Sprite.h index 6b91aac717..fbeca870eb 100644 --- a/extensions/GUI/CCControlExtension/CCScale9Sprite.h +++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.h @@ -28,7 +28,10 @@ THE SOFTWARE. #ifndef __CCScale9Sprite_H__ #define __CCScale9Sprite_H__ -#include "cocos2d.h" +#include "CCNode.h" +#include "CCSpriteFrame.h" +#include "CCSpriteBatchNode.h" + #include "../../ExtensionMacros.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCEditBox/CCEditBox.h b/extensions/GUI/CCEditBox/CCEditBox.h index a1aac55d6e..ff6a4149b4 100644 --- a/extensions/GUI/CCEditBox/CCEditBox.h +++ b/extensions/GUI/CCEditBox/CCEditBox.h @@ -26,7 +26,7 @@ #ifndef __CCEDITTEXT_H__ #define __CCEDITTEXT_H__ -#include "cocos2d.h" +#include "CCIMEDelegate.h" #include "extensions/ExtensionMacros.h" #include "../CCControlExtension/CCControlExtensions.h" diff --git a/extensions/GUI/CCEditBox/CCEditBoxImpl.h b/extensions/GUI/CCEditBox/CCEditBoxImpl.h index b01362eff0..7cb6c6ed1c 100644 --- a/extensions/GUI/CCEditBox/CCEditBoxImpl.h +++ b/extensions/GUI/CCEditBox/CCEditBoxImpl.h @@ -26,7 +26,6 @@ #ifndef __CCEditBoxIMPL_H__ #define __CCEditBoxIMPL_H__ -#include "cocos2d.h" #include "extensions/ExtensionMacros.h" #include "CCEditBox.h" diff --git a/extensions/GUI/CCEditBox/CCEditBoxImplIOS.mm b/extensions/GUI/CCEditBox/CCEditBoxImplIOS.mm index 25b07839ea..c107328dae 100644 --- a/extensions/GUI/CCEditBox/CCEditBoxImplIOS.mm +++ b/extensions/GUI/CCEditBox/CCEditBoxImplIOS.mm @@ -29,15 +29,18 @@ #define kLabelZOrder 9999 #include "CCEditBox.h" -#import "EAGLView.h" +#import "CCEAGLView.h" #define getEditBoxImplIOS() ((cocos2d::extension::EditBoxImplIOS*)editBox_) static const int CC_EDIT_BOX_PADDING = 5; @implementation CCCustomUITextField -- (CGRect)textRectForBounds:(CGRect)bounds { - float padding = CC_EDIT_BOX_PADDING * cocos2d::EGLView::getInstance()->getScaleX() / [[CCEAGLView sharedEGLView] contentScaleFactor ]; +- (CGRect)textRectForBounds:(CGRect)bounds +{ + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + + float padding = CC_EDIT_BOX_PADDING * glview->getScaleX() / glview->getContentScaleFactor(); return CGRectMake(bounds.origin.x + padding, bounds.origin.y + padding, bounds.size.width - padding*2, bounds.size.height - padding*2); } @@ -92,8 +95,10 @@ static const int CC_EDIT_BOX_PADDING = 5; -(void) doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)distance { - id eglView = [CCEAGLView sharedEGLView]; - [eglView doAnimationWhenKeyboardMoveWithDuration:duration distance:distance]; + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView *) view->getEAGLView(); + + [eaglview doAnimationWhenKeyboardMoveWithDuration:duration distance:distance]; } -(void) setPosition:(CGPoint) pos @@ -117,7 +122,10 @@ static const int CC_EDIT_BOX_PADDING = 5; -(void) openKeyboard { - [[CCEAGLView sharedEGLView] addSubview:textField_]; + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView *) view->getEAGLView(); + + [eaglview addSubview:textField_]; [textField_ becomeFirstResponder]; } @@ -137,16 +145,21 @@ static const int CC_EDIT_BOX_PADDING = 5; -(void)animationSelector { - id eglView = [CCEAGLView sharedEGLView]; - [eglView doAnimationWhenAnotherEditBeClicked]; + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView *) view->getEAGLView(); + + [eaglview doAnimationWhenAnotherEditBeClicked]; } - (BOOL)textFieldShouldBeginEditing:(UITextField *)sender // return NO to disallow editing. { CCLOG("textFieldShouldBeginEditing..."); editState_ = YES; - id eglView = [CCEAGLView sharedEGLView]; - if ([eglView isKeyboardShown]) + + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView *) view->getEAGLView(); + + if ([eaglview isKeyboardShown]) { [self performSelector:@selector(animationSelector) withObject:nil afterDelay:0.0f]; } @@ -261,7 +274,9 @@ EditBoxImplIOS::EditBoxImplIOS(EditBox* pEditText) , _systemControl(NULL) , _maxTextLength(-1) { - _inRetinaMode = [[CCEAGLView sharedEGLView] contentScaleFactor] == 2.0f ? true : false; + auto view = cocos2d::Director::getInstance()->getOpenGLView(); + + _inRetinaMode = view->isRetinaDisplay(); } EditBoxImplIOS::~EditBoxImplIOS() @@ -281,9 +296,9 @@ bool EditBoxImplIOS::initWithSize(const Size& size) { do { - EGLViewProtocol* eglView = EGLView::getInstance(); + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); - CGRect rect = CGRectMake(0, 0, size.width * eglView->getScaleX(),size.height * eglView->getScaleY()); + CGRect rect = CGRectMake(0, 0, size.width * glview->getScaleX(),size.height * glview->getScaleY()); if (_inRetinaMode) { @@ -358,7 +373,10 @@ void EditBoxImplIOS::setFont(const char* pFontName, int fontSize) float retinaFactor = _inRetinaMode ? 2.0f : 1.0f; NSString * fntName = [NSString stringWithUTF8String:pFontName]; - float scaleFactor = EGLView::getInstance()->getScaleX(); + + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + + float scaleFactor = glview->getScaleX(); UIFont *textFont = nil; if (isValidFontName) { textFont = [UIFont fontWithName:fntName size:fontSize * scaleFactor / retinaFactor]; @@ -528,11 +546,13 @@ void EditBoxImplIOS::setPlaceHolder(const char* pText) static CGPoint convertDesignCoordToScreenCoord(const Point& designCoord, bool bInRetinaMode) { - EGLViewProtocol* eglView = EGLView::getInstance(); - float viewH = (float)[[CCEAGLView sharedEGLView] getHeight]; + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView *) glview->getEAGLView(); + + float viewH = (float)[eaglview getHeight]; - Point visiblePos = Point(designCoord.x * eglView->getScaleX(), designCoord.y * eglView->getScaleY()); - Point screenGLPos = visiblePos + eglView->getViewPortRect().origin; + Point visiblePos = Point(designCoord.x * glview->getScaleX(), designCoord.y * glview->getScaleY()); + Point screenGLPos = visiblePos + glview->getViewPortRect().origin; CGPoint screenPos = CGPointMake(screenGLPos.x, viewH - screenGLPos.y); @@ -561,8 +581,8 @@ void EditBoxImplIOS::setContentSize(const Size& size) _contentSize = size; CCLOG("[Edit text] content size = (%f, %f)", size.width, size.height); placeInactiveLabels(); - EGLViewProtocol* eglView = EGLView::getInstance(); - CGSize controlSize = CGSizeMake(size.width * eglView->getScaleX(),size.height * eglView->getScaleY()); + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + CGSize controlSize = CGSizeMake(size.width * glview->getScaleX(),size.height * glview->getScaleY()); if (_inRetinaMode) { diff --git a/extensions/GUI/CCEditBox/CCEditBoxImplMac.mm b/extensions/GUI/CCEditBox/CCEditBoxImplMac.mm index a3f7654bd5..5fa5b32039 100644 --- a/extensions/GUI/CCEditBox/CCEditBoxImplMac.mm +++ b/extensions/GUI/CCEditBox/CCEditBoxImplMac.mm @@ -24,14 +24,20 @@ ****************************************************************************/ #include "CCEditBoxImplMac.h" +#include "CCDirector.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) #include "CCEditBox.h" -#import "EAGLView.h" +#define GLFW_EXPOSE_NATIVE_NSGL +#define GLFW_EXPOSE_NATIVE_COCOA +#include "glfw3native.h" + #define getEditBoxImplMac() ((cocos2d::extension::EditBoxImplMac*)editBox_) + + @implementation CCCustomNSTextField - (CGRect)textRectForBounds:(CGRect)bounds { @@ -58,6 +64,12 @@ @synthesize editState = editState_; @synthesize editBox = editBox_; +- (id) getNSWindow +{ + auto glview = cocos2d::Director::getInstance()->getOpenGLView(); + return glfwGetCocoaWindow(glview->getWindow()); +} + - (void)dealloc { [textField_ resignFirstResponder]; @@ -84,7 +96,7 @@ [textField_ setDelegate:self]; self.editBox = editBox; - [[CCEAGLView sharedEGLView] addSubview:textField_]; + [[[self getNSWindow] contentView] addSubview:textField_]; return self; }while(0); @@ -94,8 +106,7 @@ -(void) doAnimationWhenKeyboardMoveWithDuration:(float)duration distance:(float)distance { - id eglView = [CCEAGLView sharedEGLView]; - [eglView doAnimationWhenKeyboardMoveWithDuration:duration distance:distance]; + [[[self getNSWindow] contentView] doAnimationWhenKeyboardMoveWithDuration:duration distance:distance]; } -(void) setPosition:(NSPoint) pos @@ -257,7 +268,7 @@ void EditBoxImplMac::doAnimationWhenKeyboardMove(float duration, float distance) bool EditBoxImplMac::initWithSize(const Size& size) { - EGLViewProtocol* eglView = EGLView::getInstance(); + GLViewProtocol* eglView = Director::getInstance()->getOpenGLView(); NSRect rect = NSMakeRect(0, 0, size.width * eglView->getScaleX(),size.height * eglView->getScaleY()); @@ -348,7 +359,7 @@ NSPoint EditBoxImplMac::convertDesignCoordToScreenCoord(const Point& designCoord NSRect frame = [_sysEdit.textField frame]; CGFloat height = frame.size.height; - EGLViewProtocol* eglView = EGLView::getInstance(); + GLViewProtocol* eglView = Director::getInstance()->getOpenGLView(); Point visiblePos = Point(designCoord.x * eglView->getScaleX(), designCoord.y * eglView->getScaleY()); Point screenGLPos = visiblePos + eglView->getViewPortRect().origin; diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 05200d32cb..b88f7fea03 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -24,6 +24,13 @@ ****************************************************************************/ #include "CCScrollView.h" +#include "CCGLView.h" +#include "platform/CCDevice.h" +#include "CCActionInstant.h" +#include "CCActionInterval.h" +#include "CCActionTween.h" +#include "CCDirector.h" +#include "renderer/CCRenderer.h" #include @@ -37,7 +44,8 @@ NS_CC_EXT_BEGIN static float convertDistanceFromPointToInch(float pointDis) { - float factor = ( EGLView::getInstance()->getScaleX() + EGLView::getInstance()->getScaleY() ) / 2; + auto glview = Director::getInstance()->getOpenGLView(); + float factor = ( glview->getScaleX() + glview->getScaleY() ) / 2; return pointDis * factor / Device::getDPI(); } @@ -487,7 +495,7 @@ void ScrollView::addChild(Node * child, int zOrder, int tag) void ScrollView::beforeDraw() { - _beforeDrawCommand.init(0, _vertexZ); + _beforeDrawCommand.init(_globalZOrder); _beforeDrawCommand.func = CC_CALLBACK_0(ScrollView::onBeforeDraw, this); Director::getInstance()->getRenderer()->addCommand(&_beforeDrawCommand); } @@ -501,28 +509,30 @@ void ScrollView::onBeforeDraw() { _scissorRestored = false; Rect frame = getViewRect(); - if (EGLView::getInstance()->isScissorEnabled()) { + auto glview = Director::getInstance()->getOpenGLView(); + + if (glview->isScissorEnabled()) { _scissorRestored = true; - _parentScissorRect = EGLView::getInstance()->getScissorRect(); + _parentScissorRect = glview->getScissorRect(); //set the intersection of _parentScissorRect and frame as the new scissor rect if (frame.intersectsRect(_parentScissorRect)) { float x = MAX(frame.origin.x, _parentScissorRect.origin.x); float y = MAX(frame.origin.y, _parentScissorRect.origin.y); float xx = MIN(frame.origin.x+frame.size.width, _parentScissorRect.origin.x+_parentScissorRect.size.width); float yy = MIN(frame.origin.y+frame.size.height, _parentScissorRect.origin.y+_parentScissorRect.size.height); - EGLView::getInstance()->setScissorInPoints(x, y, xx-x, yy-y); + glview->setScissorInPoints(x, y, xx-x, yy-y); } } else { glEnable(GL_SCISSOR_TEST); - EGLView::getInstance()->setScissorInPoints(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height); + glview->setScissorInPoints(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height); } } } void ScrollView::afterDraw() { - _afterDrawCommand.init(0, _vertexZ); + _afterDrawCommand.init(_globalZOrder); _afterDrawCommand.func = CC_CALLBACK_0(ScrollView::onAfterDraw, this); Director::getInstance()->getRenderer()->addCommand(&_afterDrawCommand); } @@ -536,7 +546,9 @@ void ScrollView::onAfterDraw() if (_clippingToBounds) { if (_scissorRestored) {//restore the parent's scissor rect - EGLView::getInstance()->setScissorInPoints(_parentScissorRect.origin.x, _parentScissorRect.origin.y, _parentScissorRect.size.width, _parentScissorRect.size.height); + auto glview = Director::getInstance()->getOpenGLView(); + + glview->setScissorInPoints(_parentScissorRect.origin.x, _parentScissorRect.origin.y, _parentScissorRect.size.width, _parentScissorRect.size.height); } else { glDisable(GL_SCISSOR_TEST); @@ -565,7 +577,7 @@ void ScrollView::visit() for( ; i < _children.size(); i++ ) { Node *child = _children.at(i); - if ( child->getZOrder() < 0 ) + if ( child->getLocalZOrder() < 0 ) { child->visit(); } diff --git a/extensions/GUI/CCScrollView/CCScrollView.h b/extensions/GUI/CCScrollView/CCScrollView.h index c77d74bc13..88fc9b4523 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.h +++ b/extensions/GUI/CCScrollView/CCScrollView.h @@ -26,7 +26,9 @@ #ifndef __CCSCROLLVIEW_H__ #define __CCSCROLLVIEW_H__ -#include "cocos2d.h" +#include "CCLayer.h" +#include "CCEventListenerTouch.h" + #include "extensions/ExtensionMacros.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCScrollView/CCTableView.cpp b/extensions/GUI/CCScrollView/CCTableView.cpp index ff143f77d5..ad639e4986 100644 --- a/extensions/GUI/CCScrollView/CCTableView.cpp +++ b/extensions/GUI/CCScrollView/CCTableView.cpp @@ -23,7 +23,6 @@ THE SOFTWARE. ****************************************************************************/ -#include "cocos2d.h" #include "CCTableView.h" #include "CCTableViewCell.h" diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.cpp b/extensions/GUI/CCScrollView/CCTableViewCell.cpp index 7df9c478fd..aa1cf70bca 100644 --- a/extensions/GUI/CCScrollView/CCTableViewCell.cpp +++ b/extensions/GUI/CCScrollView/CCTableViewCell.cpp @@ -33,7 +33,7 @@ void TableViewCell::reset() _idx = CC_INVALID_INDEX; } -ssize_t TableViewCell::getIdx() +ssize_t TableViewCell::getIdx() const { return _idx; } diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.h b/extensions/GUI/CCScrollView/CCTableViewCell.h index 33438a0f96..fb0a509df1 100644 --- a/extensions/GUI/CCScrollView/CCTableViewCell.h +++ b/extensions/GUI/CCScrollView/CCTableViewCell.h @@ -26,8 +26,8 @@ #ifndef __CCTABLEVIEWCELL_H__ #define __CCTABLEVIEWCELL_H__ -#include "cocos2d.h" #include "extensions/ExtensionMacros.h" +#include "CCNode.h" NS_CC_EXT_BEGIN @@ -43,7 +43,7 @@ public: /** * The index used internally by SWTableView and its subclasses */ - ssize_t getIdx(); + ssize_t getIdx() const; void setIdx(ssize_t uIdx); /** * Cleans up any resources linked to this cell and resets idx property. diff --git a/extensions/cocos-ext.h b/extensions/cocos-ext.h index 8c3f242643..a204f40e43 100644 --- a/extensions/cocos-ext.h +++ b/extensions/cocos-ext.h @@ -10,10 +10,8 @@ #include "GUI/CCEditBox/CCEditBox.h" // Physics integration -#if CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION #include "physics-nodes/CCPhysicsDebugNode.h" #include "physics-nodes/CCPhysicsSprite.h" -#endif #include "assets-manager/AssetsManager.h" diff --git a/extensions/physics-nodes/CCPhysicsDebugNode.cpp b/extensions/physics-nodes/CCPhysicsDebugNode.cpp index 357092b62f..34a989da5a 100644 --- a/extensions/physics-nodes/CCPhysicsDebugNode.cpp +++ b/extensions/physics-nodes/CCPhysicsDebugNode.cpp @@ -22,10 +22,13 @@ #include "CCPhysicsDebugNode.h" #if CC_ENABLE_CHIPMUNK_INTEGRATION +#include "chipmunk.h" +#endif #include "ccTypes.h" #include "CCGeometry.h" + #include #include #include @@ -34,6 +37,7 @@ NS_CC_EXT_BEGIN +#if CC_ENABLE_CHIPMUNK_INTEGRATION /* IMPORTANT - READ ME! @@ -174,6 +178,7 @@ static void DrawConstraint(cpConstraint *constraint, DrawNode *renderer) // printf("Cannot draw constraint\n"); } } +#endif // #if CC_ENABLE_CHIPMUNK_INTEGRATION // implementation of PhysicsDebugNode @@ -183,16 +188,17 @@ void PhysicsDebugNode::draw() { return; } - +#if CC_ENABLE_CHIPMUNK_INTEGRATION cpSpaceEachShape(_spacePtr, (cpSpaceShapeIteratorFunc)DrawShape, this); cpSpaceEachConstraint(_spacePtr, (cpSpaceConstraintIteratorFunc)DrawConstraint, this); DrawNode::draw(); DrawNode::clear(); +#endif } PhysicsDebugNode::PhysicsDebugNode() -: _spacePtr(NULL) +: _spacePtr(nullptr) {} PhysicsDebugNode* PhysicsDebugNode::create(cpSpace *space) @@ -201,9 +207,11 @@ PhysicsDebugNode* PhysicsDebugNode::create(cpSpace *space) if (node) { node->init(); - +#if CC_ENABLE_CHIPMUNK_INTEGRATION node->_spacePtr = space; - +#else + CCASSERT(false, "CC_ENABLE_CHIPMUNK_INTEGRATION was not enabled!"); +#endif node->autorelease(); } else @@ -220,14 +228,21 @@ PhysicsDebugNode::~PhysicsDebugNode() cpSpace* PhysicsDebugNode::getSpace() const { +#if CC_ENABLE_CHIPMUNK_INTEGRATION return _spacePtr; +#else + CCASSERT(false, "Can't call chipmunk methods when Chipmunk is disabled"); + return nullptr; +#endif } void PhysicsDebugNode::setSpace(cpSpace *space) { +#if CC_ENABLE_CHIPMUNK_INTEGRATION _spacePtr = space; +#else + CCASSERT(false, "Can't call chipmunk methods when Chipmunk is disabled"); +#endif } NS_CC_EXT_END - -#endif // CC_ENABLE_CHIPMUNK_INTEGRATION diff --git a/extensions/physics-nodes/CCPhysicsDebugNode.h b/extensions/physics-nodes/CCPhysicsDebugNode.h index fe4d167bff..ab49107b7b 100644 --- a/extensions/physics-nodes/CCPhysicsDebugNode.h +++ b/extensions/physics-nodes/CCPhysicsDebugNode.h @@ -23,12 +23,10 @@ #ifndef __PHYSICSNODES_DEBUGNODE_H__ #define __PHYSICSNODES_DEBUGNODE_H__ -#include "cocos2d.h" #include "extensions/ExtensionMacros.h" +#include "CCDrawNode.h" -#if CC_ENABLE_CHIPMUNK_INTEGRATION - -#include "chipmunk.h" +struct cpSpace; NS_CC_EXT_BEGIN @@ -72,6 +70,4 @@ protected: NS_CC_EXT_END -#endif // CC_ENABLE_CHIPMUNK_INTEGRATION - #endif // __PHYSICSNODES_DEBUGNODE_H__ diff --git a/extensions/physics-nodes/CCPhysicsSprite.cpp b/extensions/physics-nodes/CCPhysicsSprite.cpp index 93ce054384..0e3459c41a 100644 --- a/extensions/physics-nodes/CCPhysicsSprite.cpp +++ b/extensions/physics-nodes/CCPhysicsSprite.cpp @@ -19,7 +19,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -#if (CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION) #include "CCPhysicsSprite.h" @@ -37,8 +36,8 @@ NS_CC_EXT_BEGIN PhysicsSprite::PhysicsSprite() : _ignoreBodyRotation(false) -, _CPBody(NULL) -, _pB2Body(NULL) +, _CPBody(nullptr) +, _pB2Body(nullptr) , _PTMRatio(0.0f) {} @@ -195,77 +194,64 @@ float PhysicsSprite::getPositionY() const // Chipmunk only // + + +cpBody* PhysicsSprite::getCPBody() const +{ #if CC_ENABLE_CHIPMUNK_INTEGRATION - -cpBody* PhysicsSprite::getCPBody() const -{ return _CPBody; -} - -void PhysicsSprite::setCPBody(cpBody *pBody) -{ - _CPBody = pBody; -} - -b2Body* PhysicsSprite::getB2Body() const -{ - CCASSERT(false, "Can't call box2d methods when Chipmunk is enabled"); - return NULL; -} - -void PhysicsSprite::setB2Body(b2Body *pBody) -{ - CCASSERT(false, "Can't call box2d methods when Chipmunk is enabled"); -} - -float PhysicsSprite::getPTMRatio() const -{ - CCASSERT(false, "Can't call box2d methods when Chipmunk is enabled"); - return 0; -} - -void PhysicsSprite::setPTMRatio(float fRatio) -{ - CCASSERT(false, "Can't call box2d methods when Chipmunk is enabled"); -} - -// -// Box2d only -// -#elif CC_ENABLE_BOX2D_INTEGRATION - -b2Body* PhysicsSprite::getB2Body() const -{ - return _pB2Body; -} - -void PhysicsSprite::setB2Body(b2Body *pBody) -{ - _pB2Body = pBody; -} - -float PhysicsSprite::getPTMRatio() const -{ - return _PTMRatio; -} - -void PhysicsSprite::setPTMRatio(float fRatio) -{ - _PTMRatio = fRatio; -} - -cpBody* PhysicsSprite::getCPBody() const -{ - CCASSERT(false, "Can't call Chipmunk methods when Box2d is enabled"); - return NULL; -} - -void PhysicsSprite::setCPBody(cpBody *pBody) -{ - CCASSERT(false, "Can't call Chipmunk methods when Box2d is enabled"); -} - +#else + CCASSERT(false, "Can't call chipmunk methods when Chipmunk is disabled"); + return nullptr; #endif +} + +void PhysicsSprite::setCPBody(cpBody *pBody) +{ +#if CC_ENABLE_CHIPMUNK_INTEGRATION + _CPBody = pBody; +#else + CCASSERT(false, "Can't call chipmunk methods when Chipmunk is disabled"); +#endif +} + +b2Body* PhysicsSprite::getB2Body() const +{ +#if CC_ENABLE_BOX2D_INTEGRATION + return _pB2Body; +#else + CCASSERT(false, "Can't call box2d methods when Box2d is disabled"); + return nullptr; +#endif +} + +void PhysicsSprite::setB2Body(b2Body *pBody) +{ +#if CC_ENABLE_BOX2D_INTEGRATION + _pB2Body = pBody; +#else + CCASSERT(false, "Can't call box2d methods when Box2d is disabled"); +#endif +} + +float PhysicsSprite::getPTMRatio() const +{ +#if CC_ENABLE_BOX2D_INTEGRATION + return _PTMRatio; +#else + CCASSERT(false, "Can't call box2d methods when Box2d is disabled"); + return 0; +#endif +} + +void PhysicsSprite::setPTMRatio(float fRatio) +{ +#if CC_ENABLE_BOX2D_INTEGRATION + _PTMRatio = fRatio; +#else + CCASSERT(false, "Can't call box2d methods when Box2d is disabled"); +#endif +} // // Common to Box2d and Chipmunk @@ -398,13 +384,17 @@ const kmMat4& PhysicsSprite::getNodeToParentTransform() const } // Rot, Translate Matrix - _transform = AffineTransformMake( c * _scaleX, s * _scaleX, - -s * _scaleY, c * _scaleY, - x, y ); + + kmScalar mat[] = { (kmScalar)c * _scaleX, (kmScalar)s * _scaleX, 0, 0, + (kmScalar)-s * _scaleY, (kmScalar)c * _scaleY, 0, 0, + 0, 0, 1, 0, + x, y, 0, 1}; + + + kmMat4Fill(&_transform, mat); return _transform; #endif } NS_CC_EXT_END -#endif //(CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION) diff --git a/extensions/physics-nodes/CCPhysicsSprite.h b/extensions/physics-nodes/CCPhysicsSprite.h index fcedfca031..8640e5f297 100644 --- a/extensions/physics-nodes/CCPhysicsSprite.h +++ b/extensions/physics-nodes/CCPhysicsSprite.h @@ -19,12 +19,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -#if (CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION) #ifndef __PHYSICSNODES_CCPHYSICSSPRITE_H__ #define __PHYSICSNODES_CCPHYSICSSPRITE_H__ -#include "cocos2d.h" +#include "CCSprite.h" #include "extensions/ExtensionMacros.h" struct cpBody; @@ -127,11 +126,8 @@ protected: // box2d specific b2Body *_pB2Body; float _PTMRatio; - - }; NS_CC_EXT_END #endif // __PHYSICSNODES_CCPHYSICSSPRITE_H__ -#endif //(CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION) diff --git a/external/curl/include/linux/32-bit/curl/curl.h b/external/curl/include/linux/32-bit/curl/curl.h deleted file mode 100644 index 2cad28298e..0000000000 --- a/external/curl/include/linux/32-bit/curl/curl.h +++ /dev/null @@ -1,2231 +0,0 @@ -#ifndef __CURL_CURL_H -#define __CURL_CURL_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2012, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* - * If you have libcurl problems, all docs and details are found here: - * http://curl.haxx.se/libcurl/ - * - * curl-library mailing list subscription and unsubscription web interface: - * http://cool.haxx.se/mailman/listinfo/curl-library/ - */ - -#include "curlver.h" /* libcurl version defines */ -#include "curlbuild.h" /* libcurl build definitions */ -#include "curlrules.h" /* libcurl rules enforcement */ - -/* - * Define WIN32 when build target is Win32 API - */ - -#if (defined(_WIN32) || defined(__WIN32__)) && \ - !defined(WIN32) && !defined(__SYMBIAN32__) -#define WIN32 -#endif - -#include -#include - -#if defined(__FreeBSD__) && (__FreeBSD__ >= 2) -/* Needed for __FreeBSD_version symbol definition */ -#include -#endif - -/* The include stuff here below is mainly for time_t! */ -#include -#include - -#if defined(WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__) -#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || defined(__LWIP_OPT_H__)) -/* The check above prevents the winsock2 inclusion if winsock.h already was - included, since they can't co-exist without problems */ -#include -#include -#endif -#endif - -/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish - libc5-based Linux systems. Only include it on systems that are known to - require it! */ -#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \ - defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \ - defined(ANDROID) || defined(__ANDROID__) || \ - (defined(__FreeBSD_version) && (__FreeBSD_version < 800000)) -#include -#endif - -#if !defined(WIN32) && !defined(_WIN32_WCE) -#include -#endif - -#if !defined(WIN32) && !defined(__WATCOMC__) && !defined(__VXWORKS__) -#include -#endif - -#ifdef __BEOS__ -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void CURL; - -/* - * Decorate exportable functions for Win32 and Symbian OS DLL linking. - * This avoids using a .def file for building libcurl.dll. - */ -#if (defined(WIN32) || defined(_WIN32) || defined(__SYMBIAN32__)) && \ - !defined(CURL_STATICLIB) -#if defined(BUILDING_LIBCURL) -#define CURL_EXTERN __declspec(dllexport) -#else -#define CURL_EXTERN __declspec(dllimport) -#endif -#else - -#ifdef CURL_HIDDEN_SYMBOLS -/* - * This definition is used to make external definitions visible in the - * shared library when symbols are hidden by default. It makes no - * difference when compiling applications whether this is set or not, - * only when compiling the library. - */ -#define CURL_EXTERN CURL_EXTERN_SYMBOL -#else -#define CURL_EXTERN -#endif -#endif - -#ifndef curl_socket_typedef -/* socket typedef */ -#if defined(WIN32) && !defined(__LWIP_OPT_H__) -typedef SOCKET curl_socket_t; -#define CURL_SOCKET_BAD INVALID_SOCKET -#else -typedef int curl_socket_t; -#define CURL_SOCKET_BAD -1 -#endif -#define curl_socket_typedef -#endif /* curl_socket_typedef */ - -struct curl_httppost { - struct curl_httppost *next; /* next entry in the list */ - char *name; /* pointer to allocated name */ - long namelength; /* length of name length */ - char *contents; /* pointer to allocated data contents */ - long contentslength; /* length of contents field */ - char *buffer; /* pointer to allocated buffer contents */ - long bufferlength; /* length of buffer field */ - char *contenttype; /* Content-Type */ - struct curl_slist* contentheader; /* list of extra headers for this form */ - struct curl_httppost *more; /* if one field name has more than one - file, this link should link to following - files */ - long flags; /* as defined below */ -#define HTTPPOST_FILENAME (1<<0) /* specified content is a file name */ -#define HTTPPOST_READFILE (1<<1) /* specified content is a file name */ -#define HTTPPOST_PTRNAME (1<<2) /* name is only stored pointer - do not free in formfree */ -#define HTTPPOST_PTRCONTENTS (1<<3) /* contents is only stored pointer - do not free in formfree */ -#define HTTPPOST_BUFFER (1<<4) /* upload file from buffer */ -#define HTTPPOST_PTRBUFFER (1<<5) /* upload file from pointer contents */ -#define HTTPPOST_CALLBACK (1<<6) /* upload file contents by using the - regular read callback to get the data - and pass the given pointer as custom - pointer */ - - char *showfilename; /* The file name to show. If not set, the - actual file name will be used (if this - is a file part) */ - void *userp; /* custom pointer used for - HTTPPOST_CALLBACK posts */ -}; - -typedef int (*curl_progress_callback)(void *clientp, - double dltotal, - double dlnow, - double ultotal, - double ulnow); - -#ifndef CURL_MAX_WRITE_SIZE - /* Tests have proven that 20K is a very bad buffer size for uploads on - Windows, while 16K for some odd reason performed a lot better. - We do the ifndef check to allow this value to easier be changed at build - time for those who feel adventurous. The practical minimum is about - 400 bytes since libcurl uses a buffer of this size as a scratch area - (unrelated to network send operations). */ -#define CURL_MAX_WRITE_SIZE 16384 -#endif - -#ifndef CURL_MAX_HTTP_HEADER -/* The only reason to have a max limit for this is to avoid the risk of a bad - server feeding libcurl with a never-ending header that will cause reallocs - infinitely */ -#define CURL_MAX_HTTP_HEADER (100*1024) -#endif - -/* This is a magic return code for the write callback that, when returned, - will signal libcurl to pause receiving on the current transfer. */ -#define CURL_WRITEFUNC_PAUSE 0x10000001 - -typedef size_t (*curl_write_callback)(char *buffer, - size_t size, - size_t nitems, - void *outstream); - - - -/* enumeration of file types */ -typedef enum { - CURLFILETYPE_FILE = 0, - CURLFILETYPE_DIRECTORY, - CURLFILETYPE_SYMLINK, - CURLFILETYPE_DEVICE_BLOCK, - CURLFILETYPE_DEVICE_CHAR, - CURLFILETYPE_NAMEDPIPE, - CURLFILETYPE_SOCKET, - CURLFILETYPE_DOOR, /* is possible only on Sun Solaris now */ - - CURLFILETYPE_UNKNOWN /* should never occur */ -} curlfiletype; - -#define CURLFINFOFLAG_KNOWN_FILENAME (1<<0) -#define CURLFINFOFLAG_KNOWN_FILETYPE (1<<1) -#define CURLFINFOFLAG_KNOWN_TIME (1<<2) -#define CURLFINFOFLAG_KNOWN_PERM (1<<3) -#define CURLFINFOFLAG_KNOWN_UID (1<<4) -#define CURLFINFOFLAG_KNOWN_GID (1<<5) -#define CURLFINFOFLAG_KNOWN_SIZE (1<<6) -#define CURLFINFOFLAG_KNOWN_HLINKCOUNT (1<<7) - -/* Content of this structure depends on information which is known and is - achievable (e.g. by FTP LIST parsing). Please see the url_easy_setopt(3) man - page for callbacks returning this structure -- some fields are mandatory, - some others are optional. The FLAG field has special meaning. */ -struct curl_fileinfo { - char *filename; - curlfiletype filetype; - time_t time; - unsigned int perm; - int uid; - int gid; - curl_off_t size; - long int hardlinks; - - struct { - /* If some of these fields is not NULL, it is a pointer to b_data. */ - char *time; - char *perm; - char *user; - char *group; - char *target; /* pointer to the target filename of a symlink */ - } strings; - - unsigned int flags; - - /* used internally */ - char * b_data; - size_t b_size; - size_t b_used; -}; - -/* return codes for CURLOPT_CHUNK_BGN_FUNCTION */ -#define CURL_CHUNK_BGN_FUNC_OK 0 -#define CURL_CHUNK_BGN_FUNC_FAIL 1 /* tell the lib to end the task */ -#define CURL_CHUNK_BGN_FUNC_SKIP 2 /* skip this chunk over */ - -/* if splitting of data transfer is enabled, this callback is called before - download of an individual chunk started. Note that parameter "remains" works - only for FTP wildcard downloading (for now), otherwise is not used */ -typedef long (*curl_chunk_bgn_callback)(const void *transfer_info, - void *ptr, - int remains); - -/* return codes for CURLOPT_CHUNK_END_FUNCTION */ -#define CURL_CHUNK_END_FUNC_OK 0 -#define CURL_CHUNK_END_FUNC_FAIL 1 /* tell the lib to end the task */ - -/* If splitting of data transfer is enabled this callback is called after - download of an individual chunk finished. - Note! After this callback was set then it have to be called FOR ALL chunks. - Even if downloading of this chunk was skipped in CHUNK_BGN_FUNC. - This is the reason why we don't need "transfer_info" parameter in this - callback and we are not interested in "remains" parameter too. */ -typedef long (*curl_chunk_end_callback)(void *ptr); - -/* return codes for FNMATCHFUNCTION */ -#define CURL_FNMATCHFUNC_MATCH 0 /* string corresponds to the pattern */ -#define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern doesn't match the string */ -#define CURL_FNMATCHFUNC_FAIL 2 /* an error occurred */ - -/* callback type for wildcard downloading pattern matching. If the - string matches the pattern, return CURL_FNMATCHFUNC_MATCH value, etc. */ -typedef int (*curl_fnmatch_callback)(void *ptr, - const char *pattern, - const char *string); - -/* These are the return codes for the seek callbacks */ -#define CURL_SEEKFUNC_OK 0 -#define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */ -#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking can't be done, so - libcurl might try other means instead */ -typedef int (*curl_seek_callback)(void *instream, - curl_off_t offset, - int origin); /* 'whence' */ - -/* This is a return code for the read callback that, when returned, will - signal libcurl to immediately abort the current transfer. */ -#define CURL_READFUNC_ABORT 0x10000000 -/* This is a return code for the read callback that, when returned, will - signal libcurl to pause sending data on the current transfer. */ -#define CURL_READFUNC_PAUSE 0x10000001 - -typedef size_t (*curl_read_callback)(char *buffer, - size_t size, - size_t nitems, - void *instream); - -typedef enum { - CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */ - CURLSOCKTYPE_LAST /* never use */ -} curlsocktype; - -/* The return code from the sockopt_callback can signal information back - to libcurl: */ -#define CURL_SOCKOPT_OK 0 -#define CURL_SOCKOPT_ERROR 1 /* causes libcurl to abort and return - CURLE_ABORTED_BY_CALLBACK */ -#define CURL_SOCKOPT_ALREADY_CONNECTED 2 - -typedef int (*curl_sockopt_callback)(void *clientp, - curl_socket_t curlfd, - curlsocktype purpose); - -struct curl_sockaddr { - int family; - int socktype; - int protocol; - unsigned int addrlen; /* addrlen was a socklen_t type before 7.18.0 but it - turned really ugly and painful on the systems that - lack this type */ - struct sockaddr addr; -}; - -typedef curl_socket_t -(*curl_opensocket_callback)(void *clientp, - curlsocktype purpose, - struct curl_sockaddr *address); - -typedef int -(*curl_closesocket_callback)(void *clientp, curl_socket_t item); - -typedef enum { - CURLIOE_OK, /* I/O operation successful */ - CURLIOE_UNKNOWNCMD, /* command was unknown to callback */ - CURLIOE_FAILRESTART, /* failed to restart the read */ - CURLIOE_LAST /* never use */ -} curlioerr; - -typedef enum { - CURLIOCMD_NOP, /* no operation */ - CURLIOCMD_RESTARTREAD, /* restart the read stream from start */ - CURLIOCMD_LAST /* never use */ -} curliocmd; - -typedef curlioerr (*curl_ioctl_callback)(CURL *handle, - int cmd, - void *clientp); - -/* - * The following typedef's are signatures of malloc, free, realloc, strdup and - * calloc respectively. Function pointers of these types can be passed to the - * curl_global_init_mem() function to set user defined memory management - * callback routines. - */ -typedef void *(*curl_malloc_callback)(size_t size); -typedef void (*curl_free_callback)(void *ptr); -typedef void *(*curl_realloc_callback)(void *ptr, size_t size); -typedef char *(*curl_strdup_callback)(const char *str); -typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size); - -/* the kind of data that is passed to information_callback*/ -typedef enum { - CURLINFO_TEXT = 0, - CURLINFO_HEADER_IN, /* 1 */ - CURLINFO_HEADER_OUT, /* 2 */ - CURLINFO_DATA_IN, /* 3 */ - CURLINFO_DATA_OUT, /* 4 */ - CURLINFO_SSL_DATA_IN, /* 5 */ - CURLINFO_SSL_DATA_OUT, /* 6 */ - CURLINFO_END -} curl_infotype; - -typedef int (*curl_debug_callback) - (CURL *handle, /* the handle/transfer this concerns */ - curl_infotype type, /* what kind of data */ - char *data, /* points to the data */ - size_t size, /* size of the data pointed to */ - void *userptr); /* whatever the user please */ - -/* All possible error codes from all sorts of curl functions. Future versions - may return other values, stay prepared. - - Always add new return codes last. Never *EVER* remove any. The return - codes must remain the same! - */ - -typedef enum { - CURLE_OK = 0, - CURLE_UNSUPPORTED_PROTOCOL, /* 1 */ - CURLE_FAILED_INIT, /* 2 */ - CURLE_URL_MALFORMAT, /* 3 */ - CURLE_NOT_BUILT_IN, /* 4 - [was obsoleted in August 2007 for - 7.17.0, reused in April 2011 for 7.21.5] */ - CURLE_COULDNT_RESOLVE_PROXY, /* 5 */ - CURLE_COULDNT_RESOLVE_HOST, /* 6 */ - CURLE_COULDNT_CONNECT, /* 7 */ - CURLE_FTP_WEIRD_SERVER_REPLY, /* 8 */ - CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server - due to lack of access - when login fails - this is not returned. */ - CURLE_FTP_ACCEPT_FAILED, /* 10 - [was obsoleted in April 2006 for - 7.15.4, reused in Dec 2011 for 7.24.0]*/ - CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */ - CURLE_FTP_ACCEPT_TIMEOUT, /* 12 - timeout occurred accepting server - [was obsoleted in August 2007 for 7.17.0, - reused in Dec 2011 for 7.24.0]*/ - CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */ - CURLE_FTP_WEIRD_227_FORMAT, /* 14 */ - CURLE_FTP_CANT_GET_HOST, /* 15 */ - CURLE_OBSOLETE16, /* 16 - NOT USED */ - CURLE_FTP_COULDNT_SET_TYPE, /* 17 */ - CURLE_PARTIAL_FILE, /* 18 */ - CURLE_FTP_COULDNT_RETR_FILE, /* 19 */ - CURLE_OBSOLETE20, /* 20 - NOT USED */ - CURLE_QUOTE_ERROR, /* 21 - quote command failure */ - CURLE_HTTP_RETURNED_ERROR, /* 22 */ - CURLE_WRITE_ERROR, /* 23 */ - CURLE_OBSOLETE24, /* 24 - NOT USED */ - CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */ - CURLE_READ_ERROR, /* 26 - couldn't open/read from file */ - CURLE_OUT_OF_MEMORY, /* 27 */ - /* Note: CURLE_OUT_OF_MEMORY may sometimes indicate a conversion error - instead of a memory allocation error if CURL_DOES_CONVERSIONS - is defined - */ - CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */ - CURLE_OBSOLETE29, /* 29 - NOT USED */ - CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */ - CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */ - CURLE_OBSOLETE32, /* 32 - NOT USED */ - CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */ - CURLE_HTTP_POST_ERROR, /* 34 */ - CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */ - CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */ - CURLE_FILE_COULDNT_READ_FILE, /* 37 */ - CURLE_LDAP_CANNOT_BIND, /* 38 */ - CURLE_LDAP_SEARCH_FAILED, /* 39 */ - CURLE_OBSOLETE40, /* 40 - NOT USED */ - CURLE_FUNCTION_NOT_FOUND, /* 41 */ - CURLE_ABORTED_BY_CALLBACK, /* 42 */ - CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */ - CURLE_OBSOLETE44, /* 44 - NOT USED */ - CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */ - CURLE_OBSOLETE46, /* 46 - NOT USED */ - CURLE_TOO_MANY_REDIRECTS , /* 47 - catch endless re-direct loops */ - CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */ - CURLE_TELNET_OPTION_SYNTAX , /* 49 - Malformed telnet option */ - CURLE_OBSOLETE50, /* 50 - NOT USED */ - CURLE_PEER_FAILED_VERIFICATION, /* 51 - peer's certificate or fingerprint - wasn't verified fine */ - CURLE_GOT_NOTHING, /* 52 - when this is a specific error */ - CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */ - CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as - default */ - CURLE_SEND_ERROR, /* 55 - failed sending network data */ - CURLE_RECV_ERROR, /* 56 - failure in receiving network data */ - CURLE_OBSOLETE57, /* 57 - NOT IN USE */ - CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */ - CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */ - CURLE_SSL_CACERT, /* 60 - problem with the CA cert (path?) */ - CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */ - CURLE_LDAP_INVALID_URL, /* 62 - Invalid LDAP URL */ - CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */ - CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */ - CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind - that failed */ - CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */ - CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not - accepted and we failed to login */ - CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */ - CURLE_TFTP_PERM, /* 69 - permission problem on server */ - CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */ - CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */ - CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */ - CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */ - CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */ - CURLE_CONV_FAILED, /* 75 - conversion failed */ - CURLE_CONV_REQD, /* 76 - caller must register conversion - callbacks using curl_easy_setopt options - CURLOPT_CONV_FROM_NETWORK_FUNCTION, - CURLOPT_CONV_TO_NETWORK_FUNCTION, and - CURLOPT_CONV_FROM_UTF8_FUNCTION */ - CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing - or wrong format */ - CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */ - CURLE_SSH, /* 79 - error from the SSH layer, somewhat - generic so the error message will be of - interest when this has happened */ - - CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL - connection */ - CURLE_AGAIN, /* 81 - socket is not ready for send/recv, - wait till it's ready and try again (Added - in 7.18.2) */ - CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or - wrong format (Added in 7.19.0) */ - CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in - 7.19.0) */ - CURLE_FTP_PRET_FAILED, /* 84 - a PRET command failed */ - CURLE_RTSP_CSEQ_ERROR, /* 85 - mismatch of RTSP CSeq numbers */ - CURLE_RTSP_SESSION_ERROR, /* 86 - mismatch of RTSP Session Ids */ - CURLE_FTP_BAD_FILE_LIST, /* 87 - unable to parse FTP file list */ - CURLE_CHUNK_FAILED, /* 88 - chunk callback reported error */ - CURL_LAST /* never use! */ -} CURLcode; - -#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all - the obsolete stuff removed! */ - -/* Previously obsoletes error codes re-used in 7.24.0 */ -#define CURLE_OBSOLETE10 CURLE_FTP_ACCEPT_FAILED -#define CURLE_OBSOLETE12 CURLE_FTP_ACCEPT_TIMEOUT - -/* compatibility with older names */ -#define CURLOPT_ENCODING CURLOPT_ACCEPT_ENCODING - -/* The following were added in 7.21.5, April 2011 */ -#define CURLE_UNKNOWN_TELNET_OPTION CURLE_UNKNOWN_OPTION - -/* The following were added in 7.17.1 */ -/* These are scheduled to disappear by 2009 */ -#define CURLE_SSL_PEER_CERTIFICATE CURLE_PEER_FAILED_VERIFICATION - -/* The following were added in 7.17.0 */ -/* These are scheduled to disappear by 2009 */ -#define CURLE_OBSOLETE CURLE_OBSOLETE50 /* no one should be using this! */ -#define CURLE_BAD_PASSWORD_ENTERED CURLE_OBSOLETE46 -#define CURLE_BAD_CALLING_ORDER CURLE_OBSOLETE44 -#define CURLE_FTP_USER_PASSWORD_INCORRECT CURLE_OBSOLETE10 -#define CURLE_FTP_CANT_RECONNECT CURLE_OBSOLETE16 -#define CURLE_FTP_COULDNT_GET_SIZE CURLE_OBSOLETE32 -#define CURLE_FTP_COULDNT_SET_ASCII CURLE_OBSOLETE29 -#define CURLE_FTP_WEIRD_USER_REPLY CURLE_OBSOLETE12 -#define CURLE_FTP_WRITE_ERROR CURLE_OBSOLETE20 -#define CURLE_LIBRARY_NOT_FOUND CURLE_OBSOLETE40 -#define CURLE_MALFORMAT_USER CURLE_OBSOLETE24 -#define CURLE_SHARE_IN_USE CURLE_OBSOLETE57 -#define CURLE_URL_MALFORMAT_USER CURLE_NOT_BUILT_IN - -#define CURLE_FTP_ACCESS_DENIED CURLE_REMOTE_ACCESS_DENIED -#define CURLE_FTP_COULDNT_SET_BINARY CURLE_FTP_COULDNT_SET_TYPE -#define CURLE_FTP_QUOTE_ERROR CURLE_QUOTE_ERROR -#define CURLE_TFTP_DISKFULL CURLE_REMOTE_DISK_FULL -#define CURLE_TFTP_EXISTS CURLE_REMOTE_FILE_EXISTS -#define CURLE_HTTP_RANGE_ERROR CURLE_RANGE_ERROR -#define CURLE_FTP_SSL_FAILED CURLE_USE_SSL_FAILED - -/* The following were added earlier */ - -#define CURLE_OPERATION_TIMEOUTED CURLE_OPERATION_TIMEDOUT - -#define CURLE_HTTP_NOT_FOUND CURLE_HTTP_RETURNED_ERROR -#define CURLE_HTTP_PORT_FAILED CURLE_INTERFACE_FAILED -#define CURLE_FTP_COULDNT_STOR_FILE CURLE_UPLOAD_FAILED - -#define CURLE_FTP_PARTIAL_FILE CURLE_PARTIAL_FILE -#define CURLE_FTP_BAD_DOWNLOAD_RESUME CURLE_BAD_DOWNLOAD_RESUME - -/* This was the error code 50 in 7.7.3 and a few earlier versions, this - is no longer used by libcurl but is instead #defined here only to not - make programs break */ -#define CURLE_ALREADY_COMPLETE 99999 - -#endif /*!CURL_NO_OLDIES*/ - -/* This prototype applies to all conversion callbacks */ -typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length); - -typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */ - void *ssl_ctx, /* actually an - OpenSSL SSL_CTX */ - void *userptr); - -typedef enum { - CURLPROXY_HTTP = 0, /* added in 7.10, new in 7.19.4 default is to use - CONNECT HTTP/1.1 */ - CURLPROXY_HTTP_1_0 = 1, /* added in 7.19.4, force to use CONNECT - HTTP/1.0 */ - CURLPROXY_SOCKS4 = 4, /* support added in 7.15.2, enum existed already - in 7.10 */ - CURLPROXY_SOCKS5 = 5, /* added in 7.10 */ - CURLPROXY_SOCKS4A = 6, /* added in 7.18.0 */ - CURLPROXY_SOCKS5_HOSTNAME = 7 /* Use the SOCKS5 protocol but pass along the - host name rather than the IP address. added - in 7.18.0 */ -} curl_proxytype; /* this enum was added in 7.10 */ - -/* - * Bitmasks for CURLOPT_HTTPAUTH and CURLOPT_PROXYAUTH options: - * - * CURLAUTH_NONE - No HTTP authentication - * CURLAUTH_BASIC - HTTP Basic authentication (default) - * CURLAUTH_DIGEST - HTTP Digest authentication - * CURLAUTH_GSSNEGOTIATE - HTTP GSS-Negotiate authentication - * CURLAUTH_NTLM - HTTP NTLM authentication - * CURLAUTH_DIGEST_IE - HTTP Digest authentication with IE flavour - * CURLAUTH_NTLM_WB - HTTP NTLM authentication delegated to winbind helper - * CURLAUTH_ONLY - Use together with a single other type to force no - * authentication or just that single type - * CURLAUTH_ANY - All fine types set - * CURLAUTH_ANYSAFE - All fine types except Basic - */ - -#define CURLAUTH_NONE ((unsigned long)0) -#define CURLAUTH_BASIC (((unsigned long)1)<<0) -#define CURLAUTH_DIGEST (((unsigned long)1)<<1) -#define CURLAUTH_GSSNEGOTIATE (((unsigned long)1)<<2) -#define CURLAUTH_NTLM (((unsigned long)1)<<3) -#define CURLAUTH_DIGEST_IE (((unsigned long)1)<<4) -#define CURLAUTH_NTLM_WB (((unsigned long)1)<<5) -#define CURLAUTH_ONLY (((unsigned long)1)<<31) -#define CURLAUTH_ANY (~CURLAUTH_DIGEST_IE) -#define CURLAUTH_ANYSAFE (~(CURLAUTH_BASIC|CURLAUTH_DIGEST_IE)) - -#define CURLSSH_AUTH_ANY ~0 /* all types supported by the server */ -#define CURLSSH_AUTH_NONE 0 /* none allowed, silly but complete */ -#define CURLSSH_AUTH_PUBLICKEY (1<<0) /* public/private key files */ -#define CURLSSH_AUTH_PASSWORD (1<<1) /* password */ -#define CURLSSH_AUTH_HOST (1<<2) /* host key files */ -#define CURLSSH_AUTH_KEYBOARD (1<<3) /* keyboard interactive */ -#define CURLSSH_AUTH_DEFAULT CURLSSH_AUTH_ANY - -#define CURLGSSAPI_DELEGATION_NONE 0 /* no delegation (default) */ -#define CURLGSSAPI_DELEGATION_POLICY_FLAG (1<<0) /* if permitted by policy */ -#define CURLGSSAPI_DELEGATION_FLAG (1<<1) /* delegate always */ - -#define CURL_ERROR_SIZE 256 - -struct curl_khkey { - const char *key; /* points to a zero-terminated string encoded with base64 - if len is zero, otherwise to the "raw" data */ - size_t len; - enum type { - CURLKHTYPE_UNKNOWN, - CURLKHTYPE_RSA1, - CURLKHTYPE_RSA, - CURLKHTYPE_DSS - } keytype; -}; - -/* this is the set of return values expected from the curl_sshkeycallback - callback */ -enum curl_khstat { - CURLKHSTAT_FINE_ADD_TO_FILE, - CURLKHSTAT_FINE, - CURLKHSTAT_REJECT, /* reject the connection, return an error */ - CURLKHSTAT_DEFER, /* do not accept it, but we can't answer right now so - this causes a CURLE_DEFER error but otherwise the - connection will be left intact etc */ - CURLKHSTAT_LAST /* not for use, only a marker for last-in-list */ -}; - -/* this is the set of status codes pass in to the callback */ -enum curl_khmatch { - CURLKHMATCH_OK, /* match */ - CURLKHMATCH_MISMATCH, /* host found, key mismatch! */ - CURLKHMATCH_MISSING, /* no matching host/key found */ - CURLKHMATCH_LAST /* not for use, only a marker for last-in-list */ -}; - -typedef int - (*curl_sshkeycallback) (CURL *easy, /* easy handle */ - const struct curl_khkey *knownkey, /* known */ - const struct curl_khkey *foundkey, /* found */ - enum curl_khmatch, /* libcurl's view on the keys */ - void *clientp); /* custom pointer passed from app */ - -/* parameter for the CURLOPT_USE_SSL option */ -typedef enum { - CURLUSESSL_NONE, /* do not attempt to use SSL */ - CURLUSESSL_TRY, /* try using SSL, proceed anyway otherwise */ - CURLUSESSL_CONTROL, /* SSL for the control connection or fail */ - CURLUSESSL_ALL, /* SSL for all communication or fail */ - CURLUSESSL_LAST /* not an option, never use */ -} curl_usessl; - -/* Definition of bits for the CURLOPT_SSL_OPTIONS argument: */ - -/* - ALLOW_BEAST tells libcurl to allow the BEAST SSL vulnerability in the - name of improving interoperability with older servers. Some SSL libraries - have introduced work-arounds for this flaw but those work-arounds sometimes - make the SSL communication fail. To regain functionality with those broken - servers, a user can this way allow the vulnerability back. */ -#define CURLSSLOPT_ALLOW_BEAST (1<<0) - -#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all - the obsolete stuff removed! */ - -/* Backwards compatibility with older names */ -/* These are scheduled to disappear by 2009 */ - -#define CURLFTPSSL_NONE CURLUSESSL_NONE -#define CURLFTPSSL_TRY CURLUSESSL_TRY -#define CURLFTPSSL_CONTROL CURLUSESSL_CONTROL -#define CURLFTPSSL_ALL CURLUSESSL_ALL -#define CURLFTPSSL_LAST CURLUSESSL_LAST -#define curl_ftpssl curl_usessl -#endif /*!CURL_NO_OLDIES*/ - -/* parameter for the CURLOPT_FTP_SSL_CCC option */ -typedef enum { - CURLFTPSSL_CCC_NONE, /* do not send CCC */ - CURLFTPSSL_CCC_PASSIVE, /* Let the server initiate the shutdown */ - CURLFTPSSL_CCC_ACTIVE, /* Initiate the shutdown */ - CURLFTPSSL_CCC_LAST /* not an option, never use */ -} curl_ftpccc; - -/* parameter for the CURLOPT_FTPSSLAUTH option */ -typedef enum { - CURLFTPAUTH_DEFAULT, /* let libcurl decide */ - CURLFTPAUTH_SSL, /* use "AUTH SSL" */ - CURLFTPAUTH_TLS, /* use "AUTH TLS" */ - CURLFTPAUTH_LAST /* not an option, never use */ -} curl_ftpauth; - -/* parameter for the CURLOPT_FTP_CREATE_MISSING_DIRS option */ -typedef enum { - CURLFTP_CREATE_DIR_NONE, /* do NOT create missing dirs! */ - CURLFTP_CREATE_DIR, /* (FTP/SFTP) if CWD fails, try MKD and then CWD - again if MKD succeeded, for SFTP this does - similar magic */ - CURLFTP_CREATE_DIR_RETRY, /* (FTP only) if CWD fails, try MKD and then CWD - again even if MKD failed! */ - CURLFTP_CREATE_DIR_LAST /* not an option, never use */ -} curl_ftpcreatedir; - -/* parameter for the CURLOPT_FTP_FILEMETHOD option */ -typedef enum { - CURLFTPMETHOD_DEFAULT, /* let libcurl pick */ - CURLFTPMETHOD_MULTICWD, /* single CWD operation for each path part */ - CURLFTPMETHOD_NOCWD, /* no CWD at all */ - CURLFTPMETHOD_SINGLECWD, /* one CWD to full dir, then work on file */ - CURLFTPMETHOD_LAST /* not an option, never use */ -} curl_ftpmethod; - -/* CURLPROTO_ defines are for the CURLOPT_*PROTOCOLS options */ -#define CURLPROTO_HTTP (1<<0) -#define CURLPROTO_HTTPS (1<<1) -#define CURLPROTO_FTP (1<<2) -#define CURLPROTO_FTPS (1<<3) -#define CURLPROTO_SCP (1<<4) -#define CURLPROTO_SFTP (1<<5) -#define CURLPROTO_TELNET (1<<6) -#define CURLPROTO_LDAP (1<<7) -#define CURLPROTO_LDAPS (1<<8) -#define CURLPROTO_DICT (1<<9) -#define CURLPROTO_FILE (1<<10) -#define CURLPROTO_TFTP (1<<11) -#define CURLPROTO_IMAP (1<<12) -#define CURLPROTO_IMAPS (1<<13) -#define CURLPROTO_POP3 (1<<14) -#define CURLPROTO_POP3S (1<<15) -#define CURLPROTO_SMTP (1<<16) -#define CURLPROTO_SMTPS (1<<17) -#define CURLPROTO_RTSP (1<<18) -#define CURLPROTO_RTMP (1<<19) -#define CURLPROTO_RTMPT (1<<20) -#define CURLPROTO_RTMPE (1<<21) -#define CURLPROTO_RTMPTE (1<<22) -#define CURLPROTO_RTMPS (1<<23) -#define CURLPROTO_RTMPTS (1<<24) -#define CURLPROTO_GOPHER (1<<25) -#define CURLPROTO_ALL (~0) /* enable everything */ - -/* long may be 32 or 64 bits, but we should never depend on anything else - but 32 */ -#define CURLOPTTYPE_LONG 0 -#define CURLOPTTYPE_OBJECTPOINT 10000 -#define CURLOPTTYPE_FUNCTIONPOINT 20000 -#define CURLOPTTYPE_OFF_T 30000 - -/* name is uppercase CURLOPT_, - type is one of the defined CURLOPTTYPE_ - number is unique identifier */ -#ifdef CINIT -#undef CINIT -#endif - -#ifdef CURL_ISOCPP -#define CINIT(na,t,nu) CURLOPT_ ## na = CURLOPTTYPE_ ## t + nu -#else -/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */ -#define LONG CURLOPTTYPE_LONG -#define OBJECTPOINT CURLOPTTYPE_OBJECTPOINT -#define FUNCTIONPOINT CURLOPTTYPE_FUNCTIONPOINT -#define OFF_T CURLOPTTYPE_OFF_T -#define CINIT(name,type,number) CURLOPT_/**/name = type + number -#endif - -/* - * This macro-mania below setups the CURLOPT_[what] enum, to be used with - * curl_easy_setopt(). The first argument in the CINIT() macro is the [what] - * word. - */ - -typedef enum { - /* This is the FILE * or void * the regular output should be written to. */ - CINIT(FILE, OBJECTPOINT, 1), - - /* The full URL to get/put */ - CINIT(URL, OBJECTPOINT, 2), - - /* Port number to connect to, if other than default. */ - CINIT(PORT, LONG, 3), - - /* Name of proxy to use. */ - CINIT(PROXY, OBJECTPOINT, 4), - - /* "name:password" to use when fetching. */ - CINIT(USERPWD, OBJECTPOINT, 5), - - /* "name:password" to use with proxy. */ - CINIT(PROXYUSERPWD, OBJECTPOINT, 6), - - /* Range to get, specified as an ASCII string. */ - CINIT(RANGE, OBJECTPOINT, 7), - - /* not used */ - - /* Specified file stream to upload from (use as input): */ - CINIT(INFILE, OBJECTPOINT, 9), - - /* Buffer to receive error messages in, must be at least CURL_ERROR_SIZE - * bytes big. If this is not used, error messages go to stderr instead: */ - CINIT(ERRORBUFFER, OBJECTPOINT, 10), - - /* Function that will be called to store the output (instead of fwrite). The - * parameters will use fwrite() syntax, make sure to follow them. */ - CINIT(WRITEFUNCTION, FUNCTIONPOINT, 11), - - /* Function that will be called to read the input (instead of fread). The - * parameters will use fread() syntax, make sure to follow them. */ - CINIT(READFUNCTION, FUNCTIONPOINT, 12), - - /* Time-out the read operation after this amount of seconds */ - CINIT(TIMEOUT, LONG, 13), - - /* If the CURLOPT_INFILE is used, this can be used to inform libcurl about - * how large the file being sent really is. That allows better error - * checking and better verifies that the upload was successful. -1 means - * unknown size. - * - * For large file support, there is also a _LARGE version of the key - * which takes an off_t type, allowing platforms with larger off_t - * sizes to handle larger files. See below for INFILESIZE_LARGE. - */ - CINIT(INFILESIZE, LONG, 14), - - /* POST static input fields. */ - CINIT(POSTFIELDS, OBJECTPOINT, 15), - - /* Set the referrer page (needed by some CGIs) */ - CINIT(REFERER, OBJECTPOINT, 16), - - /* Set the FTP PORT string (interface name, named or numerical IP address) - Use i.e '-' to use default address. */ - CINIT(FTPPORT, OBJECTPOINT, 17), - - /* Set the User-Agent string (examined by some CGIs) */ - CINIT(USERAGENT, OBJECTPOINT, 18), - - /* If the download receives less than "low speed limit" bytes/second - * during "low speed time" seconds, the operations is aborted. - * You could i.e if you have a pretty high speed connection, abort if - * it is less than 2000 bytes/sec during 20 seconds. - */ - - /* Set the "low speed limit" */ - CINIT(LOW_SPEED_LIMIT, LONG, 19), - - /* Set the "low speed time" */ - CINIT(LOW_SPEED_TIME, LONG, 20), - - /* Set the continuation offset. - * - * Note there is also a _LARGE version of this key which uses - * off_t types, allowing for large file offsets on platforms which - * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE. - */ - CINIT(RESUME_FROM, LONG, 21), - - /* Set cookie in request: */ - CINIT(COOKIE, OBJECTPOINT, 22), - - /* This points to a linked list of headers, struct curl_slist kind */ - CINIT(HTTPHEADER, OBJECTPOINT, 23), - - /* This points to a linked list of post entries, struct curl_httppost */ - CINIT(HTTPPOST, OBJECTPOINT, 24), - - /* name of the file keeping your private SSL-certificate */ - CINIT(SSLCERT, OBJECTPOINT, 25), - - /* password for the SSL or SSH private key */ - CINIT(KEYPASSWD, OBJECTPOINT, 26), - - /* send TYPE parameter? */ - CINIT(CRLF, LONG, 27), - - /* send linked-list of QUOTE commands */ - CINIT(QUOTE, OBJECTPOINT, 28), - - /* send FILE * or void * to store headers to, if you use a callback it - is simply passed to the callback unmodified */ - CINIT(WRITEHEADER, OBJECTPOINT, 29), - - /* point to a file to read the initial cookies from, also enables - "cookie awareness" */ - CINIT(COOKIEFILE, OBJECTPOINT, 31), - - /* What version to specifically try to use. - See CURL_SSLVERSION defines below. */ - CINIT(SSLVERSION, LONG, 32), - - /* What kind of HTTP time condition to use, see defines */ - CINIT(TIMECONDITION, LONG, 33), - - /* Time to use with the above condition. Specified in number of seconds - since 1 Jan 1970 */ - CINIT(TIMEVALUE, LONG, 34), - - /* 35 = OBSOLETE */ - - /* Custom request, for customizing the get command like - HTTP: DELETE, TRACE and others - FTP: to use a different list command - */ - CINIT(CUSTOMREQUEST, OBJECTPOINT, 36), - - /* HTTP request, for odd commands like DELETE, TRACE and others */ - CINIT(STDERR, OBJECTPOINT, 37), - - /* 38 is not used */ - - /* send linked-list of post-transfer QUOTE commands */ - CINIT(POSTQUOTE, OBJECTPOINT, 39), - - CINIT(WRITEINFO, OBJECTPOINT, 40), /* DEPRECATED, do not use! */ - - CINIT(VERBOSE, LONG, 41), /* talk a lot */ - CINIT(HEADER, LONG, 42), /* throw the header out too */ - CINIT(NOPROGRESS, LONG, 43), /* shut off the progress meter */ - CINIT(NOBODY, LONG, 44), /* use HEAD to get http document */ - CINIT(FAILONERROR, LONG, 45), /* no output on http error codes >= 300 */ - CINIT(UPLOAD, LONG, 46), /* this is an upload */ - CINIT(POST, LONG, 47), /* HTTP POST method */ - CINIT(DIRLISTONLY, LONG, 48), /* bare names when listing directories */ - - CINIT(APPEND, LONG, 50), /* Append instead of overwrite on upload! */ - - /* Specify whether to read the user+password from the .netrc or the URL. - * This must be one of the CURL_NETRC_* enums below. */ - CINIT(NETRC, LONG, 51), - - CINIT(FOLLOWLOCATION, LONG, 52), /* use Location: Luke! */ - - CINIT(TRANSFERTEXT, LONG, 53), /* transfer data in text/ASCII format */ - CINIT(PUT, LONG, 54), /* HTTP PUT */ - - /* 55 = OBSOLETE */ - - /* Function that will be called instead of the internal progress display - * function. This function should be defined as the curl_progress_callback - * prototype defines. */ - CINIT(PROGRESSFUNCTION, FUNCTIONPOINT, 56), - - /* Data passed to the progress callback */ - CINIT(PROGRESSDATA, OBJECTPOINT, 57), - - /* We want the referrer field set automatically when following locations */ - CINIT(AUTOREFERER, LONG, 58), - - /* Port of the proxy, can be set in the proxy string as well with: - "[host]:[port]" */ - CINIT(PROXYPORT, LONG, 59), - - /* size of the POST input data, if strlen() is not good to use */ - CINIT(POSTFIELDSIZE, LONG, 60), - - /* tunnel non-http operations through a HTTP proxy */ - CINIT(HTTPPROXYTUNNEL, LONG, 61), - - /* Set the interface string to use as outgoing network interface */ - CINIT(INTERFACE, OBJECTPOINT, 62), - - /* Set the krb4/5 security level, this also enables krb4/5 awareness. This - * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string - * is set but doesn't match one of these, 'private' will be used. */ - CINIT(KRBLEVEL, OBJECTPOINT, 63), - - /* Set if we should verify the peer in ssl handshake, set 1 to verify. */ - CINIT(SSL_VERIFYPEER, LONG, 64), - - /* The CApath or CAfile used to validate the peer certificate - this option is used only if SSL_VERIFYPEER is true */ - CINIT(CAINFO, OBJECTPOINT, 65), - - /* 66 = OBSOLETE */ - /* 67 = OBSOLETE */ - - /* Maximum number of http redirects to follow */ - CINIT(MAXREDIRS, LONG, 68), - - /* Pass a long set to 1 to get the date of the requested document (if - possible)! Pass a zero to shut it off. */ - CINIT(FILETIME, LONG, 69), - - /* This points to a linked list of telnet options */ - CINIT(TELNETOPTIONS, OBJECTPOINT, 70), - - /* Max amount of cached alive connections */ - CINIT(MAXCONNECTS, LONG, 71), - - CINIT(CLOSEPOLICY, LONG, 72), /* DEPRECATED, do not use! */ - - /* 73 = OBSOLETE */ - - /* Set to explicitly use a new connection for the upcoming transfer. - Do not use this unless you're absolutely sure of this, as it makes the - operation slower and is less friendly for the network. */ - CINIT(FRESH_CONNECT, LONG, 74), - - /* Set to explicitly forbid the upcoming transfer's connection to be re-used - when done. Do not use this unless you're absolutely sure of this, as it - makes the operation slower and is less friendly for the network. */ - CINIT(FORBID_REUSE, LONG, 75), - - /* Set to a file name that contains random data for libcurl to use to - seed the random engine when doing SSL connects. */ - CINIT(RANDOM_FILE, OBJECTPOINT, 76), - - /* Set to the Entropy Gathering Daemon socket pathname */ - CINIT(EGDSOCKET, OBJECTPOINT, 77), - - /* Time-out connect operations after this amount of seconds, if connects - are OK within this time, then fine... This only aborts the connect - phase. [Only works on unix-style/SIGALRM operating systems] */ - CINIT(CONNECTTIMEOUT, LONG, 78), - - /* Function that will be called to store headers (instead of fwrite). The - * parameters will use fwrite() syntax, make sure to follow them. */ - CINIT(HEADERFUNCTION, FUNCTIONPOINT, 79), - - /* Set this to force the HTTP request to get back to GET. Only really usable - if POST, PUT or a custom request have been used first. - */ - CINIT(HTTPGET, LONG, 80), - - /* Set if we should verify the Common name from the peer certificate in ssl - * handshake, set 1 to check existence, 2 to ensure that it matches the - * provided hostname. */ - CINIT(SSL_VERIFYHOST, LONG, 81), - - /* Specify which file name to write all known cookies in after completed - operation. Set file name to "-" (dash) to make it go to stdout. */ - CINIT(COOKIEJAR, OBJECTPOINT, 82), - - /* Specify which SSL ciphers to use */ - CINIT(SSL_CIPHER_LIST, OBJECTPOINT, 83), - - /* Specify which HTTP version to use! This must be set to one of the - CURL_HTTP_VERSION* enums set below. */ - CINIT(HTTP_VERSION, LONG, 84), - - /* Specifically switch on or off the FTP engine's use of the EPSV command. By - default, that one will always be attempted before the more traditional - PASV command. */ - CINIT(FTP_USE_EPSV, LONG, 85), - - /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */ - CINIT(SSLCERTTYPE, OBJECTPOINT, 86), - - /* name of the file keeping your private SSL-key */ - CINIT(SSLKEY, OBJECTPOINT, 87), - - /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */ - CINIT(SSLKEYTYPE, OBJECTPOINT, 88), - - /* crypto engine for the SSL-sub system */ - CINIT(SSLENGINE, OBJECTPOINT, 89), - - /* set the crypto engine for the SSL-sub system as default - the param has no meaning... - */ - CINIT(SSLENGINE_DEFAULT, LONG, 90), - - /* Non-zero value means to use the global dns cache */ - CINIT(DNS_USE_GLOBAL_CACHE, LONG, 91), /* DEPRECATED, do not use! */ - - /* DNS cache timeout */ - CINIT(DNS_CACHE_TIMEOUT, LONG, 92), - - /* send linked-list of pre-transfer QUOTE commands */ - CINIT(PREQUOTE, OBJECTPOINT, 93), - - /* set the debug function */ - CINIT(DEBUGFUNCTION, FUNCTIONPOINT, 94), - - /* set the data for the debug function */ - CINIT(DEBUGDATA, OBJECTPOINT, 95), - - /* mark this as start of a cookie session */ - CINIT(COOKIESESSION, LONG, 96), - - /* The CApath directory used to validate the peer certificate - this option is used only if SSL_VERIFYPEER is true */ - CINIT(CAPATH, OBJECTPOINT, 97), - - /* Instruct libcurl to use a smaller receive buffer */ - CINIT(BUFFERSIZE, LONG, 98), - - /* Instruct libcurl to not use any signal/alarm handlers, even when using - timeouts. This option is useful for multi-threaded applications. - See libcurl-the-guide for more background information. */ - CINIT(NOSIGNAL, LONG, 99), - - /* Provide a CURLShare for mutexing non-ts data */ - CINIT(SHARE, OBJECTPOINT, 100), - - /* indicates type of proxy. accepted values are CURLPROXY_HTTP (default), - CURLPROXY_SOCKS4, CURLPROXY_SOCKS4A and CURLPROXY_SOCKS5. */ - CINIT(PROXYTYPE, LONG, 101), - - /* Set the Accept-Encoding string. Use this to tell a server you would like - the response to be compressed. Before 7.21.6, this was known as - CURLOPT_ENCODING */ - CINIT(ACCEPT_ENCODING, OBJECTPOINT, 102), - - /* Set pointer to private data */ - CINIT(PRIVATE, OBJECTPOINT, 103), - - /* Set aliases for HTTP 200 in the HTTP Response header */ - CINIT(HTTP200ALIASES, OBJECTPOINT, 104), - - /* Continue to send authentication (user+password) when following locations, - even when hostname changed. This can potentially send off the name - and password to whatever host the server decides. */ - CINIT(UNRESTRICTED_AUTH, LONG, 105), - - /* Specifically switch on or off the FTP engine's use of the EPRT command ( - it also disables the LPRT attempt). By default, those ones will always be - attempted before the good old traditional PORT command. */ - CINIT(FTP_USE_EPRT, LONG, 106), - - /* Set this to a bitmask value to enable the particular authentications - methods you like. Use this in combination with CURLOPT_USERPWD. - Note that setting multiple bits may cause extra network round-trips. */ - CINIT(HTTPAUTH, LONG, 107), - - /* Set the ssl context callback function, currently only for OpenSSL ssl_ctx - in second argument. The function must be matching the - curl_ssl_ctx_callback proto. */ - CINIT(SSL_CTX_FUNCTION, FUNCTIONPOINT, 108), - - /* Set the userdata for the ssl context callback function's third - argument */ - CINIT(SSL_CTX_DATA, OBJECTPOINT, 109), - - /* FTP Option that causes missing dirs to be created on the remote server. - In 7.19.4 we introduced the convenience enums for this option using the - CURLFTP_CREATE_DIR prefix. - */ - CINIT(FTP_CREATE_MISSING_DIRS, LONG, 110), - - /* Set this to a bitmask value to enable the particular authentications - methods you like. Use this in combination with CURLOPT_PROXYUSERPWD. - Note that setting multiple bits may cause extra network round-trips. */ - CINIT(PROXYAUTH, LONG, 111), - - /* FTP option that changes the timeout, in seconds, associated with - getting a response. This is different from transfer timeout time and - essentially places a demand on the FTP server to acknowledge commands - in a timely manner. */ - CINIT(FTP_RESPONSE_TIMEOUT, LONG, 112), -#define CURLOPT_SERVER_RESPONSE_TIMEOUT CURLOPT_FTP_RESPONSE_TIMEOUT - - /* Set this option to one of the CURL_IPRESOLVE_* defines (see below) to - tell libcurl to resolve names to those IP versions only. This only has - affect on systems with support for more than one, i.e IPv4 _and_ IPv6. */ - CINIT(IPRESOLVE, LONG, 113), - - /* Set this option to limit the size of a file that will be downloaded from - an HTTP or FTP server. - - Note there is also _LARGE version which adds large file support for - platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */ - CINIT(MAXFILESIZE, LONG, 114), - - /* See the comment for INFILESIZE above, but in short, specifies - * the size of the file being uploaded. -1 means unknown. - */ - CINIT(INFILESIZE_LARGE, OFF_T, 115), - - /* Sets the continuation offset. There is also a LONG version of this; - * look above for RESUME_FROM. - */ - CINIT(RESUME_FROM_LARGE, OFF_T, 116), - - /* Sets the maximum size of data that will be downloaded from - * an HTTP or FTP server. See MAXFILESIZE above for the LONG version. - */ - CINIT(MAXFILESIZE_LARGE, OFF_T, 117), - - /* Set this option to the file name of your .netrc file you want libcurl - to parse (using the CURLOPT_NETRC option). If not set, libcurl will do - a poor attempt to find the user's home directory and check for a .netrc - file in there. */ - CINIT(NETRC_FILE, OBJECTPOINT, 118), - - /* Enable SSL/TLS for FTP, pick one of: - CURLFTPSSL_TRY - try using SSL, proceed anyway otherwise - CURLFTPSSL_CONTROL - SSL for the control connection or fail - CURLFTPSSL_ALL - SSL for all communication or fail - */ - CINIT(USE_SSL, LONG, 119), - - /* The _LARGE version of the standard POSTFIELDSIZE option */ - CINIT(POSTFIELDSIZE_LARGE, OFF_T, 120), - - /* Enable/disable the TCP Nagle algorithm */ - CINIT(TCP_NODELAY, LONG, 121), - - /* 122 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 123 OBSOLETE. Gone in 7.16.0 */ - /* 124 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 125 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 126 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 127 OBSOLETE. Gone in 7.16.0 */ - /* 128 OBSOLETE. Gone in 7.16.0 */ - - /* When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option - can be used to change libcurl's default action which is to first try - "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK - response has been received. - - Available parameters are: - CURLFTPAUTH_DEFAULT - let libcurl decide - CURLFTPAUTH_SSL - try "AUTH SSL" first, then TLS - CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL - */ - CINIT(FTPSSLAUTH, LONG, 129), - - CINIT(IOCTLFUNCTION, FUNCTIONPOINT, 130), - CINIT(IOCTLDATA, OBJECTPOINT, 131), - - /* 132 OBSOLETE. Gone in 7.16.0 */ - /* 133 OBSOLETE. Gone in 7.16.0 */ - - /* zero terminated string for pass on to the FTP server when asked for - "account" info */ - CINIT(FTP_ACCOUNT, OBJECTPOINT, 134), - - /* feed cookies into cookie engine */ - CINIT(COOKIELIST, OBJECTPOINT, 135), - - /* ignore Content-Length */ - CINIT(IGNORE_CONTENT_LENGTH, LONG, 136), - - /* Set to non-zero to skip the IP address received in a 227 PASV FTP server - response. Typically used for FTP-SSL purposes but is not restricted to - that. libcurl will then instead use the same IP address it used for the - control connection. */ - CINIT(FTP_SKIP_PASV_IP, LONG, 137), - - /* Select "file method" to use when doing FTP, see the curl_ftpmethod - above. */ - CINIT(FTP_FILEMETHOD, LONG, 138), - - /* Local port number to bind the socket to */ - CINIT(LOCALPORT, LONG, 139), - - /* Number of ports to try, including the first one set with LOCALPORT. - Thus, setting it to 1 will make no additional attempts but the first. - */ - CINIT(LOCALPORTRANGE, LONG, 140), - - /* no transfer, set up connection and let application use the socket by - extracting it with CURLINFO_LASTSOCKET */ - CINIT(CONNECT_ONLY, LONG, 141), - - /* Function that will be called to convert from the - network encoding (instead of using the iconv calls in libcurl) */ - CINIT(CONV_FROM_NETWORK_FUNCTION, FUNCTIONPOINT, 142), - - /* Function that will be called to convert to the - network encoding (instead of using the iconv calls in libcurl) */ - CINIT(CONV_TO_NETWORK_FUNCTION, FUNCTIONPOINT, 143), - - /* Function that will be called to convert from UTF8 - (instead of using the iconv calls in libcurl) - Note that this is used only for SSL certificate processing */ - CINIT(CONV_FROM_UTF8_FUNCTION, FUNCTIONPOINT, 144), - - /* if the connection proceeds too quickly then need to slow it down */ - /* limit-rate: maximum number of bytes per second to send or receive */ - CINIT(MAX_SEND_SPEED_LARGE, OFF_T, 145), - CINIT(MAX_RECV_SPEED_LARGE, OFF_T, 146), - - /* Pointer to command string to send if USER/PASS fails. */ - CINIT(FTP_ALTERNATIVE_TO_USER, OBJECTPOINT, 147), - - /* callback function for setting socket options */ - CINIT(SOCKOPTFUNCTION, FUNCTIONPOINT, 148), - CINIT(SOCKOPTDATA, OBJECTPOINT, 149), - - /* set to 0 to disable session ID re-use for this transfer, default is - enabled (== 1) */ - CINIT(SSL_SESSIONID_CACHE, LONG, 150), - - /* allowed SSH authentication methods */ - CINIT(SSH_AUTH_TYPES, LONG, 151), - - /* Used by scp/sftp to do public/private key authentication */ - CINIT(SSH_PUBLIC_KEYFILE, OBJECTPOINT, 152), - CINIT(SSH_PRIVATE_KEYFILE, OBJECTPOINT, 153), - - /* Send CCC (Clear Command Channel) after authentication */ - CINIT(FTP_SSL_CCC, LONG, 154), - - /* Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */ - CINIT(TIMEOUT_MS, LONG, 155), - CINIT(CONNECTTIMEOUT_MS, LONG, 156), - - /* set to zero to disable the libcurl's decoding and thus pass the raw body - data to the application even when it is encoded/compressed */ - CINIT(HTTP_TRANSFER_DECODING, LONG, 157), - CINIT(HTTP_CONTENT_DECODING, LONG, 158), - - /* Permission used when creating new files and directories on the remote - server for protocols that support it, SFTP/SCP/FILE */ - CINIT(NEW_FILE_PERMS, LONG, 159), - CINIT(NEW_DIRECTORY_PERMS, LONG, 160), - - /* Set the behaviour of POST when redirecting. Values must be set to one - of CURL_REDIR* defines below. This used to be called CURLOPT_POST301 */ - CINIT(POSTREDIR, LONG, 161), - - /* used by scp/sftp to verify the host's public key */ - CINIT(SSH_HOST_PUBLIC_KEY_MD5, OBJECTPOINT, 162), - - /* Callback function for opening socket (instead of socket(2)). Optionally, - callback is able change the address or refuse to connect returning - CURL_SOCKET_BAD. The callback should have type - curl_opensocket_callback */ - CINIT(OPENSOCKETFUNCTION, FUNCTIONPOINT, 163), - CINIT(OPENSOCKETDATA, OBJECTPOINT, 164), - - /* POST volatile input fields. */ - CINIT(COPYPOSTFIELDS, OBJECTPOINT, 165), - - /* set transfer mode (;type=) when doing FTP via an HTTP proxy */ - CINIT(PROXY_TRANSFER_MODE, LONG, 166), - - /* Callback function for seeking in the input stream */ - CINIT(SEEKFUNCTION, FUNCTIONPOINT, 167), - CINIT(SEEKDATA, OBJECTPOINT, 168), - - /* CRL file */ - CINIT(CRLFILE, OBJECTPOINT, 169), - - /* Issuer certificate */ - CINIT(ISSUERCERT, OBJECTPOINT, 170), - - /* (IPv6) Address scope */ - CINIT(ADDRESS_SCOPE, LONG, 171), - - /* Collect certificate chain info and allow it to get retrievable with - CURLINFO_CERTINFO after the transfer is complete. (Unfortunately) only - working with OpenSSL-powered builds. */ - CINIT(CERTINFO, LONG, 172), - - /* "name" and "pwd" to use when fetching. */ - CINIT(USERNAME, OBJECTPOINT, 173), - CINIT(PASSWORD, OBJECTPOINT, 174), - - /* "name" and "pwd" to use with Proxy when fetching. */ - CINIT(PROXYUSERNAME, OBJECTPOINT, 175), - CINIT(PROXYPASSWORD, OBJECTPOINT, 176), - - /* Comma separated list of hostnames defining no-proxy zones. These should - match both hostnames directly, and hostnames within a domain. For - example, local.com will match local.com and www.local.com, but NOT - notlocal.com or www.notlocal.com. For compatibility with other - implementations of this, .local.com will be considered to be the same as - local.com. A single * is the only valid wildcard, and effectively - disables the use of proxy. */ - CINIT(NOPROXY, OBJECTPOINT, 177), - - /* block size for TFTP transfers */ - CINIT(TFTP_BLKSIZE, LONG, 178), - - /* Socks Service */ - CINIT(SOCKS5_GSSAPI_SERVICE, OBJECTPOINT, 179), - - /* Socks Service */ - CINIT(SOCKS5_GSSAPI_NEC, LONG, 180), - - /* set the bitmask for the protocols that are allowed to be used for the - transfer, which thus helps the app which takes URLs from users or other - external inputs and want to restrict what protocol(s) to deal - with. Defaults to CURLPROTO_ALL. */ - CINIT(PROTOCOLS, LONG, 181), - - /* set the bitmask for the protocols that libcurl is allowed to follow to, - as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs - to be set in both bitmasks to be allowed to get redirected to. Defaults - to all protocols except FILE and SCP. */ - CINIT(REDIR_PROTOCOLS, LONG, 182), - - /* set the SSH knownhost file name to use */ - CINIT(SSH_KNOWNHOSTS, OBJECTPOINT, 183), - - /* set the SSH host key callback, must point to a curl_sshkeycallback - function */ - CINIT(SSH_KEYFUNCTION, FUNCTIONPOINT, 184), - - /* set the SSH host key callback custom pointer */ - CINIT(SSH_KEYDATA, OBJECTPOINT, 185), - - /* set the SMTP mail originator */ - CINIT(MAIL_FROM, OBJECTPOINT, 186), - - /* set the SMTP mail receiver(s) */ - CINIT(MAIL_RCPT, OBJECTPOINT, 187), - - /* FTP: send PRET before PASV */ - CINIT(FTP_USE_PRET, LONG, 188), - - /* RTSP request method (OPTIONS, SETUP, PLAY, etc...) */ - CINIT(RTSP_REQUEST, LONG, 189), - - /* The RTSP session identifier */ - CINIT(RTSP_SESSION_ID, OBJECTPOINT, 190), - - /* The RTSP stream URI */ - CINIT(RTSP_STREAM_URI, OBJECTPOINT, 191), - - /* The Transport: header to use in RTSP requests */ - CINIT(RTSP_TRANSPORT, OBJECTPOINT, 192), - - /* Manually initialize the client RTSP CSeq for this handle */ - CINIT(RTSP_CLIENT_CSEQ, LONG, 193), - - /* Manually initialize the server RTSP CSeq for this handle */ - CINIT(RTSP_SERVER_CSEQ, LONG, 194), - - /* The stream to pass to INTERLEAVEFUNCTION. */ - CINIT(INTERLEAVEDATA, OBJECTPOINT, 195), - - /* Let the application define a custom write method for RTP data */ - CINIT(INTERLEAVEFUNCTION, FUNCTIONPOINT, 196), - - /* Turn on wildcard matching */ - CINIT(WILDCARDMATCH, LONG, 197), - - /* Directory matching callback called before downloading of an - individual file (chunk) started */ - CINIT(CHUNK_BGN_FUNCTION, FUNCTIONPOINT, 198), - - /* Directory matching callback called after the file (chunk) - was downloaded, or skipped */ - CINIT(CHUNK_END_FUNCTION, FUNCTIONPOINT, 199), - - /* Change match (fnmatch-like) callback for wildcard matching */ - CINIT(FNMATCH_FUNCTION, FUNCTIONPOINT, 200), - - /* Let the application define custom chunk data pointer */ - CINIT(CHUNK_DATA, OBJECTPOINT, 201), - - /* FNMATCH_FUNCTION user pointer */ - CINIT(FNMATCH_DATA, OBJECTPOINT, 202), - - /* send linked-list of name:port:address sets */ - CINIT(RESOLVE, OBJECTPOINT, 203), - - /* Set a username for authenticated TLS */ - CINIT(TLSAUTH_USERNAME, OBJECTPOINT, 204), - - /* Set a password for authenticated TLS */ - CINIT(TLSAUTH_PASSWORD, OBJECTPOINT, 205), - - /* Set authentication type for authenticated TLS */ - CINIT(TLSAUTH_TYPE, OBJECTPOINT, 206), - - /* Set to 1 to enable the "TE:" header in HTTP requests to ask for - compressed transfer-encoded responses. Set to 0 to disable the use of TE: - in outgoing requests. The current default is 0, but it might change in a - future libcurl release. - - libcurl will ask for the compressed methods it knows of, and if that - isn't any, it will not ask for transfer-encoding at all even if this - option is set to 1. - - */ - CINIT(TRANSFER_ENCODING, LONG, 207), - - /* Callback function for closing socket (instead of close(2)). The callback - should have type curl_closesocket_callback */ - CINIT(CLOSESOCKETFUNCTION, FUNCTIONPOINT, 208), - CINIT(CLOSESOCKETDATA, OBJECTPOINT, 209), - - /* allow GSSAPI credential delegation */ - CINIT(GSSAPI_DELEGATION, LONG, 210), - - /* Set the name servers to use for DNS resolution */ - CINIT(DNS_SERVERS, OBJECTPOINT, 211), - - /* Time-out accept operations (currently for FTP only) after this amount - of miliseconds. */ - CINIT(ACCEPTTIMEOUT_MS, LONG, 212), - - /* Set TCP keepalive */ - CINIT(TCP_KEEPALIVE, LONG, 213), - - /* non-universal keepalive knobs (Linux, AIX, HP-UX, more) */ - CINIT(TCP_KEEPIDLE, LONG, 214), - CINIT(TCP_KEEPINTVL, LONG, 215), - - /* Enable/disable specific SSL features with a bitmask, see CURLSSLOPT_* */ - CINIT(SSL_OPTIONS, LONG, 216), - - /* set the SMTP auth originator */ - CINIT(MAIL_AUTH, OBJECTPOINT, 217), - - CURLOPT_LASTENTRY /* the last unused */ -} CURLoption; - -#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all - the obsolete stuff removed! */ - -/* Backwards compatibility with older names */ -/* These are scheduled to disappear by 2011 */ - -/* This was added in version 7.19.1 */ -#define CURLOPT_POST301 CURLOPT_POSTREDIR - -/* These are scheduled to disappear by 2009 */ - -/* The following were added in 7.17.0 */ -#define CURLOPT_SSLKEYPASSWD CURLOPT_KEYPASSWD -#define CURLOPT_FTPAPPEND CURLOPT_APPEND -#define CURLOPT_FTPLISTONLY CURLOPT_DIRLISTONLY -#define CURLOPT_FTP_SSL CURLOPT_USE_SSL - -/* The following were added earlier */ - -#define CURLOPT_SSLCERTPASSWD CURLOPT_KEYPASSWD -#define CURLOPT_KRB4LEVEL CURLOPT_KRBLEVEL - -#else -/* This is set if CURL_NO_OLDIES is defined at compile-time */ -#undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */ -#endif - - - /* Below here follows defines for the CURLOPT_IPRESOLVE option. If a host - name resolves addresses using more than one IP protocol version, this - option might be handy to force libcurl to use a specific IP version. */ -#define CURL_IPRESOLVE_WHATEVER 0 /* default, resolves addresses to all IP - versions that your system allows */ -#define CURL_IPRESOLVE_V4 1 /* resolve to ipv4 addresses */ -#define CURL_IPRESOLVE_V6 2 /* resolve to ipv6 addresses */ - - /* three convenient "aliases" that follow the name scheme better */ -#define CURLOPT_WRITEDATA CURLOPT_FILE -#define CURLOPT_READDATA CURLOPT_INFILE -#define CURLOPT_HEADERDATA CURLOPT_WRITEHEADER -#define CURLOPT_RTSPHEADER CURLOPT_HTTPHEADER - - /* These enums are for use with the CURLOPT_HTTP_VERSION option. */ -enum { - CURL_HTTP_VERSION_NONE, /* setting this means we don't care, and that we'd - like the library to choose the best possible - for us! */ - CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */ - CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */ - - CURL_HTTP_VERSION_LAST /* *ILLEGAL* http version */ -}; - -/* - * Public API enums for RTSP requests - */ -enum { - CURL_RTSPREQ_NONE, /* first in list */ - CURL_RTSPREQ_OPTIONS, - CURL_RTSPREQ_DESCRIBE, - CURL_RTSPREQ_ANNOUNCE, - CURL_RTSPREQ_SETUP, - CURL_RTSPREQ_PLAY, - CURL_RTSPREQ_PAUSE, - CURL_RTSPREQ_TEARDOWN, - CURL_RTSPREQ_GET_PARAMETER, - CURL_RTSPREQ_SET_PARAMETER, - CURL_RTSPREQ_RECORD, - CURL_RTSPREQ_RECEIVE, - CURL_RTSPREQ_LAST /* last in list */ -}; - - /* These enums are for use with the CURLOPT_NETRC option. */ -enum CURL_NETRC_OPTION { - CURL_NETRC_IGNORED, /* The .netrc will never be read. - * This is the default. */ - CURL_NETRC_OPTIONAL, /* A user:password in the URL will be preferred - * to one in the .netrc. */ - CURL_NETRC_REQUIRED, /* A user:password in the URL will be ignored. - * Unless one is set programmatically, the .netrc - * will be queried. */ - CURL_NETRC_LAST -}; - -enum { - CURL_SSLVERSION_DEFAULT, - CURL_SSLVERSION_TLSv1, - CURL_SSLVERSION_SSLv2, - CURL_SSLVERSION_SSLv3, - - CURL_SSLVERSION_LAST /* never use, keep last */ -}; - -enum CURL_TLSAUTH { - CURL_TLSAUTH_NONE, - CURL_TLSAUTH_SRP, - CURL_TLSAUTH_LAST /* never use, keep last */ -}; - -/* symbols to use with CURLOPT_POSTREDIR. - CURL_REDIR_POST_301, CURL_REDIR_POST_302 and CURL_REDIR_POST_303 - can be bitwise ORed so that CURL_REDIR_POST_301 | CURL_REDIR_POST_302 - | CURL_REDIR_POST_303 == CURL_REDIR_POST_ALL */ - -#define CURL_REDIR_GET_ALL 0 -#define CURL_REDIR_POST_301 1 -#define CURL_REDIR_POST_302 2 -#define CURL_REDIR_POST_303 4 -#define CURL_REDIR_POST_ALL \ - (CURL_REDIR_POST_301|CURL_REDIR_POST_302|CURL_REDIR_POST_303) - -typedef enum { - CURL_TIMECOND_NONE, - - CURL_TIMECOND_IFMODSINCE, - CURL_TIMECOND_IFUNMODSINCE, - CURL_TIMECOND_LASTMOD, - - CURL_TIMECOND_LAST -} curl_TimeCond; - - -/* curl_strequal() and curl_strnequal() are subject for removal in a future - libcurl, see lib/README.curlx for details */ -CURL_EXTERN int (curl_strequal)(const char *s1, const char *s2); -CURL_EXTERN int (curl_strnequal)(const char *s1, const char *s2, size_t n); - -/* name is uppercase CURLFORM_ */ -#ifdef CFINIT -#undef CFINIT -#endif - -#ifdef CURL_ISOCPP -#define CFINIT(name) CURLFORM_ ## name -#else -/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */ -#define CFINIT(name) CURLFORM_/**/name -#endif - -typedef enum { - CFINIT(NOTHING), /********* the first one is unused ************/ - - /* */ - CFINIT(COPYNAME), - CFINIT(PTRNAME), - CFINIT(NAMELENGTH), - CFINIT(COPYCONTENTS), - CFINIT(PTRCONTENTS), - CFINIT(CONTENTSLENGTH), - CFINIT(FILECONTENT), - CFINIT(ARRAY), - CFINIT(OBSOLETE), - CFINIT(FILE), - - CFINIT(BUFFER), - CFINIT(BUFFERPTR), - CFINIT(BUFFERLENGTH), - - CFINIT(CONTENTTYPE), - CFINIT(CONTENTHEADER), - CFINIT(FILENAME), - CFINIT(END), - CFINIT(OBSOLETE2), - - CFINIT(STREAM), - - CURLFORM_LASTENTRY /* the last unused */ -} CURLformoption; - -#undef CFINIT /* done */ - -/* structure to be used as parameter for CURLFORM_ARRAY */ -struct curl_forms { - CURLformoption option; - const char *value; -}; - -/* use this for multipart formpost building */ -/* Returns code for curl_formadd() - * - * Returns: - * CURL_FORMADD_OK on success - * CURL_FORMADD_MEMORY if the FormInfo allocation fails - * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form - * CURL_FORMADD_NULL if a null pointer was given for a char - * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed - * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used - * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error) - * CURL_FORMADD_MEMORY if a curl_httppost struct cannot be allocated - * CURL_FORMADD_MEMORY if some allocation for string copying failed. - * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array - * - ***************************************************************************/ -typedef enum { - CURL_FORMADD_OK, /* first, no error */ - - CURL_FORMADD_MEMORY, - CURL_FORMADD_OPTION_TWICE, - CURL_FORMADD_NULL, - CURL_FORMADD_UNKNOWN_OPTION, - CURL_FORMADD_INCOMPLETE, - CURL_FORMADD_ILLEGAL_ARRAY, - CURL_FORMADD_DISABLED, /* libcurl was built with this disabled */ - - CURL_FORMADD_LAST /* last */ -} CURLFORMcode; - -/* - * NAME curl_formadd() - * - * DESCRIPTION - * - * Pretty advanced function for building multi-part formposts. Each invoke - * adds one part that together construct a full post. Then use - * CURLOPT_HTTPPOST to send it off to libcurl. - */ -CURL_EXTERN CURLFORMcode curl_formadd(struct curl_httppost **httppost, - struct curl_httppost **last_post, - ...); - -/* - * callback function for curl_formget() - * The void *arg pointer will be the one passed as second argument to - * curl_formget(). - * The character buffer passed to it must not be freed. - * Should return the buffer length passed to it as the argument "len" on - * success. - */ -typedef size_t (*curl_formget_callback)(void *arg, const char *buf, - size_t len); - -/* - * NAME curl_formget() - * - * DESCRIPTION - * - * Serialize a curl_httppost struct built with curl_formadd(). - * Accepts a void pointer as second argument which will be passed to - * the curl_formget_callback function. - * Returns 0 on success. - */ -CURL_EXTERN int curl_formget(struct curl_httppost *form, void *arg, - curl_formget_callback append); -/* - * NAME curl_formfree() - * - * DESCRIPTION - * - * Free a multipart formpost previously built with curl_formadd(). - */ -CURL_EXTERN void curl_formfree(struct curl_httppost *form); - -/* - * NAME curl_getenv() - * - * DESCRIPTION - * - * Returns a malloc()'ed string that MUST be curl_free()ed after usage is - * complete. DEPRECATED - see lib/README.curlx - */ -CURL_EXTERN char *curl_getenv(const char *variable); - -/* - * NAME curl_version() - * - * DESCRIPTION - * - * Returns a static ascii string of the libcurl version. - */ -CURL_EXTERN char *curl_version(void); - -/* - * NAME curl_easy_escape() - * - * DESCRIPTION - * - * Escapes URL strings (converts all letters consider illegal in URLs to their - * %XX versions). This function returns a new allocated string or NULL if an - * error occurred. - */ -CURL_EXTERN char *curl_easy_escape(CURL *handle, - const char *string, - int length); - -/* the previous version: */ -CURL_EXTERN char *curl_escape(const char *string, - int length); - - -/* - * NAME curl_easy_unescape() - * - * DESCRIPTION - * - * Unescapes URL encoding in strings (converts all %XX codes to their 8bit - * versions). This function returns a new allocated string or NULL if an error - * occurred. - * Conversion Note: On non-ASCII platforms the ASCII %XX codes are - * converted into the host encoding. - */ -CURL_EXTERN char *curl_easy_unescape(CURL *handle, - const char *string, - int length, - int *outlength); - -/* the previous version */ -CURL_EXTERN char *curl_unescape(const char *string, - int length); - -/* - * NAME curl_free() - * - * DESCRIPTION - * - * Provided for de-allocation in the same translation unit that did the - * allocation. Added in libcurl 7.10 - */ -CURL_EXTERN void curl_free(void *p); - -/* - * NAME curl_global_init() - * - * DESCRIPTION - * - * curl_global_init() should be invoked exactly once for each application that - * uses libcurl and before any call of other libcurl functions. - * - * This function is not thread-safe! - */ -CURL_EXTERN CURLcode curl_global_init(long flags); - -/* - * NAME curl_global_init_mem() - * - * DESCRIPTION - * - * curl_global_init() or curl_global_init_mem() should be invoked exactly once - * for each application that uses libcurl. This function can be used to - * initialize libcurl and set user defined memory management callback - * functions. Users can implement memory management routines to check for - * memory leaks, check for mis-use of the curl library etc. User registered - * callback routines with be invoked by this library instead of the system - * memory management routines like malloc, free etc. - */ -CURL_EXTERN CURLcode curl_global_init_mem(long flags, - curl_malloc_callback m, - curl_free_callback f, - curl_realloc_callback r, - curl_strdup_callback s, - curl_calloc_callback c); - -/* - * NAME curl_global_cleanup() - * - * DESCRIPTION - * - * curl_global_cleanup() should be invoked exactly once for each application - * that uses libcurl - */ -CURL_EXTERN void curl_global_cleanup(void); - -/* linked-list structure for the CURLOPT_QUOTE option (and other) */ -struct curl_slist { - char *data; - struct curl_slist *next; -}; - -/* - * NAME curl_slist_append() - * - * DESCRIPTION - * - * Appends a string to a linked list. If no list exists, it will be created - * first. Returns the new list, after appending. - */ -CURL_EXTERN struct curl_slist *curl_slist_append(struct curl_slist *, - const char *); - -/* - * NAME curl_slist_free_all() - * - * DESCRIPTION - * - * free a previously built curl_slist. - */ -CURL_EXTERN void curl_slist_free_all(struct curl_slist *); - -/* - * NAME curl_getdate() - * - * DESCRIPTION - * - * Returns the time, in seconds since 1 Jan 1970 of the time string given in - * the first argument. The time argument in the second parameter is unused - * and should be set to NULL. - */ -CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused); - -/* info about the certificate chain, only for OpenSSL builds. Asked - for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */ -struct curl_certinfo { - int num_of_certs; /* number of certificates with information */ - struct curl_slist **certinfo; /* for each index in this array, there's a - linked list with textual information in the - format "name: value" */ -}; - -#define CURLINFO_STRING 0x100000 -#define CURLINFO_LONG 0x200000 -#define CURLINFO_DOUBLE 0x300000 -#define CURLINFO_SLIST 0x400000 -#define CURLINFO_MASK 0x0fffff -#define CURLINFO_TYPEMASK 0xf00000 - -typedef enum { - CURLINFO_NONE, /* first, never use this */ - CURLINFO_EFFECTIVE_URL = CURLINFO_STRING + 1, - CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2, - CURLINFO_TOTAL_TIME = CURLINFO_DOUBLE + 3, - CURLINFO_NAMELOOKUP_TIME = CURLINFO_DOUBLE + 4, - CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5, - CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6, - CURLINFO_SIZE_UPLOAD = CURLINFO_DOUBLE + 7, - CURLINFO_SIZE_DOWNLOAD = CURLINFO_DOUBLE + 8, - CURLINFO_SPEED_DOWNLOAD = CURLINFO_DOUBLE + 9, - CURLINFO_SPEED_UPLOAD = CURLINFO_DOUBLE + 10, - CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11, - CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12, - CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13, - CURLINFO_FILETIME = CURLINFO_LONG + 14, - CURLINFO_CONTENT_LENGTH_DOWNLOAD = CURLINFO_DOUBLE + 15, - CURLINFO_CONTENT_LENGTH_UPLOAD = CURLINFO_DOUBLE + 16, - CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17, - CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18, - CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19, - CURLINFO_REDIRECT_COUNT = CURLINFO_LONG + 20, - CURLINFO_PRIVATE = CURLINFO_STRING + 21, - CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG + 22, - CURLINFO_HTTPAUTH_AVAIL = CURLINFO_LONG + 23, - CURLINFO_PROXYAUTH_AVAIL = CURLINFO_LONG + 24, - CURLINFO_OS_ERRNO = CURLINFO_LONG + 25, - CURLINFO_NUM_CONNECTS = CURLINFO_LONG + 26, - CURLINFO_SSL_ENGINES = CURLINFO_SLIST + 27, - CURLINFO_COOKIELIST = CURLINFO_SLIST + 28, - CURLINFO_LASTSOCKET = CURLINFO_LONG + 29, - CURLINFO_FTP_ENTRY_PATH = CURLINFO_STRING + 30, - CURLINFO_REDIRECT_URL = CURLINFO_STRING + 31, - CURLINFO_PRIMARY_IP = CURLINFO_STRING + 32, - CURLINFO_APPCONNECT_TIME = CURLINFO_DOUBLE + 33, - CURLINFO_CERTINFO = CURLINFO_SLIST + 34, - CURLINFO_CONDITION_UNMET = CURLINFO_LONG + 35, - CURLINFO_RTSP_SESSION_ID = CURLINFO_STRING + 36, - CURLINFO_RTSP_CLIENT_CSEQ = CURLINFO_LONG + 37, - CURLINFO_RTSP_SERVER_CSEQ = CURLINFO_LONG + 38, - CURLINFO_RTSP_CSEQ_RECV = CURLINFO_LONG + 39, - CURLINFO_PRIMARY_PORT = CURLINFO_LONG + 40, - CURLINFO_LOCAL_IP = CURLINFO_STRING + 41, - CURLINFO_LOCAL_PORT = CURLINFO_LONG + 42, - /* Fill in new entries below here! */ - - CURLINFO_LASTONE = 42 -} CURLINFO; - -/* CURLINFO_RESPONSE_CODE is the new name for the option previously known as - CURLINFO_HTTP_CODE */ -#define CURLINFO_HTTP_CODE CURLINFO_RESPONSE_CODE - -typedef enum { - CURLCLOSEPOLICY_NONE, /* first, never use this */ - - CURLCLOSEPOLICY_OLDEST, - CURLCLOSEPOLICY_LEAST_RECENTLY_USED, - CURLCLOSEPOLICY_LEAST_TRAFFIC, - CURLCLOSEPOLICY_SLOWEST, - CURLCLOSEPOLICY_CALLBACK, - - CURLCLOSEPOLICY_LAST /* last, never use this */ -} curl_closepolicy; - -#define CURL_GLOBAL_SSL (1<<0) -#define CURL_GLOBAL_WIN32 (1<<1) -#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32) -#define CURL_GLOBAL_NOTHING 0 -#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL - - -/***************************************************************************** - * Setup defines, protos etc for the sharing stuff. - */ - -/* Different data locks for a single share */ -typedef enum { - CURL_LOCK_DATA_NONE = 0, - /* CURL_LOCK_DATA_SHARE is used internally to say that - * the locking is just made to change the internal state of the share - * itself. - */ - CURL_LOCK_DATA_SHARE, - CURL_LOCK_DATA_COOKIE, - CURL_LOCK_DATA_DNS, - CURL_LOCK_DATA_SSL_SESSION, - CURL_LOCK_DATA_CONNECT, - CURL_LOCK_DATA_LAST -} curl_lock_data; - -/* Different lock access types */ -typedef enum { - CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */ - CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */ - CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */ - CURL_LOCK_ACCESS_LAST /* never use */ -} curl_lock_access; - -typedef void (*curl_lock_function)(CURL *handle, - curl_lock_data data, - curl_lock_access locktype, - void *userptr); -typedef void (*curl_unlock_function)(CURL *handle, - curl_lock_data data, - void *userptr); - -typedef void CURLSH; - -typedef enum { - CURLSHE_OK, /* all is fine */ - CURLSHE_BAD_OPTION, /* 1 */ - CURLSHE_IN_USE, /* 2 */ - CURLSHE_INVALID, /* 3 */ - CURLSHE_NOMEM, /* 4 out of memory */ - CURLSHE_NOT_BUILT_IN, /* 5 feature not present in lib */ - CURLSHE_LAST /* never use */ -} CURLSHcode; - -typedef enum { - CURLSHOPT_NONE, /* don't use */ - CURLSHOPT_SHARE, /* specify a data type to share */ - CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */ - CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */ - CURLSHOPT_UNLOCKFUNC, /* pass in a 'curl_unlock_function' pointer */ - CURLSHOPT_USERDATA, /* pass in a user data pointer used in the lock/unlock - callback functions */ - CURLSHOPT_LAST /* never use */ -} CURLSHoption; - -CURL_EXTERN CURLSH *curl_share_init(void); -CURL_EXTERN CURLSHcode curl_share_setopt(CURLSH *, CURLSHoption option, ...); -CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *); - -/**************************************************************************** - * Structures for querying information about the curl library at runtime. - */ - -typedef enum { - CURLVERSION_FIRST, - CURLVERSION_SECOND, - CURLVERSION_THIRD, - CURLVERSION_FOURTH, - CURLVERSION_LAST /* never actually use this */ -} CURLversion; - -/* The 'CURLVERSION_NOW' is the symbolic name meant to be used by - basically all programs ever that want to get version information. It is - meant to be a built-in version number for what kind of struct the caller - expects. If the struct ever changes, we redefine the NOW to another enum - from above. */ -#define CURLVERSION_NOW CURLVERSION_FOURTH - -typedef struct { - CURLversion age; /* age of the returned struct */ - const char *version; /* LIBCURL_VERSION */ - unsigned int version_num; /* LIBCURL_VERSION_NUM */ - const char *host; /* OS/host/cpu/machine when configured */ - int features; /* bitmask, see defines below */ - const char *ssl_version; /* human readable string */ - long ssl_version_num; /* not used anymore, always 0 */ - const char *libz_version; /* human readable string */ - /* protocols is terminated by an entry with a NULL protoname */ - const char * const *protocols; - - /* The fields below this were added in CURLVERSION_SECOND */ - const char *ares; - int ares_num; - - /* This field was added in CURLVERSION_THIRD */ - const char *libidn; - - /* These field were added in CURLVERSION_FOURTH */ - - /* Same as '_libiconv_version' if built with HAVE_ICONV */ - int iconv_ver_num; - - const char *libssh_version; /* human readable string */ - -} curl_version_info_data; - -#define CURL_VERSION_IPV6 (1<<0) /* IPv6-enabled */ -#define CURL_VERSION_KERBEROS4 (1<<1) /* kerberos auth is supported */ -#define CURL_VERSION_SSL (1<<2) /* SSL options are present */ -#define CURL_VERSION_LIBZ (1<<3) /* libz features are present */ -#define CURL_VERSION_NTLM (1<<4) /* NTLM auth is supported */ -#define CURL_VERSION_GSSNEGOTIATE (1<<5) /* Negotiate auth support */ -#define CURL_VERSION_DEBUG (1<<6) /* built with debug capabilities */ -#define CURL_VERSION_ASYNCHDNS (1<<7) /* asynchronous dns resolves */ -#define CURL_VERSION_SPNEGO (1<<8) /* SPNEGO auth */ -#define CURL_VERSION_LARGEFILE (1<<9) /* supports files bigger than 2GB */ -#define CURL_VERSION_IDN (1<<10) /* International Domain Names support */ -#define CURL_VERSION_SSPI (1<<11) /* SSPI is supported */ -#define CURL_VERSION_CONV (1<<12) /* character conversions supported */ -#define CURL_VERSION_CURLDEBUG (1<<13) /* debug memory tracking supported */ -#define CURL_VERSION_TLSAUTH_SRP (1<<14) /* TLS-SRP auth is supported */ -#define CURL_VERSION_NTLM_WB (1<<15) /* NTLM delegating to winbind helper */ - - /* - * NAME curl_version_info() - * - * DESCRIPTION - * - * This function returns a pointer to a static copy of the version info - * struct. See above. - */ -CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion); - -/* - * NAME curl_easy_strerror() - * - * DESCRIPTION - * - * The curl_easy_strerror function may be used to turn a CURLcode value - * into the equivalent human readable error string. This is useful - * for printing meaningful error messages. - */ -CURL_EXTERN const char *curl_easy_strerror(CURLcode); - -/* - * NAME curl_share_strerror() - * - * DESCRIPTION - * - * The curl_share_strerror function may be used to turn a CURLSHcode value - * into the equivalent human readable error string. This is useful - * for printing meaningful error messages. - */ -CURL_EXTERN const char *curl_share_strerror(CURLSHcode); - -/* - * NAME curl_easy_pause() - * - * DESCRIPTION - * - * The curl_easy_pause function pauses or unpauses transfers. Select the new - * state by setting the bitmask, use the convenience defines below. - * - */ -CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask); - -#define CURLPAUSE_RECV (1<<0) -#define CURLPAUSE_RECV_CONT (0) - -#define CURLPAUSE_SEND (1<<2) -#define CURLPAUSE_SEND_CONT (0) - -#define CURLPAUSE_ALL (CURLPAUSE_RECV|CURLPAUSE_SEND) -#define CURLPAUSE_CONT (CURLPAUSE_RECV_CONT|CURLPAUSE_SEND_CONT) - -#ifdef __cplusplus -} -#endif - -/* unfortunately, the easy.h and multi.h include files need options and info - stuff before they can be included! */ -#include "easy.h" /* nothing in curl is fun without the easy stuff */ -#include "multi.h" - -/* the typechecker doesn't work in C++ (yet) */ -#if defined(__GNUC__) && defined(__GNUC_MINOR__) && \ - ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && \ - !defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK) -#include "typecheck-gcc.h" -#else -#if defined(__STDC__) && (__STDC__ >= 1) -/* This preprocessor magic that replaces a call with the exact same call is - only done to make sure application authors pass exactly three arguments - to these functions. */ -#define curl_easy_setopt(handle,opt,param) curl_easy_setopt(handle,opt,param) -#define curl_easy_getinfo(handle,info,arg) curl_easy_getinfo(handle,info,arg) -#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param) -#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param) -#endif /* __STDC__ >= 1 */ -#endif /* gcc >= 4.3 && !__cplusplus */ - -#endif /* __CURL_CURL_H */ diff --git a/external/curl/include/linux/32-bit/curl/curlbuild.h b/external/curl/include/linux/32-bit/curl/curlbuild.h deleted file mode 100644 index 98ede6eef7..0000000000 --- a/external/curl/include/linux/32-bit/curl/curlbuild.h +++ /dev/null @@ -1,191 +0,0 @@ -/* include/curl/curlbuild.h. Generated from curlbuild.h.in by configure. */ -#ifndef __CURL_CURLBUILD_H -#define __CURL_CURLBUILD_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2011, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* ================================================================ */ -/* NOTES FOR CONFIGURE CAPABLE SYSTEMS */ -/* ================================================================ */ - -/* - * NOTE 1: - * ------- - * - * Nothing in this file is intended to be modified or adjusted by the - * curl library user nor by the curl library builder. - * - * If you think that something actually needs to be changed, adjusted - * or fixed in this file, then, report it on the libcurl development - * mailing list: http://cool.haxx.se/mailman/listinfo/curl-library/ - * - * This header file shall only export symbols which are 'curl' or 'CURL' - * prefixed, otherwise public name space would be polluted. - * - * NOTE 2: - * ------- - * - * Right now you might be staring at file include/curl/curlbuild.h.in or - * at file include/curl/curlbuild.h, this is due to the following reason: - * - * On systems capable of running the configure script, the configure process - * will overwrite the distributed include/curl/curlbuild.h file with one that - * is suitable and specific to the library being configured and built, which - * is generated from the include/curl/curlbuild.h.in template file. - * - */ - -/* ================================================================ */ -/* DEFINITION OF THESE SYMBOLS SHALL NOT TAKE PLACE ANYWHERE ELSE */ -/* ================================================================ */ - -#ifdef CURL_SIZEOF_LONG -#error "CURL_SIZEOF_LONG shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_SIZEOF_LONG_already_defined -#endif - -#ifdef CURL_TYPEOF_CURL_SOCKLEN_T -#error "CURL_TYPEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_already_defined -#endif - -#ifdef CURL_SIZEOF_CURL_SOCKLEN_T -#error "CURL_SIZEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_already_defined -#endif - -#ifdef CURL_TYPEOF_CURL_OFF_T -#error "CURL_TYPEOF_CURL_OFF_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_already_defined -#endif - -#ifdef CURL_FORMAT_CURL_OFF_T -#error "CURL_FORMAT_CURL_OFF_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_already_defined -#endif - -#ifdef CURL_FORMAT_CURL_OFF_TU -#error "CURL_FORMAT_CURL_OFF_TU shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_already_defined -#endif - -#ifdef CURL_FORMAT_OFF_T -#error "CURL_FORMAT_OFF_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_FORMAT_OFF_T_already_defined -#endif - -#ifdef CURL_SIZEOF_CURL_OFF_T -#error "CURL_SIZEOF_CURL_OFF_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_already_defined -#endif - -#ifdef CURL_SUFFIX_CURL_OFF_T -#error "CURL_SUFFIX_CURL_OFF_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_already_defined -#endif - -#ifdef CURL_SUFFIX_CURL_OFF_TU -#error "CURL_SUFFIX_CURL_OFF_TU shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_already_defined -#endif - -/* ================================================================ */ -/* EXTERNAL INTERFACE SETTINGS FOR CONFIGURE CAPABLE SYSTEMS ONLY */ -/* ================================================================ */ - -/* Configure process defines this to 1 when it finds out that system */ -/* header file ws2tcpip.h must be included by the external interface. */ -/* #undef CURL_PULL_WS2TCPIP_H */ -#ifdef CURL_PULL_WS2TCPIP_H -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -# endif -# include -# include -# include -#endif - -/* Configure process defines this to 1 when it finds out that system */ -/* header file sys/types.h must be included by the external interface. */ -#define CURL_PULL_SYS_TYPES_H 1 -#ifdef CURL_PULL_SYS_TYPES_H -# include -#endif - -/* Configure process defines this to 1 when it finds out that system */ -/* header file stdint.h must be included by the external interface. */ -#define CURL_PULL_STDINT_H 1 -#ifdef CURL_PULL_STDINT_H -# include -#endif - -/* Configure process defines this to 1 when it finds out that system */ -/* header file inttypes.h must be included by the external interface. */ -#define CURL_PULL_INTTYPES_H 1 -#ifdef CURL_PULL_INTTYPES_H -# include -#endif - -/* Configure process defines this to 1 when it finds out that system */ -/* header file sys/socket.h must be included by the external interface. */ -#define CURL_PULL_SYS_SOCKET_H 1 -#ifdef CURL_PULL_SYS_SOCKET_H -# include -#endif - -/* The size of `long', as computed by sizeof. */ -#define CURL_SIZEOF_LONG 4 - -/* Integral data type used for curl_socklen_t. */ -#define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t - -/* The size of `curl_socklen_t', as computed by sizeof. */ -#define CURL_SIZEOF_CURL_SOCKLEN_T 4 - -/* Data type definition of curl_socklen_t. */ -typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t; - -/* Signed integral data type used for curl_off_t. */ -#define CURL_TYPEOF_CURL_OFF_T int64_t - -/* Data type definition of curl_off_t. */ -typedef CURL_TYPEOF_CURL_OFF_T curl_off_t; - -/* curl_off_t formatting string directive without "%" conversion specifier. */ -#define CURL_FORMAT_CURL_OFF_T "lld" - -/* unsigned curl_off_t formatting string without "%" conversion specifier. */ -#define CURL_FORMAT_CURL_OFF_TU "llu" - -/* curl_off_t formatting string directive with "%" conversion specifier. */ -#define CURL_FORMAT_OFF_T "%lld" - -/* The size of `curl_off_t', as computed by sizeof. */ -#define CURL_SIZEOF_CURL_OFF_T 8 - -/* curl_off_t constant suffix. */ -#define CURL_SUFFIX_CURL_OFF_T LL - -/* unsigned curl_off_t constant suffix. */ -#define CURL_SUFFIX_CURL_OFF_TU ULL - -#endif /* __CURL_CURLBUILD_H */ diff --git a/external/curl/include/linux/32-bit/curl/curlrules.h b/external/curl/include/linux/32-bit/curl/curlrules.h deleted file mode 100644 index cbc12fdd29..0000000000 --- a/external/curl/include/linux/32-bit/curl/curlrules.h +++ /dev/null @@ -1,261 +0,0 @@ -#ifndef __CURL_CURLRULES_H -#define __CURL_CURLRULES_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2011, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* ================================================================ */ -/* COMPILE TIME SANITY CHECKS */ -/* ================================================================ */ - -/* - * NOTE 1: - * ------- - * - * All checks done in this file are intentionally placed in a public - * header file which is pulled by curl/curl.h when an application is - * being built using an already built libcurl library. Additionally - * this file is also included and used when building the library. - * - * If compilation fails on this file it is certainly sure that the - * problem is elsewhere. It could be a problem in the curlbuild.h - * header file, or simply that you are using different compilation - * settings than those used to build the library. - * - * Nothing in this file is intended to be modified or adjusted by the - * curl library user nor by the curl library builder. - * - * Do not deactivate any check, these are done to make sure that the - * library is properly built and used. - * - * You can find further help on the libcurl development mailing list: - * http://cool.haxx.se/mailman/listinfo/curl-library/ - * - * NOTE 2 - * ------ - * - * Some of the following compile time checks are based on the fact - * that the dimension of a constant array can not be a negative one. - * In this way if the compile time verification fails, the compilation - * will fail issuing an error. The error description wording is compiler - * dependent but it will be quite similar to one of the following: - * - * "negative subscript or subscript is too large" - * "array must have at least one element" - * "-1 is an illegal array size" - * "size of array is negative" - * - * If you are building an application which tries to use an already - * built libcurl library and you are getting this kind of errors on - * this file, it is a clear indication that there is a mismatch between - * how the library was built and how you are trying to use it for your - * application. Your already compiled or binary library provider is the - * only one who can give you the details you need to properly use it. - */ - -/* - * Verify that some macros are actually defined. - */ - -#ifndef CURL_SIZEOF_LONG -# error "CURL_SIZEOF_LONG definition is missing!" - Error Compilation_aborted_CURL_SIZEOF_LONG_is_missing -#endif - -#ifndef CURL_TYPEOF_CURL_SOCKLEN_T -# error "CURL_TYPEOF_CURL_SOCKLEN_T definition is missing!" - Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_is_missing -#endif - -#ifndef CURL_SIZEOF_CURL_SOCKLEN_T -# error "CURL_SIZEOF_CURL_SOCKLEN_T definition is missing!" - Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_is_missing -#endif - -#ifndef CURL_TYPEOF_CURL_OFF_T -# error "CURL_TYPEOF_CURL_OFF_T definition is missing!" - Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_is_missing -#endif - -#ifndef CURL_FORMAT_CURL_OFF_T -# error "CURL_FORMAT_CURL_OFF_T definition is missing!" - Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_is_missing -#endif - -#ifndef CURL_FORMAT_CURL_OFF_TU -# error "CURL_FORMAT_CURL_OFF_TU definition is missing!" - Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_is_missing -#endif - -#ifndef CURL_FORMAT_OFF_T -# error "CURL_FORMAT_OFF_T definition is missing!" - Error Compilation_aborted_CURL_FORMAT_OFF_T_is_missing -#endif - -#ifndef CURL_SIZEOF_CURL_OFF_T -# error "CURL_SIZEOF_CURL_OFF_T definition is missing!" - Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_is_missing -#endif - -#ifndef CURL_SUFFIX_CURL_OFF_T -# error "CURL_SUFFIX_CURL_OFF_T definition is missing!" - Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_is_missing -#endif - -#ifndef CURL_SUFFIX_CURL_OFF_TU -# error "CURL_SUFFIX_CURL_OFF_TU definition is missing!" - Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_is_missing -#endif - -/* - * Macros private to this header file. - */ - -#define CurlchkszEQ(t, s) sizeof(t) == s ? 1 : -1 - -#define CurlchkszGE(t1, t2) sizeof(t1) >= sizeof(t2) ? 1 : -1 - -/* - * Verify that the size previously defined and expected for long - * is the same as the one reported by sizeof() at compile time. - */ - -typedef char - __curl_rule_01__ - [CurlchkszEQ(long, CURL_SIZEOF_LONG)]; - -/* - * Verify that the size previously defined and expected for - * curl_off_t is actually the the same as the one reported - * by sizeof() at compile time. - */ - -typedef char - __curl_rule_02__ - [CurlchkszEQ(curl_off_t, CURL_SIZEOF_CURL_OFF_T)]; - -/* - * Verify at compile time that the size of curl_off_t as reported - * by sizeof() is greater or equal than the one reported for long - * for the current compilation. - */ - -typedef char - __curl_rule_03__ - [CurlchkszGE(curl_off_t, long)]; - -/* - * Verify that the size previously defined and expected for - * curl_socklen_t is actually the the same as the one reported - * by sizeof() at compile time. - */ - -typedef char - __curl_rule_04__ - [CurlchkszEQ(curl_socklen_t, CURL_SIZEOF_CURL_SOCKLEN_T)]; - -/* - * Verify at compile time that the size of curl_socklen_t as reported - * by sizeof() is greater or equal than the one reported for int for - * the current compilation. - */ - -typedef char - __curl_rule_05__ - [CurlchkszGE(curl_socklen_t, int)]; - -/* ================================================================ */ -/* EXTERNALLY AND INTERNALLY VISIBLE DEFINITIONS */ -/* ================================================================ */ - -/* - * CURL_ISOCPP and CURL_OFF_T_C definitions are done here in order to allow - * these to be visible and exported by the external libcurl interface API, - * while also making them visible to the library internals, simply including - * setup.h, without actually needing to include curl.h internally. - * If some day this section would grow big enough, all this should be moved - * to its own header file. - */ - -/* - * Figure out if we can use the ## preprocessor operator, which is supported - * by ISO/ANSI C and C++. Some compilers support it without setting __STDC__ - * or __cplusplus so we need to carefully check for them too. - */ - -#if defined(__STDC__) || defined(_MSC_VER) || defined(__cplusplus) || \ - defined(__HP_aCC) || defined(__BORLANDC__) || defined(__LCC__) || \ - defined(__POCC__) || defined(__SALFORDC__) || defined(__HIGHC__) || \ - defined(__ILEC400__) - /* This compiler is believed to have an ISO compatible preprocessor */ -#define CURL_ISOCPP -#else - /* This compiler is believed NOT to have an ISO compatible preprocessor */ -#undef CURL_ISOCPP -#endif - -/* - * Macros for minimum-width signed and unsigned curl_off_t integer constants. - */ - -#if defined(__BORLANDC__) && (__BORLANDC__ == 0x0551) -# define __CURL_OFF_T_C_HLPR2(x) x -# define __CURL_OFF_T_C_HLPR1(x) __CURL_OFF_T_C_HLPR2(x) -# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \ - __CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_T) -# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \ - __CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_TU) -#else -# ifdef CURL_ISOCPP -# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val ## Suffix -# else -# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val/**/Suffix -# endif -# define __CURL_OFF_T_C_HLPR1(Val,Suffix) __CURL_OFF_T_C_HLPR2(Val,Suffix) -# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_T) -# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_TU) -#endif - -/* - * Get rid of macros private to this header file. - */ - -#undef CurlchkszEQ -#undef CurlchkszGE - -/* - * Get rid of macros not intended to exist beyond this point. - */ - -#undef CURL_PULL_WS2TCPIP_H -#undef CURL_PULL_SYS_TYPES_H -#undef CURL_PULL_SYS_SOCKET_H -#undef CURL_PULL_STDINT_H -#undef CURL_PULL_INTTYPES_H - -#undef CURL_TYPEOF_CURL_SOCKLEN_T -#undef CURL_TYPEOF_CURL_OFF_T - -#ifdef CURL_NO_OLDIES -#undef CURL_FORMAT_OFF_T /* not required since 7.19.0 - obsoleted in 7.20.0 */ -#endif - -#endif /* __CURL_CURLRULES_H */ diff --git a/external/curl/include/linux/32-bit/curl/curlver.h b/external/curl/include/linux/32-bit/curl/curlver.h deleted file mode 100644 index b7e8acf538..0000000000 --- a/external/curl/include/linux/32-bit/curl/curlver.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef __CURL_CURLVER_H -#define __CURL_CURLVER_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2012, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* This header file contains nothing but libcurl version info, generated by - a script at release-time. This was made its own header file in 7.11.2 */ - -/* This is the global package copyright */ -#define LIBCURL_COPYRIGHT "1996 - 2012 Daniel Stenberg, ." - -/* This is the version number of the libcurl package from which this header - file origins: */ -#define LIBCURL_VERSION "7.26.0" - -/* The numeric version number is also available "in parts" by using these - defines: */ -#define LIBCURL_VERSION_MAJOR 7 -#define LIBCURL_VERSION_MINOR 26 -#define LIBCURL_VERSION_PATCH 0 - -/* This is the numeric version of the libcurl version number, meant for easier - parsing and comparions by programs. The LIBCURL_VERSION_NUM define will - always follow this syntax: - - 0xXXYYZZ - - Where XX, YY and ZZ are the main version, release and patch numbers in - hexadecimal (using 8 bits each). All three numbers are always represented - using two digits. 1.2 would appear as "0x010200" while version 9.11.7 - appears as "0x090b07". - - This 6-digit (24 bits) hexadecimal number does not show pre-release number, - and it is always a greater number in a more recent release. It makes - comparisons with greater than and less than work. -*/ -#define LIBCURL_VERSION_NUM 0x071a00 - -/* - * This is the date and time when the full source package was created. The - * timestamp is not stored in git, as the timestamp is properly set in the - * tarballs by the maketgz script. - * - * The format of the date should follow this template: - * - * "Mon Feb 12 11:35:33 UTC 2007" - */ -#define LIBCURL_TIMESTAMP "Thu May 24 16:05:42 UTC 2012" - -#endif /* __CURL_CURLVER_H */ diff --git a/external/curl/include/linux/32-bit/curl/easy.h b/external/curl/include/linux/32-bit/curl/easy.h deleted file mode 100644 index c1e3e76096..0000000000 --- a/external/curl/include/linux/32-bit/curl/easy.h +++ /dev/null @@ -1,102 +0,0 @@ -#ifndef __CURL_EASY_H -#define __CURL_EASY_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2008, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ -#ifdef __cplusplus -extern "C" { -#endif - -CURL_EXTERN CURL *curl_easy_init(void); -CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...); -CURL_EXTERN CURLcode curl_easy_perform(CURL *curl); -CURL_EXTERN void curl_easy_cleanup(CURL *curl); - -/* - * NAME curl_easy_getinfo() - * - * DESCRIPTION - * - * Request internal information from the curl session with this function. The - * third argument MUST be a pointer to a long, a pointer to a char * or a - * pointer to a double (as the documentation describes elsewhere). The data - * pointed to will be filled in accordingly and can be relied upon only if the - * function returns CURLE_OK. This function is intended to get used *AFTER* a - * performed transfer, all results from this function are undefined until the - * transfer is completed. - */ -CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...); - - -/* - * NAME curl_easy_duphandle() - * - * DESCRIPTION - * - * Creates a new curl session handle with the same options set for the handle - * passed in. Duplicating a handle could only be a matter of cloning data and - * options, internal state info and things like persistent connections cannot - * be transferred. It is useful in multithreaded applications when you can run - * curl_easy_duphandle() for each new thread to avoid a series of identical - * curl_easy_setopt() invokes in every thread. - */ -CURL_EXTERN CURL* curl_easy_duphandle(CURL *curl); - -/* - * NAME curl_easy_reset() - * - * DESCRIPTION - * - * Re-initializes a CURL handle to the default values. This puts back the - * handle to the same state as it was in when it was just created. - * - * It does keep: live connections, the Session ID cache, the DNS cache and the - * cookies. - */ -CURL_EXTERN void curl_easy_reset(CURL *curl); - -/* - * NAME curl_easy_recv() - * - * DESCRIPTION - * - * Receives data from the connected socket. Use after successful - * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. - */ -CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, - size_t *n); - -/* - * NAME curl_easy_send() - * - * DESCRIPTION - * - * Sends data over the connected socket. Use after successful - * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. - */ -CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer, - size_t buflen, size_t *n); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/external/curl/include/linux/32-bit/curl/mprintf.h b/external/curl/include/linux/32-bit/curl/mprintf.h deleted file mode 100644 index de7dd2f3c3..0000000000 --- a/external/curl/include/linux/32-bit/curl/mprintf.h +++ /dev/null @@ -1,81 +0,0 @@ -#ifndef __CURL_MPRINTF_H -#define __CURL_MPRINTF_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2006, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -#include -#include /* needed for FILE */ - -#include "curl.h" - -#ifdef __cplusplus -extern "C" { -#endif - -CURL_EXTERN int curl_mprintf(const char *format, ...); -CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...); -CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...); -CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength, - const char *format, ...); -CURL_EXTERN int curl_mvprintf(const char *format, va_list args); -CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args); -CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args); -CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength, - const char *format, va_list args); -CURL_EXTERN char *curl_maprintf(const char *format, ...); -CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args); - -#ifdef _MPRINTF_REPLACE -# undef printf -# undef fprintf -# undef sprintf -# undef vsprintf -# undef snprintf -# undef vprintf -# undef vfprintf -# undef vsnprintf -# undef aprintf -# undef vaprintf -# define printf curl_mprintf -# define fprintf curl_mfprintf -#ifdef CURLDEBUG -/* When built with CURLDEBUG we define away the sprintf() functions since we - don't want internal code to be using them */ -# define sprintf sprintf_was_used -# define vsprintf vsprintf_was_used -#else -# define sprintf curl_msprintf -# define vsprintf curl_mvsprintf -#endif -# define snprintf curl_msnprintf -# define vprintf curl_mvprintf -# define vfprintf curl_mvfprintf -# define vsnprintf curl_mvsnprintf -# define aprintf curl_maprintf -# define vaprintf curl_mvaprintf -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* __CURL_MPRINTF_H */ diff --git a/external/curl/include/linux/32-bit/curl/multi.h b/external/curl/include/linux/32-bit/curl/multi.h deleted file mode 100644 index f96566669c..0000000000 --- a/external/curl/include/linux/32-bit/curl/multi.h +++ /dev/null @@ -1,345 +0,0 @@ -#ifndef __CURL_MULTI_H -#define __CURL_MULTI_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2007, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ -/* - This is an "external" header file. Don't give away any internals here! - - GOALS - - o Enable a "pull" interface. The application that uses libcurl decides where - and when to ask libcurl to get/send data. - - o Enable multiple simultaneous transfers in the same thread without making it - complicated for the application. - - o Enable the application to select() on its own file descriptors and curl's - file descriptors simultaneous easily. - -*/ - -/* - * This header file should not really need to include "curl.h" since curl.h - * itself includes this file and we expect user applications to do #include - * without the need for especially including multi.h. - * - * For some reason we added this include here at one point, and rather than to - * break existing (wrongly written) libcurl applications, we leave it as-is - * but with this warning attached. - */ -#include "curl.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void CURLM; - -typedef enum { - CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or - curl_multi_socket*() soon */ - CURLM_OK, - CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */ - CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */ - CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */ - CURLM_INTERNAL_ERROR, /* this is a libcurl bug */ - CURLM_BAD_SOCKET, /* the passed in socket argument did not match */ - CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */ - CURLM_LAST -} CURLMcode; - -/* just to make code nicer when using curl_multi_socket() you can now check - for CURLM_CALL_MULTI_SOCKET too in the same style it works for - curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */ -#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM - -typedef enum { - CURLMSG_NONE, /* first, not used */ - CURLMSG_DONE, /* This easy handle has completed. 'result' contains - the CURLcode of the transfer */ - CURLMSG_LAST /* last, not used */ -} CURLMSG; - -struct CURLMsg { - CURLMSG msg; /* what this message means */ - CURL *easy_handle; /* the handle it concerns */ - union { - void *whatever; /* message-specific data */ - CURLcode result; /* return code for transfer */ - } data; -}; -typedef struct CURLMsg CURLMsg; - -/* - * Name: curl_multi_init() - * - * Desc: inititalize multi-style curl usage - * - * Returns: a new CURLM handle to use in all 'curl_multi' functions. - */ -CURL_EXTERN CURLM *curl_multi_init(void); - -/* - * Name: curl_multi_add_handle() - * - * Desc: add a standard curl handle to the multi stack - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *multi_handle, - CURL *curl_handle); - - /* - * Name: curl_multi_remove_handle() - * - * Desc: removes a curl handle from the multi stack again - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *multi_handle, - CURL *curl_handle); - - /* - * Name: curl_multi_fdset() - * - * Desc: Ask curl for its fd_set sets. The app can use these to select() or - * poll() on. We want curl_multi_perform() called as soon as one of - * them are ready. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *multi_handle, - fd_set *read_fd_set, - fd_set *write_fd_set, - fd_set *exc_fd_set, - int *max_fd); - - /* - * Name: curl_multi_perform() - * - * Desc: When the app thinks there's data available for curl it calls this - * function to read/write whatever there is right now. This returns - * as soon as the reads and writes are done. This function does not - * require that there actually is data available for reading or that - * data can be written, it can be called just in case. It returns - * the number of handles that still transfer data in the second - * argument's integer-pointer. - * - * Returns: CURLMcode type, general multi error code. *NOTE* that this only - * returns errors etc regarding the whole multi stack. There might - * still have occurred problems on invidual transfers even when this - * returns OK. - */ -CURL_EXTERN CURLMcode curl_multi_perform(CURLM *multi_handle, - int *running_handles); - - /* - * Name: curl_multi_cleanup() - * - * Desc: Cleans up and removes a whole multi stack. It does not free or - * touch any individual easy handles in any way. We need to define - * in what state those handles will be if this function is called - * in the middle of a transfer. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle); - -/* - * Name: curl_multi_info_read() - * - * Desc: Ask the multi handle if there's any messages/informationals from - * the individual transfers. Messages include informationals such as - * error code from the transfer or just the fact that a transfer is - * completed. More details on these should be written down as well. - * - * Repeated calls to this function will return a new struct each - * time, until a special "end of msgs" struct is returned as a signal - * that there is no more to get at this point. - * - * The data the returned pointer points to will not survive calling - * curl_multi_cleanup(). - * - * The 'CURLMsg' struct is meant to be very simple and only contain - * very basic informations. If more involved information is wanted, - * we will provide the particular "transfer handle" in that struct - * and that should/could/would be used in subsequent - * curl_easy_getinfo() calls (or similar). The point being that we - * must never expose complex structs to applications, as then we'll - * undoubtably get backwards compatibility problems in the future. - * - * Returns: A pointer to a filled-in struct, or NULL if it failed or ran out - * of structs. It also writes the number of messages left in the - * queue (after this read) in the integer the second argument points - * to. - */ -CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle, - int *msgs_in_queue); - -/* - * Name: curl_multi_strerror() - * - * Desc: The curl_multi_strerror function may be used to turn a CURLMcode - * value into the equivalent human readable error string. This is - * useful for printing meaningful error messages. - * - * Returns: A pointer to a zero-terminated error message. - */ -CURL_EXTERN const char *curl_multi_strerror(CURLMcode); - -/* - * Name: curl_multi_socket() and - * curl_multi_socket_all() - * - * Desc: An alternative version of curl_multi_perform() that allows the - * application to pass in one of the file descriptors that have been - * detected to have "action" on them and let libcurl perform. - * See man page for details. - */ -#define CURL_POLL_NONE 0 -#define CURL_POLL_IN 1 -#define CURL_POLL_OUT 2 -#define CURL_POLL_INOUT 3 -#define CURL_POLL_REMOVE 4 - -#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD - -#define CURL_CSELECT_IN 0x01 -#define CURL_CSELECT_OUT 0x02 -#define CURL_CSELECT_ERR 0x04 - -typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */ - curl_socket_t s, /* socket */ - int what, /* see above */ - void *userp, /* private callback - pointer */ - void *socketp); /* private socket - pointer */ -/* - * Name: curl_multi_timer_callback - * - * Desc: Called by libcurl whenever the library detects a change in the - * maximum number of milliseconds the app is allowed to wait before - * curl_multi_socket() or curl_multi_perform() must be called - * (to allow libcurl's timed events to take place). - * - * Returns: The callback should return zero. - */ -typedef int (*curl_multi_timer_callback)(CURLM *multi, /* multi handle */ - long timeout_ms, /* see above */ - void *userp); /* private callback - pointer */ - -CURL_EXTERN CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s, - int *running_handles); - -CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *multi_handle, - curl_socket_t s, - int ev_bitmask, - int *running_handles); - -CURL_EXTERN CURLMcode curl_multi_socket_all(CURLM *multi_handle, - int *running_handles); - -#ifndef CURL_ALLOW_OLD_MULTI_SOCKET -/* This macro below was added in 7.16.3 to push users who recompile to use - the new curl_multi_socket_action() instead of the old curl_multi_socket() -*/ -#define curl_multi_socket(x,y,z) curl_multi_socket_action(x,y,0,z) -#endif - -/* - * Name: curl_multi_timeout() - * - * Desc: Returns the maximum number of milliseconds the app is allowed to - * wait before curl_multi_socket() or curl_multi_perform() must be - * called (to allow libcurl's timed events to take place). - * - * Returns: CURLM error code. - */ -CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *multi_handle, - long *milliseconds); - -#undef CINIT /* re-using the same name as in curl.h */ - -#ifdef CURL_ISOCPP -#define CINIT(name,type,num) CURLMOPT_ ## name = CURLOPTTYPE_ ## type + num -#else -/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */ -#define LONG CURLOPTTYPE_LONG -#define OBJECTPOINT CURLOPTTYPE_OBJECTPOINT -#define FUNCTIONPOINT CURLOPTTYPE_FUNCTIONPOINT -#define OFF_T CURLOPTTYPE_OFF_T -#define CINIT(name,type,number) CURLMOPT_/**/name = type + number -#endif - -typedef enum { - /* This is the socket callback function pointer */ - CINIT(SOCKETFUNCTION, FUNCTIONPOINT, 1), - - /* This is the argument passed to the socket callback */ - CINIT(SOCKETDATA, OBJECTPOINT, 2), - - /* set to 1 to enable pipelining for this multi handle */ - CINIT(PIPELINING, LONG, 3), - - /* This is the timer callback function pointer */ - CINIT(TIMERFUNCTION, FUNCTIONPOINT, 4), - - /* This is the argument passed to the timer callback */ - CINIT(TIMERDATA, OBJECTPOINT, 5), - - /* maximum number of entries in the connection cache */ - CINIT(MAXCONNECTS, LONG, 6), - - CURLMOPT_LASTENTRY /* the last unused */ -} CURLMoption; - - -/* - * Name: curl_multi_setopt() - * - * Desc: Sets options for the multi handle. - * - * Returns: CURLM error code. - */ -CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle, - CURLMoption option, ...); - - -/* - * Name: curl_multi_assign() - * - * Desc: This function sets an association in the multi handle between the - * given socket and a private pointer of the application. This is - * (only) useful for curl_multi_socket uses. - * - * Returns: CURLM error code. - */ -CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle, - curl_socket_t sockfd, void *sockp); - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif diff --git a/external/curl/include/linux/32-bit/curl/stdcheaders.h b/external/curl/include/linux/32-bit/curl/stdcheaders.h deleted file mode 100644 index ad82ef6335..0000000000 --- a/external/curl/include/linux/32-bit/curl/stdcheaders.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef __STDC_HEADERS_H -#define __STDC_HEADERS_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2010, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -#include - -size_t fread (void *, size_t, size_t, FILE *); -size_t fwrite (const void *, size_t, size_t, FILE *); - -int strcasecmp(const char *, const char *); -int strncasecmp(const char *, const char *, size_t); - -#endif /* __STDC_HEADERS_H */ diff --git a/external/curl/include/linux/32-bit/curl/typecheck-gcc.h b/external/curl/include/linux/32-bit/curl/typecheck-gcc.h deleted file mode 100644 index f8917e8112..0000000000 --- a/external/curl/include/linux/32-bit/curl/typecheck-gcc.h +++ /dev/null @@ -1,604 +0,0 @@ -#ifndef __CURL_TYPECHECK_GCC_H -#define __CURL_TYPECHECK_GCC_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2012, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* wraps curl_easy_setopt() with typechecking */ - -/* To add a new kind of warning, add an - * if(_curl_is_sometype_option(_curl_opt)) - * if(!_curl_is_sometype(value)) - * _curl_easy_setopt_err_sometype(); - * block and define _curl_is_sometype_option, _curl_is_sometype and - * _curl_easy_setopt_err_sometype below - * - * NOTE: We use two nested 'if' statements here instead of the && operator, in - * order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x - * when compiling with -Wlogical-op. - * - * To add an option that uses the same type as an existing option, you'll just - * need to extend the appropriate _curl_*_option macro - */ -#define curl_easy_setopt(handle, option, value) \ -__extension__ ({ \ - __typeof__ (option) _curl_opt = option; \ - if(__builtin_constant_p(_curl_opt)) { \ - if(_curl_is_long_option(_curl_opt)) \ - if(!_curl_is_long(value)) \ - _curl_easy_setopt_err_long(); \ - if(_curl_is_off_t_option(_curl_opt)) \ - if(!_curl_is_off_t(value)) \ - _curl_easy_setopt_err_curl_off_t(); \ - if(_curl_is_string_option(_curl_opt)) \ - if(!_curl_is_string(value)) \ - _curl_easy_setopt_err_string(); \ - if(_curl_is_write_cb_option(_curl_opt)) \ - if(!_curl_is_write_cb(value)) \ - _curl_easy_setopt_err_write_callback(); \ - if((_curl_opt) == CURLOPT_READFUNCTION) \ - if(!_curl_is_read_cb(value)) \ - _curl_easy_setopt_err_read_cb(); \ - if((_curl_opt) == CURLOPT_IOCTLFUNCTION) \ - if(!_curl_is_ioctl_cb(value)) \ - _curl_easy_setopt_err_ioctl_cb(); \ - if((_curl_opt) == CURLOPT_SOCKOPTFUNCTION) \ - if(!_curl_is_sockopt_cb(value)) \ - _curl_easy_setopt_err_sockopt_cb(); \ - if((_curl_opt) == CURLOPT_OPENSOCKETFUNCTION) \ - if(!_curl_is_opensocket_cb(value)) \ - _curl_easy_setopt_err_opensocket_cb(); \ - if((_curl_opt) == CURLOPT_PROGRESSFUNCTION) \ - if(!_curl_is_progress_cb(value)) \ - _curl_easy_setopt_err_progress_cb(); \ - if((_curl_opt) == CURLOPT_DEBUGFUNCTION) \ - if(!_curl_is_debug_cb(value)) \ - _curl_easy_setopt_err_debug_cb(); \ - if((_curl_opt) == CURLOPT_SSL_CTX_FUNCTION) \ - if(!_curl_is_ssl_ctx_cb(value)) \ - _curl_easy_setopt_err_ssl_ctx_cb(); \ - if(_curl_is_conv_cb_option(_curl_opt)) \ - if(!_curl_is_conv_cb(value)) \ - _curl_easy_setopt_err_conv_cb(); \ - if((_curl_opt) == CURLOPT_SEEKFUNCTION) \ - if(!_curl_is_seek_cb(value)) \ - _curl_easy_setopt_err_seek_cb(); \ - if(_curl_is_cb_data_option(_curl_opt)) \ - if(!_curl_is_cb_data(value)) \ - _curl_easy_setopt_err_cb_data(); \ - if((_curl_opt) == CURLOPT_ERRORBUFFER) \ - if(!_curl_is_error_buffer(value)) \ - _curl_easy_setopt_err_error_buffer(); \ - if((_curl_opt) == CURLOPT_STDERR) \ - if(!_curl_is_FILE(value)) \ - _curl_easy_setopt_err_FILE(); \ - if(_curl_is_postfields_option(_curl_opt)) \ - if(!_curl_is_postfields(value)) \ - _curl_easy_setopt_err_postfields(); \ - if((_curl_opt) == CURLOPT_HTTPPOST) \ - if(!_curl_is_arr((value), struct curl_httppost)) \ - _curl_easy_setopt_err_curl_httpost(); \ - if(_curl_is_slist_option(_curl_opt)) \ - if(!_curl_is_arr((value), struct curl_slist)) \ - _curl_easy_setopt_err_curl_slist(); \ - if((_curl_opt) == CURLOPT_SHARE) \ - if(!_curl_is_ptr((value), CURLSH)) \ - _curl_easy_setopt_err_CURLSH(); \ - } \ - curl_easy_setopt(handle, _curl_opt, value); \ -}) - -/* wraps curl_easy_getinfo() with typechecking */ -/* FIXME: don't allow const pointers */ -#define curl_easy_getinfo(handle, info, arg) \ -__extension__ ({ \ - __typeof__ (info) _curl_info = info; \ - if(__builtin_constant_p(_curl_info)) { \ - if(_curl_is_string_info(_curl_info)) \ - if(!_curl_is_arr((arg), char *)) \ - _curl_easy_getinfo_err_string(); \ - if(_curl_is_long_info(_curl_info)) \ - if(!_curl_is_arr((arg), long)) \ - _curl_easy_getinfo_err_long(); \ - if(_curl_is_double_info(_curl_info)) \ - if(!_curl_is_arr((arg), double)) \ - _curl_easy_getinfo_err_double(); \ - if(_curl_is_slist_info(_curl_info)) \ - if(!_curl_is_arr((arg), struct curl_slist *)) \ - _curl_easy_getinfo_err_curl_slist(); \ - } \ - curl_easy_getinfo(handle, _curl_info, arg); \ -}) - -/* TODO: typechecking for curl_share_setopt() and curl_multi_setopt(), - * for now just make sure that the functions are called with three - * arguments - */ -#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param) -#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param) - - -/* the actual warnings, triggered by calling the _curl_easy_setopt_err* - * functions */ - -/* To define a new warning, use _CURL_WARNING(identifier, "message") */ -#define _CURL_WARNING(id, message) \ - static void __attribute__((__warning__(message))) \ - __attribute__((__unused__)) __attribute__((__noinline__)) \ - id(void) { __asm__(""); } - -_CURL_WARNING(_curl_easy_setopt_err_long, - "curl_easy_setopt expects a long argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_curl_off_t, - "curl_easy_setopt expects a curl_off_t argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_string, - "curl_easy_setopt expects a " - "string (char* or char[]) argument for this option" - ) -_CURL_WARNING(_curl_easy_setopt_err_write_callback, - "curl_easy_setopt expects a curl_write_callback argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_read_cb, - "curl_easy_setopt expects a curl_read_callback argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_ioctl_cb, - "curl_easy_setopt expects a curl_ioctl_callback argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_sockopt_cb, - "curl_easy_setopt expects a curl_sockopt_callback argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_opensocket_cb, - "curl_easy_setopt expects a " - "curl_opensocket_callback argument for this option" - ) -_CURL_WARNING(_curl_easy_setopt_err_progress_cb, - "curl_easy_setopt expects a curl_progress_callback argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_debug_cb, - "curl_easy_setopt expects a curl_debug_callback argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_ssl_ctx_cb, - "curl_easy_setopt expects a curl_ssl_ctx_callback argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_conv_cb, - "curl_easy_setopt expects a curl_conv_callback argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_seek_cb, - "curl_easy_setopt expects a curl_seek_callback argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_cb_data, - "curl_easy_setopt expects a " - "private data pointer as argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_error_buffer, - "curl_easy_setopt expects a " - "char buffer of CURL_ERROR_SIZE as argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_FILE, - "curl_easy_setopt expects a FILE* argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_postfields, - "curl_easy_setopt expects a void* or char* argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_curl_httpost, - "curl_easy_setopt expects a struct curl_httppost* argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_curl_slist, - "curl_easy_setopt expects a struct curl_slist* argument for this option") -_CURL_WARNING(_curl_easy_setopt_err_CURLSH, - "curl_easy_setopt expects a CURLSH* argument for this option") - -_CURL_WARNING(_curl_easy_getinfo_err_string, - "curl_easy_getinfo expects a pointer to char * for this info") -_CURL_WARNING(_curl_easy_getinfo_err_long, - "curl_easy_getinfo expects a pointer to long for this info") -_CURL_WARNING(_curl_easy_getinfo_err_double, - "curl_easy_getinfo expects a pointer to double for this info") -_CURL_WARNING(_curl_easy_getinfo_err_curl_slist, - "curl_easy_getinfo expects a pointer to struct curl_slist * for this info") - -/* groups of curl_easy_setops options that take the same type of argument */ - -/* To add a new option to one of the groups, just add - * (option) == CURLOPT_SOMETHING - * to the or-expression. If the option takes a long or curl_off_t, you don't - * have to do anything - */ - -/* evaluates to true if option takes a long argument */ -#define _curl_is_long_option(option) \ - (0 < (option) && (option) < CURLOPTTYPE_OBJECTPOINT) - -#define _curl_is_off_t_option(option) \ - ((option) > CURLOPTTYPE_OFF_T) - -/* evaluates to true if option takes a char* argument */ -#define _curl_is_string_option(option) \ - ((option) == CURLOPT_URL || \ - (option) == CURLOPT_PROXY || \ - (option) == CURLOPT_INTERFACE || \ - (option) == CURLOPT_NETRC_FILE || \ - (option) == CURLOPT_USERPWD || \ - (option) == CURLOPT_USERNAME || \ - (option) == CURLOPT_PASSWORD || \ - (option) == CURLOPT_PROXYUSERPWD || \ - (option) == CURLOPT_PROXYUSERNAME || \ - (option) == CURLOPT_PROXYPASSWORD || \ - (option) == CURLOPT_NOPROXY || \ - (option) == CURLOPT_ACCEPT_ENCODING || \ - (option) == CURLOPT_REFERER || \ - (option) == CURLOPT_USERAGENT || \ - (option) == CURLOPT_COOKIE || \ - (option) == CURLOPT_COOKIEFILE || \ - (option) == CURLOPT_COOKIEJAR || \ - (option) == CURLOPT_COOKIELIST || \ - (option) == CURLOPT_FTPPORT || \ - (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \ - (option) == CURLOPT_FTP_ACCOUNT || \ - (option) == CURLOPT_RANGE || \ - (option) == CURLOPT_CUSTOMREQUEST || \ - (option) == CURLOPT_SSLCERT || \ - (option) == CURLOPT_SSLCERTTYPE || \ - (option) == CURLOPT_SSLKEY || \ - (option) == CURLOPT_SSLKEYTYPE || \ - (option) == CURLOPT_KEYPASSWD || \ - (option) == CURLOPT_SSLENGINE || \ - (option) == CURLOPT_CAINFO || \ - (option) == CURLOPT_CAPATH || \ - (option) == CURLOPT_RANDOM_FILE || \ - (option) == CURLOPT_EGDSOCKET || \ - (option) == CURLOPT_SSL_CIPHER_LIST || \ - (option) == CURLOPT_KRBLEVEL || \ - (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 || \ - (option) == CURLOPT_SSH_PUBLIC_KEYFILE || \ - (option) == CURLOPT_SSH_PRIVATE_KEYFILE || \ - (option) == CURLOPT_CRLFILE || \ - (option) == CURLOPT_ISSUERCERT || \ - (option) == CURLOPT_SOCKS5_GSSAPI_SERVICE || \ - (option) == CURLOPT_SSH_KNOWNHOSTS || \ - (option) == CURLOPT_MAIL_FROM || \ - (option) == CURLOPT_RTSP_SESSION_ID || \ - (option) == CURLOPT_RTSP_STREAM_URI || \ - (option) == CURLOPT_RTSP_TRANSPORT || \ - 0) - -/* evaluates to true if option takes a curl_write_callback argument */ -#define _curl_is_write_cb_option(option) \ - ((option) == CURLOPT_HEADERFUNCTION || \ - (option) == CURLOPT_WRITEFUNCTION) - -/* evaluates to true if option takes a curl_conv_callback argument */ -#define _curl_is_conv_cb_option(option) \ - ((option) == CURLOPT_CONV_TO_NETWORK_FUNCTION || \ - (option) == CURLOPT_CONV_FROM_NETWORK_FUNCTION || \ - (option) == CURLOPT_CONV_FROM_UTF8_FUNCTION) - -/* evaluates to true if option takes a data argument to pass to a callback */ -#define _curl_is_cb_data_option(option) \ - ((option) == CURLOPT_WRITEDATA || \ - (option) == CURLOPT_READDATA || \ - (option) == CURLOPT_IOCTLDATA || \ - (option) == CURLOPT_SOCKOPTDATA || \ - (option) == CURLOPT_OPENSOCKETDATA || \ - (option) == CURLOPT_PROGRESSDATA || \ - (option) == CURLOPT_WRITEHEADER || \ - (option) == CURLOPT_DEBUGDATA || \ - (option) == CURLOPT_SSL_CTX_DATA || \ - (option) == CURLOPT_SEEKDATA || \ - (option) == CURLOPT_PRIVATE || \ - (option) == CURLOPT_SSH_KEYDATA || \ - (option) == CURLOPT_INTERLEAVEDATA || \ - (option) == CURLOPT_CHUNK_DATA || \ - (option) == CURLOPT_FNMATCH_DATA || \ - 0) - -/* evaluates to true if option takes a POST data argument (void* or char*) */ -#define _curl_is_postfields_option(option) \ - ((option) == CURLOPT_POSTFIELDS || \ - (option) == CURLOPT_COPYPOSTFIELDS || \ - 0) - -/* evaluates to true if option takes a struct curl_slist * argument */ -#define _curl_is_slist_option(option) \ - ((option) == CURLOPT_HTTPHEADER || \ - (option) == CURLOPT_HTTP200ALIASES || \ - (option) == CURLOPT_QUOTE || \ - (option) == CURLOPT_POSTQUOTE || \ - (option) == CURLOPT_PREQUOTE || \ - (option) == CURLOPT_TELNETOPTIONS || \ - (option) == CURLOPT_MAIL_RCPT || \ - 0) - -/* groups of curl_easy_getinfo infos that take the same type of argument */ - -/* evaluates to true if info expects a pointer to char * argument */ -#define _curl_is_string_info(info) \ - (CURLINFO_STRING < (info) && (info) < CURLINFO_LONG) - -/* evaluates to true if info expects a pointer to long argument */ -#define _curl_is_long_info(info) \ - (CURLINFO_LONG < (info) && (info) < CURLINFO_DOUBLE) - -/* evaluates to true if info expects a pointer to double argument */ -#define _curl_is_double_info(info) \ - (CURLINFO_DOUBLE < (info) && (info) < CURLINFO_SLIST) - -/* true if info expects a pointer to struct curl_slist * argument */ -#define _curl_is_slist_info(info) \ - (CURLINFO_SLIST < (info)) - - -/* typecheck helpers -- check whether given expression has requested type*/ - -/* For pointers, you can use the _curl_is_ptr/_curl_is_arr macros, - * otherwise define a new macro. Search for __builtin_types_compatible_p - * in the GCC manual. - * NOTE: these macros MUST NOT EVALUATE their arguments! The argument is - * the actual expression passed to the curl_easy_setopt macro. This - * means that you can only apply the sizeof and __typeof__ operators, no - * == or whatsoever. - */ - -/* XXX: should evaluate to true iff expr is a pointer */ -#define _curl_is_any_ptr(expr) \ - (sizeof(expr) == sizeof(void*)) - -/* evaluates to true if expr is NULL */ -/* XXX: must not evaluate expr, so this check is not accurate */ -#define _curl_is_NULL(expr) \ - (__builtin_types_compatible_p(__typeof__(expr), __typeof__(NULL))) - -/* evaluates to true if expr is type*, const type* or NULL */ -#define _curl_is_ptr(expr, type) \ - (_curl_is_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), type *) || \ - __builtin_types_compatible_p(__typeof__(expr), const type *)) - -/* evaluates to true if expr is one of type[], type*, NULL or const type* */ -#define _curl_is_arr(expr, type) \ - (_curl_is_ptr((expr), type) || \ - __builtin_types_compatible_p(__typeof__(expr), type [])) - -/* evaluates to true if expr is a string */ -#define _curl_is_string(expr) \ - (_curl_is_arr((expr), char) || \ - _curl_is_arr((expr), signed char) || \ - _curl_is_arr((expr), unsigned char)) - -/* evaluates to true if expr is a long (no matter the signedness) - * XXX: for now, int is also accepted (and therefore short and char, which - * are promoted to int when passed to a variadic function) */ -#define _curl_is_long(expr) \ - (__builtin_types_compatible_p(__typeof__(expr), long) || \ - __builtin_types_compatible_p(__typeof__(expr), signed long) || \ - __builtin_types_compatible_p(__typeof__(expr), unsigned long) || \ - __builtin_types_compatible_p(__typeof__(expr), int) || \ - __builtin_types_compatible_p(__typeof__(expr), signed int) || \ - __builtin_types_compatible_p(__typeof__(expr), unsigned int) || \ - __builtin_types_compatible_p(__typeof__(expr), short) || \ - __builtin_types_compatible_p(__typeof__(expr), signed short) || \ - __builtin_types_compatible_p(__typeof__(expr), unsigned short) || \ - __builtin_types_compatible_p(__typeof__(expr), char) || \ - __builtin_types_compatible_p(__typeof__(expr), signed char) || \ - __builtin_types_compatible_p(__typeof__(expr), unsigned char)) - -/* evaluates to true if expr is of type curl_off_t */ -#define _curl_is_off_t(expr) \ - (__builtin_types_compatible_p(__typeof__(expr), curl_off_t)) - -/* evaluates to true if expr is abuffer suitable for CURLOPT_ERRORBUFFER */ -/* XXX: also check size of an char[] array? */ -#define _curl_is_error_buffer(expr) \ - (_curl_is_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), char *) || \ - __builtin_types_compatible_p(__typeof__(expr), char[])) - -/* evaluates to true if expr is of type (const) void* or (const) FILE* */ -#if 0 -#define _curl_is_cb_data(expr) \ - (_curl_is_ptr((expr), void) || \ - _curl_is_ptr((expr), FILE)) -#else /* be less strict */ -#define _curl_is_cb_data(expr) \ - _curl_is_any_ptr(expr) -#endif - -/* evaluates to true if expr is of type FILE* */ -#define _curl_is_FILE(expr) \ - (__builtin_types_compatible_p(__typeof__(expr), FILE *)) - -/* evaluates to true if expr can be passed as POST data (void* or char*) */ -#define _curl_is_postfields(expr) \ - (_curl_is_ptr((expr), void) || \ - _curl_is_arr((expr), char)) - -/* FIXME: the whole callback checking is messy... - * The idea is to tolerate char vs. void and const vs. not const - * pointers in arguments at least - */ -/* helper: __builtin_types_compatible_p distinguishes between functions and - * function pointers, hide it */ -#define _curl_callback_compatible(func, type) \ - (__builtin_types_compatible_p(__typeof__(func), type) || \ - __builtin_types_compatible_p(__typeof__(func), type*)) - -/* evaluates to true if expr is of type curl_read_callback or "similar" */ -#define _curl_is_read_cb(expr) \ - (_curl_is_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), __typeof__(fread)) || \ - __builtin_types_compatible_p(__typeof__(expr), curl_read_callback) || \ - _curl_callback_compatible((expr), _curl_read_callback1) || \ - _curl_callback_compatible((expr), _curl_read_callback2) || \ - _curl_callback_compatible((expr), _curl_read_callback3) || \ - _curl_callback_compatible((expr), _curl_read_callback4) || \ - _curl_callback_compatible((expr), _curl_read_callback5) || \ - _curl_callback_compatible((expr), _curl_read_callback6)) -typedef size_t (_curl_read_callback1)(char *, size_t, size_t, void*); -typedef size_t (_curl_read_callback2)(char *, size_t, size_t, const void*); -typedef size_t (_curl_read_callback3)(char *, size_t, size_t, FILE*); -typedef size_t (_curl_read_callback4)(void *, size_t, size_t, void*); -typedef size_t (_curl_read_callback5)(void *, size_t, size_t, const void*); -typedef size_t (_curl_read_callback6)(void *, size_t, size_t, FILE*); - -/* evaluates to true if expr is of type curl_write_callback or "similar" */ -#define _curl_is_write_cb(expr) \ - (_curl_is_read_cb(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), __typeof__(fwrite)) || \ - __builtin_types_compatible_p(__typeof__(expr), curl_write_callback) || \ - _curl_callback_compatible((expr), _curl_write_callback1) || \ - _curl_callback_compatible((expr), _curl_write_callback2) || \ - _curl_callback_compatible((expr), _curl_write_callback3) || \ - _curl_callback_compatible((expr), _curl_write_callback4) || \ - _curl_callback_compatible((expr), _curl_write_callback5) || \ - _curl_callback_compatible((expr), _curl_write_callback6)) -typedef size_t (_curl_write_callback1)(const char *, size_t, size_t, void*); -typedef size_t (_curl_write_callback2)(const char *, size_t, size_t, - const void*); -typedef size_t (_curl_write_callback3)(const char *, size_t, size_t, FILE*); -typedef size_t (_curl_write_callback4)(const void *, size_t, size_t, void*); -typedef size_t (_curl_write_callback5)(const void *, size_t, size_t, - const void*); -typedef size_t (_curl_write_callback6)(const void *, size_t, size_t, FILE*); - -/* evaluates to true if expr is of type curl_ioctl_callback or "similar" */ -#define _curl_is_ioctl_cb(expr) \ - (_curl_is_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), curl_ioctl_callback) || \ - _curl_callback_compatible((expr), _curl_ioctl_callback1) || \ - _curl_callback_compatible((expr), _curl_ioctl_callback2) || \ - _curl_callback_compatible((expr), _curl_ioctl_callback3) || \ - _curl_callback_compatible((expr), _curl_ioctl_callback4)) -typedef curlioerr (_curl_ioctl_callback1)(CURL *, int, void*); -typedef curlioerr (_curl_ioctl_callback2)(CURL *, int, const void*); -typedef curlioerr (_curl_ioctl_callback3)(CURL *, curliocmd, void*); -typedef curlioerr (_curl_ioctl_callback4)(CURL *, curliocmd, const void*); - -/* evaluates to true if expr is of type curl_sockopt_callback or "similar" */ -#define _curl_is_sockopt_cb(expr) \ - (_curl_is_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), curl_sockopt_callback) || \ - _curl_callback_compatible((expr), _curl_sockopt_callback1) || \ - _curl_callback_compatible((expr), _curl_sockopt_callback2)) -typedef int (_curl_sockopt_callback1)(void *, curl_socket_t, curlsocktype); -typedef int (_curl_sockopt_callback2)(const void *, curl_socket_t, - curlsocktype); - -/* evaluates to true if expr is of type curl_opensocket_callback or - "similar" */ -#define _curl_is_opensocket_cb(expr) \ - (_curl_is_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), curl_opensocket_callback) ||\ - _curl_callback_compatible((expr), _curl_opensocket_callback1) || \ - _curl_callback_compatible((expr), _curl_opensocket_callback2) || \ - _curl_callback_compatible((expr), _curl_opensocket_callback3) || \ - _curl_callback_compatible((expr), _curl_opensocket_callback4)) -typedef curl_socket_t (_curl_opensocket_callback1) - (void *, curlsocktype, struct curl_sockaddr *); -typedef curl_socket_t (_curl_opensocket_callback2) - (void *, curlsocktype, const struct curl_sockaddr *); -typedef curl_socket_t (_curl_opensocket_callback3) - (const void *, curlsocktype, struct curl_sockaddr *); -typedef curl_socket_t (_curl_opensocket_callback4) - (const void *, curlsocktype, const struct curl_sockaddr *); - -/* evaluates to true if expr is of type curl_progress_callback or "similar" */ -#define _curl_is_progress_cb(expr) \ - (_curl_is_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), curl_progress_callback) || \ - _curl_callback_compatible((expr), _curl_progress_callback1) || \ - _curl_callback_compatible((expr), _curl_progress_callback2)) -typedef int (_curl_progress_callback1)(void *, - double, double, double, double); -typedef int (_curl_progress_callback2)(const void *, - double, double, double, double); - -/* evaluates to true if expr is of type curl_debug_callback or "similar" */ -#define _curl_is_debug_cb(expr) \ - (_curl_is_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), curl_debug_callback) || \ - _curl_callback_compatible((expr), _curl_debug_callback1) || \ - _curl_callback_compatible((expr), _curl_debug_callback2) || \ - _curl_callback_compatible((expr), _curl_debug_callback3) || \ - _curl_callback_compatible((expr), _curl_debug_callback4) || \ - _curl_callback_compatible((expr), _curl_debug_callback5) || \ - _curl_callback_compatible((expr), _curl_debug_callback6) || \ - _curl_callback_compatible((expr), _curl_debug_callback7) || \ - _curl_callback_compatible((expr), _curl_debug_callback8)) -typedef int (_curl_debug_callback1) (CURL *, - curl_infotype, char *, size_t, void *); -typedef int (_curl_debug_callback2) (CURL *, - curl_infotype, char *, size_t, const void *); -typedef int (_curl_debug_callback3) (CURL *, - curl_infotype, const char *, size_t, void *); -typedef int (_curl_debug_callback4) (CURL *, - curl_infotype, const char *, size_t, const void *); -typedef int (_curl_debug_callback5) (CURL *, - curl_infotype, unsigned char *, size_t, void *); -typedef int (_curl_debug_callback6) (CURL *, - curl_infotype, unsigned char *, size_t, const void *); -typedef int (_curl_debug_callback7) (CURL *, - curl_infotype, const unsigned char *, size_t, void *); -typedef int (_curl_debug_callback8) (CURL *, - curl_infotype, const unsigned char *, size_t, const void *); - -/* evaluates to true if expr is of type curl_ssl_ctx_callback or "similar" */ -/* this is getting even messier... */ -#define _curl_is_ssl_ctx_cb(expr) \ - (_curl_is_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), curl_ssl_ctx_callback) || \ - _curl_callback_compatible((expr), _curl_ssl_ctx_callback1) || \ - _curl_callback_compatible((expr), _curl_ssl_ctx_callback2) || \ - _curl_callback_compatible((expr), _curl_ssl_ctx_callback3) || \ - _curl_callback_compatible((expr), _curl_ssl_ctx_callback4) || \ - _curl_callback_compatible((expr), _curl_ssl_ctx_callback5) || \ - _curl_callback_compatible((expr), _curl_ssl_ctx_callback6) || \ - _curl_callback_compatible((expr), _curl_ssl_ctx_callback7) || \ - _curl_callback_compatible((expr), _curl_ssl_ctx_callback8)) -typedef CURLcode (_curl_ssl_ctx_callback1)(CURL *, void *, void *); -typedef CURLcode (_curl_ssl_ctx_callback2)(CURL *, void *, const void *); -typedef CURLcode (_curl_ssl_ctx_callback3)(CURL *, const void *, void *); -typedef CURLcode (_curl_ssl_ctx_callback4)(CURL *, const void *, const void *); -#ifdef HEADER_SSL_H -/* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX - * this will of course break if we're included before OpenSSL headers... - */ -typedef CURLcode (_curl_ssl_ctx_callback5)(CURL *, SSL_CTX, void *); -typedef CURLcode (_curl_ssl_ctx_callback6)(CURL *, SSL_CTX, const void *); -typedef CURLcode (_curl_ssl_ctx_callback7)(CURL *, const SSL_CTX, void *); -typedef CURLcode (_curl_ssl_ctx_callback8)(CURL *, const SSL_CTX, - const void *); -#else -typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback5; -typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback6; -typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback7; -typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback8; -#endif - -/* evaluates to true if expr is of type curl_conv_callback or "similar" */ -#define _curl_is_conv_cb(expr) \ - (_curl_is_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), curl_conv_callback) || \ - _curl_callback_compatible((expr), _curl_conv_callback1) || \ - _curl_callback_compatible((expr), _curl_conv_callback2) || \ - _curl_callback_compatible((expr), _curl_conv_callback3) || \ - _curl_callback_compatible((expr), _curl_conv_callback4)) -typedef CURLcode (*_curl_conv_callback1)(char *, size_t length); -typedef CURLcode (*_curl_conv_callback2)(const char *, size_t length); -typedef CURLcode (*_curl_conv_callback3)(void *, size_t length); -typedef CURLcode (*_curl_conv_callback4)(const void *, size_t length); - -/* evaluates to true if expr is of type curl_seek_callback or "similar" */ -#define _curl_is_seek_cb(expr) \ - (_curl_is_NULL(expr) || \ - __builtin_types_compatible_p(__typeof__(expr), curl_seek_callback) || \ - _curl_callback_compatible((expr), _curl_seek_callback1) || \ - _curl_callback_compatible((expr), _curl_seek_callback2)) -typedef CURLcode (*_curl_seek_callback1)(void *, curl_off_t, int); -typedef CURLcode (*_curl_seek_callback2)(const void *, curl_off_t, int); - - -#endif /* __CURL_TYPECHECK_GCC_H */ diff --git a/external/curl/include/linux/64-bit/curl/curl.h b/external/curl/include/linux/64-bit/curl/curl.h deleted file mode 100644 index 2cad28298e..0000000000 --- a/external/curl/include/linux/64-bit/curl/curl.h +++ /dev/null @@ -1,2231 +0,0 @@ -#ifndef __CURL_CURL_H -#define __CURL_CURL_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2012, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* - * If you have libcurl problems, all docs and details are found here: - * http://curl.haxx.se/libcurl/ - * - * curl-library mailing list subscription and unsubscription web interface: - * http://cool.haxx.se/mailman/listinfo/curl-library/ - */ - -#include "curlver.h" /* libcurl version defines */ -#include "curlbuild.h" /* libcurl build definitions */ -#include "curlrules.h" /* libcurl rules enforcement */ - -/* - * Define WIN32 when build target is Win32 API - */ - -#if (defined(_WIN32) || defined(__WIN32__)) && \ - !defined(WIN32) && !defined(__SYMBIAN32__) -#define WIN32 -#endif - -#include -#include - -#if defined(__FreeBSD__) && (__FreeBSD__ >= 2) -/* Needed for __FreeBSD_version symbol definition */ -#include -#endif - -/* The include stuff here below is mainly for time_t! */ -#include -#include - -#if defined(WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__) -#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || defined(__LWIP_OPT_H__)) -/* The check above prevents the winsock2 inclusion if winsock.h already was - included, since they can't co-exist without problems */ -#include -#include -#endif -#endif - -/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish - libc5-based Linux systems. Only include it on systems that are known to - require it! */ -#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \ - defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \ - defined(ANDROID) || defined(__ANDROID__) || \ - (defined(__FreeBSD_version) && (__FreeBSD_version < 800000)) -#include -#endif - -#if !defined(WIN32) && !defined(_WIN32_WCE) -#include -#endif - -#if !defined(WIN32) && !defined(__WATCOMC__) && !defined(__VXWORKS__) -#include -#endif - -#ifdef __BEOS__ -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void CURL; - -/* - * Decorate exportable functions for Win32 and Symbian OS DLL linking. - * This avoids using a .def file for building libcurl.dll. - */ -#if (defined(WIN32) || defined(_WIN32) || defined(__SYMBIAN32__)) && \ - !defined(CURL_STATICLIB) -#if defined(BUILDING_LIBCURL) -#define CURL_EXTERN __declspec(dllexport) -#else -#define CURL_EXTERN __declspec(dllimport) -#endif -#else - -#ifdef CURL_HIDDEN_SYMBOLS -/* - * This definition is used to make external definitions visible in the - * shared library when symbols are hidden by default. It makes no - * difference when compiling applications whether this is set or not, - * only when compiling the library. - */ -#define CURL_EXTERN CURL_EXTERN_SYMBOL -#else -#define CURL_EXTERN -#endif -#endif - -#ifndef curl_socket_typedef -/* socket typedef */ -#if defined(WIN32) && !defined(__LWIP_OPT_H__) -typedef SOCKET curl_socket_t; -#define CURL_SOCKET_BAD INVALID_SOCKET -#else -typedef int curl_socket_t; -#define CURL_SOCKET_BAD -1 -#endif -#define curl_socket_typedef -#endif /* curl_socket_typedef */ - -struct curl_httppost { - struct curl_httppost *next; /* next entry in the list */ - char *name; /* pointer to allocated name */ - long namelength; /* length of name length */ - char *contents; /* pointer to allocated data contents */ - long contentslength; /* length of contents field */ - char *buffer; /* pointer to allocated buffer contents */ - long bufferlength; /* length of buffer field */ - char *contenttype; /* Content-Type */ - struct curl_slist* contentheader; /* list of extra headers for this form */ - struct curl_httppost *more; /* if one field name has more than one - file, this link should link to following - files */ - long flags; /* as defined below */ -#define HTTPPOST_FILENAME (1<<0) /* specified content is a file name */ -#define HTTPPOST_READFILE (1<<1) /* specified content is a file name */ -#define HTTPPOST_PTRNAME (1<<2) /* name is only stored pointer - do not free in formfree */ -#define HTTPPOST_PTRCONTENTS (1<<3) /* contents is only stored pointer - do not free in formfree */ -#define HTTPPOST_BUFFER (1<<4) /* upload file from buffer */ -#define HTTPPOST_PTRBUFFER (1<<5) /* upload file from pointer contents */ -#define HTTPPOST_CALLBACK (1<<6) /* upload file contents by using the - regular read callback to get the data - and pass the given pointer as custom - pointer */ - - char *showfilename; /* The file name to show. If not set, the - actual file name will be used (if this - is a file part) */ - void *userp; /* custom pointer used for - HTTPPOST_CALLBACK posts */ -}; - -typedef int (*curl_progress_callback)(void *clientp, - double dltotal, - double dlnow, - double ultotal, - double ulnow); - -#ifndef CURL_MAX_WRITE_SIZE - /* Tests have proven that 20K is a very bad buffer size for uploads on - Windows, while 16K for some odd reason performed a lot better. - We do the ifndef check to allow this value to easier be changed at build - time for those who feel adventurous. The practical minimum is about - 400 bytes since libcurl uses a buffer of this size as a scratch area - (unrelated to network send operations). */ -#define CURL_MAX_WRITE_SIZE 16384 -#endif - -#ifndef CURL_MAX_HTTP_HEADER -/* The only reason to have a max limit for this is to avoid the risk of a bad - server feeding libcurl with a never-ending header that will cause reallocs - infinitely */ -#define CURL_MAX_HTTP_HEADER (100*1024) -#endif - -/* This is a magic return code for the write callback that, when returned, - will signal libcurl to pause receiving on the current transfer. */ -#define CURL_WRITEFUNC_PAUSE 0x10000001 - -typedef size_t (*curl_write_callback)(char *buffer, - size_t size, - size_t nitems, - void *outstream); - - - -/* enumeration of file types */ -typedef enum { - CURLFILETYPE_FILE = 0, - CURLFILETYPE_DIRECTORY, - CURLFILETYPE_SYMLINK, - CURLFILETYPE_DEVICE_BLOCK, - CURLFILETYPE_DEVICE_CHAR, - CURLFILETYPE_NAMEDPIPE, - CURLFILETYPE_SOCKET, - CURLFILETYPE_DOOR, /* is possible only on Sun Solaris now */ - - CURLFILETYPE_UNKNOWN /* should never occur */ -} curlfiletype; - -#define CURLFINFOFLAG_KNOWN_FILENAME (1<<0) -#define CURLFINFOFLAG_KNOWN_FILETYPE (1<<1) -#define CURLFINFOFLAG_KNOWN_TIME (1<<2) -#define CURLFINFOFLAG_KNOWN_PERM (1<<3) -#define CURLFINFOFLAG_KNOWN_UID (1<<4) -#define CURLFINFOFLAG_KNOWN_GID (1<<5) -#define CURLFINFOFLAG_KNOWN_SIZE (1<<6) -#define CURLFINFOFLAG_KNOWN_HLINKCOUNT (1<<7) - -/* Content of this structure depends on information which is known and is - achievable (e.g. by FTP LIST parsing). Please see the url_easy_setopt(3) man - page for callbacks returning this structure -- some fields are mandatory, - some others are optional. The FLAG field has special meaning. */ -struct curl_fileinfo { - char *filename; - curlfiletype filetype; - time_t time; - unsigned int perm; - int uid; - int gid; - curl_off_t size; - long int hardlinks; - - struct { - /* If some of these fields is not NULL, it is a pointer to b_data. */ - char *time; - char *perm; - char *user; - char *group; - char *target; /* pointer to the target filename of a symlink */ - } strings; - - unsigned int flags; - - /* used internally */ - char * b_data; - size_t b_size; - size_t b_used; -}; - -/* return codes for CURLOPT_CHUNK_BGN_FUNCTION */ -#define CURL_CHUNK_BGN_FUNC_OK 0 -#define CURL_CHUNK_BGN_FUNC_FAIL 1 /* tell the lib to end the task */ -#define CURL_CHUNK_BGN_FUNC_SKIP 2 /* skip this chunk over */ - -/* if splitting of data transfer is enabled, this callback is called before - download of an individual chunk started. Note that parameter "remains" works - only for FTP wildcard downloading (for now), otherwise is not used */ -typedef long (*curl_chunk_bgn_callback)(const void *transfer_info, - void *ptr, - int remains); - -/* return codes for CURLOPT_CHUNK_END_FUNCTION */ -#define CURL_CHUNK_END_FUNC_OK 0 -#define CURL_CHUNK_END_FUNC_FAIL 1 /* tell the lib to end the task */ - -/* If splitting of data transfer is enabled this callback is called after - download of an individual chunk finished. - Note! After this callback was set then it have to be called FOR ALL chunks. - Even if downloading of this chunk was skipped in CHUNK_BGN_FUNC. - This is the reason why we don't need "transfer_info" parameter in this - callback and we are not interested in "remains" parameter too. */ -typedef long (*curl_chunk_end_callback)(void *ptr); - -/* return codes for FNMATCHFUNCTION */ -#define CURL_FNMATCHFUNC_MATCH 0 /* string corresponds to the pattern */ -#define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern doesn't match the string */ -#define CURL_FNMATCHFUNC_FAIL 2 /* an error occurred */ - -/* callback type for wildcard downloading pattern matching. If the - string matches the pattern, return CURL_FNMATCHFUNC_MATCH value, etc. */ -typedef int (*curl_fnmatch_callback)(void *ptr, - const char *pattern, - const char *string); - -/* These are the return codes for the seek callbacks */ -#define CURL_SEEKFUNC_OK 0 -#define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */ -#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking can't be done, so - libcurl might try other means instead */ -typedef int (*curl_seek_callback)(void *instream, - curl_off_t offset, - int origin); /* 'whence' */ - -/* This is a return code for the read callback that, when returned, will - signal libcurl to immediately abort the current transfer. */ -#define CURL_READFUNC_ABORT 0x10000000 -/* This is a return code for the read callback that, when returned, will - signal libcurl to pause sending data on the current transfer. */ -#define CURL_READFUNC_PAUSE 0x10000001 - -typedef size_t (*curl_read_callback)(char *buffer, - size_t size, - size_t nitems, - void *instream); - -typedef enum { - CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */ - CURLSOCKTYPE_LAST /* never use */ -} curlsocktype; - -/* The return code from the sockopt_callback can signal information back - to libcurl: */ -#define CURL_SOCKOPT_OK 0 -#define CURL_SOCKOPT_ERROR 1 /* causes libcurl to abort and return - CURLE_ABORTED_BY_CALLBACK */ -#define CURL_SOCKOPT_ALREADY_CONNECTED 2 - -typedef int (*curl_sockopt_callback)(void *clientp, - curl_socket_t curlfd, - curlsocktype purpose); - -struct curl_sockaddr { - int family; - int socktype; - int protocol; - unsigned int addrlen; /* addrlen was a socklen_t type before 7.18.0 but it - turned really ugly and painful on the systems that - lack this type */ - struct sockaddr addr; -}; - -typedef curl_socket_t -(*curl_opensocket_callback)(void *clientp, - curlsocktype purpose, - struct curl_sockaddr *address); - -typedef int -(*curl_closesocket_callback)(void *clientp, curl_socket_t item); - -typedef enum { - CURLIOE_OK, /* I/O operation successful */ - CURLIOE_UNKNOWNCMD, /* command was unknown to callback */ - CURLIOE_FAILRESTART, /* failed to restart the read */ - CURLIOE_LAST /* never use */ -} curlioerr; - -typedef enum { - CURLIOCMD_NOP, /* no operation */ - CURLIOCMD_RESTARTREAD, /* restart the read stream from start */ - CURLIOCMD_LAST /* never use */ -} curliocmd; - -typedef curlioerr (*curl_ioctl_callback)(CURL *handle, - int cmd, - void *clientp); - -/* - * The following typedef's are signatures of malloc, free, realloc, strdup and - * calloc respectively. Function pointers of these types can be passed to the - * curl_global_init_mem() function to set user defined memory management - * callback routines. - */ -typedef void *(*curl_malloc_callback)(size_t size); -typedef void (*curl_free_callback)(void *ptr); -typedef void *(*curl_realloc_callback)(void *ptr, size_t size); -typedef char *(*curl_strdup_callback)(const char *str); -typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size); - -/* the kind of data that is passed to information_callback*/ -typedef enum { - CURLINFO_TEXT = 0, - CURLINFO_HEADER_IN, /* 1 */ - CURLINFO_HEADER_OUT, /* 2 */ - CURLINFO_DATA_IN, /* 3 */ - CURLINFO_DATA_OUT, /* 4 */ - CURLINFO_SSL_DATA_IN, /* 5 */ - CURLINFO_SSL_DATA_OUT, /* 6 */ - CURLINFO_END -} curl_infotype; - -typedef int (*curl_debug_callback) - (CURL *handle, /* the handle/transfer this concerns */ - curl_infotype type, /* what kind of data */ - char *data, /* points to the data */ - size_t size, /* size of the data pointed to */ - void *userptr); /* whatever the user please */ - -/* All possible error codes from all sorts of curl functions. Future versions - may return other values, stay prepared. - - Always add new return codes last. Never *EVER* remove any. The return - codes must remain the same! - */ - -typedef enum { - CURLE_OK = 0, - CURLE_UNSUPPORTED_PROTOCOL, /* 1 */ - CURLE_FAILED_INIT, /* 2 */ - CURLE_URL_MALFORMAT, /* 3 */ - CURLE_NOT_BUILT_IN, /* 4 - [was obsoleted in August 2007 for - 7.17.0, reused in April 2011 for 7.21.5] */ - CURLE_COULDNT_RESOLVE_PROXY, /* 5 */ - CURLE_COULDNT_RESOLVE_HOST, /* 6 */ - CURLE_COULDNT_CONNECT, /* 7 */ - CURLE_FTP_WEIRD_SERVER_REPLY, /* 8 */ - CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server - due to lack of access - when login fails - this is not returned. */ - CURLE_FTP_ACCEPT_FAILED, /* 10 - [was obsoleted in April 2006 for - 7.15.4, reused in Dec 2011 for 7.24.0]*/ - CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */ - CURLE_FTP_ACCEPT_TIMEOUT, /* 12 - timeout occurred accepting server - [was obsoleted in August 2007 for 7.17.0, - reused in Dec 2011 for 7.24.0]*/ - CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */ - CURLE_FTP_WEIRD_227_FORMAT, /* 14 */ - CURLE_FTP_CANT_GET_HOST, /* 15 */ - CURLE_OBSOLETE16, /* 16 - NOT USED */ - CURLE_FTP_COULDNT_SET_TYPE, /* 17 */ - CURLE_PARTIAL_FILE, /* 18 */ - CURLE_FTP_COULDNT_RETR_FILE, /* 19 */ - CURLE_OBSOLETE20, /* 20 - NOT USED */ - CURLE_QUOTE_ERROR, /* 21 - quote command failure */ - CURLE_HTTP_RETURNED_ERROR, /* 22 */ - CURLE_WRITE_ERROR, /* 23 */ - CURLE_OBSOLETE24, /* 24 - NOT USED */ - CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */ - CURLE_READ_ERROR, /* 26 - couldn't open/read from file */ - CURLE_OUT_OF_MEMORY, /* 27 */ - /* Note: CURLE_OUT_OF_MEMORY may sometimes indicate a conversion error - instead of a memory allocation error if CURL_DOES_CONVERSIONS - is defined - */ - CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */ - CURLE_OBSOLETE29, /* 29 - NOT USED */ - CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */ - CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */ - CURLE_OBSOLETE32, /* 32 - NOT USED */ - CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */ - CURLE_HTTP_POST_ERROR, /* 34 */ - CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */ - CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */ - CURLE_FILE_COULDNT_READ_FILE, /* 37 */ - CURLE_LDAP_CANNOT_BIND, /* 38 */ - CURLE_LDAP_SEARCH_FAILED, /* 39 */ - CURLE_OBSOLETE40, /* 40 - NOT USED */ - CURLE_FUNCTION_NOT_FOUND, /* 41 */ - CURLE_ABORTED_BY_CALLBACK, /* 42 */ - CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */ - CURLE_OBSOLETE44, /* 44 - NOT USED */ - CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */ - CURLE_OBSOLETE46, /* 46 - NOT USED */ - CURLE_TOO_MANY_REDIRECTS , /* 47 - catch endless re-direct loops */ - CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */ - CURLE_TELNET_OPTION_SYNTAX , /* 49 - Malformed telnet option */ - CURLE_OBSOLETE50, /* 50 - NOT USED */ - CURLE_PEER_FAILED_VERIFICATION, /* 51 - peer's certificate or fingerprint - wasn't verified fine */ - CURLE_GOT_NOTHING, /* 52 - when this is a specific error */ - CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */ - CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as - default */ - CURLE_SEND_ERROR, /* 55 - failed sending network data */ - CURLE_RECV_ERROR, /* 56 - failure in receiving network data */ - CURLE_OBSOLETE57, /* 57 - NOT IN USE */ - CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */ - CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */ - CURLE_SSL_CACERT, /* 60 - problem with the CA cert (path?) */ - CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */ - CURLE_LDAP_INVALID_URL, /* 62 - Invalid LDAP URL */ - CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */ - CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */ - CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind - that failed */ - CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */ - CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not - accepted and we failed to login */ - CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */ - CURLE_TFTP_PERM, /* 69 - permission problem on server */ - CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */ - CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */ - CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */ - CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */ - CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */ - CURLE_CONV_FAILED, /* 75 - conversion failed */ - CURLE_CONV_REQD, /* 76 - caller must register conversion - callbacks using curl_easy_setopt options - CURLOPT_CONV_FROM_NETWORK_FUNCTION, - CURLOPT_CONV_TO_NETWORK_FUNCTION, and - CURLOPT_CONV_FROM_UTF8_FUNCTION */ - CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing - or wrong format */ - CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */ - CURLE_SSH, /* 79 - error from the SSH layer, somewhat - generic so the error message will be of - interest when this has happened */ - - CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL - connection */ - CURLE_AGAIN, /* 81 - socket is not ready for send/recv, - wait till it's ready and try again (Added - in 7.18.2) */ - CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or - wrong format (Added in 7.19.0) */ - CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in - 7.19.0) */ - CURLE_FTP_PRET_FAILED, /* 84 - a PRET command failed */ - CURLE_RTSP_CSEQ_ERROR, /* 85 - mismatch of RTSP CSeq numbers */ - CURLE_RTSP_SESSION_ERROR, /* 86 - mismatch of RTSP Session Ids */ - CURLE_FTP_BAD_FILE_LIST, /* 87 - unable to parse FTP file list */ - CURLE_CHUNK_FAILED, /* 88 - chunk callback reported error */ - CURL_LAST /* never use! */ -} CURLcode; - -#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all - the obsolete stuff removed! */ - -/* Previously obsoletes error codes re-used in 7.24.0 */ -#define CURLE_OBSOLETE10 CURLE_FTP_ACCEPT_FAILED -#define CURLE_OBSOLETE12 CURLE_FTP_ACCEPT_TIMEOUT - -/* compatibility with older names */ -#define CURLOPT_ENCODING CURLOPT_ACCEPT_ENCODING - -/* The following were added in 7.21.5, April 2011 */ -#define CURLE_UNKNOWN_TELNET_OPTION CURLE_UNKNOWN_OPTION - -/* The following were added in 7.17.1 */ -/* These are scheduled to disappear by 2009 */ -#define CURLE_SSL_PEER_CERTIFICATE CURLE_PEER_FAILED_VERIFICATION - -/* The following were added in 7.17.0 */ -/* These are scheduled to disappear by 2009 */ -#define CURLE_OBSOLETE CURLE_OBSOLETE50 /* no one should be using this! */ -#define CURLE_BAD_PASSWORD_ENTERED CURLE_OBSOLETE46 -#define CURLE_BAD_CALLING_ORDER CURLE_OBSOLETE44 -#define CURLE_FTP_USER_PASSWORD_INCORRECT CURLE_OBSOLETE10 -#define CURLE_FTP_CANT_RECONNECT CURLE_OBSOLETE16 -#define CURLE_FTP_COULDNT_GET_SIZE CURLE_OBSOLETE32 -#define CURLE_FTP_COULDNT_SET_ASCII CURLE_OBSOLETE29 -#define CURLE_FTP_WEIRD_USER_REPLY CURLE_OBSOLETE12 -#define CURLE_FTP_WRITE_ERROR CURLE_OBSOLETE20 -#define CURLE_LIBRARY_NOT_FOUND CURLE_OBSOLETE40 -#define CURLE_MALFORMAT_USER CURLE_OBSOLETE24 -#define CURLE_SHARE_IN_USE CURLE_OBSOLETE57 -#define CURLE_URL_MALFORMAT_USER CURLE_NOT_BUILT_IN - -#define CURLE_FTP_ACCESS_DENIED CURLE_REMOTE_ACCESS_DENIED -#define CURLE_FTP_COULDNT_SET_BINARY CURLE_FTP_COULDNT_SET_TYPE -#define CURLE_FTP_QUOTE_ERROR CURLE_QUOTE_ERROR -#define CURLE_TFTP_DISKFULL CURLE_REMOTE_DISK_FULL -#define CURLE_TFTP_EXISTS CURLE_REMOTE_FILE_EXISTS -#define CURLE_HTTP_RANGE_ERROR CURLE_RANGE_ERROR -#define CURLE_FTP_SSL_FAILED CURLE_USE_SSL_FAILED - -/* The following were added earlier */ - -#define CURLE_OPERATION_TIMEOUTED CURLE_OPERATION_TIMEDOUT - -#define CURLE_HTTP_NOT_FOUND CURLE_HTTP_RETURNED_ERROR -#define CURLE_HTTP_PORT_FAILED CURLE_INTERFACE_FAILED -#define CURLE_FTP_COULDNT_STOR_FILE CURLE_UPLOAD_FAILED - -#define CURLE_FTP_PARTIAL_FILE CURLE_PARTIAL_FILE -#define CURLE_FTP_BAD_DOWNLOAD_RESUME CURLE_BAD_DOWNLOAD_RESUME - -/* This was the error code 50 in 7.7.3 and a few earlier versions, this - is no longer used by libcurl but is instead #defined here only to not - make programs break */ -#define CURLE_ALREADY_COMPLETE 99999 - -#endif /*!CURL_NO_OLDIES*/ - -/* This prototype applies to all conversion callbacks */ -typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length); - -typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */ - void *ssl_ctx, /* actually an - OpenSSL SSL_CTX */ - void *userptr); - -typedef enum { - CURLPROXY_HTTP = 0, /* added in 7.10, new in 7.19.4 default is to use - CONNECT HTTP/1.1 */ - CURLPROXY_HTTP_1_0 = 1, /* added in 7.19.4, force to use CONNECT - HTTP/1.0 */ - CURLPROXY_SOCKS4 = 4, /* support added in 7.15.2, enum existed already - in 7.10 */ - CURLPROXY_SOCKS5 = 5, /* added in 7.10 */ - CURLPROXY_SOCKS4A = 6, /* added in 7.18.0 */ - CURLPROXY_SOCKS5_HOSTNAME = 7 /* Use the SOCKS5 protocol but pass along the - host name rather than the IP address. added - in 7.18.0 */ -} curl_proxytype; /* this enum was added in 7.10 */ - -/* - * Bitmasks for CURLOPT_HTTPAUTH and CURLOPT_PROXYAUTH options: - * - * CURLAUTH_NONE - No HTTP authentication - * CURLAUTH_BASIC - HTTP Basic authentication (default) - * CURLAUTH_DIGEST - HTTP Digest authentication - * CURLAUTH_GSSNEGOTIATE - HTTP GSS-Negotiate authentication - * CURLAUTH_NTLM - HTTP NTLM authentication - * CURLAUTH_DIGEST_IE - HTTP Digest authentication with IE flavour - * CURLAUTH_NTLM_WB - HTTP NTLM authentication delegated to winbind helper - * CURLAUTH_ONLY - Use together with a single other type to force no - * authentication or just that single type - * CURLAUTH_ANY - All fine types set - * CURLAUTH_ANYSAFE - All fine types except Basic - */ - -#define CURLAUTH_NONE ((unsigned long)0) -#define CURLAUTH_BASIC (((unsigned long)1)<<0) -#define CURLAUTH_DIGEST (((unsigned long)1)<<1) -#define CURLAUTH_GSSNEGOTIATE (((unsigned long)1)<<2) -#define CURLAUTH_NTLM (((unsigned long)1)<<3) -#define CURLAUTH_DIGEST_IE (((unsigned long)1)<<4) -#define CURLAUTH_NTLM_WB (((unsigned long)1)<<5) -#define CURLAUTH_ONLY (((unsigned long)1)<<31) -#define CURLAUTH_ANY (~CURLAUTH_DIGEST_IE) -#define CURLAUTH_ANYSAFE (~(CURLAUTH_BASIC|CURLAUTH_DIGEST_IE)) - -#define CURLSSH_AUTH_ANY ~0 /* all types supported by the server */ -#define CURLSSH_AUTH_NONE 0 /* none allowed, silly but complete */ -#define CURLSSH_AUTH_PUBLICKEY (1<<0) /* public/private key files */ -#define CURLSSH_AUTH_PASSWORD (1<<1) /* password */ -#define CURLSSH_AUTH_HOST (1<<2) /* host key files */ -#define CURLSSH_AUTH_KEYBOARD (1<<3) /* keyboard interactive */ -#define CURLSSH_AUTH_DEFAULT CURLSSH_AUTH_ANY - -#define CURLGSSAPI_DELEGATION_NONE 0 /* no delegation (default) */ -#define CURLGSSAPI_DELEGATION_POLICY_FLAG (1<<0) /* if permitted by policy */ -#define CURLGSSAPI_DELEGATION_FLAG (1<<1) /* delegate always */ - -#define CURL_ERROR_SIZE 256 - -struct curl_khkey { - const char *key; /* points to a zero-terminated string encoded with base64 - if len is zero, otherwise to the "raw" data */ - size_t len; - enum type { - CURLKHTYPE_UNKNOWN, - CURLKHTYPE_RSA1, - CURLKHTYPE_RSA, - CURLKHTYPE_DSS - } keytype; -}; - -/* this is the set of return values expected from the curl_sshkeycallback - callback */ -enum curl_khstat { - CURLKHSTAT_FINE_ADD_TO_FILE, - CURLKHSTAT_FINE, - CURLKHSTAT_REJECT, /* reject the connection, return an error */ - CURLKHSTAT_DEFER, /* do not accept it, but we can't answer right now so - this causes a CURLE_DEFER error but otherwise the - connection will be left intact etc */ - CURLKHSTAT_LAST /* not for use, only a marker for last-in-list */ -}; - -/* this is the set of status codes pass in to the callback */ -enum curl_khmatch { - CURLKHMATCH_OK, /* match */ - CURLKHMATCH_MISMATCH, /* host found, key mismatch! */ - CURLKHMATCH_MISSING, /* no matching host/key found */ - CURLKHMATCH_LAST /* not for use, only a marker for last-in-list */ -}; - -typedef int - (*curl_sshkeycallback) (CURL *easy, /* easy handle */ - const struct curl_khkey *knownkey, /* known */ - const struct curl_khkey *foundkey, /* found */ - enum curl_khmatch, /* libcurl's view on the keys */ - void *clientp); /* custom pointer passed from app */ - -/* parameter for the CURLOPT_USE_SSL option */ -typedef enum { - CURLUSESSL_NONE, /* do not attempt to use SSL */ - CURLUSESSL_TRY, /* try using SSL, proceed anyway otherwise */ - CURLUSESSL_CONTROL, /* SSL for the control connection or fail */ - CURLUSESSL_ALL, /* SSL for all communication or fail */ - CURLUSESSL_LAST /* not an option, never use */ -} curl_usessl; - -/* Definition of bits for the CURLOPT_SSL_OPTIONS argument: */ - -/* - ALLOW_BEAST tells libcurl to allow the BEAST SSL vulnerability in the - name of improving interoperability with older servers. Some SSL libraries - have introduced work-arounds for this flaw but those work-arounds sometimes - make the SSL communication fail. To regain functionality with those broken - servers, a user can this way allow the vulnerability back. */ -#define CURLSSLOPT_ALLOW_BEAST (1<<0) - -#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all - the obsolete stuff removed! */ - -/* Backwards compatibility with older names */ -/* These are scheduled to disappear by 2009 */ - -#define CURLFTPSSL_NONE CURLUSESSL_NONE -#define CURLFTPSSL_TRY CURLUSESSL_TRY -#define CURLFTPSSL_CONTROL CURLUSESSL_CONTROL -#define CURLFTPSSL_ALL CURLUSESSL_ALL -#define CURLFTPSSL_LAST CURLUSESSL_LAST -#define curl_ftpssl curl_usessl -#endif /*!CURL_NO_OLDIES*/ - -/* parameter for the CURLOPT_FTP_SSL_CCC option */ -typedef enum { - CURLFTPSSL_CCC_NONE, /* do not send CCC */ - CURLFTPSSL_CCC_PASSIVE, /* Let the server initiate the shutdown */ - CURLFTPSSL_CCC_ACTIVE, /* Initiate the shutdown */ - CURLFTPSSL_CCC_LAST /* not an option, never use */ -} curl_ftpccc; - -/* parameter for the CURLOPT_FTPSSLAUTH option */ -typedef enum { - CURLFTPAUTH_DEFAULT, /* let libcurl decide */ - CURLFTPAUTH_SSL, /* use "AUTH SSL" */ - CURLFTPAUTH_TLS, /* use "AUTH TLS" */ - CURLFTPAUTH_LAST /* not an option, never use */ -} curl_ftpauth; - -/* parameter for the CURLOPT_FTP_CREATE_MISSING_DIRS option */ -typedef enum { - CURLFTP_CREATE_DIR_NONE, /* do NOT create missing dirs! */ - CURLFTP_CREATE_DIR, /* (FTP/SFTP) if CWD fails, try MKD and then CWD - again if MKD succeeded, for SFTP this does - similar magic */ - CURLFTP_CREATE_DIR_RETRY, /* (FTP only) if CWD fails, try MKD and then CWD - again even if MKD failed! */ - CURLFTP_CREATE_DIR_LAST /* not an option, never use */ -} curl_ftpcreatedir; - -/* parameter for the CURLOPT_FTP_FILEMETHOD option */ -typedef enum { - CURLFTPMETHOD_DEFAULT, /* let libcurl pick */ - CURLFTPMETHOD_MULTICWD, /* single CWD operation for each path part */ - CURLFTPMETHOD_NOCWD, /* no CWD at all */ - CURLFTPMETHOD_SINGLECWD, /* one CWD to full dir, then work on file */ - CURLFTPMETHOD_LAST /* not an option, never use */ -} curl_ftpmethod; - -/* CURLPROTO_ defines are for the CURLOPT_*PROTOCOLS options */ -#define CURLPROTO_HTTP (1<<0) -#define CURLPROTO_HTTPS (1<<1) -#define CURLPROTO_FTP (1<<2) -#define CURLPROTO_FTPS (1<<3) -#define CURLPROTO_SCP (1<<4) -#define CURLPROTO_SFTP (1<<5) -#define CURLPROTO_TELNET (1<<6) -#define CURLPROTO_LDAP (1<<7) -#define CURLPROTO_LDAPS (1<<8) -#define CURLPROTO_DICT (1<<9) -#define CURLPROTO_FILE (1<<10) -#define CURLPROTO_TFTP (1<<11) -#define CURLPROTO_IMAP (1<<12) -#define CURLPROTO_IMAPS (1<<13) -#define CURLPROTO_POP3 (1<<14) -#define CURLPROTO_POP3S (1<<15) -#define CURLPROTO_SMTP (1<<16) -#define CURLPROTO_SMTPS (1<<17) -#define CURLPROTO_RTSP (1<<18) -#define CURLPROTO_RTMP (1<<19) -#define CURLPROTO_RTMPT (1<<20) -#define CURLPROTO_RTMPE (1<<21) -#define CURLPROTO_RTMPTE (1<<22) -#define CURLPROTO_RTMPS (1<<23) -#define CURLPROTO_RTMPTS (1<<24) -#define CURLPROTO_GOPHER (1<<25) -#define CURLPROTO_ALL (~0) /* enable everything */ - -/* long may be 32 or 64 bits, but we should never depend on anything else - but 32 */ -#define CURLOPTTYPE_LONG 0 -#define CURLOPTTYPE_OBJECTPOINT 10000 -#define CURLOPTTYPE_FUNCTIONPOINT 20000 -#define CURLOPTTYPE_OFF_T 30000 - -/* name is uppercase CURLOPT_, - type is one of the defined CURLOPTTYPE_ - number is unique identifier */ -#ifdef CINIT -#undef CINIT -#endif - -#ifdef CURL_ISOCPP -#define CINIT(na,t,nu) CURLOPT_ ## na = CURLOPTTYPE_ ## t + nu -#else -/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */ -#define LONG CURLOPTTYPE_LONG -#define OBJECTPOINT CURLOPTTYPE_OBJECTPOINT -#define FUNCTIONPOINT CURLOPTTYPE_FUNCTIONPOINT -#define OFF_T CURLOPTTYPE_OFF_T -#define CINIT(name,type,number) CURLOPT_/**/name = type + number -#endif - -/* - * This macro-mania below setups the CURLOPT_[what] enum, to be used with - * curl_easy_setopt(). The first argument in the CINIT() macro is the [what] - * word. - */ - -typedef enum { - /* This is the FILE * or void * the regular output should be written to. */ - CINIT(FILE, OBJECTPOINT, 1), - - /* The full URL to get/put */ - CINIT(URL, OBJECTPOINT, 2), - - /* Port number to connect to, if other than default. */ - CINIT(PORT, LONG, 3), - - /* Name of proxy to use. */ - CINIT(PROXY, OBJECTPOINT, 4), - - /* "name:password" to use when fetching. */ - CINIT(USERPWD, OBJECTPOINT, 5), - - /* "name:password" to use with proxy. */ - CINIT(PROXYUSERPWD, OBJECTPOINT, 6), - - /* Range to get, specified as an ASCII string. */ - CINIT(RANGE, OBJECTPOINT, 7), - - /* not used */ - - /* Specified file stream to upload from (use as input): */ - CINIT(INFILE, OBJECTPOINT, 9), - - /* Buffer to receive error messages in, must be at least CURL_ERROR_SIZE - * bytes big. If this is not used, error messages go to stderr instead: */ - CINIT(ERRORBUFFER, OBJECTPOINT, 10), - - /* Function that will be called to store the output (instead of fwrite). The - * parameters will use fwrite() syntax, make sure to follow them. */ - CINIT(WRITEFUNCTION, FUNCTIONPOINT, 11), - - /* Function that will be called to read the input (instead of fread). The - * parameters will use fread() syntax, make sure to follow them. */ - CINIT(READFUNCTION, FUNCTIONPOINT, 12), - - /* Time-out the read operation after this amount of seconds */ - CINIT(TIMEOUT, LONG, 13), - - /* If the CURLOPT_INFILE is used, this can be used to inform libcurl about - * how large the file being sent really is. That allows better error - * checking and better verifies that the upload was successful. -1 means - * unknown size. - * - * For large file support, there is also a _LARGE version of the key - * which takes an off_t type, allowing platforms with larger off_t - * sizes to handle larger files. See below for INFILESIZE_LARGE. - */ - CINIT(INFILESIZE, LONG, 14), - - /* POST static input fields. */ - CINIT(POSTFIELDS, OBJECTPOINT, 15), - - /* Set the referrer page (needed by some CGIs) */ - CINIT(REFERER, OBJECTPOINT, 16), - - /* Set the FTP PORT string (interface name, named or numerical IP address) - Use i.e '-' to use default address. */ - CINIT(FTPPORT, OBJECTPOINT, 17), - - /* Set the User-Agent string (examined by some CGIs) */ - CINIT(USERAGENT, OBJECTPOINT, 18), - - /* If the download receives less than "low speed limit" bytes/second - * during "low speed time" seconds, the operations is aborted. - * You could i.e if you have a pretty high speed connection, abort if - * it is less than 2000 bytes/sec during 20 seconds. - */ - - /* Set the "low speed limit" */ - CINIT(LOW_SPEED_LIMIT, LONG, 19), - - /* Set the "low speed time" */ - CINIT(LOW_SPEED_TIME, LONG, 20), - - /* Set the continuation offset. - * - * Note there is also a _LARGE version of this key which uses - * off_t types, allowing for large file offsets on platforms which - * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE. - */ - CINIT(RESUME_FROM, LONG, 21), - - /* Set cookie in request: */ - CINIT(COOKIE, OBJECTPOINT, 22), - - /* This points to a linked list of headers, struct curl_slist kind */ - CINIT(HTTPHEADER, OBJECTPOINT, 23), - - /* This points to a linked list of post entries, struct curl_httppost */ - CINIT(HTTPPOST, OBJECTPOINT, 24), - - /* name of the file keeping your private SSL-certificate */ - CINIT(SSLCERT, OBJECTPOINT, 25), - - /* password for the SSL or SSH private key */ - CINIT(KEYPASSWD, OBJECTPOINT, 26), - - /* send TYPE parameter? */ - CINIT(CRLF, LONG, 27), - - /* send linked-list of QUOTE commands */ - CINIT(QUOTE, OBJECTPOINT, 28), - - /* send FILE * or void * to store headers to, if you use a callback it - is simply passed to the callback unmodified */ - CINIT(WRITEHEADER, OBJECTPOINT, 29), - - /* point to a file to read the initial cookies from, also enables - "cookie awareness" */ - CINIT(COOKIEFILE, OBJECTPOINT, 31), - - /* What version to specifically try to use. - See CURL_SSLVERSION defines below. */ - CINIT(SSLVERSION, LONG, 32), - - /* What kind of HTTP time condition to use, see defines */ - CINIT(TIMECONDITION, LONG, 33), - - /* Time to use with the above condition. Specified in number of seconds - since 1 Jan 1970 */ - CINIT(TIMEVALUE, LONG, 34), - - /* 35 = OBSOLETE */ - - /* Custom request, for customizing the get command like - HTTP: DELETE, TRACE and others - FTP: to use a different list command - */ - CINIT(CUSTOMREQUEST, OBJECTPOINT, 36), - - /* HTTP request, for odd commands like DELETE, TRACE and others */ - CINIT(STDERR, OBJECTPOINT, 37), - - /* 38 is not used */ - - /* send linked-list of post-transfer QUOTE commands */ - CINIT(POSTQUOTE, OBJECTPOINT, 39), - - CINIT(WRITEINFO, OBJECTPOINT, 40), /* DEPRECATED, do not use! */ - - CINIT(VERBOSE, LONG, 41), /* talk a lot */ - CINIT(HEADER, LONG, 42), /* throw the header out too */ - CINIT(NOPROGRESS, LONG, 43), /* shut off the progress meter */ - CINIT(NOBODY, LONG, 44), /* use HEAD to get http document */ - CINIT(FAILONERROR, LONG, 45), /* no output on http error codes >= 300 */ - CINIT(UPLOAD, LONG, 46), /* this is an upload */ - CINIT(POST, LONG, 47), /* HTTP POST method */ - CINIT(DIRLISTONLY, LONG, 48), /* bare names when listing directories */ - - CINIT(APPEND, LONG, 50), /* Append instead of overwrite on upload! */ - - /* Specify whether to read the user+password from the .netrc or the URL. - * This must be one of the CURL_NETRC_* enums below. */ - CINIT(NETRC, LONG, 51), - - CINIT(FOLLOWLOCATION, LONG, 52), /* use Location: Luke! */ - - CINIT(TRANSFERTEXT, LONG, 53), /* transfer data in text/ASCII format */ - CINIT(PUT, LONG, 54), /* HTTP PUT */ - - /* 55 = OBSOLETE */ - - /* Function that will be called instead of the internal progress display - * function. This function should be defined as the curl_progress_callback - * prototype defines. */ - CINIT(PROGRESSFUNCTION, FUNCTIONPOINT, 56), - - /* Data passed to the progress callback */ - CINIT(PROGRESSDATA, OBJECTPOINT, 57), - - /* We want the referrer field set automatically when following locations */ - CINIT(AUTOREFERER, LONG, 58), - - /* Port of the proxy, can be set in the proxy string as well with: - "[host]:[port]" */ - CINIT(PROXYPORT, LONG, 59), - - /* size of the POST input data, if strlen() is not good to use */ - CINIT(POSTFIELDSIZE, LONG, 60), - - /* tunnel non-http operations through a HTTP proxy */ - CINIT(HTTPPROXYTUNNEL, LONG, 61), - - /* Set the interface string to use as outgoing network interface */ - CINIT(INTERFACE, OBJECTPOINT, 62), - - /* Set the krb4/5 security level, this also enables krb4/5 awareness. This - * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string - * is set but doesn't match one of these, 'private' will be used. */ - CINIT(KRBLEVEL, OBJECTPOINT, 63), - - /* Set if we should verify the peer in ssl handshake, set 1 to verify. */ - CINIT(SSL_VERIFYPEER, LONG, 64), - - /* The CApath or CAfile used to validate the peer certificate - this option is used only if SSL_VERIFYPEER is true */ - CINIT(CAINFO, OBJECTPOINT, 65), - - /* 66 = OBSOLETE */ - /* 67 = OBSOLETE */ - - /* Maximum number of http redirects to follow */ - CINIT(MAXREDIRS, LONG, 68), - - /* Pass a long set to 1 to get the date of the requested document (if - possible)! Pass a zero to shut it off. */ - CINIT(FILETIME, LONG, 69), - - /* This points to a linked list of telnet options */ - CINIT(TELNETOPTIONS, OBJECTPOINT, 70), - - /* Max amount of cached alive connections */ - CINIT(MAXCONNECTS, LONG, 71), - - CINIT(CLOSEPOLICY, LONG, 72), /* DEPRECATED, do not use! */ - - /* 73 = OBSOLETE */ - - /* Set to explicitly use a new connection for the upcoming transfer. - Do not use this unless you're absolutely sure of this, as it makes the - operation slower and is less friendly for the network. */ - CINIT(FRESH_CONNECT, LONG, 74), - - /* Set to explicitly forbid the upcoming transfer's connection to be re-used - when done. Do not use this unless you're absolutely sure of this, as it - makes the operation slower and is less friendly for the network. */ - CINIT(FORBID_REUSE, LONG, 75), - - /* Set to a file name that contains random data for libcurl to use to - seed the random engine when doing SSL connects. */ - CINIT(RANDOM_FILE, OBJECTPOINT, 76), - - /* Set to the Entropy Gathering Daemon socket pathname */ - CINIT(EGDSOCKET, OBJECTPOINT, 77), - - /* Time-out connect operations after this amount of seconds, if connects - are OK within this time, then fine... This only aborts the connect - phase. [Only works on unix-style/SIGALRM operating systems] */ - CINIT(CONNECTTIMEOUT, LONG, 78), - - /* Function that will be called to store headers (instead of fwrite). The - * parameters will use fwrite() syntax, make sure to follow them. */ - CINIT(HEADERFUNCTION, FUNCTIONPOINT, 79), - - /* Set this to force the HTTP request to get back to GET. Only really usable - if POST, PUT or a custom request have been used first. - */ - CINIT(HTTPGET, LONG, 80), - - /* Set if we should verify the Common name from the peer certificate in ssl - * handshake, set 1 to check existence, 2 to ensure that it matches the - * provided hostname. */ - CINIT(SSL_VERIFYHOST, LONG, 81), - - /* Specify which file name to write all known cookies in after completed - operation. Set file name to "-" (dash) to make it go to stdout. */ - CINIT(COOKIEJAR, OBJECTPOINT, 82), - - /* Specify which SSL ciphers to use */ - CINIT(SSL_CIPHER_LIST, OBJECTPOINT, 83), - - /* Specify which HTTP version to use! This must be set to one of the - CURL_HTTP_VERSION* enums set below. */ - CINIT(HTTP_VERSION, LONG, 84), - - /* Specifically switch on or off the FTP engine's use of the EPSV command. By - default, that one will always be attempted before the more traditional - PASV command. */ - CINIT(FTP_USE_EPSV, LONG, 85), - - /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */ - CINIT(SSLCERTTYPE, OBJECTPOINT, 86), - - /* name of the file keeping your private SSL-key */ - CINIT(SSLKEY, OBJECTPOINT, 87), - - /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */ - CINIT(SSLKEYTYPE, OBJECTPOINT, 88), - - /* crypto engine for the SSL-sub system */ - CINIT(SSLENGINE, OBJECTPOINT, 89), - - /* set the crypto engine for the SSL-sub system as default - the param has no meaning... - */ - CINIT(SSLENGINE_DEFAULT, LONG, 90), - - /* Non-zero value means to use the global dns cache */ - CINIT(DNS_USE_GLOBAL_CACHE, LONG, 91), /* DEPRECATED, do not use! */ - - /* DNS cache timeout */ - CINIT(DNS_CACHE_TIMEOUT, LONG, 92), - - /* send linked-list of pre-transfer QUOTE commands */ - CINIT(PREQUOTE, OBJECTPOINT, 93), - - /* set the debug function */ - CINIT(DEBUGFUNCTION, FUNCTIONPOINT, 94), - - /* set the data for the debug function */ - CINIT(DEBUGDATA, OBJECTPOINT, 95), - - /* mark this as start of a cookie session */ - CINIT(COOKIESESSION, LONG, 96), - - /* The CApath directory used to validate the peer certificate - this option is used only if SSL_VERIFYPEER is true */ - CINIT(CAPATH, OBJECTPOINT, 97), - - /* Instruct libcurl to use a smaller receive buffer */ - CINIT(BUFFERSIZE, LONG, 98), - - /* Instruct libcurl to not use any signal/alarm handlers, even when using - timeouts. This option is useful for multi-threaded applications. - See libcurl-the-guide for more background information. */ - CINIT(NOSIGNAL, LONG, 99), - - /* Provide a CURLShare for mutexing non-ts data */ - CINIT(SHARE, OBJECTPOINT, 100), - - /* indicates type of proxy. accepted values are CURLPROXY_HTTP (default), - CURLPROXY_SOCKS4, CURLPROXY_SOCKS4A and CURLPROXY_SOCKS5. */ - CINIT(PROXYTYPE, LONG, 101), - - /* Set the Accept-Encoding string. Use this to tell a server you would like - the response to be compressed. Before 7.21.6, this was known as - CURLOPT_ENCODING */ - CINIT(ACCEPT_ENCODING, OBJECTPOINT, 102), - - /* Set pointer to private data */ - CINIT(PRIVATE, OBJECTPOINT, 103), - - /* Set aliases for HTTP 200 in the HTTP Response header */ - CINIT(HTTP200ALIASES, OBJECTPOINT, 104), - - /* Continue to send authentication (user+password) when following locations, - even when hostname changed. This can potentially send off the name - and password to whatever host the server decides. */ - CINIT(UNRESTRICTED_AUTH, LONG, 105), - - /* Specifically switch on or off the FTP engine's use of the EPRT command ( - it also disables the LPRT attempt). By default, those ones will always be - attempted before the good old traditional PORT command. */ - CINIT(FTP_USE_EPRT, LONG, 106), - - /* Set this to a bitmask value to enable the particular authentications - methods you like. Use this in combination with CURLOPT_USERPWD. - Note that setting multiple bits may cause extra network round-trips. */ - CINIT(HTTPAUTH, LONG, 107), - - /* Set the ssl context callback function, currently only for OpenSSL ssl_ctx - in second argument. The function must be matching the - curl_ssl_ctx_callback proto. */ - CINIT(SSL_CTX_FUNCTION, FUNCTIONPOINT, 108), - - /* Set the userdata for the ssl context callback function's third - argument */ - CINIT(SSL_CTX_DATA, OBJECTPOINT, 109), - - /* FTP Option that causes missing dirs to be created on the remote server. - In 7.19.4 we introduced the convenience enums for this option using the - CURLFTP_CREATE_DIR prefix. - */ - CINIT(FTP_CREATE_MISSING_DIRS, LONG, 110), - - /* Set this to a bitmask value to enable the particular authentications - methods you like. Use this in combination with CURLOPT_PROXYUSERPWD. - Note that setting multiple bits may cause extra network round-trips. */ - CINIT(PROXYAUTH, LONG, 111), - - /* FTP option that changes the timeout, in seconds, associated with - getting a response. This is different from transfer timeout time and - essentially places a demand on the FTP server to acknowledge commands - in a timely manner. */ - CINIT(FTP_RESPONSE_TIMEOUT, LONG, 112), -#define CURLOPT_SERVER_RESPONSE_TIMEOUT CURLOPT_FTP_RESPONSE_TIMEOUT - - /* Set this option to one of the CURL_IPRESOLVE_* defines (see below) to - tell libcurl to resolve names to those IP versions only. This only has - affect on systems with support for more than one, i.e IPv4 _and_ IPv6. */ - CINIT(IPRESOLVE, LONG, 113), - - /* Set this option to limit the size of a file that will be downloaded from - an HTTP or FTP server. - - Note there is also _LARGE version which adds large file support for - platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */ - CINIT(MAXFILESIZE, LONG, 114), - - /* See the comment for INFILESIZE above, but in short, specifies - * the size of the file being uploaded. -1 means unknown. - */ - CINIT(INFILESIZE_LARGE, OFF_T, 115), - - /* Sets the continuation offset. There is also a LONG version of this; - * look above for RESUME_FROM. - */ - CINIT(RESUME_FROM_LARGE, OFF_T, 116), - - /* Sets the maximum size of data that will be downloaded from - * an HTTP or FTP server. See MAXFILESIZE above for the LONG version. - */ - CINIT(MAXFILESIZE_LARGE, OFF_T, 117), - - /* Set this option to the file name of your .netrc file you want libcurl - to parse (using the CURLOPT_NETRC option). If not set, libcurl will do - a poor attempt to find the user's home directory and check for a .netrc - file in there. */ - CINIT(NETRC_FILE, OBJECTPOINT, 118), - - /* Enable SSL/TLS for FTP, pick one of: - CURLFTPSSL_TRY - try using SSL, proceed anyway otherwise - CURLFTPSSL_CONTROL - SSL for the control connection or fail - CURLFTPSSL_ALL - SSL for all communication or fail - */ - CINIT(USE_SSL, LONG, 119), - - /* The _LARGE version of the standard POSTFIELDSIZE option */ - CINIT(POSTFIELDSIZE_LARGE, OFF_T, 120), - - /* Enable/disable the TCP Nagle algorithm */ - CINIT(TCP_NODELAY, LONG, 121), - - /* 122 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 123 OBSOLETE. Gone in 7.16.0 */ - /* 124 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 125 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 126 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ - /* 127 OBSOLETE. Gone in 7.16.0 */ - /* 128 OBSOLETE. Gone in 7.16.0 */ - - /* When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option - can be used to change libcurl's default action which is to first try - "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK - response has been received. - - Available parameters are: - CURLFTPAUTH_DEFAULT - let libcurl decide - CURLFTPAUTH_SSL - try "AUTH SSL" first, then TLS - CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL - */ - CINIT(FTPSSLAUTH, LONG, 129), - - CINIT(IOCTLFUNCTION, FUNCTIONPOINT, 130), - CINIT(IOCTLDATA, OBJECTPOINT, 131), - - /* 132 OBSOLETE. Gone in 7.16.0 */ - /* 133 OBSOLETE. Gone in 7.16.0 */ - - /* zero terminated string for pass on to the FTP server when asked for - "account" info */ - CINIT(FTP_ACCOUNT, OBJECTPOINT, 134), - - /* feed cookies into cookie engine */ - CINIT(COOKIELIST, OBJECTPOINT, 135), - - /* ignore Content-Length */ - CINIT(IGNORE_CONTENT_LENGTH, LONG, 136), - - /* Set to non-zero to skip the IP address received in a 227 PASV FTP server - response. Typically used for FTP-SSL purposes but is not restricted to - that. libcurl will then instead use the same IP address it used for the - control connection. */ - CINIT(FTP_SKIP_PASV_IP, LONG, 137), - - /* Select "file method" to use when doing FTP, see the curl_ftpmethod - above. */ - CINIT(FTP_FILEMETHOD, LONG, 138), - - /* Local port number to bind the socket to */ - CINIT(LOCALPORT, LONG, 139), - - /* Number of ports to try, including the first one set with LOCALPORT. - Thus, setting it to 1 will make no additional attempts but the first. - */ - CINIT(LOCALPORTRANGE, LONG, 140), - - /* no transfer, set up connection and let application use the socket by - extracting it with CURLINFO_LASTSOCKET */ - CINIT(CONNECT_ONLY, LONG, 141), - - /* Function that will be called to convert from the - network encoding (instead of using the iconv calls in libcurl) */ - CINIT(CONV_FROM_NETWORK_FUNCTION, FUNCTIONPOINT, 142), - - /* Function that will be called to convert to the - network encoding (instead of using the iconv calls in libcurl) */ - CINIT(CONV_TO_NETWORK_FUNCTION, FUNCTIONPOINT, 143), - - /* Function that will be called to convert from UTF8 - (instead of using the iconv calls in libcurl) - Note that this is used only for SSL certificate processing */ - CINIT(CONV_FROM_UTF8_FUNCTION, FUNCTIONPOINT, 144), - - /* if the connection proceeds too quickly then need to slow it down */ - /* limit-rate: maximum number of bytes per second to send or receive */ - CINIT(MAX_SEND_SPEED_LARGE, OFF_T, 145), - CINIT(MAX_RECV_SPEED_LARGE, OFF_T, 146), - - /* Pointer to command string to send if USER/PASS fails. */ - CINIT(FTP_ALTERNATIVE_TO_USER, OBJECTPOINT, 147), - - /* callback function for setting socket options */ - CINIT(SOCKOPTFUNCTION, FUNCTIONPOINT, 148), - CINIT(SOCKOPTDATA, OBJECTPOINT, 149), - - /* set to 0 to disable session ID re-use for this transfer, default is - enabled (== 1) */ - CINIT(SSL_SESSIONID_CACHE, LONG, 150), - - /* allowed SSH authentication methods */ - CINIT(SSH_AUTH_TYPES, LONG, 151), - - /* Used by scp/sftp to do public/private key authentication */ - CINIT(SSH_PUBLIC_KEYFILE, OBJECTPOINT, 152), - CINIT(SSH_PRIVATE_KEYFILE, OBJECTPOINT, 153), - - /* Send CCC (Clear Command Channel) after authentication */ - CINIT(FTP_SSL_CCC, LONG, 154), - - /* Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */ - CINIT(TIMEOUT_MS, LONG, 155), - CINIT(CONNECTTIMEOUT_MS, LONG, 156), - - /* set to zero to disable the libcurl's decoding and thus pass the raw body - data to the application even when it is encoded/compressed */ - CINIT(HTTP_TRANSFER_DECODING, LONG, 157), - CINIT(HTTP_CONTENT_DECODING, LONG, 158), - - /* Permission used when creating new files and directories on the remote - server for protocols that support it, SFTP/SCP/FILE */ - CINIT(NEW_FILE_PERMS, LONG, 159), - CINIT(NEW_DIRECTORY_PERMS, LONG, 160), - - /* Set the behaviour of POST when redirecting. Values must be set to one - of CURL_REDIR* defines below. This used to be called CURLOPT_POST301 */ - CINIT(POSTREDIR, LONG, 161), - - /* used by scp/sftp to verify the host's public key */ - CINIT(SSH_HOST_PUBLIC_KEY_MD5, OBJECTPOINT, 162), - - /* Callback function for opening socket (instead of socket(2)). Optionally, - callback is able change the address or refuse to connect returning - CURL_SOCKET_BAD. The callback should have type - curl_opensocket_callback */ - CINIT(OPENSOCKETFUNCTION, FUNCTIONPOINT, 163), - CINIT(OPENSOCKETDATA, OBJECTPOINT, 164), - - /* POST volatile input fields. */ - CINIT(COPYPOSTFIELDS, OBJECTPOINT, 165), - - /* set transfer mode (;type=) when doing FTP via an HTTP proxy */ - CINIT(PROXY_TRANSFER_MODE, LONG, 166), - - /* Callback function for seeking in the input stream */ - CINIT(SEEKFUNCTION, FUNCTIONPOINT, 167), - CINIT(SEEKDATA, OBJECTPOINT, 168), - - /* CRL file */ - CINIT(CRLFILE, OBJECTPOINT, 169), - - /* Issuer certificate */ - CINIT(ISSUERCERT, OBJECTPOINT, 170), - - /* (IPv6) Address scope */ - CINIT(ADDRESS_SCOPE, LONG, 171), - - /* Collect certificate chain info and allow it to get retrievable with - CURLINFO_CERTINFO after the transfer is complete. (Unfortunately) only - working with OpenSSL-powered builds. */ - CINIT(CERTINFO, LONG, 172), - - /* "name" and "pwd" to use when fetching. */ - CINIT(USERNAME, OBJECTPOINT, 173), - CINIT(PASSWORD, OBJECTPOINT, 174), - - /* "name" and "pwd" to use with Proxy when fetching. */ - CINIT(PROXYUSERNAME, OBJECTPOINT, 175), - CINIT(PROXYPASSWORD, OBJECTPOINT, 176), - - /* Comma separated list of hostnames defining no-proxy zones. These should - match both hostnames directly, and hostnames within a domain. For - example, local.com will match local.com and www.local.com, but NOT - notlocal.com or www.notlocal.com. For compatibility with other - implementations of this, .local.com will be considered to be the same as - local.com. A single * is the only valid wildcard, and effectively - disables the use of proxy. */ - CINIT(NOPROXY, OBJECTPOINT, 177), - - /* block size for TFTP transfers */ - CINIT(TFTP_BLKSIZE, LONG, 178), - - /* Socks Service */ - CINIT(SOCKS5_GSSAPI_SERVICE, OBJECTPOINT, 179), - - /* Socks Service */ - CINIT(SOCKS5_GSSAPI_NEC, LONG, 180), - - /* set the bitmask for the protocols that are allowed to be used for the - transfer, which thus helps the app which takes URLs from users or other - external inputs and want to restrict what protocol(s) to deal - with. Defaults to CURLPROTO_ALL. */ - CINIT(PROTOCOLS, LONG, 181), - - /* set the bitmask for the protocols that libcurl is allowed to follow to, - as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs - to be set in both bitmasks to be allowed to get redirected to. Defaults - to all protocols except FILE and SCP. */ - CINIT(REDIR_PROTOCOLS, LONG, 182), - - /* set the SSH knownhost file name to use */ - CINIT(SSH_KNOWNHOSTS, OBJECTPOINT, 183), - - /* set the SSH host key callback, must point to a curl_sshkeycallback - function */ - CINIT(SSH_KEYFUNCTION, FUNCTIONPOINT, 184), - - /* set the SSH host key callback custom pointer */ - CINIT(SSH_KEYDATA, OBJECTPOINT, 185), - - /* set the SMTP mail originator */ - CINIT(MAIL_FROM, OBJECTPOINT, 186), - - /* set the SMTP mail receiver(s) */ - CINIT(MAIL_RCPT, OBJECTPOINT, 187), - - /* FTP: send PRET before PASV */ - CINIT(FTP_USE_PRET, LONG, 188), - - /* RTSP request method (OPTIONS, SETUP, PLAY, etc...) */ - CINIT(RTSP_REQUEST, LONG, 189), - - /* The RTSP session identifier */ - CINIT(RTSP_SESSION_ID, OBJECTPOINT, 190), - - /* The RTSP stream URI */ - CINIT(RTSP_STREAM_URI, OBJECTPOINT, 191), - - /* The Transport: header to use in RTSP requests */ - CINIT(RTSP_TRANSPORT, OBJECTPOINT, 192), - - /* Manually initialize the client RTSP CSeq for this handle */ - CINIT(RTSP_CLIENT_CSEQ, LONG, 193), - - /* Manually initialize the server RTSP CSeq for this handle */ - CINIT(RTSP_SERVER_CSEQ, LONG, 194), - - /* The stream to pass to INTERLEAVEFUNCTION. */ - CINIT(INTERLEAVEDATA, OBJECTPOINT, 195), - - /* Let the application define a custom write method for RTP data */ - CINIT(INTERLEAVEFUNCTION, FUNCTIONPOINT, 196), - - /* Turn on wildcard matching */ - CINIT(WILDCARDMATCH, LONG, 197), - - /* Directory matching callback called before downloading of an - individual file (chunk) started */ - CINIT(CHUNK_BGN_FUNCTION, FUNCTIONPOINT, 198), - - /* Directory matching callback called after the file (chunk) - was downloaded, or skipped */ - CINIT(CHUNK_END_FUNCTION, FUNCTIONPOINT, 199), - - /* Change match (fnmatch-like) callback for wildcard matching */ - CINIT(FNMATCH_FUNCTION, FUNCTIONPOINT, 200), - - /* Let the application define custom chunk data pointer */ - CINIT(CHUNK_DATA, OBJECTPOINT, 201), - - /* FNMATCH_FUNCTION user pointer */ - CINIT(FNMATCH_DATA, OBJECTPOINT, 202), - - /* send linked-list of name:port:address sets */ - CINIT(RESOLVE, OBJECTPOINT, 203), - - /* Set a username for authenticated TLS */ - CINIT(TLSAUTH_USERNAME, OBJECTPOINT, 204), - - /* Set a password for authenticated TLS */ - CINIT(TLSAUTH_PASSWORD, OBJECTPOINT, 205), - - /* Set authentication type for authenticated TLS */ - CINIT(TLSAUTH_TYPE, OBJECTPOINT, 206), - - /* Set to 1 to enable the "TE:" header in HTTP requests to ask for - compressed transfer-encoded responses. Set to 0 to disable the use of TE: - in outgoing requests. The current default is 0, but it might change in a - future libcurl release. - - libcurl will ask for the compressed methods it knows of, and if that - isn't any, it will not ask for transfer-encoding at all even if this - option is set to 1. - - */ - CINIT(TRANSFER_ENCODING, LONG, 207), - - /* Callback function for closing socket (instead of close(2)). The callback - should have type curl_closesocket_callback */ - CINIT(CLOSESOCKETFUNCTION, FUNCTIONPOINT, 208), - CINIT(CLOSESOCKETDATA, OBJECTPOINT, 209), - - /* allow GSSAPI credential delegation */ - CINIT(GSSAPI_DELEGATION, LONG, 210), - - /* Set the name servers to use for DNS resolution */ - CINIT(DNS_SERVERS, OBJECTPOINT, 211), - - /* Time-out accept operations (currently for FTP only) after this amount - of miliseconds. */ - CINIT(ACCEPTTIMEOUT_MS, LONG, 212), - - /* Set TCP keepalive */ - CINIT(TCP_KEEPALIVE, LONG, 213), - - /* non-universal keepalive knobs (Linux, AIX, HP-UX, more) */ - CINIT(TCP_KEEPIDLE, LONG, 214), - CINIT(TCP_KEEPINTVL, LONG, 215), - - /* Enable/disable specific SSL features with a bitmask, see CURLSSLOPT_* */ - CINIT(SSL_OPTIONS, LONG, 216), - - /* set the SMTP auth originator */ - CINIT(MAIL_AUTH, OBJECTPOINT, 217), - - CURLOPT_LASTENTRY /* the last unused */ -} CURLoption; - -#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all - the obsolete stuff removed! */ - -/* Backwards compatibility with older names */ -/* These are scheduled to disappear by 2011 */ - -/* This was added in version 7.19.1 */ -#define CURLOPT_POST301 CURLOPT_POSTREDIR - -/* These are scheduled to disappear by 2009 */ - -/* The following were added in 7.17.0 */ -#define CURLOPT_SSLKEYPASSWD CURLOPT_KEYPASSWD -#define CURLOPT_FTPAPPEND CURLOPT_APPEND -#define CURLOPT_FTPLISTONLY CURLOPT_DIRLISTONLY -#define CURLOPT_FTP_SSL CURLOPT_USE_SSL - -/* The following were added earlier */ - -#define CURLOPT_SSLCERTPASSWD CURLOPT_KEYPASSWD -#define CURLOPT_KRB4LEVEL CURLOPT_KRBLEVEL - -#else -/* This is set if CURL_NO_OLDIES is defined at compile-time */ -#undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */ -#endif - - - /* Below here follows defines for the CURLOPT_IPRESOLVE option. If a host - name resolves addresses using more than one IP protocol version, this - option might be handy to force libcurl to use a specific IP version. */ -#define CURL_IPRESOLVE_WHATEVER 0 /* default, resolves addresses to all IP - versions that your system allows */ -#define CURL_IPRESOLVE_V4 1 /* resolve to ipv4 addresses */ -#define CURL_IPRESOLVE_V6 2 /* resolve to ipv6 addresses */ - - /* three convenient "aliases" that follow the name scheme better */ -#define CURLOPT_WRITEDATA CURLOPT_FILE -#define CURLOPT_READDATA CURLOPT_INFILE -#define CURLOPT_HEADERDATA CURLOPT_WRITEHEADER -#define CURLOPT_RTSPHEADER CURLOPT_HTTPHEADER - - /* These enums are for use with the CURLOPT_HTTP_VERSION option. */ -enum { - CURL_HTTP_VERSION_NONE, /* setting this means we don't care, and that we'd - like the library to choose the best possible - for us! */ - CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */ - CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */ - - CURL_HTTP_VERSION_LAST /* *ILLEGAL* http version */ -}; - -/* - * Public API enums for RTSP requests - */ -enum { - CURL_RTSPREQ_NONE, /* first in list */ - CURL_RTSPREQ_OPTIONS, - CURL_RTSPREQ_DESCRIBE, - CURL_RTSPREQ_ANNOUNCE, - CURL_RTSPREQ_SETUP, - CURL_RTSPREQ_PLAY, - CURL_RTSPREQ_PAUSE, - CURL_RTSPREQ_TEARDOWN, - CURL_RTSPREQ_GET_PARAMETER, - CURL_RTSPREQ_SET_PARAMETER, - CURL_RTSPREQ_RECORD, - CURL_RTSPREQ_RECEIVE, - CURL_RTSPREQ_LAST /* last in list */ -}; - - /* These enums are for use with the CURLOPT_NETRC option. */ -enum CURL_NETRC_OPTION { - CURL_NETRC_IGNORED, /* The .netrc will never be read. - * This is the default. */ - CURL_NETRC_OPTIONAL, /* A user:password in the URL will be preferred - * to one in the .netrc. */ - CURL_NETRC_REQUIRED, /* A user:password in the URL will be ignored. - * Unless one is set programmatically, the .netrc - * will be queried. */ - CURL_NETRC_LAST -}; - -enum { - CURL_SSLVERSION_DEFAULT, - CURL_SSLVERSION_TLSv1, - CURL_SSLVERSION_SSLv2, - CURL_SSLVERSION_SSLv3, - - CURL_SSLVERSION_LAST /* never use, keep last */ -}; - -enum CURL_TLSAUTH { - CURL_TLSAUTH_NONE, - CURL_TLSAUTH_SRP, - CURL_TLSAUTH_LAST /* never use, keep last */ -}; - -/* symbols to use with CURLOPT_POSTREDIR. - CURL_REDIR_POST_301, CURL_REDIR_POST_302 and CURL_REDIR_POST_303 - can be bitwise ORed so that CURL_REDIR_POST_301 | CURL_REDIR_POST_302 - | CURL_REDIR_POST_303 == CURL_REDIR_POST_ALL */ - -#define CURL_REDIR_GET_ALL 0 -#define CURL_REDIR_POST_301 1 -#define CURL_REDIR_POST_302 2 -#define CURL_REDIR_POST_303 4 -#define CURL_REDIR_POST_ALL \ - (CURL_REDIR_POST_301|CURL_REDIR_POST_302|CURL_REDIR_POST_303) - -typedef enum { - CURL_TIMECOND_NONE, - - CURL_TIMECOND_IFMODSINCE, - CURL_TIMECOND_IFUNMODSINCE, - CURL_TIMECOND_LASTMOD, - - CURL_TIMECOND_LAST -} curl_TimeCond; - - -/* curl_strequal() and curl_strnequal() are subject for removal in a future - libcurl, see lib/README.curlx for details */ -CURL_EXTERN int (curl_strequal)(const char *s1, const char *s2); -CURL_EXTERN int (curl_strnequal)(const char *s1, const char *s2, size_t n); - -/* name is uppercase CURLFORM_ */ -#ifdef CFINIT -#undef CFINIT -#endif - -#ifdef CURL_ISOCPP -#define CFINIT(name) CURLFORM_ ## name -#else -/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */ -#define CFINIT(name) CURLFORM_/**/name -#endif - -typedef enum { - CFINIT(NOTHING), /********* the first one is unused ************/ - - /* */ - CFINIT(COPYNAME), - CFINIT(PTRNAME), - CFINIT(NAMELENGTH), - CFINIT(COPYCONTENTS), - CFINIT(PTRCONTENTS), - CFINIT(CONTENTSLENGTH), - CFINIT(FILECONTENT), - CFINIT(ARRAY), - CFINIT(OBSOLETE), - CFINIT(FILE), - - CFINIT(BUFFER), - CFINIT(BUFFERPTR), - CFINIT(BUFFERLENGTH), - - CFINIT(CONTENTTYPE), - CFINIT(CONTENTHEADER), - CFINIT(FILENAME), - CFINIT(END), - CFINIT(OBSOLETE2), - - CFINIT(STREAM), - - CURLFORM_LASTENTRY /* the last unused */ -} CURLformoption; - -#undef CFINIT /* done */ - -/* structure to be used as parameter for CURLFORM_ARRAY */ -struct curl_forms { - CURLformoption option; - const char *value; -}; - -/* use this for multipart formpost building */ -/* Returns code for curl_formadd() - * - * Returns: - * CURL_FORMADD_OK on success - * CURL_FORMADD_MEMORY if the FormInfo allocation fails - * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form - * CURL_FORMADD_NULL if a null pointer was given for a char - * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed - * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used - * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error) - * CURL_FORMADD_MEMORY if a curl_httppost struct cannot be allocated - * CURL_FORMADD_MEMORY if some allocation for string copying failed. - * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array - * - ***************************************************************************/ -typedef enum { - CURL_FORMADD_OK, /* first, no error */ - - CURL_FORMADD_MEMORY, - CURL_FORMADD_OPTION_TWICE, - CURL_FORMADD_NULL, - CURL_FORMADD_UNKNOWN_OPTION, - CURL_FORMADD_INCOMPLETE, - CURL_FORMADD_ILLEGAL_ARRAY, - CURL_FORMADD_DISABLED, /* libcurl was built with this disabled */ - - CURL_FORMADD_LAST /* last */ -} CURLFORMcode; - -/* - * NAME curl_formadd() - * - * DESCRIPTION - * - * Pretty advanced function for building multi-part formposts. Each invoke - * adds one part that together construct a full post. Then use - * CURLOPT_HTTPPOST to send it off to libcurl. - */ -CURL_EXTERN CURLFORMcode curl_formadd(struct curl_httppost **httppost, - struct curl_httppost **last_post, - ...); - -/* - * callback function for curl_formget() - * The void *arg pointer will be the one passed as second argument to - * curl_formget(). - * The character buffer passed to it must not be freed. - * Should return the buffer length passed to it as the argument "len" on - * success. - */ -typedef size_t (*curl_formget_callback)(void *arg, const char *buf, - size_t len); - -/* - * NAME curl_formget() - * - * DESCRIPTION - * - * Serialize a curl_httppost struct built with curl_formadd(). - * Accepts a void pointer as second argument which will be passed to - * the curl_formget_callback function. - * Returns 0 on success. - */ -CURL_EXTERN int curl_formget(struct curl_httppost *form, void *arg, - curl_formget_callback append); -/* - * NAME curl_formfree() - * - * DESCRIPTION - * - * Free a multipart formpost previously built with curl_formadd(). - */ -CURL_EXTERN void curl_formfree(struct curl_httppost *form); - -/* - * NAME curl_getenv() - * - * DESCRIPTION - * - * Returns a malloc()'ed string that MUST be curl_free()ed after usage is - * complete. DEPRECATED - see lib/README.curlx - */ -CURL_EXTERN char *curl_getenv(const char *variable); - -/* - * NAME curl_version() - * - * DESCRIPTION - * - * Returns a static ascii string of the libcurl version. - */ -CURL_EXTERN char *curl_version(void); - -/* - * NAME curl_easy_escape() - * - * DESCRIPTION - * - * Escapes URL strings (converts all letters consider illegal in URLs to their - * %XX versions). This function returns a new allocated string or NULL if an - * error occurred. - */ -CURL_EXTERN char *curl_easy_escape(CURL *handle, - const char *string, - int length); - -/* the previous version: */ -CURL_EXTERN char *curl_escape(const char *string, - int length); - - -/* - * NAME curl_easy_unescape() - * - * DESCRIPTION - * - * Unescapes URL encoding in strings (converts all %XX codes to their 8bit - * versions). This function returns a new allocated string or NULL if an error - * occurred. - * Conversion Note: On non-ASCII platforms the ASCII %XX codes are - * converted into the host encoding. - */ -CURL_EXTERN char *curl_easy_unescape(CURL *handle, - const char *string, - int length, - int *outlength); - -/* the previous version */ -CURL_EXTERN char *curl_unescape(const char *string, - int length); - -/* - * NAME curl_free() - * - * DESCRIPTION - * - * Provided for de-allocation in the same translation unit that did the - * allocation. Added in libcurl 7.10 - */ -CURL_EXTERN void curl_free(void *p); - -/* - * NAME curl_global_init() - * - * DESCRIPTION - * - * curl_global_init() should be invoked exactly once for each application that - * uses libcurl and before any call of other libcurl functions. - * - * This function is not thread-safe! - */ -CURL_EXTERN CURLcode curl_global_init(long flags); - -/* - * NAME curl_global_init_mem() - * - * DESCRIPTION - * - * curl_global_init() or curl_global_init_mem() should be invoked exactly once - * for each application that uses libcurl. This function can be used to - * initialize libcurl and set user defined memory management callback - * functions. Users can implement memory management routines to check for - * memory leaks, check for mis-use of the curl library etc. User registered - * callback routines with be invoked by this library instead of the system - * memory management routines like malloc, free etc. - */ -CURL_EXTERN CURLcode curl_global_init_mem(long flags, - curl_malloc_callback m, - curl_free_callback f, - curl_realloc_callback r, - curl_strdup_callback s, - curl_calloc_callback c); - -/* - * NAME curl_global_cleanup() - * - * DESCRIPTION - * - * curl_global_cleanup() should be invoked exactly once for each application - * that uses libcurl - */ -CURL_EXTERN void curl_global_cleanup(void); - -/* linked-list structure for the CURLOPT_QUOTE option (and other) */ -struct curl_slist { - char *data; - struct curl_slist *next; -}; - -/* - * NAME curl_slist_append() - * - * DESCRIPTION - * - * Appends a string to a linked list. If no list exists, it will be created - * first. Returns the new list, after appending. - */ -CURL_EXTERN struct curl_slist *curl_slist_append(struct curl_slist *, - const char *); - -/* - * NAME curl_slist_free_all() - * - * DESCRIPTION - * - * free a previously built curl_slist. - */ -CURL_EXTERN void curl_slist_free_all(struct curl_slist *); - -/* - * NAME curl_getdate() - * - * DESCRIPTION - * - * Returns the time, in seconds since 1 Jan 1970 of the time string given in - * the first argument. The time argument in the second parameter is unused - * and should be set to NULL. - */ -CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused); - -/* info about the certificate chain, only for OpenSSL builds. Asked - for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */ -struct curl_certinfo { - int num_of_certs; /* number of certificates with information */ - struct curl_slist **certinfo; /* for each index in this array, there's a - linked list with textual information in the - format "name: value" */ -}; - -#define CURLINFO_STRING 0x100000 -#define CURLINFO_LONG 0x200000 -#define CURLINFO_DOUBLE 0x300000 -#define CURLINFO_SLIST 0x400000 -#define CURLINFO_MASK 0x0fffff -#define CURLINFO_TYPEMASK 0xf00000 - -typedef enum { - CURLINFO_NONE, /* first, never use this */ - CURLINFO_EFFECTIVE_URL = CURLINFO_STRING + 1, - CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2, - CURLINFO_TOTAL_TIME = CURLINFO_DOUBLE + 3, - CURLINFO_NAMELOOKUP_TIME = CURLINFO_DOUBLE + 4, - CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5, - CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6, - CURLINFO_SIZE_UPLOAD = CURLINFO_DOUBLE + 7, - CURLINFO_SIZE_DOWNLOAD = CURLINFO_DOUBLE + 8, - CURLINFO_SPEED_DOWNLOAD = CURLINFO_DOUBLE + 9, - CURLINFO_SPEED_UPLOAD = CURLINFO_DOUBLE + 10, - CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11, - CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12, - CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13, - CURLINFO_FILETIME = CURLINFO_LONG + 14, - CURLINFO_CONTENT_LENGTH_DOWNLOAD = CURLINFO_DOUBLE + 15, - CURLINFO_CONTENT_LENGTH_UPLOAD = CURLINFO_DOUBLE + 16, - CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17, - CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18, - CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19, - CURLINFO_REDIRECT_COUNT = CURLINFO_LONG + 20, - CURLINFO_PRIVATE = CURLINFO_STRING + 21, - CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG + 22, - CURLINFO_HTTPAUTH_AVAIL = CURLINFO_LONG + 23, - CURLINFO_PROXYAUTH_AVAIL = CURLINFO_LONG + 24, - CURLINFO_OS_ERRNO = CURLINFO_LONG + 25, - CURLINFO_NUM_CONNECTS = CURLINFO_LONG + 26, - CURLINFO_SSL_ENGINES = CURLINFO_SLIST + 27, - CURLINFO_COOKIELIST = CURLINFO_SLIST + 28, - CURLINFO_LASTSOCKET = CURLINFO_LONG + 29, - CURLINFO_FTP_ENTRY_PATH = CURLINFO_STRING + 30, - CURLINFO_REDIRECT_URL = CURLINFO_STRING + 31, - CURLINFO_PRIMARY_IP = CURLINFO_STRING + 32, - CURLINFO_APPCONNECT_TIME = CURLINFO_DOUBLE + 33, - CURLINFO_CERTINFO = CURLINFO_SLIST + 34, - CURLINFO_CONDITION_UNMET = CURLINFO_LONG + 35, - CURLINFO_RTSP_SESSION_ID = CURLINFO_STRING + 36, - CURLINFO_RTSP_CLIENT_CSEQ = CURLINFO_LONG + 37, - CURLINFO_RTSP_SERVER_CSEQ = CURLINFO_LONG + 38, - CURLINFO_RTSP_CSEQ_RECV = CURLINFO_LONG + 39, - CURLINFO_PRIMARY_PORT = CURLINFO_LONG + 40, - CURLINFO_LOCAL_IP = CURLINFO_STRING + 41, - CURLINFO_LOCAL_PORT = CURLINFO_LONG + 42, - /* Fill in new entries below here! */ - - CURLINFO_LASTONE = 42 -} CURLINFO; - -/* CURLINFO_RESPONSE_CODE is the new name for the option previously known as - CURLINFO_HTTP_CODE */ -#define CURLINFO_HTTP_CODE CURLINFO_RESPONSE_CODE - -typedef enum { - CURLCLOSEPOLICY_NONE, /* first, never use this */ - - CURLCLOSEPOLICY_OLDEST, - CURLCLOSEPOLICY_LEAST_RECENTLY_USED, - CURLCLOSEPOLICY_LEAST_TRAFFIC, - CURLCLOSEPOLICY_SLOWEST, - CURLCLOSEPOLICY_CALLBACK, - - CURLCLOSEPOLICY_LAST /* last, never use this */ -} curl_closepolicy; - -#define CURL_GLOBAL_SSL (1<<0) -#define CURL_GLOBAL_WIN32 (1<<1) -#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32) -#define CURL_GLOBAL_NOTHING 0 -#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL - - -/***************************************************************************** - * Setup defines, protos etc for the sharing stuff. - */ - -/* Different data locks for a single share */ -typedef enum { - CURL_LOCK_DATA_NONE = 0, - /* CURL_LOCK_DATA_SHARE is used internally to say that - * the locking is just made to change the internal state of the share - * itself. - */ - CURL_LOCK_DATA_SHARE, - CURL_LOCK_DATA_COOKIE, - CURL_LOCK_DATA_DNS, - CURL_LOCK_DATA_SSL_SESSION, - CURL_LOCK_DATA_CONNECT, - CURL_LOCK_DATA_LAST -} curl_lock_data; - -/* Different lock access types */ -typedef enum { - CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */ - CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */ - CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */ - CURL_LOCK_ACCESS_LAST /* never use */ -} curl_lock_access; - -typedef void (*curl_lock_function)(CURL *handle, - curl_lock_data data, - curl_lock_access locktype, - void *userptr); -typedef void (*curl_unlock_function)(CURL *handle, - curl_lock_data data, - void *userptr); - -typedef void CURLSH; - -typedef enum { - CURLSHE_OK, /* all is fine */ - CURLSHE_BAD_OPTION, /* 1 */ - CURLSHE_IN_USE, /* 2 */ - CURLSHE_INVALID, /* 3 */ - CURLSHE_NOMEM, /* 4 out of memory */ - CURLSHE_NOT_BUILT_IN, /* 5 feature not present in lib */ - CURLSHE_LAST /* never use */ -} CURLSHcode; - -typedef enum { - CURLSHOPT_NONE, /* don't use */ - CURLSHOPT_SHARE, /* specify a data type to share */ - CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */ - CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */ - CURLSHOPT_UNLOCKFUNC, /* pass in a 'curl_unlock_function' pointer */ - CURLSHOPT_USERDATA, /* pass in a user data pointer used in the lock/unlock - callback functions */ - CURLSHOPT_LAST /* never use */ -} CURLSHoption; - -CURL_EXTERN CURLSH *curl_share_init(void); -CURL_EXTERN CURLSHcode curl_share_setopt(CURLSH *, CURLSHoption option, ...); -CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *); - -/**************************************************************************** - * Structures for querying information about the curl library at runtime. - */ - -typedef enum { - CURLVERSION_FIRST, - CURLVERSION_SECOND, - CURLVERSION_THIRD, - CURLVERSION_FOURTH, - CURLVERSION_LAST /* never actually use this */ -} CURLversion; - -/* The 'CURLVERSION_NOW' is the symbolic name meant to be used by - basically all programs ever that want to get version information. It is - meant to be a built-in version number for what kind of struct the caller - expects. If the struct ever changes, we redefine the NOW to another enum - from above. */ -#define CURLVERSION_NOW CURLVERSION_FOURTH - -typedef struct { - CURLversion age; /* age of the returned struct */ - const char *version; /* LIBCURL_VERSION */ - unsigned int version_num; /* LIBCURL_VERSION_NUM */ - const char *host; /* OS/host/cpu/machine when configured */ - int features; /* bitmask, see defines below */ - const char *ssl_version; /* human readable string */ - long ssl_version_num; /* not used anymore, always 0 */ - const char *libz_version; /* human readable string */ - /* protocols is terminated by an entry with a NULL protoname */ - const char * const *protocols; - - /* The fields below this were added in CURLVERSION_SECOND */ - const char *ares; - int ares_num; - - /* This field was added in CURLVERSION_THIRD */ - const char *libidn; - - /* These field were added in CURLVERSION_FOURTH */ - - /* Same as '_libiconv_version' if built with HAVE_ICONV */ - int iconv_ver_num; - - const char *libssh_version; /* human readable string */ - -} curl_version_info_data; - -#define CURL_VERSION_IPV6 (1<<0) /* IPv6-enabled */ -#define CURL_VERSION_KERBEROS4 (1<<1) /* kerberos auth is supported */ -#define CURL_VERSION_SSL (1<<2) /* SSL options are present */ -#define CURL_VERSION_LIBZ (1<<3) /* libz features are present */ -#define CURL_VERSION_NTLM (1<<4) /* NTLM auth is supported */ -#define CURL_VERSION_GSSNEGOTIATE (1<<5) /* Negotiate auth support */ -#define CURL_VERSION_DEBUG (1<<6) /* built with debug capabilities */ -#define CURL_VERSION_ASYNCHDNS (1<<7) /* asynchronous dns resolves */ -#define CURL_VERSION_SPNEGO (1<<8) /* SPNEGO auth */ -#define CURL_VERSION_LARGEFILE (1<<9) /* supports files bigger than 2GB */ -#define CURL_VERSION_IDN (1<<10) /* International Domain Names support */ -#define CURL_VERSION_SSPI (1<<11) /* SSPI is supported */ -#define CURL_VERSION_CONV (1<<12) /* character conversions supported */ -#define CURL_VERSION_CURLDEBUG (1<<13) /* debug memory tracking supported */ -#define CURL_VERSION_TLSAUTH_SRP (1<<14) /* TLS-SRP auth is supported */ -#define CURL_VERSION_NTLM_WB (1<<15) /* NTLM delegating to winbind helper */ - - /* - * NAME curl_version_info() - * - * DESCRIPTION - * - * This function returns a pointer to a static copy of the version info - * struct. See above. - */ -CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion); - -/* - * NAME curl_easy_strerror() - * - * DESCRIPTION - * - * The curl_easy_strerror function may be used to turn a CURLcode value - * into the equivalent human readable error string. This is useful - * for printing meaningful error messages. - */ -CURL_EXTERN const char *curl_easy_strerror(CURLcode); - -/* - * NAME curl_share_strerror() - * - * DESCRIPTION - * - * The curl_share_strerror function may be used to turn a CURLSHcode value - * into the equivalent human readable error string. This is useful - * for printing meaningful error messages. - */ -CURL_EXTERN const char *curl_share_strerror(CURLSHcode); - -/* - * NAME curl_easy_pause() - * - * DESCRIPTION - * - * The curl_easy_pause function pauses or unpauses transfers. Select the new - * state by setting the bitmask, use the convenience defines below. - * - */ -CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask); - -#define CURLPAUSE_RECV (1<<0) -#define CURLPAUSE_RECV_CONT (0) - -#define CURLPAUSE_SEND (1<<2) -#define CURLPAUSE_SEND_CONT (0) - -#define CURLPAUSE_ALL (CURLPAUSE_RECV|CURLPAUSE_SEND) -#define CURLPAUSE_CONT (CURLPAUSE_RECV_CONT|CURLPAUSE_SEND_CONT) - -#ifdef __cplusplus -} -#endif - -/* unfortunately, the easy.h and multi.h include files need options and info - stuff before they can be included! */ -#include "easy.h" /* nothing in curl is fun without the easy stuff */ -#include "multi.h" - -/* the typechecker doesn't work in C++ (yet) */ -#if defined(__GNUC__) && defined(__GNUC_MINOR__) && \ - ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && \ - !defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK) -#include "typecheck-gcc.h" -#else -#if defined(__STDC__) && (__STDC__ >= 1) -/* This preprocessor magic that replaces a call with the exact same call is - only done to make sure application authors pass exactly three arguments - to these functions. */ -#define curl_easy_setopt(handle,opt,param) curl_easy_setopt(handle,opt,param) -#define curl_easy_getinfo(handle,info,arg) curl_easy_getinfo(handle,info,arg) -#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param) -#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param) -#endif /* __STDC__ >= 1 */ -#endif /* gcc >= 4.3 && !__cplusplus */ - -#endif /* __CURL_CURL_H */ diff --git a/external/curl/include/linux/64-bit/curl/curlbuild.h b/external/curl/include/linux/64-bit/curl/curlbuild.h deleted file mode 100644 index 6faccb1a21..0000000000 --- a/external/curl/include/linux/64-bit/curl/curlbuild.h +++ /dev/null @@ -1,191 +0,0 @@ -/* include/curl/curlbuild.h. Generated from curlbuild.h.in by configure. */ -#ifndef __CURL_CURLBUILD_H -#define __CURL_CURLBUILD_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2011, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* ================================================================ */ -/* NOTES FOR CONFIGURE CAPABLE SYSTEMS */ -/* ================================================================ */ - -/* - * NOTE 1: - * ------- - * - * Nothing in this file is intended to be modified or adjusted by the - * curl library user nor by the curl library builder. - * - * If you think that something actually needs to be changed, adjusted - * or fixed in this file, then, report it on the libcurl development - * mailing list: http://cool.haxx.se/mailman/listinfo/curl-library/ - * - * This header file shall only export symbols which are 'curl' or 'CURL' - * prefixed, otherwise public name space would be polluted. - * - * NOTE 2: - * ------- - * - * Right now you might be staring at file include/curl/curlbuild.h.in or - * at file include/curl/curlbuild.h, this is due to the following reason: - * - * On systems capable of running the configure script, the configure process - * will overwrite the distributed include/curl/curlbuild.h file with one that - * is suitable and specific to the library being configured and built, which - * is generated from the include/curl/curlbuild.h.in template file. - * - */ - -/* ================================================================ */ -/* DEFINITION OF THESE SYMBOLS SHALL NOT TAKE PLACE ANYWHERE ELSE */ -/* ================================================================ */ - -#ifdef CURL_SIZEOF_LONG -#error "CURL_SIZEOF_LONG shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_SIZEOF_LONG_already_defined -#endif - -#ifdef CURL_TYPEOF_CURL_SOCKLEN_T -#error "CURL_TYPEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_already_defined -#endif - -#ifdef CURL_SIZEOF_CURL_SOCKLEN_T -#error "CURL_SIZEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_already_defined -#endif - -#ifdef CURL_TYPEOF_CURL_OFF_T -#error "CURL_TYPEOF_CURL_OFF_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_already_defined -#endif - -#ifdef CURL_FORMAT_CURL_OFF_T -#error "CURL_FORMAT_CURL_OFF_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_already_defined -#endif - -#ifdef CURL_FORMAT_CURL_OFF_TU -#error "CURL_FORMAT_CURL_OFF_TU shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_already_defined -#endif - -#ifdef CURL_FORMAT_OFF_T -#error "CURL_FORMAT_OFF_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_FORMAT_OFF_T_already_defined -#endif - -#ifdef CURL_SIZEOF_CURL_OFF_T -#error "CURL_SIZEOF_CURL_OFF_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_already_defined -#endif - -#ifdef CURL_SUFFIX_CURL_OFF_T -#error "CURL_SUFFIX_CURL_OFF_T shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_already_defined -#endif - -#ifdef CURL_SUFFIX_CURL_OFF_TU -#error "CURL_SUFFIX_CURL_OFF_TU shall not be defined except in curlbuild.h" - Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_already_defined -#endif - -/* ================================================================ */ -/* EXTERNAL INTERFACE SETTINGS FOR CONFIGURE CAPABLE SYSTEMS ONLY */ -/* ================================================================ */ - -/* Configure process defines this to 1 when it finds out that system */ -/* header file ws2tcpip.h must be included by the external interface. */ -/* #undef CURL_PULL_WS2TCPIP_H */ -#ifdef CURL_PULL_WS2TCPIP_H -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -# endif -# include -# include -# include -#endif - -/* Configure process defines this to 1 when it finds out that system */ -/* header file sys/types.h must be included by the external interface. */ -#define CURL_PULL_SYS_TYPES_H 1 -#ifdef CURL_PULL_SYS_TYPES_H -# include -#endif - -/* Configure process defines this to 1 when it finds out that system */ -/* header file stdint.h must be included by the external interface. */ -/* #undef CURL_PULL_STDINT_H */ -#ifdef CURL_PULL_STDINT_H -# include -#endif - -/* Configure process defines this to 1 when it finds out that system */ -/* header file inttypes.h must be included by the external interface. */ -/* #undef CURL_PULL_INTTYPES_H */ -#ifdef CURL_PULL_INTTYPES_H -# include -#endif - -/* Configure process defines this to 1 when it finds out that system */ -/* header file sys/socket.h must be included by the external interface. */ -#define CURL_PULL_SYS_SOCKET_H 1 -#ifdef CURL_PULL_SYS_SOCKET_H -# include -#endif - -/* The size of `long', as computed by sizeof. */ -#define CURL_SIZEOF_LONG 8 - -/* Integral data type used for curl_socklen_t. */ -#define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t - -/* The size of `curl_socklen_t', as computed by sizeof. */ -#define CURL_SIZEOF_CURL_SOCKLEN_T 4 - -/* Data type definition of curl_socklen_t. */ -typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t; - -/* Signed integral data type used for curl_off_t. */ -#define CURL_TYPEOF_CURL_OFF_T long - -/* Data type definition of curl_off_t. */ -typedef CURL_TYPEOF_CURL_OFF_T curl_off_t; - -/* curl_off_t formatting string directive without "%" conversion specifier. */ -#define CURL_FORMAT_CURL_OFF_T "ld" - -/* unsigned curl_off_t formatting string without "%" conversion specifier. */ -#define CURL_FORMAT_CURL_OFF_TU "lu" - -/* curl_off_t formatting string directive with "%" conversion specifier. */ -#define CURL_FORMAT_OFF_T "%ld" - -/* The size of `curl_off_t', as computed by sizeof. */ -#define CURL_SIZEOF_CURL_OFF_T 8 - -/* curl_off_t constant suffix. */ -#define CURL_SUFFIX_CURL_OFF_T L - -/* unsigned curl_off_t constant suffix. */ -#define CURL_SUFFIX_CURL_OFF_TU UL - -#endif /* __CURL_CURLBUILD_H */ diff --git a/external/curl/include/linux/64-bit/curl/curlrules.h b/external/curl/include/linux/64-bit/curl/curlrules.h deleted file mode 100644 index cbc12fdd29..0000000000 --- a/external/curl/include/linux/64-bit/curl/curlrules.h +++ /dev/null @@ -1,261 +0,0 @@ -#ifndef __CURL_CURLRULES_H -#define __CURL_CURLRULES_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2011, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* ================================================================ */ -/* COMPILE TIME SANITY CHECKS */ -/* ================================================================ */ - -/* - * NOTE 1: - * ------- - * - * All checks done in this file are intentionally placed in a public - * header file which is pulled by curl/curl.h when an application is - * being built using an already built libcurl library. Additionally - * this file is also included and used when building the library. - * - * If compilation fails on this file it is certainly sure that the - * problem is elsewhere. It could be a problem in the curlbuild.h - * header file, or simply that you are using different compilation - * settings than those used to build the library. - * - * Nothing in this file is intended to be modified or adjusted by the - * curl library user nor by the curl library builder. - * - * Do not deactivate any check, these are done to make sure that the - * library is properly built and used. - * - * You can find further help on the libcurl development mailing list: - * http://cool.haxx.se/mailman/listinfo/curl-library/ - * - * NOTE 2 - * ------ - * - * Some of the following compile time checks are based on the fact - * that the dimension of a constant array can not be a negative one. - * In this way if the compile time verification fails, the compilation - * will fail issuing an error. The error description wording is compiler - * dependent but it will be quite similar to one of the following: - * - * "negative subscript or subscript is too large" - * "array must have at least one element" - * "-1 is an illegal array size" - * "size of array is negative" - * - * If you are building an application which tries to use an already - * built libcurl library and you are getting this kind of errors on - * this file, it is a clear indication that there is a mismatch between - * how the library was built and how you are trying to use it for your - * application. Your already compiled or binary library provider is the - * only one who can give you the details you need to properly use it. - */ - -/* - * Verify that some macros are actually defined. - */ - -#ifndef CURL_SIZEOF_LONG -# error "CURL_SIZEOF_LONG definition is missing!" - Error Compilation_aborted_CURL_SIZEOF_LONG_is_missing -#endif - -#ifndef CURL_TYPEOF_CURL_SOCKLEN_T -# error "CURL_TYPEOF_CURL_SOCKLEN_T definition is missing!" - Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_is_missing -#endif - -#ifndef CURL_SIZEOF_CURL_SOCKLEN_T -# error "CURL_SIZEOF_CURL_SOCKLEN_T definition is missing!" - Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_is_missing -#endif - -#ifndef CURL_TYPEOF_CURL_OFF_T -# error "CURL_TYPEOF_CURL_OFF_T definition is missing!" - Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_is_missing -#endif - -#ifndef CURL_FORMAT_CURL_OFF_T -# error "CURL_FORMAT_CURL_OFF_T definition is missing!" - Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_is_missing -#endif - -#ifndef CURL_FORMAT_CURL_OFF_TU -# error "CURL_FORMAT_CURL_OFF_TU definition is missing!" - Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_is_missing -#endif - -#ifndef CURL_FORMAT_OFF_T -# error "CURL_FORMAT_OFF_T definition is missing!" - Error Compilation_aborted_CURL_FORMAT_OFF_T_is_missing -#endif - -#ifndef CURL_SIZEOF_CURL_OFF_T -# error "CURL_SIZEOF_CURL_OFF_T definition is missing!" - Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_is_missing -#endif - -#ifndef CURL_SUFFIX_CURL_OFF_T -# error "CURL_SUFFIX_CURL_OFF_T definition is missing!" - Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_is_missing -#endif - -#ifndef CURL_SUFFIX_CURL_OFF_TU -# error "CURL_SUFFIX_CURL_OFF_TU definition is missing!" - Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_is_missing -#endif - -/* - * Macros private to this header file. - */ - -#define CurlchkszEQ(t, s) sizeof(t) == s ? 1 : -1 - -#define CurlchkszGE(t1, t2) sizeof(t1) >= sizeof(t2) ? 1 : -1 - -/* - * Verify that the size previously defined and expected for long - * is the same as the one reported by sizeof() at compile time. - */ - -typedef char - __curl_rule_01__ - [CurlchkszEQ(long, CURL_SIZEOF_LONG)]; - -/* - * Verify that the size previously defined and expected for - * curl_off_t is actually the the same as the one reported - * by sizeof() at compile time. - */ - -typedef char - __curl_rule_02__ - [CurlchkszEQ(curl_off_t, CURL_SIZEOF_CURL_OFF_T)]; - -/* - * Verify at compile time that the size of curl_off_t as reported - * by sizeof() is greater or equal than the one reported for long - * for the current compilation. - */ - -typedef char - __curl_rule_03__ - [CurlchkszGE(curl_off_t, long)]; - -/* - * Verify that the size previously defined and expected for - * curl_socklen_t is actually the the same as the one reported - * by sizeof() at compile time. - */ - -typedef char - __curl_rule_04__ - [CurlchkszEQ(curl_socklen_t, CURL_SIZEOF_CURL_SOCKLEN_T)]; - -/* - * Verify at compile time that the size of curl_socklen_t as reported - * by sizeof() is greater or equal than the one reported for int for - * the current compilation. - */ - -typedef char - __curl_rule_05__ - [CurlchkszGE(curl_socklen_t, int)]; - -/* ================================================================ */ -/* EXTERNALLY AND INTERNALLY VISIBLE DEFINITIONS */ -/* ================================================================ */ - -/* - * CURL_ISOCPP and CURL_OFF_T_C definitions are done here in order to allow - * these to be visible and exported by the external libcurl interface API, - * while also making them visible to the library internals, simply including - * setup.h, without actually needing to include curl.h internally. - * If some day this section would grow big enough, all this should be moved - * to its own header file. - */ - -/* - * Figure out if we can use the ## preprocessor operator, which is supported - * by ISO/ANSI C and C++. Some compilers support it without setting __STDC__ - * or __cplusplus so we need to carefully check for them too. - */ - -#if defined(__STDC__) || defined(_MSC_VER) || defined(__cplusplus) || \ - defined(__HP_aCC) || defined(__BORLANDC__) || defined(__LCC__) || \ - defined(__POCC__) || defined(__SALFORDC__) || defined(__HIGHC__) || \ - defined(__ILEC400__) - /* This compiler is believed to have an ISO compatible preprocessor */ -#define CURL_ISOCPP -#else - /* This compiler is believed NOT to have an ISO compatible preprocessor */ -#undef CURL_ISOCPP -#endif - -/* - * Macros for minimum-width signed and unsigned curl_off_t integer constants. - */ - -#if defined(__BORLANDC__) && (__BORLANDC__ == 0x0551) -# define __CURL_OFF_T_C_HLPR2(x) x -# define __CURL_OFF_T_C_HLPR1(x) __CURL_OFF_T_C_HLPR2(x) -# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \ - __CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_T) -# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \ - __CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_TU) -#else -# ifdef CURL_ISOCPP -# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val ## Suffix -# else -# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val/**/Suffix -# endif -# define __CURL_OFF_T_C_HLPR1(Val,Suffix) __CURL_OFF_T_C_HLPR2(Val,Suffix) -# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_T) -# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_TU) -#endif - -/* - * Get rid of macros private to this header file. - */ - -#undef CurlchkszEQ -#undef CurlchkszGE - -/* - * Get rid of macros not intended to exist beyond this point. - */ - -#undef CURL_PULL_WS2TCPIP_H -#undef CURL_PULL_SYS_TYPES_H -#undef CURL_PULL_SYS_SOCKET_H -#undef CURL_PULL_STDINT_H -#undef CURL_PULL_INTTYPES_H - -#undef CURL_TYPEOF_CURL_SOCKLEN_T -#undef CURL_TYPEOF_CURL_OFF_T - -#ifdef CURL_NO_OLDIES -#undef CURL_FORMAT_OFF_T /* not required since 7.19.0 - obsoleted in 7.20.0 */ -#endif - -#endif /* __CURL_CURLRULES_H */ diff --git a/external/curl/include/linux/64-bit/curl/curlver.h b/external/curl/include/linux/64-bit/curl/curlver.h deleted file mode 100644 index b7e8acf538..0000000000 --- a/external/curl/include/linux/64-bit/curl/curlver.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef __CURL_CURLVER_H -#define __CURL_CURLVER_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2012, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -/* This header file contains nothing but libcurl version info, generated by - a script at release-time. This was made its own header file in 7.11.2 */ - -/* This is the global package copyright */ -#define LIBCURL_COPYRIGHT "1996 - 2012 Daniel Stenberg, ." - -/* This is the version number of the libcurl package from which this header - file origins: */ -#define LIBCURL_VERSION "7.26.0" - -/* The numeric version number is also available "in parts" by using these - defines: */ -#define LIBCURL_VERSION_MAJOR 7 -#define LIBCURL_VERSION_MINOR 26 -#define LIBCURL_VERSION_PATCH 0 - -/* This is the numeric version of the libcurl version number, meant for easier - parsing and comparions by programs. The LIBCURL_VERSION_NUM define will - always follow this syntax: - - 0xXXYYZZ - - Where XX, YY and ZZ are the main version, release and patch numbers in - hexadecimal (using 8 bits each). All three numbers are always represented - using two digits. 1.2 would appear as "0x010200" while version 9.11.7 - appears as "0x090b07". - - This 6-digit (24 bits) hexadecimal number does not show pre-release number, - and it is always a greater number in a more recent release. It makes - comparisons with greater than and less than work. -*/ -#define LIBCURL_VERSION_NUM 0x071a00 - -/* - * This is the date and time when the full source package was created. The - * timestamp is not stored in git, as the timestamp is properly set in the - * tarballs by the maketgz script. - * - * The format of the date should follow this template: - * - * "Mon Feb 12 11:35:33 UTC 2007" - */ -#define LIBCURL_TIMESTAMP "Thu May 24 16:05:42 UTC 2012" - -#endif /* __CURL_CURLVER_H */ diff --git a/external/curl/include/linux/64-bit/curl/easy.h b/external/curl/include/linux/64-bit/curl/easy.h deleted file mode 100644 index c1e3e76096..0000000000 --- a/external/curl/include/linux/64-bit/curl/easy.h +++ /dev/null @@ -1,102 +0,0 @@ -#ifndef __CURL_EASY_H -#define __CURL_EASY_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2008, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ -#ifdef __cplusplus -extern "C" { -#endif - -CURL_EXTERN CURL *curl_easy_init(void); -CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...); -CURL_EXTERN CURLcode curl_easy_perform(CURL *curl); -CURL_EXTERN void curl_easy_cleanup(CURL *curl); - -/* - * NAME curl_easy_getinfo() - * - * DESCRIPTION - * - * Request internal information from the curl session with this function. The - * third argument MUST be a pointer to a long, a pointer to a char * or a - * pointer to a double (as the documentation describes elsewhere). The data - * pointed to will be filled in accordingly and can be relied upon only if the - * function returns CURLE_OK. This function is intended to get used *AFTER* a - * performed transfer, all results from this function are undefined until the - * transfer is completed. - */ -CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...); - - -/* - * NAME curl_easy_duphandle() - * - * DESCRIPTION - * - * Creates a new curl session handle with the same options set for the handle - * passed in. Duplicating a handle could only be a matter of cloning data and - * options, internal state info and things like persistent connections cannot - * be transferred. It is useful in multithreaded applications when you can run - * curl_easy_duphandle() for each new thread to avoid a series of identical - * curl_easy_setopt() invokes in every thread. - */ -CURL_EXTERN CURL* curl_easy_duphandle(CURL *curl); - -/* - * NAME curl_easy_reset() - * - * DESCRIPTION - * - * Re-initializes a CURL handle to the default values. This puts back the - * handle to the same state as it was in when it was just created. - * - * It does keep: live connections, the Session ID cache, the DNS cache and the - * cookies. - */ -CURL_EXTERN void curl_easy_reset(CURL *curl); - -/* - * NAME curl_easy_recv() - * - * DESCRIPTION - * - * Receives data from the connected socket. Use after successful - * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. - */ -CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, - size_t *n); - -/* - * NAME curl_easy_send() - * - * DESCRIPTION - * - * Sends data over the connected socket. Use after successful - * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. - */ -CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer, - size_t buflen, size_t *n); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/external/curl/include/linux/64-bit/curl/mprintf.h b/external/curl/include/linux/64-bit/curl/mprintf.h deleted file mode 100644 index de7dd2f3c3..0000000000 --- a/external/curl/include/linux/64-bit/curl/mprintf.h +++ /dev/null @@ -1,81 +0,0 @@ -#ifndef __CURL_MPRINTF_H -#define __CURL_MPRINTF_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2006, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -#include -#include /* needed for FILE */ - -#include "curl.h" - -#ifdef __cplusplus -extern "C" { -#endif - -CURL_EXTERN int curl_mprintf(const char *format, ...); -CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...); -CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...); -CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength, - const char *format, ...); -CURL_EXTERN int curl_mvprintf(const char *format, va_list args); -CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args); -CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args); -CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength, - const char *format, va_list args); -CURL_EXTERN char *curl_maprintf(const char *format, ...); -CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args); - -#ifdef _MPRINTF_REPLACE -# undef printf -# undef fprintf -# undef sprintf -# undef vsprintf -# undef snprintf -# undef vprintf -# undef vfprintf -# undef vsnprintf -# undef aprintf -# undef vaprintf -# define printf curl_mprintf -# define fprintf curl_mfprintf -#ifdef CURLDEBUG -/* When built with CURLDEBUG we define away the sprintf() functions since we - don't want internal code to be using them */ -# define sprintf sprintf_was_used -# define vsprintf vsprintf_was_used -#else -# define sprintf curl_msprintf -# define vsprintf curl_mvsprintf -#endif -# define snprintf curl_msnprintf -# define vprintf curl_mvprintf -# define vfprintf curl_mvfprintf -# define vsnprintf curl_mvsnprintf -# define aprintf curl_maprintf -# define vaprintf curl_mvaprintf -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* __CURL_MPRINTF_H */ diff --git a/external/curl/include/linux/64-bit/curl/multi.h b/external/curl/include/linux/64-bit/curl/multi.h deleted file mode 100644 index f96566669c..0000000000 --- a/external/curl/include/linux/64-bit/curl/multi.h +++ /dev/null @@ -1,345 +0,0 @@ -#ifndef __CURL_MULTI_H -#define __CURL_MULTI_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2007, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ -/* - This is an "external" header file. Don't give away any internals here! - - GOALS - - o Enable a "pull" interface. The application that uses libcurl decides where - and when to ask libcurl to get/send data. - - o Enable multiple simultaneous transfers in the same thread without making it - complicated for the application. - - o Enable the application to select() on its own file descriptors and curl's - file descriptors simultaneous easily. - -*/ - -/* - * This header file should not really need to include "curl.h" since curl.h - * itself includes this file and we expect user applications to do #include - * without the need for especially including multi.h. - * - * For some reason we added this include here at one point, and rather than to - * break existing (wrongly written) libcurl applications, we leave it as-is - * but with this warning attached. - */ -#include "curl.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void CURLM; - -typedef enum { - CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or - curl_multi_socket*() soon */ - CURLM_OK, - CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */ - CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */ - CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */ - CURLM_INTERNAL_ERROR, /* this is a libcurl bug */ - CURLM_BAD_SOCKET, /* the passed in socket argument did not match */ - CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */ - CURLM_LAST -} CURLMcode; - -/* just to make code nicer when using curl_multi_socket() you can now check - for CURLM_CALL_MULTI_SOCKET too in the same style it works for - curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */ -#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM - -typedef enum { - CURLMSG_NONE, /* first, not used */ - CURLMSG_DONE, /* This easy handle has completed. 'result' contains - the CURLcode of the transfer */ - CURLMSG_LAST /* last, not used */ -} CURLMSG; - -struct CURLMsg { - CURLMSG msg; /* what this message means */ - CURL *easy_handle; /* the handle it concerns */ - union { - void *whatever; /* message-specific data */ - CURLcode result; /* return code for transfer */ - } data; -}; -typedef struct CURLMsg CURLMsg; - -/* - * Name: curl_multi_init() - * - * Desc: inititalize multi-style curl usage - * - * Returns: a new CURLM handle to use in all 'curl_multi' functions. - */ -CURL_EXTERN CURLM *curl_multi_init(void); - -/* - * Name: curl_multi_add_handle() - * - * Desc: add a standard curl handle to the multi stack - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *multi_handle, - CURL *curl_handle); - - /* - * Name: curl_multi_remove_handle() - * - * Desc: removes a curl handle from the multi stack again - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *multi_handle, - CURL *curl_handle); - - /* - * Name: curl_multi_fdset() - * - * Desc: Ask curl for its fd_set sets. The app can use these to select() or - * poll() on. We want curl_multi_perform() called as soon as one of - * them are ready. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *multi_handle, - fd_set *read_fd_set, - fd_set *write_fd_set, - fd_set *exc_fd_set, - int *max_fd); - - /* - * Name: curl_multi_perform() - * - * Desc: When the app thinks there's data available for curl it calls this - * function to read/write whatever there is right now. This returns - * as soon as the reads and writes are done. This function does not - * require that there actually is data available for reading or that - * data can be written, it can be called just in case. It returns - * the number of handles that still transfer data in the second - * argument's integer-pointer. - * - * Returns: CURLMcode type, general multi error code. *NOTE* that this only - * returns errors etc regarding the whole multi stack. There might - * still have occurred problems on invidual transfers even when this - * returns OK. - */ -CURL_EXTERN CURLMcode curl_multi_perform(CURLM *multi_handle, - int *running_handles); - - /* - * Name: curl_multi_cleanup() - * - * Desc: Cleans up and removes a whole multi stack. It does not free or - * touch any individual easy handles in any way. We need to define - * in what state those handles will be if this function is called - * in the middle of a transfer. - * - * Returns: CURLMcode type, general multi error code. - */ -CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle); - -/* - * Name: curl_multi_info_read() - * - * Desc: Ask the multi handle if there's any messages/informationals from - * the individual transfers. Messages include informationals such as - * error code from the transfer or just the fact that a transfer is - * completed. More details on these should be written down as well. - * - * Repeated calls to this function will return a new struct each - * time, until a special "end of msgs" struct is returned as a signal - * that there is no more to get at this point. - * - * The data the returned pointer points to will not survive calling - * curl_multi_cleanup(). - * - * The 'CURLMsg' struct is meant to be very simple and only contain - * very basic informations. If more involved information is wanted, - * we will provide the particular "transfer handle" in that struct - * and that should/could/would be used in subsequent - * curl_easy_getinfo() calls (or similar). The point being that we - * must never expose complex structs to applications, as then we'll - * undoubtably get backwards compatibility problems in the future. - * - * Returns: A pointer to a filled-in struct, or NULL if it failed or ran out - * of structs. It also writes the number of messages left in the - * queue (after this read) in the integer the second argument points - * to. - */ -CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle, - int *msgs_in_queue); - -/* - * Name: curl_multi_strerror() - * - * Desc: The curl_multi_strerror function may be used to turn a CURLMcode - * value into the equivalent human readable error string. This is - * useful for printing meaningful error messages. - * - * Returns: A pointer to a zero-terminated error message. - */ -CURL_EXTERN const char *curl_multi_strerror(CURLMcode); - -/* - * Name: curl_multi_socket() and - * curl_multi_socket_all() - * - * Desc: An alternative version of curl_multi_perform() that allows the - * application to pass in one of the file descriptors that have been - * detected to have "action" on them and let libcurl perform. - * See man page for details. - */ -#define CURL_POLL_NONE 0 -#define CURL_POLL_IN 1 -#define CURL_POLL_OUT 2 -#define CURL_POLL_INOUT 3 -#define CURL_POLL_REMOVE 4 - -#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD - -#define CURL_CSELECT_IN 0x01 -#define CURL_CSELECT_OUT 0x02 -#define CURL_CSELECT_ERR 0x04 - -typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */ - curl_socket_t s, /* socket */ - int what, /* see above */ - void *userp, /* private callback - pointer */ - void *socketp); /* private socket - pointer */ -/* - * Name: curl_multi_timer_callback - * - * Desc: Called by libcurl whenever the library detects a change in the - * maximum number of milliseconds the app is allowed to wait before - * curl_multi_socket() or curl_multi_perform() must be called - * (to allow libcurl's timed events to take place). - * - * Returns: The callback should return zero. - */ -typedef int (*curl_multi_timer_callback)(CURLM *multi, /* multi handle */ - long timeout_ms, /* see above */ - void *userp); /* private callback - pointer */ - -CURL_EXTERN CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s, - int *running_handles); - -CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *multi_handle, - curl_socket_t s, - int ev_bitmask, - int *running_handles); - -CURL_EXTERN CURLMcode curl_multi_socket_all(CURLM *multi_handle, - int *running_handles); - -#ifndef CURL_ALLOW_OLD_MULTI_SOCKET -/* This macro below was added in 7.16.3 to push users who recompile to use - the new curl_multi_socket_action() instead of the old curl_multi_socket() -*/ -#define curl_multi_socket(x,y,z) curl_multi_socket_action(x,y,0,z) -#endif - -/* - * Name: curl_multi_timeout() - * - * Desc: Returns the maximum number of milliseconds the app is allowed to - * wait before curl_multi_socket() or curl_multi_perform() must be - * called (to allow libcurl's timed events to take place). - * - * Returns: CURLM error code. - */ -CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *multi_handle, - long *milliseconds); - -#undef CINIT /* re-using the same name as in curl.h */ - -#ifdef CURL_ISOCPP -#define CINIT(name,type,num) CURLMOPT_ ## name = CURLOPTTYPE_ ## type + num -#else -/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */ -#define LONG CURLOPTTYPE_LONG -#define OBJECTPOINT CURLOPTTYPE_OBJECTPOINT -#define FUNCTIONPOINT CURLOPTTYPE_FUNCTIONPOINT -#define OFF_T CURLOPTTYPE_OFF_T -#define CINIT(name,type,number) CURLMOPT_/**/name = type + number -#endif - -typedef enum { - /* This is the socket callback function pointer */ - CINIT(SOCKETFUNCTION, FUNCTIONPOINT, 1), - - /* This is the argument passed to the socket callback */ - CINIT(SOCKETDATA, OBJECTPOINT, 2), - - /* set to 1 to enable pipelining for this multi handle */ - CINIT(PIPELINING, LONG, 3), - - /* This is the timer callback function pointer */ - CINIT(TIMERFUNCTION, FUNCTIONPOINT, 4), - - /* This is the argument passed to the timer callback */ - CINIT(TIMERDATA, OBJECTPOINT, 5), - - /* maximum number of entries in the connection cache */ - CINIT(MAXCONNECTS, LONG, 6), - - CURLMOPT_LASTENTRY /* the last unused */ -} CURLMoption; - - -/* - * Name: curl_multi_setopt() - * - * Desc: Sets options for the multi handle. - * - * Returns: CURLM error code. - */ -CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle, - CURLMoption option, ...); - - -/* - * Name: curl_multi_assign() - * - * Desc: This function sets an association in the multi handle between the - * given socket and a private pointer of the application. This is - * (only) useful for curl_multi_socket uses. - * - * Returns: CURLM error code. - */ -CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle, - curl_socket_t sockfd, void *sockp); - -#ifdef __cplusplus -} /* end of extern "C" */ -#endif - -#endif diff --git a/external/curl/include/linux/64-bit/curl/stdcheaders.h b/external/curl/include/linux/64-bit/curl/stdcheaders.h deleted file mode 100644 index ad82ef6335..0000000000 --- a/external/curl/include/linux/64-bit/curl/stdcheaders.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef __STDC_HEADERS_H -#define __STDC_HEADERS_H -/*************************************************************************** - * _ _ ____ _ - * Project ___| | | | _ \| | - * / __| | | | |_) | | - * | (__| |_| | _ <| |___ - * \___|\___/|_| \_\_____| - * - * Copyright (C) 1998 - 2010, Daniel Stenberg, , et al. - * - * This software is licensed as described in the file COPYING, which - * you should have received as part of this distribution. The terms - * are also available at http://curl.haxx.se/docs/copyright.html. - * - * You may opt to use, copy, modify, merge, publish, distribute and/or sell - * copies of the Software, and permit persons to whom the Software is - * furnished to do so, under the terms of the COPYING file. - * - * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY - * KIND, either express or implied. - * - ***************************************************************************/ - -#include - -size_t fread (void *, size_t, size_t, FILE *); -size_t fwrite (const void *, size_t, size_t, FILE *); - -int strcasecmp(const char *, const char *); -int strncasecmp(const char *, const char *, size_t); - -#endif /* __STDC_HEADERS_H */ diff --git a/external/curl/prebuilt/linux/32-bit/libcurl.a.REMOVED.git-id b/external/curl/prebuilt/linux/32-bit/libcurl.a.REMOVED.git-id deleted file mode 100644 index c819edaa0a..0000000000 --- a/external/curl/prebuilt/linux/32-bit/libcurl.a.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -b4d7f374257b051c9241d6ef7fbc80bf6966ad3a \ No newline at end of file diff --git a/external/curl/prebuilt/linux/64-bit/libcurl.a.REMOVED.git-id b/external/curl/prebuilt/linux/64-bit/libcurl.a.REMOVED.git-id deleted file mode 100644 index fb8cc8b545..0000000000 --- a/external/curl/prebuilt/linux/64-bit/libcurl.a.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -62d3069171e474ac720640f58c31cac4d312a2c9 \ No newline at end of file diff --git a/external/glfw3/include/linux/glfw3.h b/external/glfw3/include/linux/glfw3.h deleted file mode 100644 index c54abde849..0000000000 --- a/external/glfw3/include/linux/glfw3.h +++ /dev/null @@ -1,2269 +0,0 @@ -/************************************************************************* - * GLFW - An OpenGL library - * API version: 3.0 - * WWW: http://www.glfw.org/ - *------------------------------------------------------------------------ - * Copyright (c) 2002-2006 Marcus Geelnard - * Copyright (c) 2006-2010 Camilla Berglund - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would - * be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and must not - * be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - *************************************************************************/ - -#ifndef _glfw3_h_ -#define _glfw3_h_ - -#ifdef __cplusplus -extern "C" { -#endif - - -/************************************************************************* - * Doxygen documentation - *************************************************************************/ - -/*! @defgroup clipboard Clipboard support - */ -/*! @defgroup context Context handling - */ -/*! @defgroup error Error handling - */ -/*! @defgroup gamma Gamma ramp support - */ -/*! @defgroup init Initialization and version information - */ -/*! @defgroup input Input handling - */ -/*! @defgroup monitor Monitor handling - */ -/*! @defgroup time Time input - */ -/*! @defgroup window Window handling - * - * This is the reference documentation for the window handling API, including - * creation, deletion and event polling. For more information, see the - * [article on window handling](@ref window). - */ - - -/************************************************************************* - * Global definitions - *************************************************************************/ - -/* ------------------- BEGIN SYSTEM/COMPILER SPECIFIC -------------------- */ - -/* Please report any problems that you find with your compiler, which may - * be solved in this section! There are several compilers that I have not - * been able to test this file with yet. - * - * First: If we are we on Windows, we want a single define for it (_WIN32) - * (Note: For Cygwin the compiler flag -mwin32 should be used, but to - * make sure that things run smoothly for Cygwin users, we add __CYGWIN__ - * to the list of "valid Win32 identifiers", which removes the need for - * -mwin32) - */ -#if !defined(_WIN32) && (defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__)) - #define _WIN32 -#endif /* _WIN32 */ - -/* In order for extension support to be portable, we need to define an - * OpenGL function call method. We use the keyword APIENTRY, which is - * defined for Win32. (Note: Windows also needs this for ) - */ -#ifndef APIENTRY - #ifdef _WIN32 - #define APIENTRY __stdcall - #else - #define APIENTRY - #endif -#endif /* APIENTRY */ - -/* The following three defines are here solely to make some Windows-based - * files happy. Theoretically we could include , but - * it has the major drawback of severely polluting our namespace. - */ - -/* Under Windows, we need WINGDIAPI defined */ -#if !defined(WINGDIAPI) && defined(_WIN32) - #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__POCC__) - /* Microsoft Visual C++, Borland C++ Builder and Pelles C */ - #define WINGDIAPI __declspec(dllimport) - #elif defined(__LCC__) - /* LCC-Win32 */ - #define WINGDIAPI __stdcall - #else - /* Others (e.g. MinGW, Cygwin) */ - #define WINGDIAPI extern - #endif - #define GLFW_WINGDIAPI_DEFINED -#endif /* WINGDIAPI */ - -/* Some files also need CALLBACK defined */ -#if !defined(CALLBACK) && defined(_WIN32) - #if defined(_MSC_VER) - /* Microsoft Visual C++ */ - #if (defined(_M_MRX000) || defined(_M_IX86) || defined(_M_ALPHA) || defined(_M_PPC)) && !defined(MIDL_PASS) - #define CALLBACK __stdcall - #else - #define CALLBACK - #endif - #else - /* Other Windows compilers */ - #define CALLBACK __stdcall - #endif - #define GLFW_CALLBACK_DEFINED -#endif /* CALLBACK */ - -/* Most variants on Windows need wchar_t */ -#if defined(_WIN32) - #include -#endif - - -/* ---------------- GLFW related system specific defines ----------------- */ - -#if defined(GLFW_DLL) && defined(_GLFW_BUILD_DLL) - #error "You must not have both GLFW_DLL and _GLFW_BUILD_DLL defined" -#endif - -#if defined(_WIN32) && defined(_GLFW_BUILD_DLL) - - /* We are building a Win32 DLL */ - #define GLFWAPI __declspec(dllexport) - -#elif defined(_WIN32) && defined(GLFW_DLL) - - /* We are calling a Win32 DLL */ - #if defined(__LCC__) - #define GLFWAPI extern - #else - #define GLFWAPI __declspec(dllimport) - #endif - -#elif defined(__GNUC__) && defined(_GLFW_BUILD_DLL) - - #define GLFWAPI __attribute__((visibility("default"))) - -#else - - /* We are either building/calling a static lib or we are non-win32 */ - #define GLFWAPI - -#endif - -/* -------------------- END SYSTEM/COMPILER SPECIFIC --------------------- */ - -/* Include the chosen client API headers. - */ -#if defined(__APPLE_CC__) - #if defined(GLFW_INCLUDE_GLCOREARB) - #include - #elif !defined(GLFW_INCLUDE_NONE) - #define GL_GLEXT_LEGACY - #include - #endif - #if defined(GLFW_INCLUDE_GLU) - #include - #endif -#else - #if defined(GLFW_INCLUDE_GLCOREARB) - #include - #elif defined(GLFW_INCLUDE_ES1) - #include - #elif defined(GLFW_INCLUDE_ES2) - #include - #elif defined(GLFW_INCLUDE_ES3) - #include - #elif !defined(GLFW_INCLUDE_NONE) - #include - #endif - #if defined(GLFW_INCLUDE_GLU) - #include - #endif -#endif - - -/************************************************************************* - * GLFW API tokens - *************************************************************************/ - -/*! @name GLFW version macros - * @{ */ -/*! @brief The major version number of the GLFW library. - * - * This is incremented when the API is changed in non-compatible ways. - * @ingroup init - */ -#define GLFW_VERSION_MAJOR 3 -/*! @brief The minor version number of the GLFW library. - * - * This is incremented when features are added to the API but it remains - * backward-compatible. - * @ingroup init - */ -#define GLFW_VERSION_MINOR 0 -/*! @brief The revision number of the GLFW library. - * - * This is incremented when a bug fix release is made that does not contain any - * API changes. - * @ingroup init - */ -#define GLFW_VERSION_REVISION 1 -/*! @} */ - -/*! @name Key and button actions - * @{ */ -/*! @brief The key or button was released. - * @ingroup input - */ -#define GLFW_RELEASE 0 -/*! @brief The key or button was pressed. - * @ingroup input - */ -#define GLFW_PRESS 1 -/*! @brief The key was held down until it repeated. - * @ingroup input - */ -#define GLFW_REPEAT 2 -/*! @} */ - -/*! @defgroup keys Keyboard keys - * - * These key codes are inspired by the *USB HID Usage Tables v1.12* (p. 53-60), - * but re-arranged to map to 7-bit ASCII for printable keys (function keys are - * put in the 256+ range). - * - * The naming of the key codes follow these rules: - * - The US keyboard layout is used - * - Names of printable alpha-numeric characters are used (e.g. "A", "R", - * "3", etc.) - * - For non-alphanumeric characters, Unicode:ish names are used (e.g. - * "COMMA", "LEFT_SQUARE_BRACKET", etc.). Note that some names do not - * correspond to the Unicode standard (usually for brevity) - * - Keys that lack a clear US mapping are named "WORLD_x" - * - For non-printable keys, custom names are used (e.g. "F4", - * "BACKSPACE", etc.) - * - * @ingroup input - * @{ - */ - -/* The unknown key */ -#define GLFW_KEY_UNKNOWN -1 - -/* Printable keys */ -#define GLFW_KEY_SPACE 32 -#define GLFW_KEY_APOSTROPHE 39 /* ' */ -#define GLFW_KEY_COMMA 44 /* , */ -#define GLFW_KEY_MINUS 45 /* - */ -#define GLFW_KEY_PERIOD 46 /* . */ -#define GLFW_KEY_SLASH 47 /* / */ -#define GLFW_KEY_0 48 -#define GLFW_KEY_1 49 -#define GLFW_KEY_2 50 -#define GLFW_KEY_3 51 -#define GLFW_KEY_4 52 -#define GLFW_KEY_5 53 -#define GLFW_KEY_6 54 -#define GLFW_KEY_7 55 -#define GLFW_KEY_8 56 -#define GLFW_KEY_9 57 -#define GLFW_KEY_SEMICOLON 59 /* ; */ -#define GLFW_KEY_EQUAL 61 /* = */ -#define GLFW_KEY_A 65 -#define GLFW_KEY_B 66 -#define GLFW_KEY_C 67 -#define GLFW_KEY_D 68 -#define GLFW_KEY_E 69 -#define GLFW_KEY_F 70 -#define GLFW_KEY_G 71 -#define GLFW_KEY_H 72 -#define GLFW_KEY_I 73 -#define GLFW_KEY_J 74 -#define GLFW_KEY_K 75 -#define GLFW_KEY_L 76 -#define GLFW_KEY_M 77 -#define GLFW_KEY_N 78 -#define GLFW_KEY_O 79 -#define GLFW_KEY_P 80 -#define GLFW_KEY_Q 81 -#define GLFW_KEY_R 82 -#define GLFW_KEY_S 83 -#define GLFW_KEY_T 84 -#define GLFW_KEY_U 85 -#define GLFW_KEY_V 86 -#define GLFW_KEY_W 87 -#define GLFW_KEY_X 88 -#define GLFW_KEY_Y 89 -#define GLFW_KEY_Z 90 -#define GLFW_KEY_LEFT_BRACKET 91 /* [ */ -#define GLFW_KEY_BACKSLASH 92 /* \ */ -#define GLFW_KEY_RIGHT_BRACKET 93 /* ] */ -#define GLFW_KEY_GRAVE_ACCENT 96 /* ` */ -#define GLFW_KEY_WORLD_1 161 /* non-US #1 */ -#define GLFW_KEY_WORLD_2 162 /* non-US #2 */ - -/* Function keys */ -#define GLFW_KEY_ESCAPE 256 -#define GLFW_KEY_ENTER 257 -#define GLFW_KEY_TAB 258 -#define GLFW_KEY_BACKSPACE 259 -#define GLFW_KEY_INSERT 260 -#define GLFW_KEY_DELETE 261 -#define GLFW_KEY_RIGHT 262 -#define GLFW_KEY_LEFT 263 -#define GLFW_KEY_DOWN 264 -#define GLFW_KEY_UP 265 -#define GLFW_KEY_PAGE_UP 266 -#define GLFW_KEY_PAGE_DOWN 267 -#define GLFW_KEY_HOME 268 -#define GLFW_KEY_END 269 -#define GLFW_KEY_CAPS_LOCK 280 -#define GLFW_KEY_SCROLL_LOCK 281 -#define GLFW_KEY_NUM_LOCK 282 -#define GLFW_KEY_PRINT_SCREEN 283 -#define GLFW_KEY_PAUSE 284 -#define GLFW_KEY_F1 290 -#define GLFW_KEY_F2 291 -#define GLFW_KEY_F3 292 -#define GLFW_KEY_F4 293 -#define GLFW_KEY_F5 294 -#define GLFW_KEY_F6 295 -#define GLFW_KEY_F7 296 -#define GLFW_KEY_F8 297 -#define GLFW_KEY_F9 298 -#define GLFW_KEY_F10 299 -#define GLFW_KEY_F11 300 -#define GLFW_KEY_F12 301 -#define GLFW_KEY_F13 302 -#define GLFW_KEY_F14 303 -#define GLFW_KEY_F15 304 -#define GLFW_KEY_F16 305 -#define GLFW_KEY_F17 306 -#define GLFW_KEY_F18 307 -#define GLFW_KEY_F19 308 -#define GLFW_KEY_F20 309 -#define GLFW_KEY_F21 310 -#define GLFW_KEY_F22 311 -#define GLFW_KEY_F23 312 -#define GLFW_KEY_F24 313 -#define GLFW_KEY_F25 314 -#define GLFW_KEY_KP_0 320 -#define GLFW_KEY_KP_1 321 -#define GLFW_KEY_KP_2 322 -#define GLFW_KEY_KP_3 323 -#define GLFW_KEY_KP_4 324 -#define GLFW_KEY_KP_5 325 -#define GLFW_KEY_KP_6 326 -#define GLFW_KEY_KP_7 327 -#define GLFW_KEY_KP_8 328 -#define GLFW_KEY_KP_9 329 -#define GLFW_KEY_KP_DECIMAL 330 -#define GLFW_KEY_KP_DIVIDE 331 -#define GLFW_KEY_KP_MULTIPLY 332 -#define GLFW_KEY_KP_SUBTRACT 333 -#define GLFW_KEY_KP_ADD 334 -#define GLFW_KEY_KP_ENTER 335 -#define GLFW_KEY_KP_EQUAL 336 -#define GLFW_KEY_LEFT_SHIFT 340 -#define GLFW_KEY_LEFT_CONTROL 341 -#define GLFW_KEY_LEFT_ALT 342 -#define GLFW_KEY_LEFT_SUPER 343 -#define GLFW_KEY_RIGHT_SHIFT 344 -#define GLFW_KEY_RIGHT_CONTROL 345 -#define GLFW_KEY_RIGHT_ALT 346 -#define GLFW_KEY_RIGHT_SUPER 347 -#define GLFW_KEY_MENU 348 -#define GLFW_KEY_LAST GLFW_KEY_MENU - -/*! @} */ - -/*! @defgroup mods Modifier key flags - * @ingroup input - * @{ */ - -/*! @brief If this bit is set one or more Shift keys were held down. - */ -#define GLFW_MOD_SHIFT 0x0001 -/*! @brief If this bit is set one or more Control keys were held down. - */ -#define GLFW_MOD_CONTROL 0x0002 -/*! @brief If this bit is set one or more Alt keys were held down. - */ -#define GLFW_MOD_ALT 0x0004 -/*! @brief If this bit is set one or more Super keys were held down. - */ -#define GLFW_MOD_SUPER 0x0008 - -/*! @} */ - -/*! @defgroup buttons Mouse buttons - * @ingroup input - * @{ */ -#define GLFW_MOUSE_BUTTON_1 0 -#define GLFW_MOUSE_BUTTON_2 1 -#define GLFW_MOUSE_BUTTON_3 2 -#define GLFW_MOUSE_BUTTON_4 3 -#define GLFW_MOUSE_BUTTON_5 4 -#define GLFW_MOUSE_BUTTON_6 5 -#define GLFW_MOUSE_BUTTON_7 6 -#define GLFW_MOUSE_BUTTON_8 7 -#define GLFW_MOUSE_BUTTON_LAST GLFW_MOUSE_BUTTON_8 -#define GLFW_MOUSE_BUTTON_LEFT GLFW_MOUSE_BUTTON_1 -#define GLFW_MOUSE_BUTTON_RIGHT GLFW_MOUSE_BUTTON_2 -#define GLFW_MOUSE_BUTTON_MIDDLE GLFW_MOUSE_BUTTON_3 -/*! @} */ - -/*! @defgroup joysticks Joysticks - * @ingroup input - * @{ */ -#define GLFW_JOYSTICK_1 0 -#define GLFW_JOYSTICK_2 1 -#define GLFW_JOYSTICK_3 2 -#define GLFW_JOYSTICK_4 3 -#define GLFW_JOYSTICK_5 4 -#define GLFW_JOYSTICK_6 5 -#define GLFW_JOYSTICK_7 6 -#define GLFW_JOYSTICK_8 7 -#define GLFW_JOYSTICK_9 8 -#define GLFW_JOYSTICK_10 9 -#define GLFW_JOYSTICK_11 10 -#define GLFW_JOYSTICK_12 11 -#define GLFW_JOYSTICK_13 12 -#define GLFW_JOYSTICK_14 13 -#define GLFW_JOYSTICK_15 14 -#define GLFW_JOYSTICK_16 15 -#define GLFW_JOYSTICK_LAST GLFW_JOYSTICK_16 -/*! @} */ - -/*! @defgroup errors Error codes - * @ingroup error - * @{ */ -/*! @brief GLFW has not been initialized. - */ -#define GLFW_NOT_INITIALIZED 0x00010001 -/*! @brief No context is current for this thread. - */ -#define GLFW_NO_CURRENT_CONTEXT 0x00010002 -/*! @brief One of the enum parameters for the function was given an invalid - * enum. - */ -#define GLFW_INVALID_ENUM 0x00010003 -/*! @brief One of the parameters for the function was given an invalid value. - */ -#define GLFW_INVALID_VALUE 0x00010004 -/*! @brief A memory allocation failed. - */ -#define GLFW_OUT_OF_MEMORY 0x00010005 -/*! @brief GLFW could not find support for the requested client API on the - * system. - */ -#define GLFW_API_UNAVAILABLE 0x00010006 -/*! @brief The requested client API version is not available. - */ -#define GLFW_VERSION_UNAVAILABLE 0x00010007 -/*! @brief A platform-specific error occurred that does not match any of the - * more specific categories. - */ -#define GLFW_PLATFORM_ERROR 0x00010008 -/*! @brief The clipboard did not contain data in the requested format. - */ -#define GLFW_FORMAT_UNAVAILABLE 0x00010009 -/*! @} */ - -#define GLFW_FOCUSED 0x00020001 -#define GLFW_ICONIFIED 0x00020002 -#define GLFW_RESIZABLE 0x00020003 -#define GLFW_VISIBLE 0x00020004 -#define GLFW_DECORATED 0x00020005 - -#define GLFW_RED_BITS 0x00021001 -#define GLFW_GREEN_BITS 0x00021002 -#define GLFW_BLUE_BITS 0x00021003 -#define GLFW_ALPHA_BITS 0x00021004 -#define GLFW_DEPTH_BITS 0x00021005 -#define GLFW_STENCIL_BITS 0x00021006 -#define GLFW_ACCUM_RED_BITS 0x00021007 -#define GLFW_ACCUM_GREEN_BITS 0x00021008 -#define GLFW_ACCUM_BLUE_BITS 0x00021009 -#define GLFW_ACCUM_ALPHA_BITS 0x0002100A -#define GLFW_AUX_BUFFERS 0x0002100B -#define GLFW_STEREO 0x0002100C -#define GLFW_SAMPLES 0x0002100D -#define GLFW_SRGB_CAPABLE 0x0002100E -#define GLFW_REFRESH_RATE 0x0002100F - -#define GLFW_CLIENT_API 0x00022001 -#define GLFW_CONTEXT_VERSION_MAJOR 0x00022002 -#define GLFW_CONTEXT_VERSION_MINOR 0x00022003 -#define GLFW_CONTEXT_REVISION 0x00022004 -#define GLFW_CONTEXT_ROBUSTNESS 0x00022005 -#define GLFW_OPENGL_FORWARD_COMPAT 0x00022006 -#define GLFW_OPENGL_DEBUG_CONTEXT 0x00022007 -#define GLFW_OPENGL_PROFILE 0x00022008 - -#define GLFW_OPENGL_API 0x00030001 -#define GLFW_OPENGL_ES_API 0x00030002 - -#define GLFW_NO_ROBUSTNESS 0 -#define GLFW_NO_RESET_NOTIFICATION 0x00031001 -#define GLFW_LOSE_CONTEXT_ON_RESET 0x00031002 - -#define GLFW_OPENGL_ANY_PROFILE 0 -#define GLFW_OPENGL_CORE_PROFILE 0x00032001 -#define GLFW_OPENGL_COMPAT_PROFILE 0x00032002 - -#define GLFW_CURSOR 0x00033001 -#define GLFW_STICKY_KEYS 0x00033002 -#define GLFW_STICKY_MOUSE_BUTTONS 0x00033003 - -#define GLFW_CURSOR_NORMAL 0x00034001 -#define GLFW_CURSOR_HIDDEN 0x00034002 -#define GLFW_CURSOR_DISABLED 0x00034003 - -#define GLFW_CONNECTED 0x00040001 -#define GLFW_DISCONNECTED 0x00040002 - - -/************************************************************************* - * GLFW API types - *************************************************************************/ - -/*! @brief Client API function pointer type. - * - * Generic function pointer used for returning client API function pointers - * without forcing a cast from a regular pointer. - * - * @ingroup context - */ -typedef void (*GLFWglproc)(void); - -/*! @brief Opaque monitor object. - * - * Opaque monitor object. - * - * @ingroup monitor - */ -typedef struct GLFWmonitor GLFWmonitor; - -/*! @brief Opaque window object. - * - * Opaque window object. - * - * @ingroup window - */ -typedef struct GLFWwindow GLFWwindow; - -/*! @brief The function signature for error callbacks. - * - * This is the function signature for error callback functions. - * - * @param[in] error An [error code](@ref errors). - * @param[in] description A UTF-8 encoded string describing the error. - * - * @sa glfwSetErrorCallback - * - * @ingroup error - */ -typedef void (* GLFWerrorfun)(int,const char*); - -/*! @brief The function signature for window position callbacks. - * - * This is the function signature for window position callback functions. - * - * @param[in] window The window that the user moved. - * @param[in] xpos The new x-coordinate, in screen coordinates, of the - * upper-left corner of the client area of the window. - * @param[in] ypos The new y-coordinate, in screen coordinates, of the - * upper-left corner of the client area of the window. - * - * @sa glfwSetWindowPosCallback - * - * @ingroup window - */ -typedef void (* GLFWwindowposfun)(GLFWwindow*,int,int); - -/*! @brief The function signature for window resize callbacks. - * - * This is the function signature for window size callback functions. - * - * @param[in] window The window that the user resized. - * @param[in] width The new width, in screen coordinates, of the window. - * @param[in] height The new height, in screen coordinates, of the window. - * - * @sa glfwSetWindowSizeCallback - * - * @ingroup window - */ -typedef void (* GLFWwindowsizefun)(GLFWwindow*,int,int); - -/*! @brief The function signature for window close callbacks. - * - * This is the function signature for window close callback functions. - * - * @param[in] window The window that the user attempted to close. - * - * @sa glfwSetWindowCloseCallback - * - * @ingroup window - */ -typedef void (* GLFWwindowclosefun)(GLFWwindow*); - -/*! @brief The function signature for window content refresh callbacks. - * - * This is the function signature for window refresh callback functions. - * - * @param[in] window The window whose content needs to be refreshed. - * - * @sa glfwSetWindowRefreshCallback - * - * @ingroup window - */ -typedef void (* GLFWwindowrefreshfun)(GLFWwindow*); - -/*! @brief The function signature for window focus/defocus callbacks. - * - * This is the function signature for window focus callback functions. - * - * @param[in] window The window that was focused or defocused. - * @param[in] focused `GL_TRUE` if the window was focused, or `GL_FALSE` if - * it was defocused. - * - * @sa glfwSetWindowFocusCallback - * - * @ingroup window - */ -typedef void (* GLFWwindowfocusfun)(GLFWwindow*,int); - -/*! @brief The function signature for window iconify/restore callbacks. - * - * This is the function signature for window iconify/restore callback - * functions. - * - * @param[in] window The window that was iconified or restored. - * @param[in] iconified `GL_TRUE` if the window was iconified, or `GL_FALSE` - * if it was restored. - * - * @sa glfwSetWindowIconifyCallback - * - * @ingroup window - */ -typedef void (* GLFWwindowiconifyfun)(GLFWwindow*,int); - -/*! @brief The function signature for framebuffer resize callbacks. - * - * This is the function signature for framebuffer resize callback - * functions. - * - * @param[in] window The window whose framebuffer was resized. - * @param[in] width The new width, in pixels, of the framebuffer. - * @param[in] height The new height, in pixels, of the framebuffer. - * - * @sa glfwSetFramebufferSizeCallback - * - * @ingroup window - */ -typedef void (* GLFWframebuffersizefun)(GLFWwindow*,int,int); - -/*! @brief The function signature for mouse button callbacks. - * - * This is the function signature for mouse button callback functions. - * - * @param[in] window The window that received the event. - * @param[in] button The [mouse button](@ref buttons) that was pressed or - * released. - * @param[in] action One of `GLFW_PRESS` or `GLFW_RELEASE`. - * @param[in] mods Bit field describing which [modifier keys](@ref mods) were - * held down. - * - * @sa glfwSetMouseButtonCallback - * - * @ingroup input - */ -typedef void (* GLFWmousebuttonfun)(GLFWwindow*,int,int,int); - -/*! @brief The function signature for cursor position callbacks. - * - * This is the function signature for cursor position callback functions. - * - * @param[in] window The window that received the event. - * @param[in] xpos The new x-coordinate of the cursor. - * @param[in] ypos The new y-coordinate of the cursor. - * - * @sa glfwSetCursorPosCallback - * - * @ingroup input - */ -typedef void (* GLFWcursorposfun)(GLFWwindow*,double,double); - -/*! @brief The function signature for cursor enter/leave callbacks. - * - * This is the function signature for cursor enter/leave callback functions. - * - * @param[in] window The window that received the event. - * @param[in] entered `GL_TRUE` if the cursor entered the window's client - * area, or `GL_FALSE` if it left it. - * - * @sa glfwSetCursorEnterCallback - * - * @ingroup input - */ -typedef void (* GLFWcursorenterfun)(GLFWwindow*,int); - -/*! @brief The function signature for scroll callbacks. - * - * This is the function signature for scroll callback functions. - * - * @param[in] window The window that received the event. - * @param[in] xoffset The scroll offset along the x-axis. - * @param[in] yoffset The scroll offset along the y-axis. - * - * @sa glfwSetScrollCallback - * - * @ingroup input - */ -typedef void (* GLFWscrollfun)(GLFWwindow*,double,double); - -/*! @brief The function signature for keyboard key callbacks. - * - * This is the function signature for keyboard key callback functions. - * - * @param[in] window The window that received the event. - * @param[in] key The [keyboard key](@ref keys) that was pressed or released. - * @param[in] scancode The system-specific scancode of the key. - * @param[in] action @ref GLFW_PRESS, @ref GLFW_RELEASE or @ref GLFW_REPEAT. - * @param[in] mods Bit field describing which [modifier keys](@ref mods) were - * held down. - * - * @sa glfwSetKeyCallback - * - * @ingroup input - */ -typedef void (* GLFWkeyfun)(GLFWwindow*,int,int,int,int); - -/*! @brief The function signature for Unicode character callbacks. - * - * This is the function signature for Unicode character callback functions. - * - * @param[in] window The window that received the event. - * @param[in] character The Unicode code point of the character. - * - * @sa glfwSetCharCallback - * - * @ingroup input - */ -typedef void (* GLFWcharfun)(GLFWwindow*,unsigned int); - -/*! @brief The function signature for monitor configuration callbacks. - * - * This is the function signature for monitor configuration callback functions. - * - * @param[in] monitor The monitor that was connected or disconnected. - * @param[in] event One of `GLFW_CONNECTED` or `GLFW_DISCONNECTED`. - * - * @sa glfwSetMonitorCallback - * - * @ingroup monitor - */ -typedef void (* GLFWmonitorfun)(GLFWmonitor*,int); - -/*! @brief Video mode type. - * - * This describes a single video mode. - * - * @ingroup monitor - */ -typedef struct -{ - /*! The width, in screen coordinates, of the video mode. - */ - int width; - /*! The height, in screen coordinates, of the video mode. - */ - int height; - /*! The bit depth of the red channel of the video mode. - */ - int redBits; - /*! The bit depth of the green channel of the video mode. - */ - int greenBits; - /*! The bit depth of the blue channel of the video mode. - */ - int blueBits; - /*! The refresh rate, in Hz, of the video mode. - */ - int refreshRate; -} GLFWvidmode; - -/*! @brief Gamma ramp. - * - * This describes the gamma ramp for a monitor. - * - * @sa glfwGetGammaRamp glfwSetGammaRamp - * - * @ingroup gamma - */ -typedef struct -{ - /*! An array of value describing the response of the red channel. - */ - unsigned short* red; - /*! An array of value describing the response of the green channel. - */ - unsigned short* green; - /*! An array of value describing the response of the blue channel. - */ - unsigned short* blue; - /*! The number of elements in each array. - */ - unsigned int size; -} GLFWgammaramp; - - -/************************************************************************* - * GLFW API functions - *************************************************************************/ - -/*! @brief Initializes the GLFW library. - * - * This function initializes the GLFW library. Before most GLFW functions can - * be used, GLFW must be initialized, and before a program terminates GLFW - * should be terminated in order to free any resources allocated during or - * after initialization. - * - * If this function fails, it calls @ref glfwTerminate before returning. If it - * succeeds, you should call @ref glfwTerminate before the program exits. - * - * Additional calls to this function after successful initialization but before - * termination will succeed but will do nothing. - * - * @return `GL_TRUE` if successful, or `GL_FALSE` if an error occurred. - * - * @par New in GLFW 3 - * This function no longer registers @ref glfwTerminate with `atexit`. - * - * @note This function may only be called from the main thread. - * - * @note This function may take several seconds to complete on some systems, - * while on other systems it may take only a fraction of a second to complete. - * - * @note **Mac OS X:** This function will change the current directory of the - * application to the `Contents/Resources` subdirectory of the application's - * bundle, if present. - * - * @sa glfwTerminate - * - * @ingroup init - */ -GLFWAPI int glfwInit(void); - -/*! @brief Terminates the GLFW library. - * - * This function destroys all remaining windows, frees any allocated resources - * and sets the library to an uninitialized state. Once this is called, you - * must again call @ref glfwInit successfully before you will be able to use - * most GLFW functions. - * - * If GLFW has been successfully initialized, this function should be called - * before the program exits. If initialization fails, there is no need to call - * this function, as it is called by @ref glfwInit before it returns failure. - * - * @remarks This function may be called before @ref glfwInit. - * - * @note This function may only be called from the main thread. - * - * @warning No window's context may be current on another thread when this - * function is called. - * - * @sa glfwInit - * - * @ingroup init - */ -GLFWAPI void glfwTerminate(void); - -/*! @brief Retrieves the version of the GLFW library. - * - * This function retrieves the major, minor and revision numbers of the GLFW - * library. It is intended for when you are using GLFW as a shared library and - * want to ensure that you are using the minimum required version. - * - * @param[out] major Where to store the major version number, or `NULL`. - * @param[out] minor Where to store the minor version number, or `NULL`. - * @param[out] rev Where to store the revision number, or `NULL`. - * - * @remarks This function may be called before @ref glfwInit. - * - * @remarks This function may be called from any thread. - * - * @sa glfwGetVersionString - * - * @ingroup init - */ -GLFWAPI void glfwGetVersion(int* major, int* minor, int* rev); - -/*! @brief Returns a string describing the compile-time configuration. - * - * This function returns a static string generated at compile-time according to - * which configuration macros were defined. This is intended for use when - * submitting bug reports, to allow developers to see which code paths are - * enabled in a binary. - * - * The format of the string is as follows: - * - The version of GLFW - * - The name of the window system API - * - The name of the context creation API - * - Any additional options or APIs - * - * For example, when compiling GLFW 3.0 with MinGW using the Win32 and WGL - * back ends, the version string may look something like this: - * - * 3.0.0 Win32 WGL MinGW - * - * @return The GLFW version string. - * - * @remarks This function may be called before @ref glfwInit. - * - * @remarks This function may be called from any thread. - * - * @sa glfwGetVersion - * - * @ingroup init - */ -GLFWAPI const char* glfwGetVersionString(void); - -/*! @brief Sets the error callback. - * - * This function sets the error callback, which is called with an error code - * and a human-readable description each time a GLFW error occurs. - * - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @remarks This function may be called before @ref glfwInit. - * - * @note The error callback is called by the thread where the error was - * generated. If you are using GLFW from multiple threads, your error callback - * needs to be written accordingly. - * - * @note Because the description string provided to the callback may have been - * generated specifically for that error, it is not guaranteed to be valid - * after the callback has returned. If you wish to use it after that, you need - * to make your own copy of it before returning. - * - * @ingroup error - */ -GLFWAPI GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun); - -/*! @brief Returns the currently connected monitors. - * - * This function returns an array of handles for all currently connected - * monitors. - * - * @param[out] count Where to store the size of the returned array. This is - * set to zero if an error occurred. - * @return An array of monitor handles, or `NULL` if an error occurred. - * - * @note The returned array is allocated and freed by GLFW. You should not - * free it yourself. - * - * @note The returned array is valid only until the monitor configuration - * changes. See @ref glfwSetMonitorCallback to receive notifications of - * configuration changes. - * - * @sa glfwGetPrimaryMonitor - * - * @ingroup monitor - */ -GLFWAPI GLFWmonitor** glfwGetMonitors(int* count); - -/*! @brief Returns the primary monitor. - * - * This function returns the primary monitor. This is usually the monitor - * where elements like the Windows task bar or the OS X menu bar is located. - * - * @return The primary monitor, or `NULL` if an error occurred. - * - * @sa glfwGetMonitors - * - * @ingroup monitor - */ -GLFWAPI GLFWmonitor* glfwGetPrimaryMonitor(void); - -/*! @brief Returns the position of the monitor's viewport on the virtual screen. - * - * This function returns the position, in screen coordinates, of the upper-left - * corner of the specified monitor. - * - * @param[in] monitor The monitor to query. - * @param[out] xpos Where to store the monitor x-coordinate, or `NULL`. - * @param[out] ypos Where to store the monitor y-coordinate, or `NULL`. - * - * @ingroup monitor - */ -GLFWAPI void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos); - -/*! @brief Returns the physical size of the monitor. - * - * This function returns the size, in millimetres, of the display area of the - * specified monitor. - * - * @param[in] monitor The monitor to query. - * @param[out] width Where to store the width, in mm, of the monitor's display - * area, or `NULL`. - * @param[out] height Where to store the height, in mm, of the monitor's - * display area, or `NULL`. - * - * @note Some operating systems do not provide accurate information, either - * because the monitor's EDID data is incorrect, or because the driver does not - * report it accurately. - * - * @ingroup monitor - */ -GLFWAPI void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height); - -/*! @brief Returns the name of the specified monitor. - * - * This function returns a human-readable name, encoded as UTF-8, of the - * specified monitor. - * - * @param[in] monitor The monitor to query. - * @return The UTF-8 encoded name of the monitor, or `NULL` if an error - * occurred. - * - * @note The returned string is allocated and freed by GLFW. You should not - * free it yourself. - * - * @ingroup monitor - */ -GLFWAPI const char* glfwGetMonitorName(GLFWmonitor* monitor); - -/*! @brief Sets the monitor configuration callback. - * - * This function sets the monitor configuration callback, or removes the - * currently set callback. This is called when a monitor is connected to or - * disconnected from the system. - * - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @bug **X11:** This callback is not yet called on monitor configuration - * changes. - * - * @ingroup monitor - */ -GLFWAPI GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun); - -/*! @brief Returns the available video modes for the specified monitor. - * - * This function returns an array of all video modes supported by the specified - * monitor. The returned array is sorted in ascending order, first by color - * bit depth (the sum of all channel depths) and then by resolution area (the - * product of width and height). - * - * @param[in] monitor The monitor to query. - * @param[out] count Where to store the number of video modes in the returned - * array. This is set to zero if an error occurred. - * @return An array of video modes, or `NULL` if an error occurred. - * - * @note The returned array is allocated and freed by GLFW. You should not - * free it yourself. - * - * @note The returned array is valid only until this function is called again - * for the specified monitor. - * - * @sa glfwGetVideoMode - * - * @ingroup monitor - */ -GLFWAPI const GLFWvidmode* glfwGetVideoModes(GLFWmonitor* monitor, int* count); - -/*! @brief Returns the current mode of the specified monitor. - * - * This function returns the current video mode of the specified monitor. If - * you are using a full screen window, the return value will therefore depend - * on whether it is focused. - * - * @param[in] monitor The monitor to query. - * @return The current mode of the monitor, or `NULL` if an error occurred. - * - * @note The returned struct is allocated and freed by GLFW. You should not - * free it yourself. - * - * @sa glfwGetVideoModes - * - * @ingroup monitor - */ -GLFWAPI const GLFWvidmode* glfwGetVideoMode(GLFWmonitor* monitor); - -/*! @brief Generates a gamma ramp and sets it for the specified monitor. - * - * This function generates a 256-element gamma ramp from the specified exponent - * and then calls @ref glfwSetGammaRamp with it. - * - * @param[in] monitor The monitor whose gamma ramp to set. - * @param[in] gamma The desired exponent. - * - * @ingroup gamma - */ -GLFWAPI void glfwSetGamma(GLFWmonitor* monitor, float gamma); - -/*! @brief Retrieves the current gamma ramp for the specified monitor. - * - * This function retrieves the current gamma ramp of the specified monitor. - * - * @param[in] monitor The monitor to query. - * @return The current gamma ramp, or `NULL` if an error occurred. - * - * @note The value arrays of the returned ramp are allocated and freed by GLFW. - * You should not free them yourself. - * - * @ingroup gamma - */ -GLFWAPI const GLFWgammaramp* glfwGetGammaRamp(GLFWmonitor* monitor); - -/*! @brief Sets the current gamma ramp for the specified monitor. - * - * This function sets the current gamma ramp for the specified monitor. - * - * @param[in] monitor The monitor whose gamma ramp to set. - * @param[in] ramp The gamma ramp to use. - * - * @note Gamma ramp sizes other than 256 are not supported by all hardware. - * - * @ingroup gamma - */ -GLFWAPI void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp); - -/*! @brief Resets all window hints to their default values. - * - * This function resets all window hints to their - * [default values](@ref window_hints_values). - * - * @note This function may only be called from the main thread. - * - * @sa glfwWindowHint - * - * @ingroup window - */ -GLFWAPI void glfwDefaultWindowHints(void); - -/*! @brief Sets the specified window hint to the desired value. - * - * This function sets hints for the next call to @ref glfwCreateWindow. The - * hints, once set, retain their values until changed by a call to @ref - * glfwWindowHint or @ref glfwDefaultWindowHints, or until the library is - * terminated with @ref glfwTerminate. - * - * @param[in] target The [window hint](@ref window_hints) to set. - * @param[in] hint The new value of the window hint. - * - * @par New in GLFW 3 - * Hints are no longer reset to their default values on window creation. To - * set default hint values, use @ref glfwDefaultWindowHints. - * - * @note This function may only be called from the main thread. - * - * @sa glfwDefaultWindowHints - * - * @ingroup window - */ -GLFWAPI void glfwWindowHint(int target, int hint); - -/*! @brief Creates a window and its associated context. - * - * This function creates a window and its associated context. Most of the - * options controlling how the window and its context should be created are - * specified through @ref glfwWindowHint. - * - * Successful creation does not change which context is current. Before you - * can use the newly created context, you need to make it current using @ref - * glfwMakeContextCurrent. - * - * Note that the created window and context may differ from what you requested, - * as not all parameters and hints are - * [hard constraints](@ref window_hints_hard). This includes the size of the - * window, especially for full screen windows. To retrieve the actual - * attributes of the created window and context, use queries like @ref - * glfwGetWindowAttrib and @ref glfwGetWindowSize. - * - * To create the window at a specific position, make it initially invisible - * using the `GLFW_VISIBLE` window hint, set its position and then show it. - * - * If a fullscreen window is active, the screensaver is prohibited from - * starting. - * - * @param[in] width The desired width, in screen coordinates, of the window. - * This must be greater than zero. - * @param[in] height The desired height, in screen coordinates, of the window. - * This must be greater than zero. - * @param[in] title The initial, UTF-8 encoded window title. - * @param[in] monitor The monitor to use for full screen mode, or `NULL` to use - * windowed mode. - * @param[in] share The window whose context to share resources with, or `NULL` - * to not share resources. - * @return The handle of the created window, or `NULL` if an error occurred. - * - * @remarks **Windows:** If the executable has an icon resource named - * `GLFW_ICON,` it will be set as the icon for the window. If no such icon is - * present, the `IDI_WINLOGO` icon will be used instead. - * - * @remarks **Mac OS X:** The GLFW window has no icon, as it is not a document - * window, but the dock icon will be the same as the application bundle's icon. - * Also, the first time a window is opened the menu bar is populated with - * common commands like Hide, Quit and About. The (minimal) about dialog uses - * information from the application's bundle. For more information on bundles, - * see the Bundle Programming Guide provided by Apple. - * - * @note This function may only be called from the main thread. - * - * @sa glfwDestroyWindow - * - * @ingroup window - */ -GLFWAPI GLFWwindow* glfwCreateWindow(int width, int height, const char* title, GLFWmonitor* monitor, GLFWwindow* share); - -/*! @brief Destroys the specified window and its context. - * - * This function destroys the specified window and its context. On calling - * this function, no further callbacks will be called for that window. - * - * @param[in] window The window to destroy. - * - * @note This function may only be called from the main thread. - * - * @note This function may not be called from a callback. - * - * @note If the window's context is current on the main thread, it is - * detached before being destroyed. - * - * @warning The window's context must not be current on any other thread. - * - * @sa glfwCreateWindow - * - * @ingroup window - */ -GLFWAPI void glfwDestroyWindow(GLFWwindow* window); - -/*! @brief Checks the close flag of the specified window. - * - * This function returns the value of the close flag of the specified window. - * - * @param[in] window The window to query. - * @return The value of the close flag. - * - * @ingroup window - */ -GLFWAPI int glfwWindowShouldClose(GLFWwindow* window); - -/*! @brief Sets the close flag of the specified window. - * - * This function sets the value of the close flag of the specified window. - * This can be used to override the user's attempt to close the window, or - * to signal that it should be closed. - * - * @param[in] window The window whose flag to change. - * @param[in] value The new value. - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowShouldClose(GLFWwindow* window, int value); - -/*! @brief Sets the title of the specified window. - * - * This function sets the window title, encoded as UTF-8, of the specified - * window. - * - * @param[in] window The window whose title to change. - * @param[in] title The UTF-8 encoded window title. - * - * @note This function may only be called from the main thread. - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowTitle(GLFWwindow* window, const char* title); - -/*! @brief Retrieves the position of the client area of the specified window. - * - * This function retrieves the position, in screen coordinates, of the - * upper-left corner of the client area of the specified window. - * - * @param[in] window The window to query. - * @param[out] xpos Where to store the x-coordinate of the upper-left corner of - * the client area, or `NULL`. - * @param[out] ypos Where to store the y-coordinate of the upper-left corner of - * the client area, or `NULL`. - * - * @sa glfwSetWindowPos - * - * @ingroup window - */ -GLFWAPI void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos); - -/*! @brief Sets the position of the client area of the specified window. - * - * This function sets the position, in screen coordinates, of the upper-left - * corner of the client area of the window. - * - * If the specified window is a full screen window, this function does nothing. - * - * If you wish to set an initial window position you should create a hidden - * window (using @ref glfwWindowHint and `GLFW_VISIBLE`), set its position and - * then show it. - * - * @param[in] window The window to query. - * @param[in] xpos The x-coordinate of the upper-left corner of the client area. - * @param[in] ypos The y-coordinate of the upper-left corner of the client area. - * - * @note It is very rarely a good idea to move an already visible window, as it - * will confuse and annoy the user. - * - * @note This function may only be called from the main thread. - * - * @note The window manager may put limits on what positions are allowed. - * - * @bug **X11:** Some window managers ignore the set position of hidden (i.e. - * unmapped) windows, instead placing them where it thinks is appropriate once - * they are shown. - * - * @sa glfwGetWindowPos - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowPos(GLFWwindow* window, int xpos, int ypos); - -/*! @brief Retrieves the size of the client area of the specified window. - * - * This function retrieves the size, in screen coordinates, of the client area - * of the specified window. - * - * @param[in] window The window whose size to retrieve. - * @param[out] width Where to store the width, in screen coordinates, of the - * client area, or `NULL`. - * @param[out] height Where to store the height, in screen coordinates, of the - * client area, or `NULL`. - * - * @sa glfwSetWindowSize - * - * @ingroup window - */ -GLFWAPI void glfwGetWindowSize(GLFWwindow* window, int* width, int* height); - -/*! @brief Sets the size of the client area of the specified window. - * - * This function sets the size, in screen coordinates, of the client area of - * the specified window. - * - * For full screen windows, this function selects and switches to the resolution - * closest to the specified size, without affecting the window's context. As - * the context is unaffected, the bit depths of the framebuffer remain - * unchanged. - * - * @param[in] window The window to resize. - * @param[in] width The desired width of the specified window. - * @param[in] height The desired height of the specified window. - * - * @note This function may only be called from the main thread. - * - * @note The window manager may put limits on what window sizes are allowed. - * - * @sa glfwGetWindowSize - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowSize(GLFWwindow* window, int width, int height); - -/*! @brief Retrieves the size of the framebuffer of the specified window. - * - * This function retrieves the size, in pixels, of the framebuffer of the - * specified window. - * - * @param[in] window The window whose framebuffer to query. - * @param[out] width Where to store the width, in pixels, of the framebuffer, - * or `NULL`. - * @param[out] height Where to store the height, in pixels, of the framebuffer, - * or `NULL`. - * - * @sa glfwSetFramebufferSizeCallback - * - * @ingroup window - */ -GLFWAPI void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height); - -/*! @brief Iconifies the specified window. - * - * This function iconifies/minimizes the specified window, if it was previously - * restored. If it is a full screen window, the original monitor resolution is - * restored until the window is restored. If the window is already iconified, - * this function does nothing. - * - * @param[in] window The window to iconify. - * - * @note This function may only be called from the main thread. - * - * @sa glfwRestoreWindow - * - * @ingroup window - */ -GLFWAPI void glfwIconifyWindow(GLFWwindow* window); - -/*! @brief Restores the specified window. - * - * This function restores the specified window, if it was previously - * iconified/minimized. If it is a full screen window, the resolution chosen - * for the window is restored on the selected monitor. If the window is - * already restored, this function does nothing. - * - * @param[in] window The window to restore. - * - * @note This function may only be called from the main thread. - * - * @sa glfwIconifyWindow - * - * @ingroup window - */ -GLFWAPI void glfwRestoreWindow(GLFWwindow* window); - -/*! @brief Makes the specified window visible. - * - * This function makes the specified window visible, if it was previously - * hidden. If the window is already visible or is in full screen mode, this - * function does nothing. - * - * @param[in] window The window to make visible. - * - * @note This function may only be called from the main thread. - * - * @sa glfwHideWindow - * - * @ingroup window - */ -GLFWAPI void glfwShowWindow(GLFWwindow* window); - -/*! @brief Hides the specified window. - * - * This function hides the specified window, if it was previously visible. If - * the window is already hidden or is in full screen mode, this function does - * nothing. - * - * @param[in] window The window to hide. - * - * @note This function may only be called from the main thread. - * - * @sa glfwShowWindow - * - * @ingroup window - */ -GLFWAPI void glfwHideWindow(GLFWwindow* window); - -/*! @brief Returns the monitor that the window uses for full screen mode. - * - * This function returns the handle of the monitor that the specified window is - * in full screen on. - * - * @param[in] window The window to query. - * @return The monitor, or `NULL` if the window is in windowed mode. - * - * @ingroup window - */ -GLFWAPI GLFWmonitor* glfwGetWindowMonitor(GLFWwindow* window); - -/*! @brief Returns an attribute of the specified window. - * - * This function returns an attribute of the specified window. There are many - * attributes, some related to the window and others to its context. - * - * @param[in] window The window to query. - * @param[in] attrib The [window attribute](@ref window_attribs) whose value to - * return. - * @return The value of the attribute, or zero if an error occurred. - * - * @ingroup window - */ -GLFWAPI int glfwGetWindowAttrib(GLFWwindow* window, int attrib); - -/*! @brief Sets the user pointer of the specified window. - * - * This function sets the user-defined pointer of the specified window. The - * current value is retained until the window is destroyed. The initial value - * is `NULL`. - * - * @param[in] window The window whose pointer to set. - * @param[in] pointer The new value. - * - * @sa glfwGetWindowUserPointer - * - * @ingroup window - */ -GLFWAPI void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer); - -/*! @brief Returns the user pointer of the specified window. - * - * This function returns the current value of the user-defined pointer of the - * specified window. The initial value is `NULL`. - * - * @param[in] window The window whose pointer to return. - * - * @sa glfwSetWindowUserPointer - * - * @ingroup window - */ -GLFWAPI void* glfwGetWindowUserPointer(GLFWwindow* window); - -/*! @brief Sets the position callback for the specified window. - * - * This function sets the position callback of the specified window, which is - * called when the window is moved. The callback is provided with the screen - * position of the upper-left corner of the client area of the window. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup window - */ -GLFWAPI GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun); - -/*! @brief Sets the size callback for the specified window. - * - * This function sets the size callback of the specified window, which is - * called when the window is resized. The callback is provided with the size, - * in screen coordinates, of the client area of the window. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup window - */ -GLFWAPI GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun); - -/*! @brief Sets the close callback for the specified window. - * - * This function sets the close callback of the specified window, which is - * called when the user attempts to close the window, for example by clicking - * the close widget in the title bar. - * - * The close flag is set before this callback is called, but you can modify it - * at any time with @ref glfwSetWindowShouldClose. - * - * The close callback is not triggered by @ref glfwDestroyWindow. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @remarks **Mac OS X:** Selecting Quit from the application menu will - * trigger the close callback for all windows. - * - * @ingroup window - */ -GLFWAPI GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun); - -/*! @brief Sets the refresh callback for the specified window. - * - * This function sets the refresh callback of the specified window, which is - * called when the client area of the window needs to be redrawn, for example - * if the window has been exposed after having been covered by another window. - * - * On compositing window systems such as Aero, Compiz or Aqua, where the window - * contents are saved off-screen, this callback may be called only very - * infrequently or never at all. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @note On compositing window systems such as Aero, Compiz or Aqua, where the - * window contents are saved off-screen, this callback may be called only very - * infrequently or never at all. - * - * @ingroup window - */ -GLFWAPI GLFWwindowrefreshfun glfwSetWindowRefreshCallback(GLFWwindow* window, GLFWwindowrefreshfun cbfun); - -/*! @brief Sets the focus callback for the specified window. - * - * This function sets the focus callback of the specified window, which is - * called when the window gains or loses focus. - * - * After the focus callback is called for a window that lost focus, synthetic - * key and mouse button release events will be generated for all such that had - * been pressed. For more information, see @ref glfwSetKeyCallback and @ref - * glfwSetMouseButtonCallback. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup window - */ -GLFWAPI GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun cbfun); - -/*! @brief Sets the iconify callback for the specified window. - * - * This function sets the iconification callback of the specified window, which - * is called when the window is iconified or restored. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup window - */ -GLFWAPI GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, GLFWwindowiconifyfun cbfun); - -/*! @brief Sets the framebuffer resize callback for the specified window. - * - * This function sets the framebuffer resize callback of the specified window, - * which is called when the framebuffer of the specified window is resized. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup window - */ -GLFWAPI GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, GLFWframebuffersizefun cbfun); - -/*! @brief Processes all pending events. - * - * This function processes only those events that have already been received - * and then returns immediately. Processing events will cause the window and - * input callbacks associated with those events to be called. - * - * This function is not required for joystick input to work. - * - * @par New in GLFW 3 - * This function is no longer called by @ref glfwSwapBuffers. You need to call - * it or @ref glfwWaitEvents yourself. - * - * @note This function may only be called from the main thread. - * - * @note This function may not be called from a callback. - * - * @note On some platforms, certain callbacks may be called outside of a call - * to one of the event processing functions. - * - * @sa glfwWaitEvents - * - * @ingroup window - */ -GLFWAPI void glfwPollEvents(void); - -/*! @brief Waits until events are pending and processes them. - * - * This function puts the calling thread to sleep until at least one event has - * been received. Once one or more events have been recevied, it behaves as if - * @ref glfwPollEvents was called, i.e. the events are processed and the - * function then returns immediately. Processing events will cause the window - * and input callbacks associated with those events to be called. - * - * Since not all events are associated with callbacks, this function may return - * without a callback having been called even if you are monitoring all - * callbacks. - * - * This function is not required for joystick input to work. - * - * @note This function may only be called from the main thread. - * - * @note This function may not be called from a callback. - * - * @note On some platforms, certain callbacks may be called outside of a call - * to one of the event processing functions. - * - * @sa glfwPollEvents - * - * @ingroup window - */ -GLFWAPI void glfwWaitEvents(void); - -/*! @brief Returns the value of an input option for the specified window. - * - * @param[in] window The window to query. - * @param[in] mode One of `GLFW_CURSOR`, `GLFW_STICKY_KEYS` or - * `GLFW_STICKY_MOUSE_BUTTONS`. - * - * @sa glfwSetInputMode - * - * @ingroup input - */ -GLFWAPI int glfwGetInputMode(GLFWwindow* window, int mode); - -/*! @brief Sets an input option for the specified window. - * @param[in] window The window whose input mode to set. - * @param[in] mode One of `GLFW_CURSOR`, `GLFW_STICKY_KEYS` or - * `GLFW_STICKY_MOUSE_BUTTONS`. - * @param[in] value The new value of the specified input mode. - * - * If `mode` is `GLFW_CURSOR`, the value must be one of the supported input - * modes: - * - `GLFW_CURSOR_NORMAL` makes the cursor visible and behaving normally. - * - `GLFW_CURSOR_HIDDEN` makes the cursor invisible when it is over the client - * area of the window. - * - `GLFW_CURSOR_DISABLED` disables the cursor and removes any limitations on - * cursor movement. - * - * If `mode` is `GLFW_STICKY_KEYS`, the value must be either `GL_TRUE` to - * enable sticky keys, or `GL_FALSE` to disable it. If sticky keys are - * enabled, a key press will ensure that @ref glfwGetKey returns @ref - * GLFW_PRESS the next time it is called even if the key had been released - * before the call. This is useful when you are only interested in whether - * keys have been pressed but not when or in which order. - * - * If `mode` is `GLFW_STICKY_MOUSE_BUTTONS`, the value must be either `GL_TRUE` - * to enable sticky mouse buttons, or `GL_FALSE` to disable it. If sticky - * mouse buttons are enabled, a mouse button press will ensure that @ref - * glfwGetMouseButton returns @ref GLFW_PRESS the next time it is called even - * if the mouse button had been released before the call. This is useful when - * you are only interested in whether mouse buttons have been pressed but not - * when or in which order. - * - * @sa glfwGetInputMode - * - * @ingroup input - */ -GLFWAPI void glfwSetInputMode(GLFWwindow* window, int mode, int value); - -/*! @brief Returns the last reported state of a keyboard key for the specified - * window. - * - * This function returns the last state reported for the specified key to the - * specified window. The returned state is one of `GLFW_PRESS` or - * `GLFW_RELEASE`. The higher-level state `GLFW_REPEAT` is only reported to - * the key callback. - * - * If the `GLFW_STICKY_KEYS` input mode is enabled, this function returns - * `GLFW_PRESS` the first time you call this function after a key has been - * pressed, even if the key has already been released. - * - * The key functions deal with physical keys, with [key tokens](@ref keys) - * named after their use on the standard US keyboard layout. If you want to - * input text, use the Unicode character callback instead. - * - * @param[in] window The desired window. - * @param[in] key The desired [keyboard key](@ref keys). - * @return One of `GLFW_PRESS` or `GLFW_RELEASE`. - * - * @note `GLFW_KEY_UNKNOWN` is not a valid key for this function. - * - * @ingroup input - */ -GLFWAPI int glfwGetKey(GLFWwindow* window, int key); - -/*! @brief Returns the last reported state of a mouse button for the specified - * window. - * - * This function returns the last state reported for the specified mouse button - * to the specified window. - * - * If the `GLFW_STICKY_MOUSE_BUTTONS` input mode is enabled, this function - * returns `GLFW_PRESS` the first time you call this function after a mouse - * button has been pressed, even if the mouse button has already been released. - * - * @param[in] window The desired window. - * @param[in] button The desired [mouse button](@ref buttons). - * @return One of `GLFW_PRESS` or `GLFW_RELEASE`. - * - * @ingroup input - */ -GLFWAPI int glfwGetMouseButton(GLFWwindow* window, int button); - -/*! @brief Retrieves the last reported cursor position, relative to the client - * area of the window. - * - * This function returns the last reported position of the cursor to the - * specified window. - * - * If the cursor is disabled (with `GLFW_CURSOR_DISABLED`) then the cursor - * position is unbounded and limited only by the minimum and maximum values of - * a `double`. - * - * The coordinate can be converted to their integer equivalents with the - * `floor` function. Casting directly to an integer type works for positive - * coordinates, but fails for negative ones. - * - * @param[in] window The desired window. - * @param[out] xpos Where to store the cursor x-coordinate, relative to the - * left edge of the client area, or `NULL`. - * @param[out] ypos Where to store the cursor y-coordinate, relative to the to - * top edge of the client area, or `NULL`. - * - * @sa glfwSetCursorPos - * - * @ingroup input - */ -GLFWAPI void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); - -/*! @brief Sets the position of the cursor, relative to the client area of the window. - * - * This function sets the position of the cursor. The specified window must be - * focused. If the window does not have focus when this function is called, it - * fails silently. - * - * If the cursor is disabled (with `GLFW_CURSOR_DISABLED`) then the cursor - * position is unbounded and limited only by the minimum and maximum values of - * a `double`. - * - * @param[in] window The desired window. - * @param[in] xpos The desired x-coordinate, relative to the left edge of the - * client area, or `NULL`. - * @param[in] ypos The desired y-coordinate, relative to the top edge of the - * client area, or `NULL`. - * - * @sa glfwGetCursorPos - * - * @ingroup input - */ -GLFWAPI void glfwSetCursorPos(GLFWwindow* window, double xpos, double ypos); - -/*! @brief Sets the key callback. - * - * This function sets the key callback of the specific window, which is called - * when a key is pressed, repeated or released. - * - * The key functions deal with physical keys, with layout independent - * [key tokens](@ref keys) named after their values in the standard US keyboard - * layout. If you want to input text, use the - * [character callback](@ref glfwSetCharCallback) instead. - * - * When a window loses focus, it will generate synthetic key release events - * for all pressed keys. You can tell these events from user-generated events - * by the fact that the synthetic ones are generated after the window has lost - * focus, i.e. `GLFW_FOCUSED` will be false and the focus callback will have - * already been called. - * - * The scancode of a key is specific to that platform or sometimes even to that - * machine. Scancodes are intended to allow users to bind keys that don't have - * a GLFW key token. Such keys have `key` set to `GLFW_KEY_UNKNOWN`, their - * state is not saved and so it cannot be retrieved with @ref glfwGetKey. - * - * Sometimes GLFW needs to generate synthetic key events, in which case the - * scancode may be zero. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new key callback, or `NULL` to remove the currently - * set callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup input - */ -GLFWAPI GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun); - -/*! @brief Sets the Unicode character callback. - * - * This function sets the character callback of the specific window, which is - * called when a Unicode character is input. - * - * The character callback is intended for text input. If you want to know - * whether a specific key was pressed or released, use the - * [key callback](@ref glfwSetKeyCallback) instead. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup input - */ -GLFWAPI GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun cbfun); - -/*! @brief Sets the mouse button callback. - * - * This function sets the mouse button callback of the specified window, which - * is called when a mouse button is pressed or released. - * - * When a window loses focus, it will generate synthetic mouse button release - * events for all pressed mouse buttons. You can tell these events from - * user-generated events by the fact that the synthetic ones are generated - * after the window has lost focus, i.e. `GLFW_FOCUSED` will be false and the - * focus callback will have already been called. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup input - */ -GLFWAPI GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun cbfun); - -/*! @brief Sets the cursor position callback. - * - * This function sets the cursor position callback of the specified window, - * which is called when the cursor is moved. The callback is provided with the - * position relative to the upper-left corner of the client area of the window. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup input - */ -GLFWAPI GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun); - -/*! @brief Sets the cursor enter/exit callback. - * - * This function sets the cursor boundary crossing callback of the specified - * window, which is called when the cursor enters or leaves the client area of - * the window. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new callback, or `NULL` to remove the currently set - * callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup input - */ -GLFWAPI GLFWcursorenterfun glfwSetCursorEnterCallback(GLFWwindow* window, GLFWcursorenterfun cbfun); - -/*! @brief Sets the scroll callback. - * - * This function sets the scroll callback of the specified window, which is - * called when a scrolling device is used, such as a mouse wheel or scrolling - * area of a touchpad. - * - * The scroll callback receives all scrolling input, like that from a mouse - * wheel or a touchpad scrolling area. - * - * @param[in] window The window whose callback to set. - * @param[in] cbfun The new scroll callback, or `NULL` to remove the currently - * set callback. - * @return The previously set callback, or `NULL` if no callback was set or an - * error occurred. - * - * @ingroup input - */ -GLFWAPI GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun); - -/*! @brief Returns whether the specified joystick is present. - * - * This function returns whether the specified joystick is present. - * - * @param[in] joy The joystick to query. - * @return `GL_TRUE` if the joystick is present, or `GL_FALSE` otherwise. - * - * @ingroup input - */ -GLFWAPI int glfwJoystickPresent(int joy); - -/*! @brief Returns the values of all axes of the specified joystick. - * - * This function returns the values of all axes of the specified joystick. - * - * @param[in] joy The joystick to query. - * @param[out] count Where to store the size of the returned array. This is - * set to zero if an error occurred. - * @return An array of axis values, or `NULL` if the joystick is not present. - * - * @note The returned array is allocated and freed by GLFW. You should not - * free it yourself. - * - * @note The returned array is valid only until the next call to @ref - * glfwGetJoystickAxes for that joystick. - * - * @ingroup input - */ -GLFWAPI const float* glfwGetJoystickAxes(int joy, int* count); - -/*! @brief Returns the state of all buttons of the specified joystick. - * - * This function returns the state of all buttons of the specified joystick. - * - * @param[in] joy The joystick to query. - * @param[out] count Where to store the size of the returned array. This is - * set to zero if an error occurred. - * @return An array of button states, or `NULL` if the joystick is not present. - * - * @note The returned array is allocated and freed by GLFW. You should not - * free it yourself. - * - * @note The returned array is valid only until the next call to @ref - * glfwGetJoystickButtons for that joystick. - * - * @ingroup input - */ -GLFWAPI const unsigned char* glfwGetJoystickButtons(int joy, int* count); - -/*! @brief Returns the name of the specified joystick. - * - * This function returns the name, encoded as UTF-8, of the specified joystick. - * - * @param[in] joy The joystick to query. - * @return The UTF-8 encoded name of the joystick, or `NULL` if the joystick - * is not present. - * - * @note The returned string is allocated and freed by GLFW. You should not - * free it yourself. - * - * @note The returned string is valid only until the next call to @ref - * glfwGetJoystickName for that joystick. - * - * @ingroup input - */ -GLFWAPI const char* glfwGetJoystickName(int joy); - -/*! @brief Sets the clipboard to the specified string. - * - * This function sets the system clipboard to the specified, UTF-8 encoded - * string. The string is copied before returning, so you don't have to retain - * it afterwards. - * - * @param[in] window The window that will own the clipboard contents. - * @param[in] string A UTF-8 encoded string. - * - * @note This function may only be called from the main thread. - * - * @sa glfwGetClipboardString - * - * @ingroup clipboard - */ -GLFWAPI void glfwSetClipboardString(GLFWwindow* window, const char* string); - -/*! @brief Retrieves the contents of the clipboard as a string. - * - * This function returns the contents of the system clipboard, if it contains - * or is convertible to a UTF-8 encoded string. - * - * @param[in] window The window that will request the clipboard contents. - * @return The contents of the clipboard as a UTF-8 encoded string, or `NULL` - * if an error occurred. - * - * @note This function may only be called from the main thread. - * - * @note The returned string is allocated and freed by GLFW. You should not - * free it yourself. - * - * @note The returned string is valid only until the next call to @ref - * glfwGetClipboardString or @ref glfwSetClipboardString. - * - * @sa glfwSetClipboardString - * - * @ingroup clipboard - */ -GLFWAPI const char* glfwGetClipboardString(GLFWwindow* window); - -/*! @brief Returns the value of the GLFW timer. - * - * This function returns the value of the GLFW timer. Unless the timer has - * been set using @ref glfwSetTime, the timer measures time elapsed since GLFW - * was initialized. - * - * @return The current value, in seconds, or zero if an error occurred. - * - * @remarks This function may be called from secondary threads. - * - * @note The resolution of the timer is system dependent, but is usually on the - * order of a few micro- or nanoseconds. It uses the highest-resolution - * monotonic time source on each supported platform. - * - * @ingroup time - */ -GLFWAPI double glfwGetTime(void); - -/*! @brief Sets the GLFW timer. - * - * This function sets the value of the GLFW timer. It then continues to count - * up from that value. - * - * @param[in] time The new value, in seconds. - * - * @note The resolution of the timer is system dependent, but is usually on the - * order of a few micro- or nanoseconds. It uses the highest-resolution - * monotonic time source on each supported platform. - * - * @ingroup time - */ -GLFWAPI void glfwSetTime(double time); - -/*! @brief Makes the context of the specified window current for the calling - * thread. - * - * This function makes the context of the specified window current on the - * calling thread. A context can only be made current on a single thread at - * a time and each thread can have only a single current context at a time. - * - * @param[in] window The window whose context to make current, or `NULL` to - * detach the current context. - * - * @remarks This function may be called from secondary threads. - * - * @sa glfwGetCurrentContext - * - * @ingroup context - */ -GLFWAPI void glfwMakeContextCurrent(GLFWwindow* window); - -/*! @brief Returns the window whose context is current on the calling thread. - * - * This function returns the window whose context is current on the calling - * thread. - * - * @return The window whose context is current, or `NULL` if no window's - * context is current. - * - * @remarks This function may be called from secondary threads. - * - * @sa glfwMakeContextCurrent - * - * @ingroup context - */ -GLFWAPI GLFWwindow* glfwGetCurrentContext(void); - -/*! @brief Swaps the front and back buffers of the specified window. - * - * This function swaps the front and back buffers of the specified window. If - * the swap interval is greater than zero, the GPU driver waits the specified - * number of screen updates before swapping the buffers. - * - * @param[in] window The window whose buffers to swap. - * - * @remarks This function may be called from secondary threads. - * - * @par New in GLFW 3 - * This function no longer calls @ref glfwPollEvents. You need to call it or - * @ref glfwWaitEvents yourself. - * - * @sa glfwSwapInterval - * - * @ingroup context - */ -GLFWAPI void glfwSwapBuffers(GLFWwindow* window); - -/*! @brief Sets the swap interval for the current context. - * - * This function sets the swap interval for the current context, i.e. the - * number of screen updates to wait before swapping the buffers of a window and - * returning from @ref glfwSwapBuffers. This is sometimes called 'vertical - * synchronization', 'vertical retrace synchronization' or 'vsync'. - * - * Contexts that support either of the `WGL_EXT_swap_control_tear` and - * `GLX_EXT_swap_control_tear` extensions also accept negative swap intervals, - * which allow the driver to swap even if a frame arrives a little bit late. - * You can check for the presence of these extensions using @ref - * glfwExtensionSupported. For more information about swap tearing, see the - * extension specifications. - * - * @param[in] interval The minimum number of screen updates to wait for - * until the buffers are swapped by @ref glfwSwapBuffers. - * - * @remarks This function may be called from secondary threads. - * - * @note Some GPU drivers do not honor the requested swap interval, either - * because of user settings that override the request or due to bugs in the - * driver. - * - * @sa glfwSwapBuffers - * - * @ingroup context - */ -GLFWAPI void glfwSwapInterval(int interval); - -/*! @brief Returns whether the specified extension is available. - * - * This function returns whether the specified - * [OpenGL or context creation API extension](@ref context_glext) is supported - * by the current context. For example, on Windows both the OpenGL and WGL - * extension strings are checked. - * - * @param[in] extension The ASCII encoded name of the extension. - * @return `GL_TRUE` if the extension is available, or `GL_FALSE` otherwise. - * - * @remarks This function may be called from secondary threads. - * - * @note As this functions searches one or more extension strings on each call, - * it is recommended that you cache its results if it's going to be used - * frequently. The extension strings will not change during the lifetime of - * a context, so there is no danger in doing this. - * - * @ingroup context - */ -GLFWAPI int glfwExtensionSupported(const char* extension); - -/*! @brief Returns the address of the specified function for the current - * context. - * - * This function returns the address of the specified - * [client API or extension function](@ref context_glext), if it is supported - * by the current context. - * - * @param[in] procname The ASCII encoded name of the function. - * @return The address of the function, or `NULL` if the function is - * unavailable. - * - * @remarks This function may be called from secondary threads. - * - * @note The addresses of these functions are not guaranteed to be the same for - * all contexts, especially if they use different client APIs or even different - * context creation hints. - * - * @ingroup context - */ -GLFWAPI GLFWglproc glfwGetProcAddress(const char* procname); - - -/************************************************************************* - * Global definition cleanup - *************************************************************************/ - -/* ------------------- BEGIN SYSTEM/COMPILER SPECIFIC -------------------- */ - -#ifdef GLFW_WINGDIAPI_DEFINED - #undef WINGDIAPI - #undef GLFW_WINGDIAPI_DEFINED -#endif - -#ifdef GLFW_CALLBACK_DEFINED - #undef CALLBACK - #undef GLFW_CALLBACK_DEFINED -#endif - -/* -------------------- END SYSTEM/COMPILER SPECIFIC --------------------- */ - - -#ifdef __cplusplus -} -#endif - -#endif /* _glfw3_h_ */ - diff --git a/external/glfw3/include/linux/glfw3native.h b/external/glfw3/include/linux/glfw3native.h deleted file mode 100644 index 7507260621..0000000000 --- a/external/glfw3/include/linux/glfw3native.h +++ /dev/null @@ -1,181 +0,0 @@ -/************************************************************************* - * GLFW - An OpenGL library - * API version: 3.0 - * WWW: http://www.glfw.org/ - *------------------------------------------------------------------------ - * Copyright (c) 2002-2006 Marcus Geelnard - * Copyright (c) 2006-2010 Camilla Berglund - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would - * be appreciated but is not required. - * - * 2. Altered source versions must be plainly marked as such, and must not - * be misrepresented as being the original software. - * - * 3. This notice may not be removed or altered from any source - * distribution. - * - *************************************************************************/ - -#ifndef _glfw3_native_h_ -#define _glfw3_native_h_ - -#ifdef __cplusplus -extern "C" { -#endif - - -/************************************************************************* - * Doxygen documentation - *************************************************************************/ - -/*! @defgroup native Native access - * - * **By using the native API, you assert that you know what you are doing and - * how to fix problems caused by using it. If you don't, you shouldn't be - * using it.** - * - * Before the inclusion of @ref glfw3native.h, you must define exactly one - * window API macro and exactly one context API macro. Failure to do this - * will cause a compile-time error. - * - * The available window API macros are: - * * `GLFW_EXPOSE_NATIVE_WIN32` - * * `GLFW_EXPOSE_NATIVE_COCOA` - * * `GLFW_EXPOSE_NATIVE_X11` - * - * The available context API macros are: - * * `GLFW_EXPOSE_NATIVE_WGL` - * * `GLFW_EXPOSE_NATIVE_NSGL` - * * `GLFW_EXPOSE_NATIVE_GLX` - * * `GLFW_EXPOSE_NATIVE_EGL` - * - * These macros select which of the native access functions that are declared - * and which platform-specific headers to include. It is then up your (by - * definition platform-specific) code to handle which of these should be - * defined. - */ - - -/************************************************************************* - * System headers and types - *************************************************************************/ - -#if defined(GLFW_EXPOSE_NATIVE_WIN32) - #include -#elif defined(GLFW_EXPOSE_NATIVE_COCOA) - #if defined(__OBJC__) - #import - #else - typedef void* id; - #endif -#elif defined(GLFW_EXPOSE_NATIVE_X11) - #include -#else - #error "No window API specified" -#endif - -#if defined(GLFW_EXPOSE_NATIVE_WGL) - /* WGL is declared by windows.h */ -#elif defined(GLFW_EXPOSE_NATIVE_NSGL) - /* NSGL is declared by Cocoa.h */ -#elif defined(GLFW_EXPOSE_NATIVE_GLX) - #include -#elif defined(GLFW_EXPOSE_NATIVE_EGL) - #include -#else - #error "No context API specified" -#endif - - -/************************************************************************* - * Functions - *************************************************************************/ - -#if defined(GLFW_EXPOSE_NATIVE_WIN32) -/*! @brief Returns the `HWND` of the specified window. - * @return The `HWND` of the specified window. - * @ingroup native - */ -GLFWAPI HWND glfwGetWin32Window(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_WGL) -/*! @brief Returns the `HGLRC` of the specified window. - * @return The `HGLRC` of the specified window. - * @ingroup native - */ -GLFWAPI HGLRC glfwGetWGLContext(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_COCOA) -/*! @brief Returns the `NSWindow` of the specified window. - * @return The `NSWindow` of the specified window. - * @ingroup native - */ -GLFWAPI id glfwGetCocoaWindow(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_NSGL) -/*! @brief Returns the `NSOpenGLContext` of the specified window. - * @return The `NSOpenGLContext` of the specified window. - * @ingroup native - */ -GLFWAPI id glfwGetNSGLContext(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_X11) -/*! @brief Returns the `Display` used by GLFW. - * @return The `Display` used by GLFW. - * @ingroup native - */ -GLFWAPI Display* glfwGetX11Display(void); -/*! @brief Returns the `Window` of the specified window. - * @return The `Window` of the specified window. - * @ingroup native - */ -GLFWAPI Window glfwGetX11Window(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_GLX) -/*! @brief Returns the `GLXContext` of the specified window. - * @return The `GLXContext` of the specified window. - * @ingroup native - */ -GLFWAPI GLXContext glfwGetGLXContext(GLFWwindow* window); -#endif - -#if defined(GLFW_EXPOSE_NATIVE_EGL) -/*! @brief Returns the `EGLDisplay` used by GLFW. - * @return The `EGLDisplay` used by GLFW. - * @ingroup native - */ -GLFWAPI EGLDisplay glfwGetEGLDisplay(void); -/*! @brief Returns the `EGLContext` of the specified window. - * @return The `EGLContext` of the specified window. - * @ingroup native - */ -GLFWAPI EGLContext glfwGetEGLContext(GLFWwindow* window); -/*! @brief Returns the `EGLSurface` of the specified window. - * @return The `EGLSurface` of the specified window. - * @ingroup native - */ -GLFWAPI EGLSurface glfwGetEGLSurface(GLFWwindow* window); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* _glfw3_native_h_ */ - diff --git a/external/glfw3/include/mac/glfw3.h b/external/glfw3/include/mac/glfw3.h index c54abde849..0f97738c71 100644 --- a/external/glfw3/include/mac/glfw3.h +++ b/external/glfw3/include/mac/glfw3.h @@ -1,7 +1,6 @@ /************************************************************************* - * GLFW - An OpenGL library - * API version: 3.0 - * WWW: http://www.glfw.org/ + * GLFW 3.0 - www.glfw.org + * A library for OpenGL, window and input *------------------------------------------------------------------------ * Copyright (c) 2002-2006 Marcus Geelnard * Copyright (c) 2006-2010 Camilla Berglund @@ -45,21 +44,22 @@ extern "C" { */ /*! @defgroup error Error handling */ -/*! @defgroup gamma Gamma ramp support - */ /*! @defgroup init Initialization and version information */ /*! @defgroup input Input handling */ /*! @defgroup monitor Monitor handling + * + * This is the reference documentation for monitor related functions and types. + * For more information, see the @ref monitor. */ /*! @defgroup time Time input */ /*! @defgroup window Window handling * - * This is the reference documentation for the window handling API, including - * creation, deletion and event polling. For more information, see the - * [article on window handling](@ref window). + * This is the reference documentation for window related functions and types, + * including creation, deletion and event polling. For more information, see + * the @ref window. */ @@ -131,45 +131,12 @@ extern "C" { #define GLFW_CALLBACK_DEFINED #endif /* CALLBACK */ -/* Most variants on Windows need wchar_t */ -#if defined(_WIN32) +/* Most GL/glu.h variants on Windows need wchar_t + * OpenGL/gl.h blocks the definition of ptrdiff_t by glext.h on OS X */ +#if !defined(GLFW_INCLUDE_NONE) #include #endif - -/* ---------------- GLFW related system specific defines ----------------- */ - -#if defined(GLFW_DLL) && defined(_GLFW_BUILD_DLL) - #error "You must not have both GLFW_DLL and _GLFW_BUILD_DLL defined" -#endif - -#if defined(_WIN32) && defined(_GLFW_BUILD_DLL) - - /* We are building a Win32 DLL */ - #define GLFWAPI __declspec(dllexport) - -#elif defined(_WIN32) && defined(GLFW_DLL) - - /* We are calling a Win32 DLL */ - #if defined(__LCC__) - #define GLFWAPI extern - #else - #define GLFWAPI __declspec(dllimport) - #endif - -#elif defined(__GNUC__) && defined(_GLFW_BUILD_DLL) - - #define GLFWAPI __attribute__((visibility("default"))) - -#else - - /* We are either building/calling a static lib or we are non-win32 */ - #define GLFWAPI - -#endif - -/* -------------------- END SYSTEM/COMPILER SPECIFIC --------------------- */ - /* Include the chosen client API headers. */ #if defined(__APPLE_CC__) @@ -199,6 +166,41 @@ extern "C" { #endif #endif +#if defined(GLFW_DLL) && defined(_GLFW_BUILD_DLL) + /* GLFW_DLL is defined by users of GLFW when compiling programs that will link + * to the DLL version of the GLFW library. _GLFW_BUILD_DLL is defined by the + * GLFW configuration header when compiling the DLL version of the library. + */ + #error "You must not have both GLFW_DLL and _GLFW_BUILD_DLL defined" +#endif + +#if defined(_WIN32) && defined(_GLFW_BUILD_DLL) + + /* We are building a Win32 DLL */ + #define GLFWAPI __declspec(dllexport) + +#elif defined(_WIN32) && defined(GLFW_DLL) + + /* We are calling a Win32 DLL */ + #if defined(__LCC__) + #define GLFWAPI extern + #else + #define GLFWAPI __declspec(dllimport) + #endif + +#elif defined(__GNUC__) && defined(_GLFW_BUILD_DLL) + + #define GLFWAPI __attribute__((visibility("default"))) + +#else + + /* We are either building/calling a static lib or we are non-win32 */ + #define GLFWAPI + +#endif + +/* -------------------- END SYSTEM/COMPILER SPECIFIC --------------------- */ + /************************************************************************* * GLFW API tokens @@ -225,7 +227,7 @@ extern "C" { * API changes. * @ingroup init */ -#define GLFW_VERSION_REVISION 1 +#define GLFW_VERSION_REVISION 4 /*! @} */ /*! @name Key and button actions @@ -704,8 +706,8 @@ typedef void (* GLFWmousebuttonfun)(GLFWwindow*,int,int,int); * This is the function signature for cursor position callback functions. * * @param[in] window The window that received the event. - * @param[in] xpos The new x-coordinate of the cursor. - * @param[in] ypos The new y-coordinate of the cursor. + * @param[in] xpos The new x-coordinate, in screen coordinates, of the cursor. + * @param[in] ypos The new y-coordinate, in screen coordinates, of the cursor. * * @sa glfwSetCursorPosCallback * @@ -763,7 +765,7 @@ typedef void (* GLFWkeyfun)(GLFWwindow*,int,int,int,int); * This is the function signature for Unicode character callback functions. * * @param[in] window The window that received the event. - * @param[in] character The Unicode code point of the character. + * @param[in] codepoint The Unicode code point of the character. * * @sa glfwSetCharCallback * @@ -790,7 +792,7 @@ typedef void (* GLFWmonitorfun)(GLFWmonitor*,int); * * @ingroup monitor */ -typedef struct +typedef struct GLFWvidmode { /*! The width, in screen coordinates, of the video mode. */ @@ -818,9 +820,9 @@ typedef struct * * @sa glfwGetGammaRamp glfwSetGammaRamp * - * @ingroup gamma + * @ingroup monitor */ -typedef struct +typedef struct GLFWgammaramp { /*! An array of value describing the response of the red channel. */ @@ -861,10 +863,7 @@ typedef struct * * @note This function may only be called from the main thread. * - * @note This function may take several seconds to complete on some systems, - * while on other systems it may take only a fraction of a second to complete. - * - * @note **Mac OS X:** This function will change the current directory of the + * @note **OS X:** This function will change the current directory of the * application to the `Contents/Resources` subdirectory of the application's * bundle, if present. * @@ -1124,7 +1123,7 @@ GLFWAPI const GLFWvidmode* glfwGetVideoMode(GLFWmonitor* monitor); * @param[in] monitor The monitor whose gamma ramp to set. * @param[in] gamma The desired exponent. * - * @ingroup gamma + * @ingroup monitor */ GLFWAPI void glfwSetGamma(GLFWmonitor* monitor, float gamma); @@ -1138,7 +1137,7 @@ GLFWAPI void glfwSetGamma(GLFWmonitor* monitor, float gamma); * @note The value arrays of the returned ramp are allocated and freed by GLFW. * You should not free them yourself. * - * @ingroup gamma + * @ingroup monitor */ GLFWAPI const GLFWgammaramp* glfwGetGammaRamp(GLFWmonitor* monitor); @@ -1151,7 +1150,7 @@ GLFWAPI const GLFWgammaramp* glfwGetGammaRamp(GLFWmonitor* monitor); * * @note Gamma ramp sizes other than 256 are not supported by all hardware. * - * @ingroup gamma + * @ingroup monitor */ GLFWAPI void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp); @@ -1207,10 +1206,16 @@ GLFWAPI void glfwWindowHint(int target, int hint); * attributes of the created window and context, use queries like @ref * glfwGetWindowAttrib and @ref glfwGetWindowSize. * + * To create a full screen window, you need to specify the monitor to use. If + * no monitor is specified, windowed mode will be used. Unless you have a way + * for the user to choose a specific monitor, it is recommended that you pick + * the primary monitor. For more information on how to retrieve monitors, see + * @ref monitor_monitors. + * * To create the window at a specific position, make it initially invisible * using the `GLFW_VISIBLE` window hint, set its position and then show it. * - * If a fullscreen window is active, the screensaver is prohibited from + * If a full screen window is active, the screensaver is prohibited from * starting. * * @param[in] width The desired width, in screen coordinates, of the window. @@ -1224,17 +1229,26 @@ GLFWAPI void glfwWindowHint(int target, int hint); * to not share resources. * @return The handle of the created window, or `NULL` if an error occurred. * + * @remarks **Windows:** Window creation will fail if the Microsoft GDI + * software OpenGL implementation is the only one available. + * * @remarks **Windows:** If the executable has an icon resource named * `GLFW_ICON,` it will be set as the icon for the window. If no such icon is * present, the `IDI_WINLOGO` icon will be used instead. * - * @remarks **Mac OS X:** The GLFW window has no icon, as it is not a document + * @remarks **OS X:** The GLFW window has no icon, as it is not a document * window, but the dock icon will be the same as the application bundle's icon. * Also, the first time a window is opened the menu bar is populated with * common commands like Hide, Quit and About. The (minimal) about dialog uses * information from the application's bundle. For more information on bundles, * see the Bundle Programming Guide provided by Apple. * + * @remarks **X11:** There is no mechanism for setting the window icon yet. + * + * @remarks The swap interval is not set during window creation, but is left at + * the default value for that platform. For more information, see @ref + * glfwSwapInterval. + * * @note This function may only be called from the main thread. * * @sa glfwDestroyWindow @@ -1272,6 +1286,8 @@ GLFWAPI void glfwDestroyWindow(GLFWwindow* window); * @param[in] window The window to query. * @return The value of the close flag. * + * @remarks This function may be called from secondary threads. + * * @ingroup window */ GLFWAPI int glfwWindowShouldClose(GLFWwindow* window); @@ -1285,6 +1301,8 @@ GLFWAPI int glfwWindowShouldClose(GLFWwindow* window); * @param[in] window The window whose flag to change. * @param[in] value The new value. * + * @remarks This function may be called from secondary threads. + * * @ingroup window */ GLFWAPI void glfwSetWindowShouldClose(GLFWwindow* window, int value); @@ -1342,10 +1360,6 @@ GLFWAPI void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos); * * @note The window manager may put limits on what positions are allowed. * - * @bug **X11:** Some window managers ignore the set position of hidden (i.e. - * unmapped) windows, instead placing them where it thinks is appropriate once - * they are shown. - * * @sa glfwGetWindowPos * * @ingroup window @@ -1355,7 +1369,8 @@ GLFWAPI void glfwSetWindowPos(GLFWwindow* window, int xpos, int ypos); /*! @brief Retrieves the size of the client area of the specified window. * * This function retrieves the size, in screen coordinates, of the client area - * of the specified window. + * of the specified window. If you wish to retrieve the size of the + * framebuffer in pixels, see @ref glfwGetFramebufferSize. * * @param[in] window The window whose size to retrieve. * @param[out] width Where to store the width, in screen coordinates, of the @@ -1396,7 +1411,8 @@ GLFWAPI void glfwSetWindowSize(GLFWwindow* window, int width, int height); /*! @brief Retrieves the size of the framebuffer of the specified window. * * This function retrieves the size, in pixels, of the framebuffer of the - * specified window. + * specified window. If you wish to retrieve the size of the window in screen + * coordinates, see @ref glfwGetWindowSize. * * @param[in] window The window whose framebuffer to query. * @param[out] width Where to store the width, in pixels, of the framebuffer, @@ -1579,7 +1595,10 @@ GLFWAPI GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwind * @return The previously set callback, or `NULL` if no callback was set or an * error occurred. * - * @remarks **Mac OS X:** Selecting Quit from the application menu will + * @par New in GLFW 3 + * The close callback no longer returns a value. + * + * @remarks **OS X:** Selecting Quit from the application menu will * trigger the close callback for all windows. * * @ingroup window @@ -1672,6 +1691,12 @@ GLFWAPI GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window * This function is no longer called by @ref glfwSwapBuffers. You need to call * it or @ref glfwWaitEvents yourself. * + * @remarks On some platforms, a window move, resize or menu operation will + * cause event processing to block. This is due to how event processing is + * designed on those platforms. You can use the + * [window refresh callback](@ref GLFWwindowrefreshfun) to redraw the contents + * of your window when necessary during the operation. + * * @note This function may only be called from the main thread. * * @note This function may not be called from a callback. @@ -1688,7 +1713,7 @@ GLFWAPI void glfwPollEvents(void); /*! @brief Waits until events are pending and processes them. * * This function puts the calling thread to sleep until at least one event has - * been received. Once one or more events have been recevied, it behaves as if + * been received. Once one or more events have been received, it behaves as if * @ref glfwPollEvents was called, i.e. the events are processed and the * function then returns immediately. Processing events will cause the window * and input callbacks associated with those events to be called. @@ -1699,6 +1724,12 @@ GLFWAPI void glfwPollEvents(void); * * This function is not required for joystick input to work. * + * @remarks On some platforms, a window move, resize or menu operation will + * cause event processing to block. This is due to how event processing is + * designed on those platforms. You can use the + * [window refresh callback](@ref GLFWwindowrefreshfun) to redraw the contents + * of your window when necessary during the operation. + * * @note This function may only be called from the main thread. * * @note This function may not be called from a callback. @@ -1734,9 +1765,12 @@ GLFWAPI int glfwGetInputMode(GLFWwindow* window, int mode); * modes: * - `GLFW_CURSOR_NORMAL` makes the cursor visible and behaving normally. * - `GLFW_CURSOR_HIDDEN` makes the cursor invisible when it is over the client - * area of the window. - * - `GLFW_CURSOR_DISABLED` disables the cursor and removes any limitations on - * cursor movement. + * area of the window but does not restrict the cursor from leaving. This is + * useful if you wish to render your own cursor or have no visible cursor at + * all. + * - `GLFW_CURSOR_DISABLED` hides and grabs the cursor, providing virtual + * and unlimited cursor movement. This is useful for implementing for + * example 3D camera controls. * * If `mode` is `GLFW_STICKY_KEYS`, the value must be either `GL_TRUE` to * enable sticky keys, or `GL_FALSE` to disable it. If sticky keys are @@ -1806,7 +1840,8 @@ GLFWAPI int glfwGetMouseButton(GLFWwindow* window, int button); /*! @brief Retrieves the last reported cursor position, relative to the client * area of the window. * - * This function returns the last reported position of the cursor to the + * This function returns the last reported position of the cursor, in screen + * coordinates, relative to the upper-left corner of the client area of the * specified window. * * If the cursor is disabled (with `GLFW_CURSOR_DISABLED`) then the cursor @@ -1829,11 +1864,13 @@ GLFWAPI int glfwGetMouseButton(GLFWwindow* window, int button); */ GLFWAPI void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); -/*! @brief Sets the position of the cursor, relative to the client area of the window. +/*! @brief Sets the position of the cursor, relative to the client area of the + * window. * - * This function sets the position of the cursor. The specified window must be - * focused. If the window does not have focus when this function is called, it - * fails silently. + * This function sets the position, in screen coordinates, of the cursor + * relative to the upper-left corner of the client area of the specified + * window. The window must be focused. If the window does not have focus when + * this function is called, it fails silently. * * If the cursor is disabled (with `GLFW_CURSOR_DISABLED`) then the cursor * position is unbounded and limited only by the minimum and maximum values of @@ -1841,9 +1878,9 @@ GLFWAPI void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); * * @param[in] window The desired window. * @param[in] xpos The desired x-coordinate, relative to the left edge of the - * client area, or `NULL`. + * client area. * @param[in] ypos The desired y-coordinate, relative to the top edge of the - * client area, or `NULL`. + * client area. * * @sa glfwGetCursorPos * @@ -1929,7 +1966,8 @@ GLFWAPI GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmo * * This function sets the cursor position callback of the specified window, * which is called when the cursor is moved. The callback is provided with the - * position relative to the upper-left corner of the client area of the window. + * position, in screen coordinates, relative to the upper-left corner of the + * client area of the window. * * @param[in] window The window whose callback to set. * @param[in] cbfun The new callback, or `NULL` to remove the currently set @@ -2189,6 +2227,11 @@ GLFWAPI void glfwSwapBuffers(GLFWwindow* window); * * @remarks This function may be called from secondary threads. * + * @note This function is not called during window creation, leaving the swap + * interval set to whatever is the default on that platform. This is done + * because some swap interval extensions used by GLFW do not allow the swap + * interval to be reset to zero once it has been set to a non-zero value. + * * @note Some GPU drivers do not honor the requested swap interval, either * because of user settings that override the request or due to bugs in the * driver. diff --git a/external/glfw3/include/mac/glfw3native.h b/external/glfw3/include/mac/glfw3native.h index 7507260621..d570f58762 100644 --- a/external/glfw3/include/mac/glfw3native.h +++ b/external/glfw3/include/mac/glfw3native.h @@ -1,7 +1,6 @@ /************************************************************************* - * GLFW - An OpenGL library - * API version: 3.0 - * WWW: http://www.glfw.org/ + * GLFW 3.0 - www.glfw.org + * A library for OpenGL, window and input *------------------------------------------------------------------------ * Copyright (c) 2002-2006 Marcus Geelnard * Copyright (c) 2006-2010 Camilla Berglund @@ -41,7 +40,7 @@ extern "C" { /*! @defgroup native Native access * - * **By using the native API, you assert that you know what you are doing and + * **By using the native API, you assert that you know what you're doing and * how to fix problems caused by using it. If you don't, you shouldn't be * using it.** * diff --git a/external/glfw3/include/win32/glfw3.h b/external/glfw3/include/win32/glfw3.h index c54abde849..0f97738c71 100644 --- a/external/glfw3/include/win32/glfw3.h +++ b/external/glfw3/include/win32/glfw3.h @@ -1,7 +1,6 @@ /************************************************************************* - * GLFW - An OpenGL library - * API version: 3.0 - * WWW: http://www.glfw.org/ + * GLFW 3.0 - www.glfw.org + * A library for OpenGL, window and input *------------------------------------------------------------------------ * Copyright (c) 2002-2006 Marcus Geelnard * Copyright (c) 2006-2010 Camilla Berglund @@ -45,21 +44,22 @@ extern "C" { */ /*! @defgroup error Error handling */ -/*! @defgroup gamma Gamma ramp support - */ /*! @defgroup init Initialization and version information */ /*! @defgroup input Input handling */ /*! @defgroup monitor Monitor handling + * + * This is the reference documentation for monitor related functions and types. + * For more information, see the @ref monitor. */ /*! @defgroup time Time input */ /*! @defgroup window Window handling * - * This is the reference documentation for the window handling API, including - * creation, deletion and event polling. For more information, see the - * [article on window handling](@ref window). + * This is the reference documentation for window related functions and types, + * including creation, deletion and event polling. For more information, see + * the @ref window. */ @@ -131,45 +131,12 @@ extern "C" { #define GLFW_CALLBACK_DEFINED #endif /* CALLBACK */ -/* Most variants on Windows need wchar_t */ -#if defined(_WIN32) +/* Most GL/glu.h variants on Windows need wchar_t + * OpenGL/gl.h blocks the definition of ptrdiff_t by glext.h on OS X */ +#if !defined(GLFW_INCLUDE_NONE) #include #endif - -/* ---------------- GLFW related system specific defines ----------------- */ - -#if defined(GLFW_DLL) && defined(_GLFW_BUILD_DLL) - #error "You must not have both GLFW_DLL and _GLFW_BUILD_DLL defined" -#endif - -#if defined(_WIN32) && defined(_GLFW_BUILD_DLL) - - /* We are building a Win32 DLL */ - #define GLFWAPI __declspec(dllexport) - -#elif defined(_WIN32) && defined(GLFW_DLL) - - /* We are calling a Win32 DLL */ - #if defined(__LCC__) - #define GLFWAPI extern - #else - #define GLFWAPI __declspec(dllimport) - #endif - -#elif defined(__GNUC__) && defined(_GLFW_BUILD_DLL) - - #define GLFWAPI __attribute__((visibility("default"))) - -#else - - /* We are either building/calling a static lib or we are non-win32 */ - #define GLFWAPI - -#endif - -/* -------------------- END SYSTEM/COMPILER SPECIFIC --------------------- */ - /* Include the chosen client API headers. */ #if defined(__APPLE_CC__) @@ -199,6 +166,41 @@ extern "C" { #endif #endif +#if defined(GLFW_DLL) && defined(_GLFW_BUILD_DLL) + /* GLFW_DLL is defined by users of GLFW when compiling programs that will link + * to the DLL version of the GLFW library. _GLFW_BUILD_DLL is defined by the + * GLFW configuration header when compiling the DLL version of the library. + */ + #error "You must not have both GLFW_DLL and _GLFW_BUILD_DLL defined" +#endif + +#if defined(_WIN32) && defined(_GLFW_BUILD_DLL) + + /* We are building a Win32 DLL */ + #define GLFWAPI __declspec(dllexport) + +#elif defined(_WIN32) && defined(GLFW_DLL) + + /* We are calling a Win32 DLL */ + #if defined(__LCC__) + #define GLFWAPI extern + #else + #define GLFWAPI __declspec(dllimport) + #endif + +#elif defined(__GNUC__) && defined(_GLFW_BUILD_DLL) + + #define GLFWAPI __attribute__((visibility("default"))) + +#else + + /* We are either building/calling a static lib or we are non-win32 */ + #define GLFWAPI + +#endif + +/* -------------------- END SYSTEM/COMPILER SPECIFIC --------------------- */ + /************************************************************************* * GLFW API tokens @@ -225,7 +227,7 @@ extern "C" { * API changes. * @ingroup init */ -#define GLFW_VERSION_REVISION 1 +#define GLFW_VERSION_REVISION 4 /*! @} */ /*! @name Key and button actions @@ -704,8 +706,8 @@ typedef void (* GLFWmousebuttonfun)(GLFWwindow*,int,int,int); * This is the function signature for cursor position callback functions. * * @param[in] window The window that received the event. - * @param[in] xpos The new x-coordinate of the cursor. - * @param[in] ypos The new y-coordinate of the cursor. + * @param[in] xpos The new x-coordinate, in screen coordinates, of the cursor. + * @param[in] ypos The new y-coordinate, in screen coordinates, of the cursor. * * @sa glfwSetCursorPosCallback * @@ -763,7 +765,7 @@ typedef void (* GLFWkeyfun)(GLFWwindow*,int,int,int,int); * This is the function signature for Unicode character callback functions. * * @param[in] window The window that received the event. - * @param[in] character The Unicode code point of the character. + * @param[in] codepoint The Unicode code point of the character. * * @sa glfwSetCharCallback * @@ -790,7 +792,7 @@ typedef void (* GLFWmonitorfun)(GLFWmonitor*,int); * * @ingroup monitor */ -typedef struct +typedef struct GLFWvidmode { /*! The width, in screen coordinates, of the video mode. */ @@ -818,9 +820,9 @@ typedef struct * * @sa glfwGetGammaRamp glfwSetGammaRamp * - * @ingroup gamma + * @ingroup monitor */ -typedef struct +typedef struct GLFWgammaramp { /*! An array of value describing the response of the red channel. */ @@ -861,10 +863,7 @@ typedef struct * * @note This function may only be called from the main thread. * - * @note This function may take several seconds to complete on some systems, - * while on other systems it may take only a fraction of a second to complete. - * - * @note **Mac OS X:** This function will change the current directory of the + * @note **OS X:** This function will change the current directory of the * application to the `Contents/Resources` subdirectory of the application's * bundle, if present. * @@ -1124,7 +1123,7 @@ GLFWAPI const GLFWvidmode* glfwGetVideoMode(GLFWmonitor* monitor); * @param[in] monitor The monitor whose gamma ramp to set. * @param[in] gamma The desired exponent. * - * @ingroup gamma + * @ingroup monitor */ GLFWAPI void glfwSetGamma(GLFWmonitor* monitor, float gamma); @@ -1138,7 +1137,7 @@ GLFWAPI void glfwSetGamma(GLFWmonitor* monitor, float gamma); * @note The value arrays of the returned ramp are allocated and freed by GLFW. * You should not free them yourself. * - * @ingroup gamma + * @ingroup monitor */ GLFWAPI const GLFWgammaramp* glfwGetGammaRamp(GLFWmonitor* monitor); @@ -1151,7 +1150,7 @@ GLFWAPI const GLFWgammaramp* glfwGetGammaRamp(GLFWmonitor* monitor); * * @note Gamma ramp sizes other than 256 are not supported by all hardware. * - * @ingroup gamma + * @ingroup monitor */ GLFWAPI void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp); @@ -1207,10 +1206,16 @@ GLFWAPI void glfwWindowHint(int target, int hint); * attributes of the created window and context, use queries like @ref * glfwGetWindowAttrib and @ref glfwGetWindowSize. * + * To create a full screen window, you need to specify the monitor to use. If + * no monitor is specified, windowed mode will be used. Unless you have a way + * for the user to choose a specific monitor, it is recommended that you pick + * the primary monitor. For more information on how to retrieve monitors, see + * @ref monitor_monitors. + * * To create the window at a specific position, make it initially invisible * using the `GLFW_VISIBLE` window hint, set its position and then show it. * - * If a fullscreen window is active, the screensaver is prohibited from + * If a full screen window is active, the screensaver is prohibited from * starting. * * @param[in] width The desired width, in screen coordinates, of the window. @@ -1224,17 +1229,26 @@ GLFWAPI void glfwWindowHint(int target, int hint); * to not share resources. * @return The handle of the created window, or `NULL` if an error occurred. * + * @remarks **Windows:** Window creation will fail if the Microsoft GDI + * software OpenGL implementation is the only one available. + * * @remarks **Windows:** If the executable has an icon resource named * `GLFW_ICON,` it will be set as the icon for the window. If no such icon is * present, the `IDI_WINLOGO` icon will be used instead. * - * @remarks **Mac OS X:** The GLFW window has no icon, as it is not a document + * @remarks **OS X:** The GLFW window has no icon, as it is not a document * window, but the dock icon will be the same as the application bundle's icon. * Also, the first time a window is opened the menu bar is populated with * common commands like Hide, Quit and About. The (minimal) about dialog uses * information from the application's bundle. For more information on bundles, * see the Bundle Programming Guide provided by Apple. * + * @remarks **X11:** There is no mechanism for setting the window icon yet. + * + * @remarks The swap interval is not set during window creation, but is left at + * the default value for that platform. For more information, see @ref + * glfwSwapInterval. + * * @note This function may only be called from the main thread. * * @sa glfwDestroyWindow @@ -1272,6 +1286,8 @@ GLFWAPI void glfwDestroyWindow(GLFWwindow* window); * @param[in] window The window to query. * @return The value of the close flag. * + * @remarks This function may be called from secondary threads. + * * @ingroup window */ GLFWAPI int glfwWindowShouldClose(GLFWwindow* window); @@ -1285,6 +1301,8 @@ GLFWAPI int glfwWindowShouldClose(GLFWwindow* window); * @param[in] window The window whose flag to change. * @param[in] value The new value. * + * @remarks This function may be called from secondary threads. + * * @ingroup window */ GLFWAPI void glfwSetWindowShouldClose(GLFWwindow* window, int value); @@ -1342,10 +1360,6 @@ GLFWAPI void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos); * * @note The window manager may put limits on what positions are allowed. * - * @bug **X11:** Some window managers ignore the set position of hidden (i.e. - * unmapped) windows, instead placing them where it thinks is appropriate once - * they are shown. - * * @sa glfwGetWindowPos * * @ingroup window @@ -1355,7 +1369,8 @@ GLFWAPI void glfwSetWindowPos(GLFWwindow* window, int xpos, int ypos); /*! @brief Retrieves the size of the client area of the specified window. * * This function retrieves the size, in screen coordinates, of the client area - * of the specified window. + * of the specified window. If you wish to retrieve the size of the + * framebuffer in pixels, see @ref glfwGetFramebufferSize. * * @param[in] window The window whose size to retrieve. * @param[out] width Where to store the width, in screen coordinates, of the @@ -1396,7 +1411,8 @@ GLFWAPI void glfwSetWindowSize(GLFWwindow* window, int width, int height); /*! @brief Retrieves the size of the framebuffer of the specified window. * * This function retrieves the size, in pixels, of the framebuffer of the - * specified window. + * specified window. If you wish to retrieve the size of the window in screen + * coordinates, see @ref glfwGetWindowSize. * * @param[in] window The window whose framebuffer to query. * @param[out] width Where to store the width, in pixels, of the framebuffer, @@ -1579,7 +1595,10 @@ GLFWAPI GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwind * @return The previously set callback, or `NULL` if no callback was set or an * error occurred. * - * @remarks **Mac OS X:** Selecting Quit from the application menu will + * @par New in GLFW 3 + * The close callback no longer returns a value. + * + * @remarks **OS X:** Selecting Quit from the application menu will * trigger the close callback for all windows. * * @ingroup window @@ -1672,6 +1691,12 @@ GLFWAPI GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window * This function is no longer called by @ref glfwSwapBuffers. You need to call * it or @ref glfwWaitEvents yourself. * + * @remarks On some platforms, a window move, resize or menu operation will + * cause event processing to block. This is due to how event processing is + * designed on those platforms. You can use the + * [window refresh callback](@ref GLFWwindowrefreshfun) to redraw the contents + * of your window when necessary during the operation. + * * @note This function may only be called from the main thread. * * @note This function may not be called from a callback. @@ -1688,7 +1713,7 @@ GLFWAPI void glfwPollEvents(void); /*! @brief Waits until events are pending and processes them. * * This function puts the calling thread to sleep until at least one event has - * been received. Once one or more events have been recevied, it behaves as if + * been received. Once one or more events have been received, it behaves as if * @ref glfwPollEvents was called, i.e. the events are processed and the * function then returns immediately. Processing events will cause the window * and input callbacks associated with those events to be called. @@ -1699,6 +1724,12 @@ GLFWAPI void glfwPollEvents(void); * * This function is not required for joystick input to work. * + * @remarks On some platforms, a window move, resize or menu operation will + * cause event processing to block. This is due to how event processing is + * designed on those platforms. You can use the + * [window refresh callback](@ref GLFWwindowrefreshfun) to redraw the contents + * of your window when necessary during the operation. + * * @note This function may only be called from the main thread. * * @note This function may not be called from a callback. @@ -1734,9 +1765,12 @@ GLFWAPI int glfwGetInputMode(GLFWwindow* window, int mode); * modes: * - `GLFW_CURSOR_NORMAL` makes the cursor visible and behaving normally. * - `GLFW_CURSOR_HIDDEN` makes the cursor invisible when it is over the client - * area of the window. - * - `GLFW_CURSOR_DISABLED` disables the cursor and removes any limitations on - * cursor movement. + * area of the window but does not restrict the cursor from leaving. This is + * useful if you wish to render your own cursor or have no visible cursor at + * all. + * - `GLFW_CURSOR_DISABLED` hides and grabs the cursor, providing virtual + * and unlimited cursor movement. This is useful for implementing for + * example 3D camera controls. * * If `mode` is `GLFW_STICKY_KEYS`, the value must be either `GL_TRUE` to * enable sticky keys, or `GL_FALSE` to disable it. If sticky keys are @@ -1806,7 +1840,8 @@ GLFWAPI int glfwGetMouseButton(GLFWwindow* window, int button); /*! @brief Retrieves the last reported cursor position, relative to the client * area of the window. * - * This function returns the last reported position of the cursor to the + * This function returns the last reported position of the cursor, in screen + * coordinates, relative to the upper-left corner of the client area of the * specified window. * * If the cursor is disabled (with `GLFW_CURSOR_DISABLED`) then the cursor @@ -1829,11 +1864,13 @@ GLFWAPI int glfwGetMouseButton(GLFWwindow* window, int button); */ GLFWAPI void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); -/*! @brief Sets the position of the cursor, relative to the client area of the window. +/*! @brief Sets the position of the cursor, relative to the client area of the + * window. * - * This function sets the position of the cursor. The specified window must be - * focused. If the window does not have focus when this function is called, it - * fails silently. + * This function sets the position, in screen coordinates, of the cursor + * relative to the upper-left corner of the client area of the specified + * window. The window must be focused. If the window does not have focus when + * this function is called, it fails silently. * * If the cursor is disabled (with `GLFW_CURSOR_DISABLED`) then the cursor * position is unbounded and limited only by the minimum and maximum values of @@ -1841,9 +1878,9 @@ GLFWAPI void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); * * @param[in] window The desired window. * @param[in] xpos The desired x-coordinate, relative to the left edge of the - * client area, or `NULL`. + * client area. * @param[in] ypos The desired y-coordinate, relative to the top edge of the - * client area, or `NULL`. + * client area. * * @sa glfwGetCursorPos * @@ -1929,7 +1966,8 @@ GLFWAPI GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmo * * This function sets the cursor position callback of the specified window, * which is called when the cursor is moved. The callback is provided with the - * position relative to the upper-left corner of the client area of the window. + * position, in screen coordinates, relative to the upper-left corner of the + * client area of the window. * * @param[in] window The window whose callback to set. * @param[in] cbfun The new callback, or `NULL` to remove the currently set @@ -2189,6 +2227,11 @@ GLFWAPI void glfwSwapBuffers(GLFWwindow* window); * * @remarks This function may be called from secondary threads. * + * @note This function is not called during window creation, leaving the swap + * interval set to whatever is the default on that platform. This is done + * because some swap interval extensions used by GLFW do not allow the swap + * interval to be reset to zero once it has been set to a non-zero value. + * * @note Some GPU drivers do not honor the requested swap interval, either * because of user settings that override the request or due to bugs in the * driver. diff --git a/external/glfw3/include/win32/glfw3native.h b/external/glfw3/include/win32/glfw3native.h index 7507260621..d570f58762 100644 --- a/external/glfw3/include/win32/glfw3native.h +++ b/external/glfw3/include/win32/glfw3native.h @@ -1,7 +1,6 @@ /************************************************************************* - * GLFW - An OpenGL library - * API version: 3.0 - * WWW: http://www.glfw.org/ + * GLFW 3.0 - www.glfw.org + * A library for OpenGL, window and input *------------------------------------------------------------------------ * Copyright (c) 2002-2006 Marcus Geelnard * Copyright (c) 2006-2010 Camilla Berglund @@ -41,7 +40,7 @@ extern "C" { /*! @defgroup native Native access * - * **By using the native API, you assert that you know what you are doing and + * **By using the native API, you assert that you know what you're doing and * how to fix problems caused by using it. If you don't, you shouldn't be * using it.** * diff --git a/external/glfw3/prebuilt/mac/libglfw3.a.REMOVED.git-id b/external/glfw3/prebuilt/mac/libglfw3.a.REMOVED.git-id index 4dfc7af549..ac4e3e81e2 100644 --- a/external/glfw3/prebuilt/mac/libglfw3.a.REMOVED.git-id +++ b/external/glfw3/prebuilt/mac/libglfw3.a.REMOVED.git-id @@ -1 +1 @@ -963bbf033d259310949b926857e909373f47af7a \ No newline at end of file +6e8b26c0b4616633d6976b064a3e3345dd3967ff \ No newline at end of file diff --git a/external/glfw3/prebuilt/win32/glfw3.lib.REMOVED.git-id b/external/glfw3/prebuilt/win32/glfw3.lib.REMOVED.git-id index e5b26c5a9a..f88152da7c 100644 --- a/external/glfw3/prebuilt/win32/glfw3.lib.REMOVED.git-id +++ b/external/glfw3/prebuilt/win32/glfw3.lib.REMOVED.git-id @@ -1 +1 @@ -ce2af28afe9e68d0ec3f94258ae7bb058567cb58 \ No newline at end of file +b3d2e2ea94386cd9d106a58194bd83090a89b6c9 \ No newline at end of file diff --git a/external/spidermonkey/include/android/js-config.h b/external/spidermonkey/include/android/js-config.h index 4b893482f4..b1563e37e9 100644 --- a/external/spidermonkey/include/android/js-config.h +++ b/external/spidermonkey/include/android/js-config.h @@ -5,8 +5,8 @@ * 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/. */ -#ifndef js_config_h___ -#define js_config_h___ +#ifndef js_config_h +#define js_config_h /* Definitions set at build time that affect SpiderMonkey's public API. This header file is generated by the SpiderMonkey configure script, @@ -34,12 +34,8 @@ useable. See jscpucfg.h. */ /* #undef JS_HAVE_SYS_ISA_DEFS_H */ -/* The configure script defines these if it doesn't #define - JS_HAVE_STDINT_H. */ -#define JS_BYTES_PER_WORD 4 - /* MOZILLA JSAPI version number components */ -#define MOZJS_MAJOR_VERSION 25 +#define MOZJS_MAJOR_VERSION 27 #define MOZJS_MINOR_VERSION 0 -#endif /* js_config_h___ */ +#endif /* js_config_h */ diff --git a/external/spidermonkey/include/android/js.msg b/external/spidermonkey/include/android/js.msg index 3f665d8d54..da7361d5df 100644 --- a/external/spidermonkey/include/android/js.msg +++ b/external/spidermonkey/include/android/js.msg @@ -221,8 +221,8 @@ MSG_DEF(JSMSG_CANT_DECODE_PRINCIPALS, 167, 0, JSEXN_INTERNALERR, "can't decode J MSG_DEF(JSMSG_CANT_SEAL_OBJECT, 168, 1, JSEXN_ERR, "can't seal {0} objects") MSG_DEF(JSMSG_TOO_MANY_CATCH_VARS, 169, 0, JSEXN_SYNTAXERR, "too many catch variables") MSG_DEF(JSMSG_NEGATIVE_REPETITION_COUNT, 170, 0, JSEXN_RANGEERR, "repeat count must be non-negative") -MSG_DEF(JSMSG_UNUSED171, 171, 0, JSEXN_NONE, "") -MSG_DEF(JSMSG_UNUSED172, 172, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_INVALID_FOR_OF_INIT, 171, 0, JSEXN_SYNTAXERR, "for-of loop variable declaration may not have an initializer") +MSG_DEF(JSMSG_INVALID_MAP_ITERABLE, 172, 0, JSEXN_TYPEERR, "iterable for map should have array-like objects") MSG_DEF(JSMSG_UNUSED173, 173, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED174, 174, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_NESTING_GENERATOR, 175, 0, JSEXN_TYPEERR, "already executing generator") @@ -233,8 +233,8 @@ MSG_DEF(JSMSG_UNUSED179, 179, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED180, 180, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED181, 181, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_BAD_GENERATOR_SEND, 182, 1, JSEXN_TYPEERR, "attempt to send {0} to newborn generator") -MSG_DEF(JSMSG_UNUSED183, 183, 0, JSEXN_NONE, "") -MSG_DEF(JSMSG_UNUSED184, 184, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_SC_NOT_TRANSFERABLE, 183, 0, JSEXN_TYPEERR, "invalid transferable array for structured clone") +MSG_DEF(JSMSG_SC_DUP_TRANSFERABLE, 184, 0, JSEXN_TYPEERR, "duplicate transferable for structured clone") MSG_DEF(JSMSG_CANT_REPORT_AS_NON_EXTENSIBLE, 185, 0, JSEXN_TYPEERR, "proxy can't report an extensible object as non-extensible") MSG_DEF(JSMSG_UNUSED186, 186, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED187, 187, 0, JSEXN_NONE, "") @@ -260,7 +260,7 @@ MSG_DEF(JSMSG_USER_DEFINED_ERROR, 206, 0, JSEXN_ERR, "JS_ReportError was cal MSG_DEF(JSMSG_WRONG_CONSTRUCTOR, 207, 1, JSEXN_TYPEERR, "wrong constructor called for {0}") MSG_DEF(JSMSG_BAD_GENERATOR_RETURN, 208, 1, JSEXN_TYPEERR, "generator function {0} returns a value") MSG_DEF(JSMSG_BAD_ANON_GENERATOR_RETURN, 209, 0, JSEXN_TYPEERR, "anonymous generator function returns a value") -MSG_DEF(JSMSG_NAME_AFTER_FOR_PAREN, 210, 0, JSEXN_SYNTAXERR, "missing name after for (") +MSG_DEF(JSMSG_UNUSED210, 210, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_IN_AFTER_FOR_NAME, 211, 0, JSEXN_SYNTAXERR, "missing 'in' or 'of' after for") MSG_DEF(JSMSG_BAD_TRAP_RETURN_VALUE, 212, 2, JSEXN_TYPEERR,"trap {1} for {0} returned a primitive value") MSG_DEF(JSMSG_UNUSED213, 213, 0, JSEXN_NONE, "") @@ -269,7 +269,7 @@ MSG_DEF(JSMSG_BAD_GENERATOR_SYNTAX, 215, 1, JSEXN_SYNTAXERR, "{0} expression m MSG_DEF(JSMSG_ARRAY_COMP_LEFTSIDE, 216, 0, JSEXN_SYNTAXERR, "invalid array comprehension left-hand side") MSG_DEF(JSMSG_UNUSED217, 217, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_EMPTY_ARRAY_REDUCE, 218, 0, JSEXN_TYPEERR, "reduce of empty array with no initial value") -MSG_DEF(JSMSG_UNUSED219, 219, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_BAD_SYMBOL, 219, 1, JSEXN_TYPEERR, "{0} is not a well-known @@-symbol") MSG_DEF(JSMSG_BAD_DELETE_OPERAND, 220, 0, JSEXN_REFERENCEERR, "invalid delete operand") MSG_DEF(JSMSG_BAD_INCOP_OPERAND, 221, 0, JSEXN_REFERENCEERR, "invalid increment/decrement operand") MSG_DEF(JSMSG_UNEXPECTED_TYPE, 222, 2, JSEXN_TYPEERR, "{0} is {1}") @@ -353,7 +353,7 @@ MSG_DEF(JSMSG_REST_WITH_DEFAULT, 299, 0, JSEXN_SYNTAXERR, "rest parameter m MSG_DEF(JSMSG_NONDEFAULT_FORMAL_AFTER_DEFAULT, 300, 0, JSEXN_SYNTAXERR, "parameter(s) with default followed by parameter without default") MSG_DEF(JSMSG_YIELD_IN_DEFAULT, 301, 0, JSEXN_SYNTAXERR, "yield in default expression") MSG_DEF(JSMSG_INTRINSIC_NOT_DEFINED, 302, 1, JSEXN_REFERENCEERR, "no intrinsic function {0}") -MSG_DEF(JSMSG_ALREADY_HAS_SOURCEMAP, 303, 1, JSEXN_ERR, "{0} is being assigned a source map, yet already has one") +MSG_DEF(JSMSG_ALREADY_HAS_PRAGMA, 303, 2, JSEXN_ERR, "{0} is being assigned a {1}, but already has one") MSG_DEF(JSMSG_PAR_ARRAY_BAD_ARG, 304, 1, JSEXN_RANGEERR, "invalid ParallelArray{0} argument") MSG_DEF(JSMSG_PAR_ARRAY_BAD_PARTITION, 305, 0, JSEXN_ERR, "argument must be divisible by outermost dimension") MSG_DEF(JSMSG_PAR_ARRAY_REDUCE_EMPTY, 306, 0, JSEXN_ERR, "cannot reduce ParallelArray object whose outermost dimension is empty") @@ -375,7 +375,7 @@ MSG_DEF(JSMSG_MUST_REPORT_UNDEFINED, 321, 0, JSEXN_TYPEERR, "proxy must report MSG_DEF(JSMSG_CANT_SET_NW_NC, 322, 0, JSEXN_TYPEERR, "proxy can't successfully set a non-writable, non-configurable property") MSG_DEF(JSMSG_CANT_SET_WO_SETTER, 323, 0, JSEXN_TYPEERR, "proxy can't succesfully set an accessor property without a setter") MSG_DEF(JSMSG_DEBUG_BAD_REFERENT, 324, 2, JSEXN_TYPEERR, "{0} does not refer to {1}") -MSG_DEF(JSMSG_DEBUG_WRAPPER_IN_WAY, 325, 2, JSEXN_TYPEERR, "{0} is a wrapper around {1}, but a direct reference is required") +MSG_DEF(JSMSG_DEBUG_WRAPPER_IN_WAY, 325, 3, JSEXN_TYPEERR, "{0} is {1}{2}a global object, but a direct reference is required") MSG_DEF(JSMSG_UNWRAP_DENIED, 326, 0, JSEXN_ERR, "permission denied to unwrap object") MSG_DEF(JSMSG_INTL_OBJECT_NOT_INITED, 327, 3, JSEXN_TYPEERR, "Intl.{0}.prototype.{1} called on value that's not an object initialized as a {2}") MSG_DEF(JSMSG_INVALID_LOCALES_ELEMENT,328, 0, JSEXN_TYPEERR, "invalid element in locales argument") @@ -400,12 +400,23 @@ MSG_DEF(JSMSG_YIELD_IN_ARROW, 346, 0, JSEXN_SYNTAXERR, "arrow function m MSG_DEF(JSMSG_WRONG_VALUE, 347, 2, JSEXN_ERR, "expected {0} but found {1}") MSG_DEF(JSMSG_PAR_ARRAY_SCATTER_BAD_TARGET, 348, 1, JSEXN_ERR, "target for index {0} is not an integer") MSG_DEF(JSMSG_SELFHOSTED_UNBOUND_NAME,349, 0, JSEXN_TYPEERR, "self-hosted code may not contain unbound name lookups") -MSG_DEF(JSMSG_DEPRECATED_SOURCE_MAP, 350, 0, JSEXN_SYNTAXERR, "Using //@ to indicate source map URL pragmas is deprecated. Use //# instead") +MSG_DEF(JSMSG_DEPRECATED_PRAGMA, 350, 1, JSEXN_SYNTAXERR, "Using //@ to indicate {0} pragmas is deprecated. Use //# instead") MSG_DEF(JSMSG_BAD_DESTRUCT_ASSIGN, 351, 1, JSEXN_SYNTAXERR, "can't assign to {0} using destructuring assignment") -MSG_DEF(JSMSG_BINARYDATA_ARRAYTYPE_BAD_ARGS, 352, 0, JSEXN_ERR, "Invalid arguments") -MSG_DEF(JSMSG_BINARYDATA_BINARYARRAY_BAD_INDEX, 353, 0, JSEXN_RANGEERR, "invalid or out-of-range index") -MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_ARGS, 354, 0, JSEXN_RANGEERR, "invalid field descriptor") -MSG_DEF(JSMSG_BINARYDATA_NOT_BINARYSTRUCT, 355, 1, JSEXN_TYPEERR, "{0} is not a BinaryStruct") -MSG_DEF(JSMSG_BINARYDATA_SUBARRAY_INTEGER_ARG, 356, 1, JSEXN_ERR, "argument {0} must be an integer") -MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_EMPTY_DESCRIPTOR, 357, 0, JSEXN_ERR, "field descriptor cannot be empty") -MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_FIELD, 358, 1, JSEXN_ERR, "field {0} is not a valid BinaryData Type descriptor") +MSG_DEF(JSMSG_TYPEDOBJECT_ARRAYTYPE_BAD_ARGS, 352, 0, JSEXN_ERR, "Invalid arguments") +MSG_DEF(JSMSG_TYPEDOBJECT_BINARYARRAY_BAD_INDEX, 353, 0, JSEXN_RANGEERR, "invalid or out-of-range index") +MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_BAD_ARGS, 354, 0, JSEXN_RANGEERR, "invalid field descriptor") +MSG_DEF(JSMSG_TYPEDOBJECT_NOT_BINARYSTRUCT, 355, 1, JSEXN_TYPEERR, "{0} is not a BinaryStruct") +MSG_DEF(JSMSG_TYPEDOBJECT_SUBARRAY_INTEGER_ARG, 356, 1, JSEXN_ERR, "argument {0} must be an integer") +MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_EMPTY_DESCRIPTOR, 357, 0, JSEXN_ERR, "field descriptor cannot be empty") +MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_BAD_FIELD, 358, 1, JSEXN_ERR, "field {0} is not a valid BinaryData Type descriptor") +MSG_DEF(JSMSG_GENERATOR_FINISHED, 359, 0, JSEXN_TYPEERR, "generator has already finished") +MSG_DEF(JSMSG_TYPEDOBJECT_TOO_BIG, 360, 0, JSEXN_ERR, "Type is too large to allocate") +MSG_DEF(JSMSG_TYPEDOBJECT_NOT_TYPE_OBJECT, 361, 0, JSEXN_ERR, "Expected a type object") +MSG_DEF(JSMSG_TOO_MANY_CON_SPREADARGS, 362, 0, JSEXN_RANGEERR, "too many constructor arguments") +MSG_DEF(JSMSG_TOO_MANY_FUN_SPREADARGS, 363, 0, JSEXN_RANGEERR, "too many function arguments") +MSG_DEF(JSMSG_DEBUG_NOT_DEBUGGEE, 364, 2, JSEXN_ERR, "{0} is not a debuggee {1}") +MSG_DEF(JSMSG_TYPEDOBJECT_NOT_TYPED_OBJECT, 365, 0, JSEXN_ERR, "Expected a typed object") +MSG_DEF(JSMSG_TYPEDOBJECT_NO_SUCH_PROP, 366, 1, JSEXN_TYPEERR, "No such property: {0}") +MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_BAD_ARGS, 367, 2, JSEXN_TYPEERR, "argument {0} invalid: expected {1}") +MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_UNATTACHED, 368, 0, JSEXN_TYPEERR, "handle unattached") +MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_BAD_TYPE, 369, 0, JSEXN_TYPEERR, "handle moved to destination of incorrect type") diff --git a/external/spidermonkey/include/android/js/Anchor.h b/external/spidermonkey/include/android/js/Anchor.h index 0d458e6fb6..c2324fb2e9 100644 --- a/external/spidermonkey/include/android/js/Anchor.h +++ b/external/spidermonkey/include/android/js/Anchor.h @@ -11,12 +11,7 @@ #include "mozilla/Attributes.h" -class JSFunction; -class JSObject; -class JSScript; -class JSString; - -namespace JS { class Value; } +#include "js/TypeDecls.h" namespace JS { diff --git a/external/spidermonkey/include/android/js/CallArgs.h b/external/spidermonkey/include/android/js/CallArgs.h index 8027ffc71a..5c7a201101 100644 --- a/external/spidermonkey/include/android/js/CallArgs.h +++ b/external/spidermonkey/include/android/js/CallArgs.h @@ -38,22 +38,19 @@ #include "js/RootingAPI.h" #include "js/Value.h" -struct JSContext; -class JSObject; - /* Typedef for native functions called by the JS VM. */ -typedef JSBool +typedef bool (* JSNative)(JSContext *cx, unsigned argc, JS::Value *vp); /* Typedef for native functions that may be called in parallel. */ -typedef js::ParallelResult +typedef bool (* JSParallelNative)(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); /* * Typedef for native functions that may be called either in parallel or * sequential execution. */ -typedef JSBool +typedef bool (* JSThreadSafeNative)(js::ThreadSafeContext *cx, unsigned argc, JS::Value *vp); /* @@ -61,11 +58,11 @@ typedef JSBool * a JSNative or a JSParallelNative. */ template -inline JSBool +inline bool JSNativeThreadSafeWrapper(JSContext *cx, unsigned argc, JS::Value *vp); template -inline js::ParallelResult +inline bool JSParallelNativeThreadSafeWrapper(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); /* @@ -89,7 +86,7 @@ extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; * return value for a function call. The principal way to create a * CallReceiver is using JS::CallReceiverFromVp: * - * static JSBool + * static bool * FunctionReturningThis(JSContext *cx, unsigned argc, JS::Value *vp) * { * JS::CallReceiver rec = JS::CallReceiverFromVp(vp); @@ -282,7 +279,7 @@ CallReceiverFromVp(Value *vp) * the function call's arguments. The principal way to create a CallArgs is * like so, using JS::CallArgsFromVp: * - * static JSBool + * static bool * FunctionReturningArgcTimesArg0(JSContext *cx, unsigned argc, JS::Value *vp) * { * JS::CallArgs args = JS::CallArgsFromVp(argc, vp); diff --git a/external/spidermonkey/include/android/js/CallNonGenericMethod.h b/external/spidermonkey/include/android/js/CallNonGenericMethod.h new file mode 100644 index 0000000000..05097f0294 --- /dev/null +++ b/external/spidermonkey/include/android/js/CallNonGenericMethod.h @@ -0,0 +1,117 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_CallNonGenericMethod_h +#define js_CallNonGenericMethod_h + +#include "jstypes.h" + +#include "js/CallArgs.h" + +namespace JS { + +// Returns true if |v| is considered an acceptable this-value. +typedef bool (*IsAcceptableThis)(Handle v); + +// Implements the guts of a method; guaranteed to be provided an acceptable +// this-value, as determined by a corresponding IsAcceptableThis method. +typedef bool (*NativeImpl)(JSContext *cx, CallArgs args); + +namespace detail { + +// DON'T CALL THIS DIRECTLY. It's for use only by CallNonGenericMethod! +extern JS_PUBLIC_API(bool) +CallMethodIfWrapped(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args); + +} // namespace detail + +// Methods usually act upon |this| objects only from a single global object and +// compartment. Sometimes, however, a method must act upon |this| values from +// multiple global objects or compartments. In such cases the |this| value a +// method might see will be wrapped, such that various access to the object -- +// to its class, its private data, its reserved slots, and so on -- will not +// work properly without entering that object's compartment. This method +// implements a solution to this problem. +// +// To implement a method that accepts |this| values from multiple compartments, +// define two functions. The first function matches the IsAcceptableThis type +// and indicates whether the provided value is an acceptable |this| for the +// method; it must be a pure function only of its argument. +// +// static const JSClass AnswerClass = { ... }; +// +// static bool +// IsAnswerObject(const Value &v) +// { +// if (!v.isObject()) +// return false; +// return JS_GetClass(&v.toObject()) == &AnswerClass; +// } +// +// The second function implements the NativeImpl signature and defines the +// behavior of the method when it is provided an acceptable |this| value. +// Aside from some typing niceties -- see the CallArgs interface for details -- +// its interface is the same as that of JSNative. +// +// static bool +// answer_getAnswer_impl(JSContext *cx, JS::CallArgs args) +// { +// args.rval().setInt32(42); +// return true; +// } +// +// The implementation function is guaranteed to be called *only* with a |this| +// value which is considered acceptable. +// +// Now to implement the actual method, write a JSNative that calls the method +// declared below, passing the appropriate template and runtime arguments. +// +// static bool +// answer_getAnswer(JSContext *cx, unsigned argc, JS::Value *vp) +// { +// JS::CallArgs args = JS::CallArgsFromVp(argc, vp); +// return JS::CallNonGenericMethod(cx, args); +// } +// +// Note that, because they are used as template arguments, the predicate +// and implementation functions must have external linkage. (This is +// unfortunate, but GCC wasn't inlining things as one would hope when we +// passed them as function arguments.) +// +// JS::CallNonGenericMethod will test whether |args.thisv()| is acceptable. If +// it is, it will call the provided implementation function, which will return +// a value and indicate success. If it is not, it will attempt to unwrap +// |this| and call the implementation function on the unwrapped |this|. If +// that succeeds, all well and good. If it doesn't succeed, a TypeError will +// be thrown. +// +// Note: JS::CallNonGenericMethod will only work correctly if it's called in +// tail position in a JSNative. Do not call it from any other place. +// +template +JS_ALWAYS_INLINE bool +CallNonGenericMethod(JSContext *cx, CallArgs args) +{ + HandleValue thisv = args.thisv(); + if (Test(thisv)) + return Impl(cx, args); + + return detail::CallMethodIfWrapped(cx, Test, Impl, args); +} + +JS_ALWAYS_INLINE bool +CallNonGenericMethod(JSContext *cx, IsAcceptableThis Test, NativeImpl Impl, CallArgs args) +{ + HandleValue thisv = args.thisv(); + if (Test(thisv)) + return Impl(cx, args); + + return detail::CallMethodIfWrapped(cx, Test, Impl, args); +} + +} // namespace JS + +#endif /* js_CallNonGenericMethod_h */ diff --git a/external/spidermonkey/include/android/js/CharacterEncoding.h b/external/spidermonkey/include/android/js/CharacterEncoding.h index e88e08e1be..7918b83484 100644 --- a/external/spidermonkey/include/android/js/CharacterEncoding.h +++ b/external/spidermonkey/include/android/js/CharacterEncoding.h @@ -7,11 +7,15 @@ #ifndef js_CharacterEncoding_h #define js_CharacterEncoding_h +#include "mozilla/NullPtr.h" #include "mozilla/Range.h" +#include "js/TypeDecls.h" #include "js/Utility.h" -#include "jspubtd.h" +namespace js { +struct ThreadSafeContext; +} namespace JS { @@ -41,7 +45,7 @@ class Latin1CharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: - Latin1CharsZ() : Base(NULL, 0) {} + Latin1CharsZ() : Base(nullptr, 0) {} Latin1CharsZ(char *aBytes, size_t aLength) : Base(reinterpret_cast(aBytes), aLength) @@ -80,7 +84,7 @@ class UTF8CharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: - UTF8CharsZ() : Base(NULL, 0) {} + UTF8CharsZ() : Base(nullptr, 0) {} UTF8CharsZ(char *aBytes, size_t aLength) : Base(reinterpret_cast(aBytes), aLength) @@ -138,7 +142,7 @@ class TwoByteCharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: - TwoByteCharsZ() : Base(NULL, 0) {} + TwoByteCharsZ() : Base(nullptr, 0) {} TwoByteCharsZ(jschar *chars, size_t length) : Base(chars, length) @@ -154,7 +158,7 @@ class TwoByteCharsZ : public mozilla::RangedPtr * output. The returned string is zero terminated. The returned string or the * returned string's |start()| must be freed with JS_free or js_free, * respectively. If allocation fails, an OOM error will be set and the method - * will return a NULL chars (which can be tested for with the ! operator). + * will return a nullptr chars (which can be tested for with the ! operator). * This method cannot trigger GC. */ extern Latin1CharsZ diff --git a/external/spidermonkey/include/android/js/Class.h b/external/spidermonkey/include/android/js/Class.h new file mode 100644 index 0000000000..4058688e99 --- /dev/null +++ b/external/spidermonkey/include/android/js/Class.h @@ -0,0 +1,699 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +/* JSClass definition and its component types, plus related interfaces. */ + +#ifndef js_Class_h +#define js_Class_h + +#include "mozilla/NullPtr.h" + +#include "jstypes.h" + +#include "js/CallArgs.h" +#include "js/Id.h" +#include "js/TypeDecls.h" + +/* + * A JSClass acts as a vtable for JS objects that allows JSAPI clients to + * control various aspects of the behavior of an object like property lookup. + * js::Class is an engine-private extension that allows more control over + * object behavior and, e.g., allows custom slow layout. + */ + +class JSFreeOp; + +namespace js { + +class Class; +class FreeOp; +class PropertyId; +class PropertyName; +class Shape; +class SpecialId; + +// This is equal to JSFunction::class_. Use it in places where you don't want +// to #include jsfun.h. +extern JS_FRIEND_DATA(const js::Class* const) FunctionClassPtr; + +static JS_ALWAYS_INLINE jsid +SPECIALID_TO_JSID(const SpecialId &sid); + +/* + * We partition the ways to refer to a property into three: by an index + * (uint32_t); by a string whose characters do not represent an index + * (PropertyName, see vm/String.h); and by various special values. + * + * Special values are encoded using SpecialId, which is layout-compatible but + * non-interconvertible with jsid. A SpecialId is used for JSID_VOID, which + * does not occur in JS scripts but may be used to indicate the absence of a + * valid identifier. In the future, a SpecialId may also be an object used by + * Harmony-proposed private names. + */ +class SpecialId +{ + uintptr_t bits_; + + /* Needs access to raw bits. */ + friend JS_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid); + friend class PropertyId; + + static const uintptr_t TYPE_VOID = JSID_TYPE_VOID; + static const uintptr_t TYPE_OBJECT = JSID_TYPE_OBJECT; + static const uintptr_t TYPE_MASK = JSID_TYPE_MASK; + + SpecialId(uintptr_t bits) : bits_(bits) { } + + public: + SpecialId() : bits_(TYPE_VOID) { } + + /* Object-valued */ + + SpecialId(JSObject &obj) + : bits_(uintptr_t(&obj) | TYPE_OBJECT) + { + JS_ASSERT(&obj != nullptr); + JS_ASSERT((uintptr_t(&obj) & TYPE_MASK) == 0); + } + + bool isObject() const { + return (bits_ & TYPE_MASK) == TYPE_OBJECT && bits_ != TYPE_OBJECT; + } + + JSObject *toObject() const { + JS_ASSERT(isObject()); + return reinterpret_cast(bits_ & ~TYPE_MASK); + } + + /* Empty */ + + static SpecialId empty() { + SpecialId sid(TYPE_OBJECT); + JS_ASSERT(sid.isEmpty()); + return sid; + } + + bool isEmpty() const { + return bits_ == TYPE_OBJECT; + } + + /* Void */ + + static SpecialId voidId() { + SpecialId sid(TYPE_VOID); + JS_ASSERT(sid.isVoid()); + return sid; + } + + bool isVoid() const { + return bits_ == TYPE_VOID; + } +}; + +static JS_ALWAYS_INLINE jsid +SPECIALID_TO_JSID(const SpecialId &sid) +{ + jsid id; + JSID_BITS(id) = sid.bits_; + JS_ASSERT_IF(sid.isObject(), JSID_IS_OBJECT(id) && JSID_TO_OBJECT(id) == sid.toObject()); + JS_ASSERT_IF(sid.isVoid(), JSID_IS_VOID(id)); + JS_ASSERT_IF(sid.isEmpty(), JSID_IS_EMPTY(id)); + return id; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_SPECIAL(jsid id) +{ + return JSID_IS_OBJECT(id) || JSID_IS_EMPTY(id) || JSID_IS_VOID(id); +} + +static JS_ALWAYS_INLINE SpecialId +JSID_TO_SPECIALID(jsid id) +{ + JS_ASSERT(JSID_IS_SPECIAL(id)); + if (JSID_IS_OBJECT(id)) + return SpecialId(*JSID_TO_OBJECT(id)); + if (JSID_IS_EMPTY(id)) + return SpecialId::empty(); + JS_ASSERT(JSID_IS_VOID(id)); + return SpecialId::voidId(); +} + +typedef JS::Handle HandleSpecialId; + +} // namespace js + +// JSClass operation signatures. + +// Add or get a property named by id in obj. Note the jsid id type -- id may +// be a string (Unicode property identifier) or an int (element index). The +// *vp out parameter, on success, is the new property value after the action. +typedef bool +(* JSPropertyOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + JS::MutableHandle vp); + +// Set a property named by id in obj, treating the assignment as strict +// mode code if strict is true. Note the jsid id type -- id may be a string +// (Unicode property identifier) or an int (element index). The *vp out +// parameter, on success, is the new property value after the +// set. +typedef bool +(* JSStrictPropertyOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + bool strict, JS::MutableHandle vp); + +// Delete a property named by id in obj. +// +// If an error occurred, return false as per normal JSAPI error practice. +// +// If no error occurred, but the deletion attempt wasn't allowed (perhaps +// because the property was non-configurable), set *succeeded to false and +// return true. This will cause |delete obj[id]| to evaluate to false in +// non-strict mode code, and to throw a TypeError in strict mode code. +// +// If no error occurred and the deletion wasn't disallowed (this is *not* the +// same as saying that a deletion actually occurred -- deleting a non-existent +// property, or an inherited property, is allowed -- it's just pointless), +// set *succeeded to true and return true. +typedef bool +(* JSDeletePropertyOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + bool *succeeded); + +// This function type is used for callbacks that enumerate the properties of +// a JSObject. The behavior depends on the value of enum_op: +// +// JSENUMERATE_INIT +// A new, opaque iterator state should be allocated and stored in *statep. +// (You can use PRIVATE_TO_JSVAL() to tag the pointer to be stored). +// +// The number of properties that will be enumerated should be returned as +// an integer jsval in *idp, if idp is non-null, and provided the number of +// enumerable properties is known. If idp is non-null and the number of +// enumerable properties can't be computed in advance, *idp should be set +// to JSVAL_ZERO. +// +// JSENUMERATE_INIT_ALL +// Used identically to JSENUMERATE_INIT, but exposes all properties of the +// object regardless of enumerability. +// +// JSENUMERATE_NEXT +// A previously allocated opaque iterator state is passed in via statep. +// Return the next jsid in the iteration using *idp. The opaque iterator +// state pointed at by statep is destroyed and *statep is set to JSVAL_NULL +// if there are no properties left to enumerate. +// +// JSENUMERATE_DESTROY +// Destroy the opaque iterator state previously allocated in *statep by a +// call to this function when enum_op was JSENUMERATE_INIT or +// JSENUMERATE_INIT_ALL. +// +// The return value is used to indicate success, with a value of false +// indicating failure. +typedef bool +(* JSNewEnumerateOp)(JSContext *cx, JS::Handle obj, JSIterateOp enum_op, + JS::MutableHandle statep, JS::MutableHandle idp); + +// The old-style JSClass.enumerate op should define all lazy properties not +// yet reflected in obj. +typedef bool +(* JSEnumerateOp)(JSContext *cx, JS::Handle obj); + +// Resolve a lazy property named by id in obj by defining it directly in obj. +// Lazy properties are those reflected from some peer native property space +// (e.g., the DOM attributes for a given node reflected as obj) on demand. +// +// JS looks for a property in an object, and if not found, tries to resolve +// the given id. If resolve succeeds, the engine looks again in case resolve +// defined obj[id]. If no such property exists directly in obj, the process +// is repeated with obj's prototype, etc. +// +// NB: JSNewResolveOp provides a cheaper way to resolve lazy properties. +typedef bool +(* JSResolveOp)(JSContext *cx, JS::Handle obj, JS::Handle id); + +// Like JSResolveOp, but flags provide contextual information as follows: +// +// JSRESOLVE_ASSIGNING obj[id] is on the left-hand side of an assignment +// +// The *objp out parameter, on success, should be null to indicate that id +// was not resolved; and non-null, referring to obj or one of its prototypes, +// if id was resolved. The hook may assume *objp is null on entry. +// +// This hook instead of JSResolveOp is called via the JSClass.resolve member +// if JSCLASS_NEW_RESOLVE is set in JSClass.flags. +typedef bool +(* JSNewResolveOp)(JSContext *cx, JS::Handle obj, JS::Handle id, unsigned flags, + JS::MutableHandle objp); + +// Convert obj to the given type, returning true with the resulting value in +// *vp on success, and returning false on error or exception. +typedef bool +(* JSConvertOp)(JSContext *cx, JS::Handle obj, JSType type, + JS::MutableHandle vp); + +// Finalize obj, which the garbage collector has determined to be unreachable +// from other live objects or from GC roots. Obviously, finalizers must never +// store a reference to obj. +typedef void +(* JSFinalizeOp)(JSFreeOp *fop, JSObject *obj); + +// Finalizes external strings created by JS_NewExternalString. +struct JSStringFinalizer { + void (*finalize)(const JSStringFinalizer *fin, jschar *chars); +}; + +// JSClass.checkAccess type: check whether obj[id] may be accessed per mode, +// returning false on error/exception, true on success with obj[id]'s last-got +// value in *vp, and its attributes in *attrsp. As for JSPropertyOp above, id +// is either a string or an int jsval. +typedef bool +(* JSCheckAccessOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + JSAccessMode mode, JS::MutableHandle vp); + +// Return whether the first principal subsumes the second. The exact meaning of +// 'subsumes' is left up to the browser. Subsumption is checked inside the JS +// engine when determining, e.g., which stack frames to display in a backtrace. +typedef bool +(* JSSubsumesOp)(JSPrincipals *first, JSPrincipals *second); + +// Check whether v is an instance of obj. Return false on error or exception, +// true on success with true in *bp if v is an instance of obj, false in +// *bp otherwise. +typedef bool +(* JSHasInstanceOp)(JSContext *cx, JS::Handle obj, JS::MutableHandle vp, + bool *bp); + +// Function type for trace operation of the class called to enumerate all +// traceable things reachable from obj's private data structure. For each such +// thing, a trace implementation must call one of the JS_Call*Tracer variants +// on the thing. +// +// JSTraceOp implementation can assume that no other threads mutates object +// state. It must not change state of the object or corresponding native +// structures. The only exception for this rule is the case when the embedding +// needs a tight integration with GC. In that case the embedding can check if +// the traversal is a part of the marking phase through calling +// JS_IsGCMarkingTracer and apply a special code like emptying caches or +// marking its native structures. +typedef void +(* JSTraceOp)(JSTracer *trc, JSObject *obj); + +// A generic type for functions mapping an object to another object, or null +// if an error or exception was thrown on cx. +typedef JSObject * +(* JSObjectOp)(JSContext *cx, JS::Handle obj); + +// Hook that creates an iterator object for a given object. Returns the +// iterator object or null if an error or exception was thrown on cx. +typedef JSObject * +(* JSIteratorOp)(JSContext *cx, JS::HandleObject obj, bool keysonly); + +typedef JSObject * +(* JSWeakmapKeyDelegateOp)(JSObject *obj); + +/* js::Class operation signatures. */ + +namespace js { + +typedef bool +(* LookupGenericOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* LookupPropOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* LookupElementOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* LookupSpecialOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* DefineGenericOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue value, + JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs); +typedef bool +(* DefinePropOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + JS::HandleValue value, JSPropertyOp getter, JSStrictPropertyOp setter, + unsigned attrs); +typedef bool +(* DefineElementOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, JS::HandleValue value, + JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs); +typedef bool +(* DefineSpecialOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, + JS::HandleValue value, JSPropertyOp getter, JSStrictPropertyOp setter, + unsigned attrs); +typedef bool +(* GenericIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, JS::HandleId id, + JS::MutableHandleValue vp); +typedef bool +(* PropertyIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, + JS::Handle name, JS::MutableHandleValue vp); +typedef bool +(* ElementIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, uint32_t index, + JS::MutableHandleValue vp); +typedef bool +(* ElementIfPresentOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, + uint32_t index, JS::MutableHandleValue vp, bool* present); +typedef bool +(* SpecialIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, + HandleSpecialId sid, JS::MutableHandleValue vp); +typedef bool +(* StrictGenericIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* StrictPropertyIdOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* StrictElementIdOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* StrictSpecialIdOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* GenericAttributesOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, unsigned *attrsp); +typedef bool +(* PropertyAttributesOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + unsigned *attrsp); +typedef bool +(* DeletePropertyOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + bool *succeeded); +typedef bool +(* DeleteElementOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, bool *succeeded); +typedef bool +(* DeleteSpecialOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, bool *succeeded); + +typedef bool +(* WatchOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); + +typedef bool +(* UnwatchOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id); + +typedef JSObject * +(* ObjectOp)(JSContext *cx, JS::HandleObject obj); +typedef void +(* FinalizeOp)(FreeOp *fop, JSObject *obj); + +#define JS_CLASS_MEMBERS \ + const char *name; \ + uint32_t flags; \ + \ + /* Mandatory function pointer members. */ \ + JSPropertyOp addProperty; \ + JSDeletePropertyOp delProperty; \ + JSPropertyOp getProperty; \ + JSStrictPropertyOp setProperty; \ + JSEnumerateOp enumerate; \ + JSResolveOp resolve; \ + JSConvertOp convert; \ + \ + /* Optional members (may be null). */ \ + FinalizeOp finalize; \ + JSCheckAccessOp checkAccess; \ + JSNative call; \ + JSHasInstanceOp hasInstance; \ + JSNative construct; \ + JSTraceOp trace + +/* + * The helper struct to measure the size of JS_CLASS_MEMBERS to know how much + * we have to pad js::Class to match the size of JSClass. + */ +struct ClassSizeMeasurement +{ + JS_CLASS_MEMBERS; +}; + +struct ClassExtension +{ + JSObjectOp outerObject; + JSObjectOp innerObject; + JSIteratorOp iteratorObject; + + /* + * isWrappedNative is true only if the class is an XPCWrappedNative. + * WeakMaps use this to override the wrapper disposal optimization. + */ + bool isWrappedNative; + + /* + * If an object is used as a key in a weakmap, it may be desirable for the + * garbage collector to keep that object around longer than it otherwise + * would. A common case is when the key is a wrapper around an object in + * another compartment, and we want to avoid collecting the wrapper (and + * removing the weakmap entry) as long as the wrapped object is alive. In + * that case, the wrapped object is returned by the wrapper's + * weakmapKeyDelegateOp hook. As long as the wrapper is used as a weakmap + * key, it will not be collected (and remain in the weakmap) until the + * wrapped object is collected. + */ + JSWeakmapKeyDelegateOp weakmapKeyDelegateOp; +}; + +#define JS_NULL_CLASS_EXT {nullptr,nullptr,nullptr,false,nullptr} + +struct ObjectOps +{ + LookupGenericOp lookupGeneric; + LookupPropOp lookupProperty; + LookupElementOp lookupElement; + LookupSpecialOp lookupSpecial; + DefineGenericOp defineGeneric; + DefinePropOp defineProperty; + DefineElementOp defineElement; + DefineSpecialOp defineSpecial; + GenericIdOp getGeneric; + PropertyIdOp getProperty; + ElementIdOp getElement; + ElementIfPresentOp getElementIfPresent; /* can be null */ + SpecialIdOp getSpecial; + StrictGenericIdOp setGeneric; + StrictPropertyIdOp setProperty; + StrictElementIdOp setElement; + StrictSpecialIdOp setSpecial; + GenericAttributesOp getGenericAttributes; + GenericAttributesOp setGenericAttributes; + DeletePropertyOp deleteProperty; + DeleteElementOp deleteElement; + DeleteSpecialOp deleteSpecial; + WatchOp watch; + UnwatchOp unwatch; + + JSNewEnumerateOp enumerate; + ObjectOp thisObject; +}; + +#define JS_NULL_OBJECT_OPS \ + {nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr, \ + nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr, \ + nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr} + +} // namespace js + +// Classes, objects, and properties. + +typedef void (*JSClassInternal)(); + +struct JSClass { + const char *name; + uint32_t flags; + + // Mandatory function pointer members. + JSPropertyOp addProperty; + JSDeletePropertyOp delProperty; + JSPropertyOp getProperty; + JSStrictPropertyOp setProperty; + JSEnumerateOp enumerate; + JSResolveOp resolve; + JSConvertOp convert; + + // Optional members (may be null). + JSFinalizeOp finalize; + JSCheckAccessOp checkAccess; + JSNative call; + JSHasInstanceOp hasInstance; + JSNative construct; + JSTraceOp trace; + + void *reserved[42]; +}; + +#define JSCLASS_HAS_PRIVATE (1<<0) // objects have private slot +#define JSCLASS_NEW_ENUMERATE (1<<1) // has JSNewEnumerateOp hook +#define JSCLASS_NEW_RESOLVE (1<<2) // has JSNewResolveOp hook +#define JSCLASS_PRIVATE_IS_NSISUPPORTS (1<<3) // private is (nsISupports *) +#define JSCLASS_IS_DOMJSCLASS (1<<4) // objects are DOM +#define JSCLASS_IMPLEMENTS_BARRIERS (1<<5) // Correctly implements GC read + // and write barriers +#define JSCLASS_EMULATES_UNDEFINED (1<<6) // objects of this class act + // like the value undefined, + // in some contexts +#define JSCLASS_USERBIT1 (1<<7) // Reserved for embeddings. + +// To reserve slots fetched and stored via JS_Get/SetReservedSlot, bitwise-or +// JSCLASS_HAS_RESERVED_SLOTS(n) into the initializer for JSClass.flags, where +// n is a constant in [1, 255]. Reserved slots are indexed from 0 to n-1. +#define JSCLASS_RESERVED_SLOTS_SHIFT 8 // room for 8 flags below */ +#define JSCLASS_RESERVED_SLOTS_WIDTH 8 // and 16 above this field */ +#define JSCLASS_RESERVED_SLOTS_MASK JS_BITMASK(JSCLASS_RESERVED_SLOTS_WIDTH) +#define JSCLASS_HAS_RESERVED_SLOTS(n) (((n) & JSCLASS_RESERVED_SLOTS_MASK) \ + << JSCLASS_RESERVED_SLOTS_SHIFT) +#define JSCLASS_RESERVED_SLOTS(clasp) (((clasp)->flags \ + >> JSCLASS_RESERVED_SLOTS_SHIFT) \ + & JSCLASS_RESERVED_SLOTS_MASK) + +#define JSCLASS_HIGH_FLAGS_SHIFT (JSCLASS_RESERVED_SLOTS_SHIFT + \ + JSCLASS_RESERVED_SLOTS_WIDTH) + +#define JSCLASS_IS_ANONYMOUS (1<<(JSCLASS_HIGH_FLAGS_SHIFT+0)) +#define JSCLASS_IS_GLOBAL (1<<(JSCLASS_HIGH_FLAGS_SHIFT+1)) +#define JSCLASS_INTERNAL_FLAG2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+2)) +#define JSCLASS_INTERNAL_FLAG3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+3)) + +// Indicate whether the proto or ctor should be frozen. +#define JSCLASS_FREEZE_PROTO (1<<(JSCLASS_HIGH_FLAGS_SHIFT+4)) +#define JSCLASS_FREEZE_CTOR (1<<(JSCLASS_HIGH_FLAGS_SHIFT+5)) + +// Reserved for embeddings. +#define JSCLASS_USERBIT2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+6)) +#define JSCLASS_USERBIT3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+7)) + +#define JSCLASS_BACKGROUND_FINALIZE (1<<(JSCLASS_HIGH_FLAGS_SHIFT+8)) + +// Bits 26 through 31 are reserved for the CACHED_PROTO_KEY mechanism, see +// below. + +// ECMA-262 requires that most constructors used internally create objects +// with "the original Foo.prototype value" as their [[Prototype]] (__proto__) +// member initial value. The "original ... value" verbiage is there because +// in ECMA-262, global properties naming class objects are read/write and +// deleteable, for the most part. +// +// Implementing this efficiently requires that global objects have classes +// with the following flags. Failure to use JSCLASS_GLOBAL_FLAGS was +// previously allowed, but is now an ES5 violation and thus unsupported. +// +#define JSCLASS_GLOBAL_SLOT_COUNT (3 + JSProto_LIMIT * 3 + 28) +#define JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(n) \ + (JSCLASS_IS_GLOBAL | JSCLASS_HAS_RESERVED_SLOTS(JSCLASS_GLOBAL_SLOT_COUNT + (n))) +#define JSCLASS_GLOBAL_FLAGS \ + JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(0) +#define JSCLASS_HAS_GLOBAL_FLAG_AND_SLOTS(clasp) \ + (((clasp)->flags & JSCLASS_IS_GLOBAL) \ + && JSCLASS_RESERVED_SLOTS(clasp) >= JSCLASS_GLOBAL_SLOT_COUNT) + +// Fast access to the original value of each standard class's prototype. +#define JSCLASS_CACHED_PROTO_SHIFT (JSCLASS_HIGH_FLAGS_SHIFT + 10) +#define JSCLASS_CACHED_PROTO_WIDTH 6 +#define JSCLASS_CACHED_PROTO_MASK JS_BITMASK(JSCLASS_CACHED_PROTO_WIDTH) +#define JSCLASS_HAS_CACHED_PROTO(key) (uint32_t(key) << JSCLASS_CACHED_PROTO_SHIFT) +#define JSCLASS_CACHED_PROTO_KEY(clasp) ((JSProtoKey) \ + (((clasp)->flags \ + >> JSCLASS_CACHED_PROTO_SHIFT) \ + & JSCLASS_CACHED_PROTO_MASK)) + +// Initializer for unused members of statically initialized JSClass structs. +#define JSCLASS_NO_INTERNAL_MEMBERS {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} +#define JSCLASS_NO_OPTIONAL_MEMBERS 0,0,0,0,0,JSCLASS_NO_INTERNAL_MEMBERS + +namespace js { + +struct Class +{ + JS_CLASS_MEMBERS; + ClassExtension ext; + ObjectOps ops; + uint8_t pad[sizeof(JSClass) - sizeof(ClassSizeMeasurement) - + sizeof(ClassExtension) - sizeof(ObjectOps)]; + + /* Class is not native and its map is not a scope. */ + static const uint32_t NON_NATIVE = JSCLASS_INTERNAL_FLAG2; + + bool isNative() const { + return !(flags & NON_NATIVE); + } + + bool hasPrivate() const { + return !!(flags & JSCLASS_HAS_PRIVATE); + } + + bool emulatesUndefined() const { + return flags & JSCLASS_EMULATES_UNDEFINED; + } + + bool isCallable() const { + return this == js::FunctionClassPtr || call; + } + + static size_t offsetOfFlags() { return offsetof(Class, flags); } +}; + +JS_STATIC_ASSERT(offsetof(JSClass, name) == offsetof(Class, name)); +JS_STATIC_ASSERT(offsetof(JSClass, flags) == offsetof(Class, flags)); +JS_STATIC_ASSERT(offsetof(JSClass, addProperty) == offsetof(Class, addProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, delProperty) == offsetof(Class, delProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, getProperty) == offsetof(Class, getProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, setProperty) == offsetof(Class, setProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, enumerate) == offsetof(Class, enumerate)); +JS_STATIC_ASSERT(offsetof(JSClass, resolve) == offsetof(Class, resolve)); +JS_STATIC_ASSERT(offsetof(JSClass, convert) == offsetof(Class, convert)); +JS_STATIC_ASSERT(offsetof(JSClass, finalize) == offsetof(Class, finalize)); +JS_STATIC_ASSERT(offsetof(JSClass, checkAccess) == offsetof(Class, checkAccess)); +JS_STATIC_ASSERT(offsetof(JSClass, call) == offsetof(Class, call)); +JS_STATIC_ASSERT(offsetof(JSClass, construct) == offsetof(Class, construct)); +JS_STATIC_ASSERT(offsetof(JSClass, hasInstance) == offsetof(Class, hasInstance)); +JS_STATIC_ASSERT(offsetof(JSClass, trace) == offsetof(Class, trace)); +JS_STATIC_ASSERT(sizeof(JSClass) == sizeof(Class)); + +static JS_ALWAYS_INLINE const JSClass * +Jsvalify(const Class *c) +{ + return (const JSClass *)c; +} + +static JS_ALWAYS_INLINE const Class * +Valueify(const JSClass *c) +{ + return (const Class *)c; +} + +/* + * Enumeration describing possible values of the [[Class]] internal property + * value of objects. + */ +enum ESClassValue { + ESClass_Array, ESClass_Number, ESClass_String, ESClass_Boolean, + ESClass_RegExp, ESClass_ArrayBuffer, ESClass_Date +}; + +/* + * Return whether the given object has the given [[Class]] internal property + * value. Beware, this query says nothing about the js::Class of the JSObject + * so the caller must not assume anything about obj's representation (e.g., obj + * may be a proxy). + */ +inline bool +ObjectClassIs(JSObject &obj, ESClassValue classValue, JSContext *cx); + +/* Just a helper that checks v.isObject before calling ObjectClassIs. */ +inline bool +IsObjectWithClass(const JS::Value &v, ESClassValue classValue, JSContext *cx); + +inline bool +IsPoisonedSpecialId(js::SpecialId iden) +{ + if (iden.isObject()) + return JS::IsPoisonedPtr(iden.toObject()); + return false; +} + +template <> struct GCMethods +{ + static SpecialId initial() { return SpecialId(); } + static ThingRootKind kind() { return THING_ROOT_ID; } + static bool poisoned(SpecialId id) { return IsPoisonedSpecialId(id); } +}; + +} /* namespace js */ + +#endif /* js_Class_h */ diff --git a/external/spidermonkey/include/android/js/GCAPI.h b/external/spidermonkey/include/android/js/GCAPI.h index a9bef77c09..9cdf56bcce 100644 --- a/external/spidermonkey/include/android/js/GCAPI.h +++ b/external/spidermonkey/include/android/js/GCAPI.h @@ -7,7 +7,11 @@ #ifndef js_GCAPI_h #define js_GCAPI_h +#include "mozilla/NullPtr.h" + #include "js/HeapAPI.h" +#include "js/RootingAPI.h" +#include "js/Value.h" namespace JS { @@ -15,13 +19,12 @@ namespace JS { /* Reasons internal to the JS engine */ \ D(API) \ D(MAYBEGC) \ - D(LAST_CONTEXT) \ + D(DESTROY_RUNTIME) \ D(DESTROY_CONTEXT) \ D(LAST_DITCH) \ D(TOO_MUCH_MALLOC) \ D(ALLOC_TRIGGER) \ D(DEBUG_GC) \ - D(DEBUG_MODE_GC) \ D(TRANSPLANT) \ D(RESET) \ D(OUT_OF_NURSERY) \ @@ -206,12 +209,25 @@ PokeGC(JSRuntime *rt); extern JS_FRIEND_API(bool) WasIncrementalGC(JSRuntime *rt); -class ObjectPtr +extern JS_FRIEND_API(size_t) +GetGCNumber(); + +class AutoAssertNoGC { +#ifdef DEBUG + size_t gcNumber; + + public: + AutoAssertNoGC(); + ~AutoAssertNoGC(); +#endif +}; + +class JS_PUBLIC_API(ObjectPtr) { Heap value; public: - ObjectPtr() : value(NULL) {} + ObjectPtr() : value(nullptr) {} ObjectPtr(JSObject *obj) : value(obj) {} @@ -221,7 +237,7 @@ class ObjectPtr void finalize(JSRuntime *rt) { if (IsIncrementalBarrierNeeded(rt)) IncrementalObjectBarrier(value); - value = NULL; + value = nullptr; } void init(JSObject *obj) { value = obj; } @@ -232,9 +248,7 @@ class ObjectPtr IncrementalObjectBarrier(value); } - bool isAboutToBeFinalized() { - return JS_IsAboutToBeFinalized(&value); - } + bool isAboutToBeFinalized(); ObjectPtr &operator=(JSObject *obj) { IncrementalObjectBarrier(value); @@ -242,9 +256,7 @@ class ObjectPtr return *this; } - void trace(JSTracer *trc, const char *name) { - JS_CallHeapObjectTracer(trc, &value, name); - } + void trace(JSTracer *trc, const char *name); JSObject &operator*() const { return *value; } JSObject *operator->() const { return value; } @@ -255,7 +267,7 @@ class ObjectPtr * Unsets the gray bit for anything reachable from |thing|. |kind| should not be * JSTRACE_SHAPE. |thing| should be non-null. */ -extern JS_FRIEND_API(void) +extern JS_FRIEND_API(bool) UnmarkGrayGCThingRecursively(void *thing, JSGCTraceKind kind); /* @@ -276,7 +288,7 @@ ExposeGCThingToActiveJS(void *thing, JSGCTraceKind kind) * All live objects in the nursery are moved to tenured at the beginning of * each GC slice, so the gray marker never sees nursery things. */ - if (uintptr_t(thing) >= rt->gcNurseryStart_ && uintptr_t(thing) < rt->gcNurseryEnd_) + if (js::gc::IsInsideNursery(rt, thing)) return; #endif if (IsIncrementalBarrierNeededOnGCThing(rt, thing, kind)) @@ -292,6 +304,37 @@ ExposeValueToActiveJS(const Value &v) ExposeGCThingToActiveJS(v.toGCThing(), v.gcKind()); } +static JS_ALWAYS_INLINE void +ExposeObjectToActiveJS(JSObject *obj) +{ + ExposeGCThingToActiveJS(obj, JSTRACE_OBJECT); +} + +/* + * If a GC is currently marking, mark the object black. + */ +static JS_ALWAYS_INLINE void +MarkGCThingAsLive(JSRuntime *rt_, void *thing, JSGCTraceKind kind) +{ + shadow::Runtime *rt = shadow::Runtime::asShadowRuntime(rt_); +#ifdef JSGC_GENERATIONAL + /* + * Any object in the nursery will not be freed during any GC running at that time. + */ + if (js::gc::IsInsideNursery(rt, thing)) + return; +#endif + if (IsIncrementalBarrierNeededOnGCThing(rt, thing, kind)) + IncrementalReferenceBarrier(thing, kind); +} + +static JS_ALWAYS_INLINE void +MarkStringAsLive(Zone *zone, JSString *string) +{ + JSRuntime *rt = JS::shadow::Zone::asShadowZone(zone)->runtimeFromMainThread(); + MarkGCThingAsLive(rt, string, JSTRACE_STRING); +} + } /* namespace JS */ #endif /* js_GCAPI_h */ diff --git a/external/spidermonkey/include/android/js/HashTable.h b/external/spidermonkey/include/android/js/HashTable.h index aa05b71472..a6b4361dea 100644 --- a/external/spidermonkey/include/android/js/HashTable.h +++ b/external/spidermonkey/include/android/js/HashTable.h @@ -7,17 +7,18 @@ #ifndef js_HashTable_h #define js_HashTable_h +#include "mozilla/Alignment.h" #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Casting.h" #include "mozilla/DebugOnly.h" #include "mozilla/MemoryReporting.h" #include "mozilla/Move.h" +#include "mozilla/NullPtr.h" #include "mozilla/PodOperations.h" #include "mozilla/ReentrancyGuard.h" #include "mozilla/TemplateLib.h" #include "mozilla/TypeTraits.h" -#include "mozilla/Util.h" #include "js/Utility.h" @@ -60,7 +61,7 @@ class HashMap { typedef Key KeyType; static const Key &getKey(TableEntry &e) { return e.key; } - static void setKey(TableEntry &e, Key &k) { const_cast(e.key) = k; } + static void setKey(TableEntry &e, Key &k) { HashPolicy::rekey(const_cast(e.key), k); } }; typedef detail::HashTable Impl; @@ -138,18 +139,18 @@ class HashMap template bool add(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.add(p, mozilla::Move(e)); + return impl.add(p, mozilla::OldMove(e)); } bool add(AddPtr &p, const Key &k) { Entry e(k, Value()); - return impl.add(p, mozilla::Move(e)); + return impl.add(p, mozilla::OldMove(e)); } template bool relookupOrAdd(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.relookupOrAdd(p, k, mozilla::Move(e)); + return impl.relookupOrAdd(p, k, mozilla::OldMove(e)); } // |all()| returns a Range containing |count()| elements. E.g.: @@ -213,7 +214,7 @@ class HashMap /************************************************** Shorthand operations */ bool has(const Lookup &l) const { - return impl.lookup(l) != NULL; + return impl.lookup(l) != nullptr; } // Overwrite existing value with v. Return false on oom. @@ -231,7 +232,7 @@ class HashMap template bool putNew(const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.putNew(k, mozilla::Move(e)); + return impl.putNew(k, mozilla::OldMove(e)); } // Add (k,defaultValue) if |k| is not found. Return a false-y Ptr on oom. @@ -249,17 +250,22 @@ class HashMap remove(p); } + // Infallibly rekey one entry, if necessary. + // Requires template parameters Key and HashPolicy::Lookup to be the same type. + void rekeyIfMoved(const Key &old_key, const Key &new_key) { + if (old_key != new_key) + rekeyAs(old_key, new_key, new_key); + } + // Infallibly rekey one entry, if present. - void rekey(const Lookup &old_key, const Key &new_key) { - if (old_key != new_key) { - if (Ptr p = lookup(old_key)) - impl.rekey(p, new_key, new_key); - } + void rekeyAs(const Lookup &old_lookup, const Lookup &new_lookup, const Key &new_key) { + if (Ptr p = lookup(old_lookup)) + impl.rekeyAndMaybeRehash(p, new_lookup, new_key); } // HashMap is movable - HashMap(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} - void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } + HashMap(mozilla::MoveRef rhs) : impl(mozilla::OldMove(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::OldMove(rhs->impl); } private: // HashMap is not copyable or assignable @@ -295,7 +301,7 @@ class HashSet { typedef T KeyType; static const KeyType &getKey(const T &t) { return t; } - static void setKey(T &t, KeyType &k) { t = k; } + static void setKey(T &t, KeyType &k) { HashPolicy::rekey(t, k); } }; typedef detail::HashTable Impl; @@ -323,6 +329,10 @@ class HashSet typedef typename Impl::Ptr Ptr; Ptr lookup(const Lookup &l) const { return impl.lookup(l); } + // Like lookup, but does not assert if two threads call lookup at the same + // time. Only use this method when none of the threads will modify the map. + Ptr readonlyThreadsafeLookup(const Lookup &l) const { return impl.readonlyThreadsafeLookup(l); } + // Assuming |p.found()|, remove |*p|. void remove(Ptr p) { impl.remove(p); } @@ -425,7 +435,7 @@ class HashSet /************************************************** Shorthand operations */ bool has(const Lookup &l) const { - return impl.lookup(l) != NULL; + return impl.lookup(l) != nullptr; } // Overwrite existing value with v. Return false on oom. @@ -449,16 +459,21 @@ class HashSet } // Infallibly rekey one entry, if present. - void rekey(const Lookup &old_key, const T &new_key) { - if (old_key != new_key) { - if (Ptr p = lookup(old_key)) - impl.rekey(p, new_key, new_key); - } + // Requires template parameters T and HashPolicy::Lookup to be the same type. + void rekeyIfMoved(const Lookup &old_value, const T &new_value) { + if (old_value != new_value) + rekeyAs(old_value, new_value, new_value); + } + + // Infallibly rekey one entry, if present. + void rekeyAs(const Lookup &old_lookup, const Lookup &new_lookup, const T &new_value) { + if (Ptr p = lookup(old_lookup)) + impl.rekeyAndMaybeRehash(p, new_lookup, new_value); } // HashSet is movable - HashSet(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} - void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } + HashSet(mozilla::MoveRef rhs) : impl(mozilla::OldMove(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::OldMove(rhs->impl); } private: // HashSet is not copyable or assignable @@ -505,7 +520,7 @@ struct PointerHasher JS_ASSERT(!JS::IsPoisonedPtr(l)); size_t word = reinterpret_cast(l) >> zeroBits; JS_STATIC_ASSERT(sizeof(HashNumber) == 4); -#if JS_BYTES_PER_WORD == 4 +#if JS_BITS_PER_WORD == 32 return HashNumber(word); #else JS_STATIC_ASSERT(sizeof word == 8); @@ -517,6 +532,9 @@ struct PointerHasher JS_ASSERT(!JS::IsPoisonedPtr(l)); return k == l; } + static void rekey(Key &k, const Key& newKey) { + k = newKey; + } }; // Default hash policy: just use the 'lookup' value. This of course only @@ -535,6 +553,9 @@ struct DefaultHasher // Use builtin or overloaded operator==. return k == l; } + static void rekey(Key &k, const Key& newKey) { + k = newKey; + } }; // Specialize hashing policy for pointer types. It assumes that the type is @@ -558,6 +579,19 @@ struct DefaultHasher } }; +template <> +struct DefaultHasher +{ + typedef float Lookup; + static HashNumber hash(float f) { + JS_STATIC_ASSERT(sizeof(HashNumber) == 4); + return HashNumber(mozilla::BitwiseCast(f)); + } + static bool match(float lhs, float rhs) { + return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); + } +}; + /*****************************************************************************/ // Both HashMap and HashSet are implemented by a single HashTable that is even @@ -579,7 +613,7 @@ class HashMapEntry HashMapEntry(const KeyInput &k, const ValueInput &v) : key(k), value(v) {} HashMapEntry(mozilla::MoveRef rhs) - : key(mozilla::Move(rhs->key)), value(mozilla::Move(rhs->value)) { } + : key(mozilla::OldMove(rhs->key)), value(mozilla::OldMove(rhs->value)) { } typedef Key KeyType; typedef Value ValueType; @@ -750,7 +784,7 @@ class HashTable : private AllocPolicy mozilla::DebugOnly validEntry; public: - Range() : cur(NULL), end(NULL), validEntry(false) {} + Range() : cur(nullptr), end(nullptr), validEntry(false) {} bool empty() const { return cur == end; @@ -808,7 +842,7 @@ class HashTable : private AllocPolicy // a new key at the new Lookup position. |front()| is invalid after // this operation until the next call to |popFront()|. void rekeyFront(const Lookup &l, const Key &k) { - table.rekey(*this->cur, l, k); + table.rekeyWithoutRehash(*this->cur, l, k); rekeyed = true; this->validEntry = false; } @@ -834,13 +868,13 @@ class HashTable : private AllocPolicy : AllocPolicy(*rhs) { mozilla::PodAssign(this, &*rhs); - rhs->table = NULL; + rhs->table = nullptr; } void operator=(mozilla::MoveRef rhs) { if (table) destroyTable(*this, table, capacity()); mozilla::PodAssign(this, &*rhs); - rhs->table = NULL; + rhs->table = nullptr; } private: @@ -941,7 +975,7 @@ class HashTable : private AllocPolicy entryCount(0), gen(0), removedCount(0), - table(NULL), + table(nullptr), entered(false), mutationCount(0) {} @@ -1067,7 +1101,7 @@ class HashTable : private AllocPolicy DoubleHash dh = hash2(keyHash); // Save the first removed entry pointer so we can recycle later. - Entry *firstRemoved = NULL; + Entry *firstRemoved = nullptr; while(true) { if (JS_UNLIKELY(entry->isRemoved())) { @@ -1163,7 +1197,7 @@ class HashTable : private AllocPolicy for (Entry *src = oldTable, *end = src + oldCap; src < end; ++src) { if (src->isLive()) { HashNumber hn = src->getKeyHash(); - findFreeEntry(hn).setLive(hn, mozilla::Move(src->get())); + findFreeEntry(hn).setLive(hn, mozilla::OldMove(src->get())); src->destroy(); } } @@ -1307,7 +1341,7 @@ class HashTable : private AllocPolicy return; destroyTable(*this, table, capacity()); - table = NULL; + table = nullptr; gen++; entryCount = 0; removedCount = 0; @@ -1456,15 +1490,21 @@ class HashTable : private AllocPolicy checkUnderloaded(); } - void rekey(Ptr p, const Lookup &l, const Key &k) + void rekeyWithoutRehash(Ptr p, const Lookup &l, const Key &k) { JS_ASSERT(table); mozilla::ReentrancyGuard g(*this); JS_ASSERT(p.found()); - typename HashTableEntry::NonConstT t(mozilla::Move(*p)); + typename HashTableEntry::NonConstT t(mozilla::OldMove(*p)); HashPolicy::setKey(t, const_cast(k)); remove(*p.entry_); - putNewInfallible(l, mozilla::Move(t)); + putNewInfallible(l, mozilla::OldMove(t)); + } + + void rekeyAndMaybeRehash(Ptr p, const Lookup &l, const Key &k) + { + rekeyWithoutRehash(p, l, k); + checkOverRemoved(); } #undef METER diff --git a/external/spidermonkey/include/android/js/HeapAPI.h b/external/spidermonkey/include/android/js/HeapAPI.h index 4d739304bc..438c23c05f 100644 --- a/external/spidermonkey/include/android/js/HeapAPI.h +++ b/external/spidermonkey/include/android/js/HeapAPI.h @@ -7,12 +7,23 @@ #ifndef js_HeapAPI_h #define js_HeapAPI_h +#include + #include "jspubtd.h" #include "js/Utility.h" /* These values are private to the JS engine. */ namespace js { + +// Whether the current thread is permitted access to any part of the specified +// runtime or zone. +JS_FRIEND_API(bool) +CurrentThreadCanAccessRuntime(JSRuntime *rt); + +JS_FRIEND_API(bool) +CurrentThreadCanAccessZone(JS::Zone *zone); + namespace gc { const size_t ArenaShift = 12; @@ -57,9 +68,43 @@ struct ArenaHeader struct Zone { + protected: + JSRuntime *const runtime_; + JSTracer *const barrierTracer_; // A pointer to the JSRuntime's |gcMarker|. + + public: bool needsBarrier_; - Zone() : needsBarrier_(false) {} + Zone(JSRuntime *runtime, JSTracer *barrierTracerArg) + : runtime_(runtime), + barrierTracer_(barrierTracerArg), + needsBarrier_(false) + {} + + bool needsBarrier() const { + return needsBarrier_; + } + + JSTracer *barrierTracer() { + JS_ASSERT(needsBarrier_); + JS_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); + return barrierTracer_; + } + + JSRuntime *runtimeFromMainThread() const { + JS_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); + return runtime_; + } + + // Note: Unrestricted access to the zone's runtime from an arbitrary + // thread can easily lead to races. Use this method very carefully. + JSRuntime *runtimeFromAnyThread() const { + return runtime_; + } + + static JS::shadow::Zone *asShadowZone(JS::Zone *zone) { + return reinterpret_cast(zone); + } }; } /* namespace shadow */ @@ -94,8 +139,9 @@ GetGCThingMarkWordAndMask(const void *thing, uint32_t color, size_t bit = (addr & js::gc::ChunkMask) / js::gc::CellSize + color; JS_ASSERT(bit < js::gc::ChunkMarkBitmapBits); uintptr_t *bitmap = GetGCThingMarkBitmap(thing); - *maskp = uintptr_t(1) << (bit % JS_BITS_PER_WORD); - *wordp = &bitmap[bit / JS_BITS_PER_WORD]; + const uintptr_t nbits = sizeof(*bitmap) * CHAR_BIT; + *maskp = uintptr_t(1) << (bit % nbits); + *wordp = &bitmap[bit / nbits]; } static JS_ALWAYS_INLINE JS::shadow::ArenaHeader * @@ -106,6 +152,16 @@ GetGCThingArena(void *thing) return reinterpret_cast(addr); } +JS_ALWAYS_INLINE bool +IsInsideNursery(const JS::shadow::Runtime *runtime, const void *p) +{ +#ifdef JSGC_GENERATIONAL + return uintptr_t(p) >= runtime->gcNurseryStart_ && uintptr_t(p) < runtime->gcNurseryEnd_; +#else + return false; +#endif +} + } /* namespace gc */ } /* namespace js */ @@ -128,6 +184,16 @@ GetObjectZone(JSObject *obj) static JS_ALWAYS_INLINE bool GCThingIsMarkedGray(void *thing) { +#ifdef JSGC_GENERATIONAL + /* + * GC things residing in the nursery cannot be gray: they have no mark bits. + * All live objects in the nursery are moved to tenured at the beginning of + * each GC slice, so the gray marker never sees nursery things. + */ + JS::shadow::Runtime *rt = js::gc::GetGCThingRuntime(thing); + if (js::gc::IsInsideNursery(rt, thing)) + return false; +#endif uintptr_t *word, mask; js::gc::GetGCThingMarkWordAndMask(thing, js::gc::GRAY, &word, &mask); return *word & mask; diff --git a/external/spidermonkey/include/android/js/Id.h b/external/spidermonkey/include/android/js/Id.h new file mode 100644 index 0000000000..447deb62e6 --- /dev/null +++ b/external/spidermonkey/include/android/js/Id.h @@ -0,0 +1,192 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_Id_h +#define js_Id_h + +// A jsid is an identifier for a property or method of an object which is +// either a 31-bit signed integer, interned string or object. +// +// Also, there is an additional jsid value, JSID_VOID, which does not occur in +// JS scripts but may be used to indicate the absence of a valid jsid. A void +// jsid is not a valid id and only arises as an exceptional API return value, +// such as in JS_NextProperty. Embeddings must not pass JSID_VOID into JSAPI +// entry points expecting a jsid and do not need to handle JSID_VOID in hooks +// receiving a jsid except when explicitly noted in the API contract. +// +// A jsid is not implicitly convertible to or from a jsval; JS_ValueToId or +// JS_IdToValue must be used instead. + +#include "mozilla/NullPtr.h" + +#include "jstypes.h" + +#include "js/RootingAPI.h" +#include "js/TypeDecls.h" +#include "js/Utility.h" + +#ifdef JS_USE_JSID_STRUCT_TYPES +struct jsid +{ + size_t asBits; + bool operator==(jsid rhs) const { return asBits == rhs.asBits; } + bool operator!=(jsid rhs) const { return asBits != rhs.asBits; } +}; +# define JSID_BITS(id) (id.asBits) +#else +# define JSID_BITS(id) (id) +#endif + +#define JSID_TYPE_STRING 0x0 +#define JSID_TYPE_INT 0x1 +#define JSID_TYPE_VOID 0x2 +#define JSID_TYPE_OBJECT 0x4 +#define JSID_TYPE_MASK 0x7 + +// Avoid using canonical 'id' for jsid parameters since this is a magic word in +// Objective-C++ which, apparently, wants to be able to #include jsapi.h. +#define id iden + +static JS_ALWAYS_INLINE bool +JSID_IS_STRING(jsid id) +{ + return (JSID_BITS(id) & JSID_TYPE_MASK) == 0; +} + +static JS_ALWAYS_INLINE JSString * +JSID_TO_STRING(jsid id) +{ + JS_ASSERT(JSID_IS_STRING(id)); + return (JSString *)JSID_BITS(id); +} + +static JS_ALWAYS_INLINE bool +JSID_IS_ZERO(jsid id) +{ + return JSID_BITS(id) == 0; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_INT(jsid id) +{ + return !!(JSID_BITS(id) & JSID_TYPE_INT); +} + +static JS_ALWAYS_INLINE int32_t +JSID_TO_INT(jsid id) +{ + JS_ASSERT(JSID_IS_INT(id)); + return ((uint32_t)JSID_BITS(id)) >> 1; +} + +#define JSID_INT_MIN 0 +#define JSID_INT_MAX INT32_MAX + +static JS_ALWAYS_INLINE bool +INT_FITS_IN_JSID(int32_t i) +{ + return i >= 0; +} + +static JS_ALWAYS_INLINE jsid +INT_TO_JSID(int32_t i) +{ + jsid id; + JS_ASSERT(INT_FITS_IN_JSID(i)); + JSID_BITS(id) = ((i << 1) | JSID_TYPE_INT); + return id; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_OBJECT(jsid id) +{ + return (JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_OBJECT && + (size_t)JSID_BITS(id) != JSID_TYPE_OBJECT; +} + +static JS_ALWAYS_INLINE JSObject * +JSID_TO_OBJECT(jsid id) +{ + JS_ASSERT(JSID_IS_OBJECT(id)); + return (JSObject *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); +} + +static JS_ALWAYS_INLINE jsid +OBJECT_TO_JSID(JSObject *obj) +{ + jsid id; + JS_ASSERT(obj != nullptr); + JS_ASSERT(((size_t)obj & JSID_TYPE_MASK) == 0); + JSID_BITS(id) = ((size_t)obj | JSID_TYPE_OBJECT); + return id; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_GCTHING(jsid id) +{ + return JSID_IS_STRING(id) || JSID_IS_OBJECT(id); +} + +static JS_ALWAYS_INLINE void * +JSID_TO_GCTHING(jsid id) +{ + return (void *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); +} + +static JS_ALWAYS_INLINE bool +JSID_IS_VOID(const jsid id) +{ + JS_ASSERT_IF(((size_t)JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_VOID, + JSID_BITS(id) == JSID_TYPE_VOID); + return ((size_t)JSID_BITS(id) == JSID_TYPE_VOID); +} + +static JS_ALWAYS_INLINE bool +JSID_IS_EMPTY(const jsid id) +{ + return ((size_t)JSID_BITS(id) == JSID_TYPE_OBJECT); +} + +#undef id + +#ifdef JS_USE_JSID_STRUCT_TYPES +extern JS_PUBLIC_DATA(const jsid) JSID_VOID; +extern JS_PUBLIC_DATA(const jsid) JSID_EMPTY; +#else +# define JSID_VOID ((jsid)JSID_TYPE_VOID) +# define JSID_EMPTY ((jsid)JSID_TYPE_OBJECT) +#endif + +extern JS_PUBLIC_DATA(const JS::Handle) JSID_VOIDHANDLE; +extern JS_PUBLIC_DATA(const JS::Handle) JSID_EMPTYHANDLE; + +namespace js { + +inline bool +IsPoisonedId(jsid iden) +{ + if (JSID_IS_STRING(iden)) + return JS::IsPoisonedPtr(JSID_TO_STRING(iden)); + if (JSID_IS_OBJECT(iden)) + return JS::IsPoisonedPtr(JSID_TO_OBJECT(iden)); + return false; +} + +template <> struct GCMethods +{ + static jsid initial() { return JSID_VOID; } + static ThingRootKind kind() { return THING_ROOT_ID; } + static bool poisoned(jsid id) { return IsPoisonedId(id); } + static bool needsPostBarrier(jsid id) { return false; } +#ifdef JSGC_GENERATIONAL + static void postBarrier(jsid *idp) {} + static void relocate(jsid *idp) {} +#endif +}; + +} + +#endif /* js_Id_h */ diff --git a/external/spidermonkey/include/android/js/MemoryMetrics.h b/external/spidermonkey/include/android/js/MemoryMetrics.h index ed61e1c427..2336e35624 100644 --- a/external/spidermonkey/include/android/js/MemoryMetrics.h +++ b/external/spidermonkey/include/android/js/MemoryMetrics.h @@ -7,20 +7,54 @@ #ifndef js_MemoryMetrics_h #define js_MemoryMetrics_h -// These declarations are not within jsapi.h because they are highly likely to -// change in the future. Depend on them at your own risk. +// These declarations are highly likely to change in the future. Depend on them +// at your own risk. #include "mozilla/MemoryReporting.h" +#include "mozilla/NullPtr.h" +#include "mozilla/PodOperations.h" #include #include "jsalloc.h" #include "jspubtd.h" +#include "js/HashTable.h" #include "js/Utility.h" #include "js/Vector.h" -class nsISupports; // This is needed for ObjectPrivateVisitor. +class nsISupports; // Needed for ObjectPrivateVisitor. + +namespace JS { + +struct TabSizes +{ + enum Kind { + Objects, + Strings, + Private, + Other + }; + + TabSizes() { mozilla::PodZero(this); } + + void add(Kind kind, size_t n) { + switch (kind) { + case Objects: objects += n; break; + case Strings: strings += n; break; + case Private: private_ += n; break; + case Other: other += n; break; + default: MOZ_CRASH("bad TabSizes kind"); + } + } + + size_t objects; + size_t strings; + size_t private_; + size_t other; +}; + +} // namespace JS namespace js { @@ -30,9 +64,86 @@ namespace js { // MemoryReportingSundriesThreshold() bytes. // // We need to define this value here, rather than in the code which actually -// generates the memory reports, because HugeStringInfo uses this value. +// generates the memory reports, because NotableStringInfo uses this value. JS_FRIEND_API(size_t) MemoryReportingSundriesThreshold(); +// This hash policy avoids flattening ropes (which perturbs the site being +// measured and requires a JSContext) at the expense of doing a FULL ROPE COPY +// on every hash and match! Beware. +struct InefficientNonFlatteningStringHashPolicy +{ + typedef JSString *Lookup; + static HashNumber hash(const Lookup &l); + static bool match(const JSString *const &k, const Lookup &l); +}; + +// This file features many classes with numerous size_t fields, and each such +// class has one or more methods that need to operate on all of these fields. +// Writing these individually is error-prone -- it's easy to add a new field +// without updating all the required methods. So we define a single macro list +// in each class to name the fields (and notable characteristics of them), and +// then use the following macros to transform those lists into the required +// methods. +// +// In some classes, one or more of the macro arguments aren't used. We use '_' +// for those. +// +#define DECL_SIZE(kind, gc, mSize) size_t mSize; +#define ZERO_SIZE(kind, gc, mSize) mSize(0), +#define COPY_OTHER_SIZE(kind, gc, mSize) mSize(other.mSize), +#define ADD_OTHER_SIZE(kind, gc, mSize) mSize += other.mSize; +#define ADD_SIZE_TO_N_IF_LIVE_GC_THING(kind, gc, mSize) n += (js::gc == js::IsLiveGCThing) ? mSize : 0; +#define ADD_TO_TAB_SIZES(kind, gc, mSize) sizes->add(JS::TabSizes::kind, mSize); + +// Used to annotate which size_t fields measure live GC things and which don't. +enum { + NotLiveGCThing = false, + IsLiveGCThing = true +}; + +struct ZoneStatsPod +{ +#define FOR_EACH_SIZE(macro) \ + macro(Other, NotLiveGCThing, gcHeapArenaAdmin) \ + macro(Other, NotLiveGCThing, unusedGCThings) \ + macro(Other, IsLiveGCThing, lazyScriptsGCHeap) \ + macro(Other, NotLiveGCThing, lazyScriptsMallocHeap) \ + macro(Other, IsLiveGCThing, ionCodesGCHeap) \ + macro(Other, IsLiveGCThing, typeObjectsGCHeap) \ + macro(Other, NotLiveGCThing, typeObjectsMallocHeap) \ + macro(Other, NotLiveGCThing, typePool) \ + macro(Strings, IsLiveGCThing, stringsShortGCHeap) \ + macro(Strings, IsLiveGCThing, stringsNormalGCHeap) \ + macro(Strings, NotLiveGCThing, stringsNormalMallocHeap) + + ZoneStatsPod() + : FOR_EACH_SIZE(ZERO_SIZE) + extra() + {} + + void add(const ZoneStatsPod &other) { + FOR_EACH_SIZE(ADD_OTHER_SIZE) + // Do nothing with |extra|. + } + + size_t sizeOfLiveGCThings() const { + size_t n = 0; + FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) + // Do nothing with |extra|. + return n; + } + + void addToTabSizes(JS::TabSizes *sizes) const { + FOR_EACH_SIZE(ADD_TO_TAB_SIZES) + // Do nothing with |extra|. + } + + FOR_EACH_SIZE(DECL_SIZE) + void *extra; // This field can be used by embedders. + +#undef FOR_EACH_SIZE +}; + } // namespace js namespace JS { @@ -40,352 +151,320 @@ namespace JS { // Data for tracking memory usage of things hanging off objects. struct ObjectsExtraSizes { - size_t slots; - size_t elementsNonAsmJS; - size_t elementsAsmJSHeap; - size_t elementsAsmJSNonHeap; - size_t argumentsData; - size_t regExpStatics; - size_t propertyIteratorData; - size_t ctypesData; - size_t private_; // The '_' suffix is required because |private| is a keyword. - // Note that this field is measured separately from the others. +#define FOR_EACH_SIZE(macro) \ + macro(Objects, NotLiveGCThing, mallocHeapSlots) \ + macro(Objects, NotLiveGCThing, mallocHeapElementsNonAsmJS) \ + macro(Objects, NotLiveGCThing, mallocHeapElementsAsmJS) \ + macro(Objects, NotLiveGCThing, nonHeapElementsAsmJS) \ + macro(Objects, NotLiveGCThing, nonHeapCodeAsmJS) \ + macro(Objects, NotLiveGCThing, mallocHeapAsmJSModuleData) \ + macro(Objects, NotLiveGCThing, mallocHeapArgumentsData) \ + macro(Objects, NotLiveGCThing, mallocHeapRegExpStatics) \ + macro(Objects, NotLiveGCThing, mallocHeapPropertyIteratorData) \ + macro(Objects, NotLiveGCThing, mallocHeapCtypesData) - ObjectsExtraSizes() { memset(this, 0, sizeof(ObjectsExtraSizes)); } + ObjectsExtraSizes() + : FOR_EACH_SIZE(ZERO_SIZE) + dummy() + {} - void add(ObjectsExtraSizes &sizes) { - this->slots += sizes.slots; - this->elementsNonAsmJS += sizes.elementsNonAsmJS; - this->elementsAsmJSHeap += sizes.elementsAsmJSHeap; - this->elementsAsmJSNonHeap += sizes.elementsAsmJSNonHeap; - this->argumentsData += sizes.argumentsData; - this->regExpStatics += sizes.regExpStatics; - this->propertyIteratorData += sizes.propertyIteratorData; - this->ctypesData += sizes.ctypesData; - this->private_ += sizes.private_; + void add(const ObjectsExtraSizes &other) { + FOR_EACH_SIZE(ADD_OTHER_SIZE) } -}; -// Data for tracking analysis/inference memory usage. -struct TypeInferenceSizes -{ - size_t typeScripts; - size_t typeResults; - size_t analysisPool; - size_t pendingArrays; - size_t allocationSiteTables; - size_t arrayTypeTables; - size_t objectTypeTables; - - TypeInferenceSizes() { memset(this, 0, sizeof(TypeInferenceSizes)); } - - void add(TypeInferenceSizes &sizes) { - this->typeScripts += sizes.typeScripts; - this->typeResults += sizes.typeResults; - this->analysisPool += sizes.analysisPool; - this->pendingArrays += sizes.pendingArrays; - this->allocationSiteTables += sizes.allocationSiteTables; - this->arrayTypeTables += sizes.arrayTypeTables; - this->objectTypeTables += sizes.objectTypeTables; + size_t sizeOfLiveGCThings() const { + size_t n = 0; + FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) + return n; } + + void addToTabSizes(TabSizes *sizes) const { + FOR_EACH_SIZE(ADD_TO_TAB_SIZES) + } + + FOR_EACH_SIZE(DECL_SIZE) + int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) + +#undef FOR_EACH_SIZE }; // Data for tracking JIT-code memory usage. struct CodeSizes { - size_t ion; - size_t asmJS; - size_t baseline; - size_t regexp; - size_t other; - size_t unused; +#define FOR_EACH_SIZE(macro) \ + macro(_, _, ion) \ + macro(_, _, baseline) \ + macro(_, _, regexp) \ + macro(_, _, other) \ + macro(_, _, unused) - CodeSizes() { memset(this, 0, sizeof(CodeSizes)); } + CodeSizes() + : FOR_EACH_SIZE(ZERO_SIZE) + dummy() + {} + + FOR_EACH_SIZE(DECL_SIZE) + int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) + +#undef FOR_EACH_SIZE }; -// Holds data about a huge string (one which uses more HugeStringInfo::MinSize -// bytes of memory), so we can report it individually. -struct HugeStringInfo +// This class holds information about the memory taken up by identical copies of +// a particular string. Multiple JSStrings may have their sizes aggregated +// together into one StringInfo object. +struct StringInfo { - HugeStringInfo() : length(0), size(0) { memset(&buffer, 0, sizeof(buffer)); } + StringInfo() + : length(0), numCopies(0), shortGCHeap(0), normalGCHeap(0), normalMallocHeap(0) + {} + + StringInfo(size_t len, size_t shorts, size_t normals, size_t chars) + : length(len), + numCopies(1), + shortGCHeap(shorts), + normalGCHeap(normals), + normalMallocHeap(chars) + {} + + void add(size_t shorts, size_t normals, size_t chars) { + shortGCHeap += shorts; + normalGCHeap += normals; + normalMallocHeap += chars; + numCopies++; + } + + void add(const StringInfo& info) { + MOZ_ASSERT(length == info.length); + + shortGCHeap += info.shortGCHeap; + normalGCHeap += info.normalGCHeap; + normalMallocHeap += info.normalMallocHeap; + numCopies += info.numCopies; + } + + size_t totalSizeOf() const { + return shortGCHeap + normalGCHeap + normalMallocHeap; + } + + size_t totalGCHeapSizeOf() const { + return shortGCHeap + normalGCHeap; + } + + // The string's length, excluding the null-terminator. + size_t length; + + // How many copies of the string have we seen? + size_t numCopies; + + // These are all totals across all copies of the string we've seen. + size_t shortGCHeap; + size_t normalGCHeap; + size_t normalMallocHeap; +}; + +// Holds data about a notable string (one which uses more than +// NotableStringInfo::notableSize() bytes of memory), so we can report it +// individually. +// +// Essentially the only difference between this class and StringInfo is that +// NotableStringInfo holds a copy of the string's chars. +struct NotableStringInfo : public StringInfo +{ + NotableStringInfo(); + NotableStringInfo(JSString *str, const StringInfo &info); + NotableStringInfo(mozilla::MoveRef info); + NotableStringInfo &operator=(mozilla::MoveRef info); + + ~NotableStringInfo() { + js_free(buffer); + } // A string needs to take up this many bytes of storage before we consider - // it to be "huge". - static size_t MinSize() { + // it to be "notable". + static size_t notableSize() { return js::MemoryReportingSundriesThreshold(); } - // A string's size in memory is not necessarily equal to twice its length - // because the allocator and the JS engine both may round up. - size_t length; - size_t size; + char *buffer; - // We record the first 32 chars of the escaped string here. (We escape the - // string so we can use a char[] instead of a jschar[] here. - char buffer[32]; + private: + NotableStringInfo(const NotableStringInfo& info) MOZ_DELETE; }; -// These measurements relate directly to the JSRuntime, and not to +// These measurements relate directly to the JSRuntime, and not to zones and // compartments within it. struct RuntimeSizes { - RuntimeSizes() { memset(this, 0, sizeof(RuntimeSizes)); } +#define FOR_EACH_SIZE(macro) \ + macro(_, _, object) \ + macro(_, _, atomsTable) \ + macro(_, _, contexts) \ + macro(_, _, dtoa) \ + macro(_, _, temporary) \ + macro(_, _, regexpData) \ + macro(_, _, interpreterStack) \ + macro(_, _, gcMarker) \ + macro(_, _, mathCache) \ + macro(_, _, scriptData) \ + macro(_, _, scriptSources) - size_t object; - size_t atomsTable; - size_t contexts; - size_t dtoa; - size_t temporary; - size_t regexpData; - size_t interpreterStack; - size_t gcMarker; - size_t mathCache; - size_t scriptData; - size_t scriptSources; - - CodeSizes code; -}; - -struct ZoneStats -{ - ZoneStats() - : extra(NULL), - gcHeapArenaAdmin(0), - gcHeapUnusedGcThings(0), - gcHeapStringsNormal(0), - gcHeapStringsShort(0), - gcHeapLazyScripts(0), - gcHeapTypeObjects(0), - gcHeapIonCodes(0), - stringCharsNonHuge(0), - lazyScripts(0), - typeObjects(0), - typePool(0), - hugeStrings() + RuntimeSizes() + : FOR_EACH_SIZE(ZERO_SIZE) + code() {} - ZoneStats(const ZoneStats &other) - : extra(other.extra), - gcHeapArenaAdmin(other.gcHeapArenaAdmin), - gcHeapUnusedGcThings(other.gcHeapUnusedGcThings), - gcHeapStringsNormal(other.gcHeapStringsNormal), - gcHeapStringsShort(other.gcHeapStringsShort), - gcHeapLazyScripts(other.gcHeapLazyScripts), - gcHeapTypeObjects(other.gcHeapTypeObjects), - gcHeapIonCodes(other.gcHeapIonCodes), - stringCharsNonHuge(other.stringCharsNonHuge), - lazyScripts(other.lazyScripts), - typeObjects(other.typeObjects), - typePool(other.typePool), - hugeStrings() - { - hugeStrings.appendAll(other.hugeStrings); + FOR_EACH_SIZE(DECL_SIZE) + CodeSizes code; + +#undef FOR_EACH_SIZE +}; + +struct ZoneStats : js::ZoneStatsPod +{ + ZoneStats() { + strings.init(); } - // Add other's numbers to this object's numbers. - void add(ZoneStats &other) { - #define ADD(x) this->x += other.x + ZoneStats(mozilla::MoveRef other) + : ZoneStatsPod(other), + strings(mozilla::OldMove(other->strings)), + notableStrings(mozilla::OldMove(other->notableStrings)) + {} - ADD(gcHeapArenaAdmin); - ADD(gcHeapUnusedGcThings); + // Add other's numbers to this object's numbers. Both objects' + // notableStrings vectors must be empty at this point, because we can't + // merge them. (A NotableStringInfo contains only a prefix of the string, + // so we can't tell whether two NotableStringInfo objects correspond to the + // same string.) + void add(const ZoneStats &other) { + ZoneStatsPod::add(other); - ADD(gcHeapStringsNormal); - ADD(gcHeapStringsShort); - ADD(gcHeapLazyScripts); - ADD(gcHeapTypeObjects); - ADD(gcHeapIonCodes); + MOZ_ASSERT(notableStrings.empty()); + MOZ_ASSERT(other.notableStrings.empty()); - ADD(stringCharsNonHuge); - ADD(lazyScripts); - ADD(typeObjects); - ADD(typePool); - - #undef ADD - - hugeStrings.appendAll(other.hugeStrings); + for (StringsHashMap::Range r = other.strings.all(); !r.empty(); r.popFront()) { + StringsHashMap::AddPtr p = strings.lookupForAdd(r.front().key); + if (p) { + // We've seen this string before; add its size to our tally. + p->value.add(r.front().value); + } else { + // We haven't seen this string before; add it to the hashtable. + strings.add(p, r.front().key, r.front().value); + } + } } - // This field can be used by embedders. - void *extra; + size_t sizeOfLiveGCThings() const { + size_t n = ZoneStatsPod::sizeOfLiveGCThings(); + for (size_t i = 0; i < notableStrings.length(); i++) { + const JS::NotableStringInfo& info = notableStrings[i]; + n += info.totalGCHeapSizeOf(); + } + return n; + } - size_t gcHeapArenaAdmin; - size_t gcHeapUnusedGcThings; + typedef js::HashMap StringsHashMap; - size_t gcHeapStringsNormal; - size_t gcHeapStringsShort; - - size_t gcHeapLazyScripts; - size_t gcHeapTypeObjects; - size_t gcHeapIonCodes; - - size_t stringCharsNonHuge; - size_t lazyScripts; - size_t typeObjects; - size_t typePool; - - js::Vector hugeStrings; - - // The size of all the live things in the GC heap that don't belong to any - // compartment. - size_t GCHeapThingsSize(); + StringsHashMap strings; + js::Vector notableStrings; }; struct CompartmentStats { +#define FOR_EACH_SIZE(macro) \ + macro(Objects, IsLiveGCThing, objectsGCHeapOrdinary) \ + macro(Objects, IsLiveGCThing, objectsGCHeapFunction) \ + macro(Objects, IsLiveGCThing, objectsGCHeapDenseArray) \ + macro(Objects, IsLiveGCThing, objectsGCHeapSlowArray) \ + macro(Objects, IsLiveGCThing, objectsGCHeapCrossCompartmentWrapper) \ + macro(Private, NotLiveGCThing, objectsPrivate) \ + macro(Other, IsLiveGCThing, shapesGCHeapTreeGlobalParented) \ + macro(Other, IsLiveGCThing, shapesGCHeapTreeNonGlobalParented) \ + macro(Other, IsLiveGCThing, shapesGCHeapDict) \ + macro(Other, IsLiveGCThing, shapesGCHeapBase) \ + macro(Other, NotLiveGCThing, shapesMallocHeapTreeTables) \ + macro(Other, NotLiveGCThing, shapesMallocHeapDictTables) \ + macro(Other, NotLiveGCThing, shapesMallocHeapTreeShapeKids) \ + macro(Other, NotLiveGCThing, shapesMallocHeapCompartmentTables) \ + macro(Other, IsLiveGCThing, scriptsGCHeap) \ + macro(Other, NotLiveGCThing, scriptsMallocHeapData) \ + macro(Other, NotLiveGCThing, baselineData) \ + macro(Other, NotLiveGCThing, baselineStubsFallback) \ + macro(Other, NotLiveGCThing, baselineStubsOptimized) \ + macro(Other, NotLiveGCThing, ionData) \ + macro(Other, NotLiveGCThing, typeInferenceTypeScripts) \ + macro(Other, NotLiveGCThing, typeInferencePendingArrays) \ + macro(Other, NotLiveGCThing, typeInferenceAllocationSiteTables) \ + macro(Other, NotLiveGCThing, typeInferenceArrayTypeTables) \ + macro(Other, NotLiveGCThing, typeInferenceObjectTypeTables) \ + macro(Other, NotLiveGCThing, compartmentObject) \ + macro(Other, NotLiveGCThing, crossCompartmentWrappersTable) \ + macro(Other, NotLiveGCThing, regexpCompartment) \ + macro(Other, NotLiveGCThing, debuggeesSet) + CompartmentStats() - : extra(NULL), - gcHeapObjectsOrdinary(0), - gcHeapObjectsFunction(0), - gcHeapObjectsDenseArray(0), - gcHeapObjectsSlowArray(0), - gcHeapObjectsCrossCompartmentWrapper(0), - gcHeapShapesTreeGlobalParented(0), - gcHeapShapesTreeNonGlobalParented(0), - gcHeapShapesDict(0), - gcHeapShapesBase(0), - gcHeapScripts(0), + : FOR_EACH_SIZE(ZERO_SIZE) objectsExtra(), - shapesExtraTreeTables(0), - shapesExtraDictTables(0), - shapesExtraTreeShapeKids(0), - shapesCompartmentTables(0), - scriptData(0), - baselineData(0), - baselineStubsFallback(0), - baselineStubsOptimized(0), - ionData(0), - compartmentObject(0), - crossCompartmentWrappersTable(0), - regexpCompartment(0), - debuggeesSet(0), - typeInference() + extra() {} CompartmentStats(const CompartmentStats &other) - : extra(other.extra), - gcHeapObjectsOrdinary(other.gcHeapObjectsOrdinary), - gcHeapObjectsFunction(other.gcHeapObjectsFunction), - gcHeapObjectsDenseArray(other.gcHeapObjectsDenseArray), - gcHeapObjectsSlowArray(other.gcHeapObjectsSlowArray), - gcHeapObjectsCrossCompartmentWrapper(other.gcHeapObjectsCrossCompartmentWrapper), - gcHeapShapesTreeGlobalParented(other.gcHeapShapesTreeGlobalParented), - gcHeapShapesTreeNonGlobalParented(other.gcHeapShapesTreeNonGlobalParented), - gcHeapShapesDict(other.gcHeapShapesDict), - gcHeapShapesBase(other.gcHeapShapesBase), - gcHeapScripts(other.gcHeapScripts), + : FOR_EACH_SIZE(COPY_OTHER_SIZE) objectsExtra(other.objectsExtra), - shapesExtraTreeTables(other.shapesExtraTreeTables), - shapesExtraDictTables(other.shapesExtraDictTables), - shapesExtraTreeShapeKids(other.shapesExtraTreeShapeKids), - shapesCompartmentTables(other.shapesCompartmentTables), - scriptData(other.scriptData), - baselineData(other.baselineData), - baselineStubsFallback(other.baselineStubsFallback), - baselineStubsOptimized(other.baselineStubsOptimized), - ionData(other.ionData), - compartmentObject(other.compartmentObject), - crossCompartmentWrappersTable(other.crossCompartmentWrappersTable), - regexpCompartment(other.regexpCompartment), - debuggeesSet(other.debuggeesSet), - typeInference(other.typeInference) - { + extra(other.extra) + {} + + void add(const CompartmentStats &other) { + FOR_EACH_SIZE(ADD_OTHER_SIZE) + objectsExtra.add(other.objectsExtra); + // Do nothing with |extra|. } - // This field can be used by embedders. - void *extra; - - // If you add a new number, remember to update the constructors, add(), and - // maybe gcHeapThingsSize()! - size_t gcHeapObjectsOrdinary; - size_t gcHeapObjectsFunction; - size_t gcHeapObjectsDenseArray; - size_t gcHeapObjectsSlowArray; - size_t gcHeapObjectsCrossCompartmentWrapper; - size_t gcHeapShapesTreeGlobalParented; - size_t gcHeapShapesTreeNonGlobalParented; - size_t gcHeapShapesDict; - size_t gcHeapShapesBase; - size_t gcHeapScripts; - ObjectsExtraSizes objectsExtra; - - size_t shapesExtraTreeTables; - size_t shapesExtraDictTables; - size_t shapesExtraTreeShapeKids; - size_t shapesCompartmentTables; - size_t scriptData; - size_t baselineData; - size_t baselineStubsFallback; - size_t baselineStubsOptimized; - size_t ionData; - size_t compartmentObject; - size_t crossCompartmentWrappersTable; - size_t regexpCompartment; - size_t debuggeesSet; - - TypeInferenceSizes typeInference; - - // Add cStats's numbers to this object's numbers. - void add(CompartmentStats &cStats) { - #define ADD(x) this->x += cStats.x - - ADD(gcHeapObjectsOrdinary); - ADD(gcHeapObjectsFunction); - ADD(gcHeapObjectsDenseArray); - ADD(gcHeapObjectsSlowArray); - ADD(gcHeapObjectsCrossCompartmentWrapper); - ADD(gcHeapShapesTreeGlobalParented); - ADD(gcHeapShapesTreeNonGlobalParented); - ADD(gcHeapShapesDict); - ADD(gcHeapShapesBase); - ADD(gcHeapScripts); - objectsExtra.add(cStats.objectsExtra); - - ADD(shapesExtraTreeTables); - ADD(shapesExtraDictTables); - ADD(shapesExtraTreeShapeKids); - ADD(shapesCompartmentTables); - ADD(scriptData); - ADD(baselineData); - ADD(baselineStubsFallback); - ADD(baselineStubsOptimized); - ADD(ionData); - ADD(compartmentObject); - ADD(crossCompartmentWrappersTable); - ADD(regexpCompartment); - ADD(debuggeesSet); - - #undef ADD - - typeInference.add(cStats.typeInference); + size_t sizeOfLiveGCThings() const { + size_t n = 0; + FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) + n += objectsExtra.sizeOfLiveGCThings(); + // Do nothing with |extra|. + return n; } - // The size of all the live things in the GC heap. - size_t GCHeapThingsSize(); + void addToTabSizes(TabSizes *sizes) const { + FOR_EACH_SIZE(ADD_TO_TAB_SIZES); + objectsExtra.addToTabSizes(sizes); + // Do nothing with |extra|. + } + + FOR_EACH_SIZE(DECL_SIZE) + ObjectsExtraSizes objectsExtra; + void *extra; // This field can be used by embedders. + +#undef FOR_EACH_SIZE }; struct RuntimeStats { +#define FOR_EACH_SIZE(macro) \ + macro(_, _, gcHeapChunkTotal) \ + macro(_, _, gcHeapDecommittedArenas) \ + macro(_, _, gcHeapUnusedChunks) \ + macro(_, _, gcHeapUnusedArenas) \ + macro(_, _, gcHeapChunkAdmin) \ + macro(_, _, gcHeapGCThings) \ + RuntimeStats(mozilla::MallocSizeOf mallocSizeOf) - : runtime(), - gcHeapChunkTotal(0), - gcHeapDecommittedArenas(0), - gcHeapUnusedChunks(0), - gcHeapUnusedArenas(0), - gcHeapUnusedGcThings(0), - gcHeapChunkAdmin(0), - gcHeapGcThings(0), + : FOR_EACH_SIZE(ZERO_SIZE) + runtime(), cTotals(), zTotals(), compartmentStatsVector(), zoneStatsVector(), - currZoneStats(NULL), + currZoneStats(nullptr), mallocSizeOf_(mallocSizeOf) {} - RuntimeSizes runtime; - - // If you add a new number, remember to update the constructor! - // Here's a useful breakdown of the GC heap. // // - rtStats.gcHeapChunkTotal @@ -394,28 +473,24 @@ struct RuntimeStats // - unused bytes // - rtStats.gcHeapUnusedChunks (empty chunks) // - rtStats.gcHeapUnusedArenas (empty arenas within non-empty chunks) - // - rtStats.total.gcHeapUnusedGcThings (empty GC thing slots within non-empty arenas) + // - rtStats.zTotals.unusedGCThings (empty GC thing slots within non-empty arenas) // - used bytes // - rtStats.gcHeapChunkAdmin - // - rtStats.total.gcHeapArenaAdmin - // - rtStats.gcHeapGcThings (in-use GC things) + // - rtStats.zTotals.gcHeapArenaAdmin + // - rtStats.gcHeapGCThings (in-use GC things) + // == rtStats.zTotals.sizeOfLiveGCThings() + rtStats.cTotals.sizeOfLiveGCThings() // // It's possible that some arenas in empty chunks may be decommitted, but // we don't count those under rtStats.gcHeapDecommittedArenas because (a) // it's rare, and (b) this means that rtStats.gcHeapUnusedChunks is a // multiple of the chunk size, which is good. - size_t gcHeapChunkTotal; - size_t gcHeapDecommittedArenas; - size_t gcHeapUnusedChunks; - size_t gcHeapUnusedArenas; - size_t gcHeapUnusedGcThings; - size_t gcHeapChunkAdmin; - size_t gcHeapGcThings; + FOR_EACH_SIZE(DECL_SIZE) - // The sum of all compartment's measurements. - CompartmentStats cTotals; - ZoneStats zTotals; + RuntimeSizes runtime; + + CompartmentStats cTotals; // The sum of this runtime's compartments' measurements. + ZoneStats zTotals; // The sum of this runtime's zones' measurements. js::Vector compartmentStatsVector; js::Vector zoneStatsVector; @@ -426,6 +501,8 @@ struct RuntimeStats virtual void initExtraCompartmentStats(JSCompartment *c, CompartmentStats *cstats) = 0; virtual void initExtraZoneStats(JS::Zone *zone, ZoneStats *zstats) = 0; + +#undef FOR_EACH_SIZE }; class ObjectPrivateVisitor @@ -437,7 +514,7 @@ class ObjectPrivateVisitor // A callback that gets a JSObject's nsISupports pointer, if it has one. // Note: this function does *not* addref |iface|. - typedef JSBool(*GetISupportsFun)(JSObject *obj, nsISupports **iface); + typedef bool(*GetISupportsFun)(JSObject *obj, nsISupports **iface); GetISupportsFun getISupports_; ObjectPrivateVisitor(GetISupportsFun getISupports) @@ -457,6 +534,17 @@ UserCompartmentCount(JSRuntime *rt); extern JS_PUBLIC_API(size_t) PeakSizeOfTemporary(const JSRuntime *rt); +extern JS_PUBLIC_API(bool) +AddSizeOfTab(JSRuntime *rt, JSObject *obj, mozilla::MallocSizeOf mallocSizeOf, + ObjectPrivateVisitor *opv, TabSizes *sizes); + } // namespace JS +#undef DECL_SIZE +#undef ZERO_SIZE +#undef COPY_OTHER_SIZE +#undef ADD_OTHER_SIZE +#undef ADD_SIZE_TO_N_IF_LIVE_GC_THING +#undef ADD_TO_TAB_SIZES + #endif /* js_MemoryMetrics_h */ diff --git a/external/spidermonkey/include/ios/jsdbgapi.h b/external/spidermonkey/include/android/js/OldDebugAPI.h similarity index 77% rename from external/spidermonkey/include/ios/jsdbgapi.h rename to external/spidermonkey/include/android/js/OldDebugAPI.h index 0ce7101337..5e5bdf38d7 100644 --- a/external/spidermonkey/include/ios/jsdbgapi.h +++ b/external/spidermonkey/include/android/js/OldDebugAPI.h @@ -4,13 +4,24 @@ * 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/. */ -#ifndef jsdbgapi_h -#define jsdbgapi_h +#ifndef js_OldDebugAPI_h +#define js_OldDebugAPI_h + /* * JS debugger API. */ -#include "jsprvtd.h" +#include "mozilla/NullPtr.h" + +#include "jsbytecode.h" + +#include "js/CallArgs.h" +#include "js/TypeDecls.h" + +class JSAtom; +class JSFreeOp; + +namespace js { class StackFrame; } namespace JS { @@ -34,21 +45,68 @@ extern JS_PUBLIC_API(void) FreeStackDescription(JSContext *cx, StackDescription *desc); extern JS_PUBLIC_API(char *) -FormatStackDump(JSContext *cx, char *buf, - JSBool showArgs, JSBool showLocals, - JSBool showThisProps); +FormatStackDump(JSContext *cx, char *buf, bool showArgs, bool showLocals, bool showThisProps); } # ifdef DEBUG -JS_FRIEND_API(void) js_DumpValue(const js::Value &val); +JS_FRIEND_API(void) js_DumpValue(const JS::Value &val); JS_FRIEND_API(void) js_DumpId(jsid id); -JS_FRIEND_API(void) js_DumpStackFrame(JSContext *cx, js::StackFrame *start = NULL); +JS_FRIEND_API(void) js_DumpStackFrame(JSContext *cx, js::StackFrame *start = nullptr); # endif JS_FRIEND_API(void) js_DumpBacktrace(JSContext *cx); +typedef enum JSTrapStatus { + JSTRAP_ERROR, + JSTRAP_CONTINUE, + JSTRAP_RETURN, + JSTRAP_THROW, + JSTRAP_LIMIT +} JSTrapStatus; + +typedef JSTrapStatus +(* JSTrapHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + JS::Value closure); + +typedef JSTrapStatus +(* JSInterruptHook)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + void *closure); + +typedef JSTrapStatus +(* JSDebuggerHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + void *closure); + +typedef JSTrapStatus +(* JSThrowHook)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + void *closure); + +typedef bool +(* JSWatchPointHandler)(JSContext *cx, JSObject *obj, jsid id, JS::Value old, + JS::Value *newp, void *closure); + +/* called just after script creation */ +typedef void +(* JSNewScriptHook)(JSContext *cx, + const char *filename, /* URL of script */ + unsigned lineno, /* first line */ + JSScript *script, + JSFunction *fun, + void *callerdata); + +/* called just before script destruction */ +typedef void +(* JSDestroyScriptHook)(JSFreeOp *fop, + JSScript *script, + void *callerdata); + +typedef void +(* JSSourceHandler)(const char *filename, unsigned lineno, const jschar *str, + size_t length, void **listenerTSData, void *closure); + + + extern JS_PUBLIC_API(JSCompartment *) JS_EnterCompartmentOfScript(JSContext *cx, JSScript *target); @@ -60,7 +118,7 @@ JS_DecompileScript(JSContext *cx, JSScript *script, const char *name, unsigned i * be able to support compartment-wide debugging. */ extern JS_PUBLIC_API(void) -JS_SetRuntimeDebugMode(JSRuntime *rt, JSBool debug); +JS_SetRuntimeDebugMode(JSRuntime *rt, bool debug); /* * Debug mode is a compartment-wide mode that enables a debugger to attach @@ -73,42 +131,42 @@ JS_SetRuntimeDebugMode(JSRuntime *rt, JSBool debug); */ /* Get current state of debugging mode. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_GetDebugMode(JSContext *cx); /* * Turn on/off debugging mode for all compartments. This returns false if any code * from any of the runtime's compartments is running or on the stack. */ -JS_FRIEND_API(JSBool) -JS_SetDebugModeForAllCompartments(JSContext *cx, JSBool debug); +JS_FRIEND_API(bool) +JS_SetDebugModeForAllCompartments(JSContext *cx, bool debug); /* * Turn on/off debugging mode for a single compartment. This should only be * used when no code from this compartment is running or on the stack in any * thread. */ -JS_FRIEND_API(JSBool) -JS_SetDebugModeForCompartment(JSContext *cx, JSCompartment *comp, JSBool debug); +JS_FRIEND_API(bool) +JS_SetDebugModeForCompartment(JSContext *cx, JSCompartment *comp, bool debug); /* * Turn on/off debugging mode for a context's compartment. */ -JS_FRIEND_API(JSBool) -JS_SetDebugMode(JSContext *cx, JSBool debug); +JS_FRIEND_API(bool) +JS_SetDebugMode(JSContext *cx, bool debug); /* Turn on single step mode. */ -extern JS_PUBLIC_API(JSBool) -JS_SetSingleStepMode(JSContext *cx, JSScript *script, JSBool singleStep); +extern JS_PUBLIC_API(bool) +JS_SetSingleStepMode(JSContext *cx, JSScript *script, bool singleStep); /* The closure argument will be marked. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetTrap(JSContext *cx, JSScript *script, jsbytecode *pc, - JSTrapHandler handler, jsval closure); + JSTrapHandler handler, JS::Value closure); extern JS_PUBLIC_API(void) JS_ClearTrap(JSContext *cx, JSScript *script, jsbytecode *pc, - JSTrapHandler *handlerp, jsval *closurep); + JSTrapHandler *handlerp, JS::Value *closurep); extern JS_PUBLIC_API(void) JS_ClearScriptTraps(JSRuntime *rt, JSScript *script); @@ -116,28 +174,25 @@ JS_ClearScriptTraps(JSRuntime *rt, JSScript *script); extern JS_PUBLIC_API(void) JS_ClearAllTrapsForCompartment(JSContext *cx); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetInterrupt(JSRuntime *rt, JSInterruptHook handler, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_ClearInterrupt(JSRuntime *rt, JSInterruptHook *handlerp, void **closurep); /************************************************************************/ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetWatchPoint(JSContext *cx, JSObject *obj, jsid id, JSWatchPointHandler handler, JSObject *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_ClearWatchPoint(JSContext *cx, JSObject *obj, jsid id, JSWatchPointHandler *handlerp, JSObject **closurep); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_ClearWatchPointsForObject(JSContext *cx, JSObject *obj); -extern JS_PUBLIC_API(JSBool) -JS_ClearAllWatchPoints(JSContext *cx); - /************************************************************************/ // Raw JSScript* because this needs to be callable from a signal handler. @@ -150,7 +205,7 @@ JS_LineNumberToPC(JSContext *cx, JSScript *script, unsigned lineno); extern JS_PUBLIC_API(jsbytecode *) JS_EndPC(JSContext *cx, JSScript *script); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_GetLinePCs(JSContext *cx, JSScript *script, unsigned startLine, unsigned maxLines, unsigned* count, unsigned** lines, jsbytecode*** pcs); @@ -158,7 +213,7 @@ JS_GetLinePCs(JSContext *cx, JSScript *script, extern JS_PUBLIC_API(unsigned) JS_GetFunctionArgumentCount(JSContext *cx, JSFunction *fun); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_FunctionHasLocalNames(JSContext *cx, JSFunction *fun); /* @@ -230,9 +285,8 @@ JS_GetScriptIsSelfHosted(JSScript *script); /************************************************************************/ /* - * Hook setters for script creation and destruction, see jsprvtd.h for the - * typedefs. These macros provide binary compatibility and newer, shorter - * synonyms. + * Hook setters for script creation and destruction. These macros provide + * binary compatibility and newer, shorter synonyms. */ #define JS_SetNewScriptHook JS_SetNewScriptHookProc #define JS_SetDestroyScriptHook JS_SetDestroyScriptHookProc @@ -247,11 +301,11 @@ JS_SetDestroyScriptHook(JSRuntime *rt, JSDestroyScriptHook hook, /************************************************************************/ typedef struct JSPropertyDesc { - jsval id; /* primary id, atomized string, or int */ - jsval value; /* property value */ + JS::Value id; /* primary id, atomized string, or int */ + JS::Value value; /* property value */ uint8_t flags; /* flags, see below */ uint8_t spare; /* unused */ - jsval alias; /* alias id if JSPD_ALIAS flag */ + JS::Value alias; /* alias id if JSPD_ALIAS flag */ } JSPropertyDesc; #define JSPD_ENUMERATE 0x01 /* visible to for/in loop */ @@ -260,7 +314,7 @@ typedef struct JSPropertyDesc { #define JSPD_ALIAS 0x08 /* property has an alias id */ #define JSPD_EXCEPTION 0x40 /* exception occurred fetching the property, */ /* value is exception */ -#define JSPD_ERROR 0x80 /* native getter returned JS_FALSE without */ +#define JSPD_ERROR 0x80 /* native getter returned false without */ /* throwing an exception */ typedef struct JSPropertyDescArray { @@ -270,7 +324,7 @@ typedef struct JSPropertyDescArray { typedef struct JSScopeProperty JSScopeProperty; -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_GetPropertyDescArray(JSContext *cx, JSObject *obj, JSPropertyDescArray *pda); extern JS_PUBLIC_API(void) @@ -358,8 +412,8 @@ class JS_PUBLIC_API(JSBrokenFrameIterator) * or function call: just before execution begins and just after it finishes. * In both cases the 'current' frame is that of the executing code. * - * The 'before' param is JS_TRUE for the hook invocation before the execution - * and JS_FALSE for the invocation after the code has run. + * The 'before' param is true for the hook invocation before the execution + * and false for the invocation after the code has run. * * The 'ok' param is significant only on the post execution invocation to * signify whether or not the code completed 'normally'. @@ -373,14 +427,14 @@ class JS_PUBLIC_API(JSBrokenFrameIterator) * in 'closure' to cause the 'after' invocation to be called with the same * 'closure' value as the 'before'. * - * Returning NULL in the 'before' hook will cause the 'after' hook *not* to + * Returning nullptr in the 'before' hook will cause the 'after' hook *not* to * be called. */ typedef void * (* JSInterpreterHook)(JSContext *cx, JSAbstractFramePtr frame, bool isConstructing, - JSBool before, JSBool *ok, void *closure); + bool before, bool *ok, void *closure); -typedef JSBool +typedef bool (* JSDebugErrorHook)(JSContext *cx, const char *message, JSErrorReport *report, void *closure); @@ -407,22 +461,22 @@ typedef struct JSDebugHooks { /************************************************************************/ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetDebuggerHandler(JSRuntime *rt, JSDebuggerHandler hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetSourceHandler(JSRuntime *rt, JSSourceHandler handler, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetExecuteHook(JSRuntime *rt, JSInterpreterHook hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetCallHook(JSRuntime *rt, JSInterpreterHook hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetThrowHook(JSRuntime *rt, JSThrowHook hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetDebugErrorHook(JSRuntime *rt, JSDebugErrorHook hook, void *closure); /************************************************************************/ @@ -433,11 +487,11 @@ JS_GetGlobalDebugHooks(JSRuntime *rt); /** * Add various profiling-related functions as properties of the given object. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_DefineProfilingFunctions(JSContext *cx, JSObject *obj); /* Defined in vm/Debugger.cpp. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_DefineDebuggerObject(JSContext *cx, JSObject *obj); extern JS_PUBLIC_API(void) @@ -452,8 +506,13 @@ JS_DumpPCCounts(JSContext *cx, JSScript *script); extern JS_PUBLIC_API(void) JS_DumpCompartmentPCCounts(JSContext *cx); +namespace js { +extern JS_FRIEND_API(bool) +CanCallContextDebugHandler(JSContext *cx); +} + /* Call the context debug handler on the topmost scripted frame. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_CallContextDebugHandler(JSContext *cx); -#endif /* jsdbgapi_h */ +#endif /* js_OldDebugAPI_h */ diff --git a/external/spidermonkey/include/android/js/ProfilingStack.h b/external/spidermonkey/include/android/js/ProfilingStack.h new file mode 100644 index 0000000000..c67f98952c --- /dev/null +++ b/external/spidermonkey/include/android/js/ProfilingStack.h @@ -0,0 +1,95 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_ProfilingStack_h +#define js_ProfilingStack_h + +#include "mozilla/NullPtr.h" + +#include "jsbytecode.h" +#include "jstypes.h" + +#include "js/Utility.h" + +struct JSRuntime; + +namespace js { + +// A call stack can be specified to the JS engine such that all JS entry/exits +// to functions push/pop an entry to/from the specified stack. +// +// For more detailed information, see vm/SPSProfiler.h. +// +class ProfileEntry +{ + // All fields are marked volatile to prevent the compiler from re-ordering + // instructions. Namely this sequence: + // + // entry[size] = ...; + // size++; + // + // If the size modification were somehow reordered before the stores, then + // if a sample were taken it would be examining bogus information. + // + // A ProfileEntry represents both a C++ profile entry and a JS one. Both use + // the string as a description, but JS uses the sp as nullptr to indicate + // that it is a JS entry. The script_ is then only ever examined for a JS + // entry, and the idx is used by both, but with different meanings. + // + const char * volatile string; // Descriptive string of this entry + void * volatile sp; // Relevant stack pointer for the entry + JSScript * volatile script_; // if js(), non-null script which is running + int32_t volatile idx; // if js(), idx of pc, otherwise line number + + public: + // All of these methods are marked with the 'volatile' keyword because SPS's + // representation of the stack is stored such that all ProfileEntry + // instances are volatile. These methods would not be available unless they + // were marked as volatile as well. + + bool js() volatile { + JS_ASSERT_IF(sp == nullptr, script_ != nullptr); + return sp == nullptr; + } + + uint32_t line() volatile { JS_ASSERT(!js()); return idx; } + JSScript *script() volatile { JS_ASSERT(js()); return script_; } + void *stackAddress() volatile { return sp; } + const char *label() volatile { return string; } + + void setLine(uint32_t aLine) volatile { JS_ASSERT(!js()); idx = aLine; } + void setLabel(const char *aString) volatile { string = aString; } + void setStackAddress(void *aSp) volatile { sp = aSp; } + void setScript(JSScript *aScript) volatile { script_ = aScript; } + + // We can't know the layout of JSScript, so look in vm/SPSProfiler.cpp. + JS_FRIEND_API(jsbytecode *) pc() volatile; + JS_FRIEND_API(void) setPC(jsbytecode *pc) volatile; + + static size_t offsetOfString() { return offsetof(ProfileEntry, string); } + static size_t offsetOfStackAddress() { return offsetof(ProfileEntry, sp); } + static size_t offsetOfPCIdx() { return offsetof(ProfileEntry, idx); } + static size_t offsetOfScript() { return offsetof(ProfileEntry, script_); } + + // The index used in the entry can either be a line number or the offset of + // a pc into a script's code. To signify a nullptr pc, use a -1 index. This + // is checked against in pc() and setPC() to set/get the right pc. + static const int32_t NullPCIndex = -1; +}; + +JS_FRIEND_API(void) +SetRuntimeProfilingStack(JSRuntime *rt, ProfileEntry *stack, uint32_t *size, + uint32_t max); + +JS_FRIEND_API(void) +EnableRuntimeProfilingStack(JSRuntime *rt, bool enabled); + +JS_FRIEND_API(jsbytecode*) +ProfilingGetPC(JSRuntime *rt, JSScript *script, void *ip); + +} // namespace js + +#endif /* js_ProfilingStack_h */ diff --git a/external/spidermonkey/include/android/js/PropertyKey.h b/external/spidermonkey/include/android/js/PropertyKey.h index c949db13a5..1f90653b40 100644 --- a/external/spidermonkey/include/android/js/PropertyKey.h +++ b/external/spidermonkey/include/android/js/PropertyKey.h @@ -9,12 +9,9 @@ #ifndef js_PropertyKey_h #define js_PropertyKey_h -#include "mozilla/Attributes.h" - +#include "js/TypeDecls.h" #include "js/Value.h" -struct JSContext; - namespace JS { class PropertyKey; diff --git a/external/spidermonkey/include/android/js/RequiredDefines.h b/external/spidermonkey/include/android/js/RequiredDefines.h index 6af9ca871b..3c8f429132 100644 --- a/external/spidermonkey/include/android/js/RequiredDefines.h +++ b/external/spidermonkey/include/android/js/RequiredDefines.h @@ -15,9 +15,17 @@ /* * The c99 defining the limit macros (UINT32_MAX for example), says: - * C++ implementations should define these macros only when __STDC_LIMIT_MACROS - * is defined before is included. + * + * C++ implementations should define these macros only when + * __STDC_LIMIT_MACROS is defined before is included. + * + * The same also occurs with __STDC_CONSTANT_MACROS for the constant macros + * (INT8_C for example) used to specify a literal constant of the proper type, + * and with __STDC_FORMAT_MACROS for the format macros (PRId32 for example) used + * with the fprintf function family. */ #define __STDC_LIMIT_MACROS +#define __STDC_CONSTANT_MACROS +#define __STDC_FORMAT_MACROS #endif /* js_RequiredDefines_h */ diff --git a/external/spidermonkey/include/android/js/RootingAPI.h b/external/spidermonkey/include/android/js/RootingAPI.h index c4a5925ae7..82863f020a 100644 --- a/external/spidermonkey/include/android/js/RootingAPI.h +++ b/external/spidermonkey/include/android/js/RootingAPI.h @@ -8,12 +8,14 @@ #define js_RootingAPI_h #include "mozilla/GuardObjects.h" +#include "mozilla/NullPtr.h" #include "mozilla/TypeTraits.h" -#include "js/Utility.h" - #include "jspubtd.h" +#include "js/TypeDecls.h" +#include "js/Utility.h" + /* * Moving GC Stack Rooting * @@ -97,7 +99,6 @@ namespace js { -class Module; class ScriptSourceObject; template @@ -116,13 +117,13 @@ template class HeapBase {}; /* - * js::NullPtr acts like a NULL pointer in contexts that require a Handle. + * js::NullPtr acts like a nullptr pointer in contexts that require a Handle. * * Handle provides an implicit constructor for js::NullPtr so that, given: * foo(Handle h); * callers can simply write: * foo(js::NullPtr()); - * which avoids creating a Rooted just to pass NULL. + * which avoids creating a Rooted just to pass nullptr. * * This is the SpiderMonkey internal variant. js::NullPtr should be used in * preference to JS::NullPtr to avoid the GOT access required for JS_PUBLIC_API @@ -143,9 +144,6 @@ namespace JS { template class Rooted; -template class Handle; -template class MutableHandle; - /* This is exposing internal state of the GC for inlining purposes. */ JS_FRIEND_API(bool) isGCEnabled(); @@ -155,13 +153,13 @@ CheckStackRoots(JSContext *cx); #endif /* - * JS::NullPtr acts like a NULL pointer in contexts that require a Handle. + * JS::NullPtr acts like a nullptr pointer in contexts that require a Handle. * * Handle provides an implicit constructor for JS::NullPtr so that, given: * foo(Handle h); * callers can simply write: * foo(JS::NullPtr()); - * which avoids creating a Rooted just to pass NULL. + * which avoids creating a Rooted just to pass nullptr. */ struct JS_PUBLIC_API(NullPtr) { @@ -377,7 +375,7 @@ class TenuredHeap : public js::HeapBase template class MOZ_NONHEAP_CLASS Handle : public js::HandleBase { - friend class MutableHandle; + friend class JS::MutableHandle; public: /* Creates a handle from a handle of a type convertible to T. */ @@ -390,14 +388,14 @@ class MOZ_NONHEAP_CLASS Handle : public js::HandleBase ptr = reinterpret_cast(handle.address()); } - /* Create a handle for a NULL pointer. */ + /* Create a handle for a nullptr pointer. */ Handle(js::NullPtr) { static_assert(mozilla::IsPointer::value, "js::NullPtr overload not valid for non-pointer types"); ptr = reinterpret_cast(&js::NullPtr::constNullValue); } - /* Create a handle for a NULL pointer. */ + /* Create a handle for a nullptr pointer. */ Handle(JS::NullPtr) { static_assert(mozilla::IsPointer::value, "JS::NullPtr overload not valid for non-pointer types"); @@ -457,24 +455,18 @@ class MOZ_NONHEAP_CLASS Handle : public js::HandleBase bool operator!=(const T &other) const { return *ptr != other; } bool operator==(const T &other) const { return *ptr == other; } + /* Change this handle to point to the same rooted location RHS does. */ + void repoint(const Handle &rhs) { ptr = rhs.address(); } + private: Handle() {} const T *ptr; - template - void operator=(S v) MOZ_DELETE; + template void operator=(S) MOZ_DELETE; + void operator=(Handle) MOZ_DELETE; }; -typedef Handle HandleObject; -typedef Handle HandleModule; -typedef Handle HandleScriptSource; -typedef Handle HandleFunction; -typedef Handle HandleScript; -typedef Handle HandleString; -typedef Handle HandleId; -typedef Handle HandleValue; - /* * Similar to a handle, but the underlying storage can be changed. This is * useful for outparams. @@ -488,6 +480,10 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase { public: inline MutableHandle(Rooted *root); + MutableHandle(int) MOZ_DELETE; +#ifdef MOZ_HAVE_CXX11_NULLPTR + MutableHandle(decltype(nullptr)) MOZ_DELETE; +#endif void set(T v) { JS_ASSERT(!js::GCMethods::poisoned(v)); @@ -526,13 +522,6 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase void operator=(MutableHandle other) MOZ_DELETE; }; -typedef MutableHandle MutableHandleObject; -typedef MutableHandle MutableHandleFunction; -typedef MutableHandle MutableHandleScript; -typedef MutableHandle MutableHandleString; -typedef MutableHandle MutableHandleId; -typedef MutableHandle MutableHandleValue; - #ifdef JSGC_GENERATIONAL JS_PUBLIC_API(void) HeapCellPostBarrier(js::gc::Cell **cellp); JS_PUBLIC_API(void) HeapCellRelocate(js::gc::Cell **cellp); @@ -614,7 +603,7 @@ struct RootKind template struct GCMethods { - static T *initial() { return NULL; } + static T *initial() { return nullptr; } static ThingRootKind kind() { return RootKind::rootKind(); } static bool poisoned(T *v) { return JS::IsPoisonedPtr(v); } static bool needsPostBarrier(T *v) { return v; } @@ -628,12 +617,11 @@ struct GCMethods #endif }; -// XXX: Needed for cocos2d JS Bindings -//#if defined(DEBUG) +#if defined(DEBUG) /* This helper allows us to assert that Rooted is scoped within a request. */ extern JS_PUBLIC_API(bool) IsInRequest(JSContext *cx); -//#endif +#endif } /* namespace js */ @@ -730,12 +718,15 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase init(js::PerThreadDataFriendFields::getMainThread(rt)); } - ~Rooted() { + // Note that we need to let the compiler generate the default destructor in + // non-exact-rooting builds because of a bug in the instrumented PGO builds + // using MSVC, see bug 915735 for more details. #ifdef JSGC_TRACK_EXACT_ROOTS + ~Rooted() { JS_ASSERT(*stack == reinterpret_cast*>(this)); *stack = prev; -#endif } +#endif #ifdef JSGC_TRACK_EXACT_ROOTS Rooted *previous() { return prev; } @@ -803,8 +794,6 @@ class Rooted; #endif typedef Rooted RootedObject; -typedef Rooted RootedModule; -typedef Rooted RootedScriptSource; typedef Rooted RootedFunction; typedef Rooted RootedScript; typedef Rooted RootedString; @@ -857,6 +846,10 @@ class SkipRoot void init(js::ContextFriendFields *cx, const T *ptr, size_t count) {} public: + ~SkipRoot() { + // An empty destructor is needed to avoid warnings from clang about + // unused local variables of this type. + } #endif /* DEBUG && JSGC_ROOT_ANALYSIS */ @@ -1063,7 +1056,7 @@ inline void MaybeCheckStackRoots(JSContext *cx) class CompilerRootNode { protected: - CompilerRootNode(js::gc::Cell *ptr) : next(NULL), ptr_(ptr) {} + CompilerRootNode(js::gc::Cell *ptr) : next(nullptr), ptr_(ptr) {} public: void **address() { return (void **)&ptr_; } diff --git a/external/spidermonkey/include/android/js/StructuredClone.h b/external/spidermonkey/include/android/js/StructuredClone.h new file mode 100644 index 0000000000..d32bdd8dd6 --- /dev/null +++ b/external/spidermonkey/include/android/js/StructuredClone.h @@ -0,0 +1,163 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_StructuredClone_h +#define js_StructuredClone_h + +#include "mozilla/NullPtr.h" + +#include + +#include "jstypes.h" + +#include "js/RootingAPI.h" +#include "js/TypeDecls.h" +#include "js/Value.h" + +struct JSRuntime; +struct JSStructuredCloneReader; +struct JSStructuredCloneWriter; + +// API for the HTML5 internal structured cloning algorithm. + +// Read structured data from the reader r. This hook is used to read a value +// previously serialized by a call to the WriteStructuredCloneOp hook. +// +// tag and data are the pair of uint32_t values from the header. The callback +// may use the JS_Read* APIs to read any other relevant parts of the object +// from the reader r. closure is any value passed to the JS_ReadStructuredClone +// function. Return the new object on success, nullptr on error/exception. +typedef JSObject *(*ReadStructuredCloneOp)(JSContext *cx, JSStructuredCloneReader *r, + uint32_t tag, uint32_t data, void *closure); + +// Structured data serialization hook. The engine can write primitive values, +// Objects, Arrays, Dates, RegExps, TypedArrays, and ArrayBuffers. Any other +// type of object requires application support. This callback must first use +// the JS_WriteUint32Pair API to write an object header, passing a value +// greater than JS_SCTAG_USER to the tag parameter. Then it can use the +// JS_Write* APIs to write any other relevant parts of the value v to the +// writer w. closure is any value passed to the JS_WriteStructuredCLone function. +// +// Return true on success, false on error/exception. +typedef bool (*WriteStructuredCloneOp)(JSContext *cx, JSStructuredCloneWriter *w, + JS::Handle obj, void *closure); + +// This is called when JS_WriteStructuredClone is given an invalid transferable. +// To follow HTML5, the application must throw a DATA_CLONE_ERR DOMException +// with error set to one of the JS_SCERR_* values. +typedef void (*StructuredCloneErrorOp)(JSContext *cx, uint32_t errorid); + +// The maximum supported structured-clone serialization format version. Note +// that this does not need to be bumped for Transferable-only changes, since +// they are never saved to persistent storage. +#define JS_STRUCTURED_CLONE_VERSION 2 + +struct JSStructuredCloneCallbacks { + ReadStructuredCloneOp read; + WriteStructuredCloneOp write; + StructuredCloneErrorOp reportError; +}; + +// Note: if the *data contains transferable objects, it can be read only once. +JS_PUBLIC_API(bool) +JS_ReadStructuredClone(JSContext *cx, uint64_t *data, size_t nbytes, uint32_t version, + JS::MutableHandleValue vp, + const JSStructuredCloneCallbacks *optionalCallbacks, void *closure); + +// Note: On success, the caller is responsible for calling +// JS_ClearStructuredClone(*datap, nbytesp). +JS_PUBLIC_API(bool) +JS_WriteStructuredClone(JSContext *cx, JS::HandleValue v, uint64_t **datap, size_t *nbytesp, + const JSStructuredCloneCallbacks *optionalCallbacks, + void *closure, JS::HandleValue transferable); + +JS_PUBLIC_API(bool) +JS_ClearStructuredClone(const uint64_t *data, size_t nbytes); + +JS_PUBLIC_API(bool) +JS_StructuredCloneHasTransferables(const uint64_t *data, size_t nbytes, bool *hasTransferable); + +JS_PUBLIC_API(bool) +JS_StructuredClone(JSContext *cx, JS::HandleValue v, JS::MutableHandleValue vp, + const JSStructuredCloneCallbacks *optionalCallbacks, void *closure); + +// RAII sugar for JS_WriteStructuredClone. +class JS_PUBLIC_API(JSAutoStructuredCloneBuffer) { + uint64_t *data_; + size_t nbytes_; + uint32_t version_; + + public: + JSAutoStructuredCloneBuffer() + : data_(nullptr), nbytes_(0), version_(JS_STRUCTURED_CLONE_VERSION) {} + + ~JSAutoStructuredCloneBuffer() { clear(); } + + uint64_t *data() const { return data_; } + size_t nbytes() const { return nbytes_; } + + void clear(); + + // Copy some memory. It will be automatically freed by the destructor. + bool copy(const uint64_t *data, size_t nbytes, uint32_t version=JS_STRUCTURED_CLONE_VERSION); + + // Adopt some memory. It will be automatically freed by the destructor. + // data must have been allocated by the JS engine (e.g., extracted via + // JSAutoStructuredCloneBuffer::steal). + void adopt(uint64_t *data, size_t nbytes, uint32_t version=JS_STRUCTURED_CLONE_VERSION); + + // Remove the buffer so that it will not be automatically freed. + // After this, the caller is responsible for feeding the memory back to + // JSAutoStructuredCloneBuffer::adopt. + void steal(uint64_t **datap, size_t *nbytesp, uint32_t *versionp=nullptr); + + bool read(JSContext *cx, JS::MutableHandleValue vp, + const JSStructuredCloneCallbacks *optionalCallbacks=nullptr, void *closure=nullptr); + + bool write(JSContext *cx, JS::HandleValue v, + const JSStructuredCloneCallbacks *optionalCallbacks=nullptr, void *closure=nullptr); + + bool write(JSContext *cx, JS::HandleValue v, JS::HandleValue transferable, + const JSStructuredCloneCallbacks *optionalCallbacks=nullptr, void *closure=nullptr); + + // Swap ownership with another JSAutoStructuredCloneBuffer. + void swap(JSAutoStructuredCloneBuffer &other); + + private: + // Copy and assignment are not supported. + JSAutoStructuredCloneBuffer(const JSAutoStructuredCloneBuffer &other); + JSAutoStructuredCloneBuffer &operator=(const JSAutoStructuredCloneBuffer &other); +}; + +// The range of tag values the application may use for its own custom object types. +#define JS_SCTAG_USER_MIN ((uint32_t) 0xFFFF8000) +#define JS_SCTAG_USER_MAX ((uint32_t) 0xFFFFFFFF) + +#define JS_SCERR_RECURSION 0 +#define JS_SCERR_TRANSFERABLE 1 + +JS_PUBLIC_API(void) +JS_SetStructuredCloneCallbacks(JSRuntime *rt, const JSStructuredCloneCallbacks *callbacks); + +JS_PUBLIC_API(bool) +JS_ReadUint32Pair(JSStructuredCloneReader *r, uint32_t *p1, uint32_t *p2); + +JS_PUBLIC_API(bool) +JS_ReadBytes(JSStructuredCloneReader *r, void *p, size_t len); + +JS_PUBLIC_API(bool) +JS_ReadTypedArray(JSStructuredCloneReader *r, JS::Value *vp); + +JS_PUBLIC_API(bool) +JS_WriteUint32Pair(JSStructuredCloneWriter *w, uint32_t tag, uint32_t data); + +JS_PUBLIC_API(bool) +JS_WriteBytes(JSStructuredCloneWriter *w, const void *p, size_t len); + +JS_PUBLIC_API(bool) +JS_WriteTypedArray(JSStructuredCloneWriter *w, JS::Value v); + +#endif /* js_StructuredClone_h */ diff --git a/external/spidermonkey/include/android/js/Tracer.h b/external/spidermonkey/include/android/js/Tracer.h new file mode 100644 index 0000000000..89994612f6 --- /dev/null +++ b/external/spidermonkey/include/android/js/Tracer.h @@ -0,0 +1,193 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_Tracer_h +#define js_Tracer_h + +#include "mozilla/NullPtr.h" + +#include "jspubtd.h" + +struct JSTracer; + +namespace JS { +template class Heap; +template class TenuredHeap; +} + +// Tracer callback, called for each traceable thing directly referenced by a +// particular object or runtime structure. It is the callback responsibility +// to ensure the traversal of the full object graph via calling eventually +// JS_TraceChildren on the passed thing. In this case the callback must be +// prepared to deal with cycles in the traversal graph. +// +// kind argument is one of JSTRACE_OBJECT, JSTRACE_STRING or a tag denoting +// internal implementation-specific traversal kind. In the latter case the only +// operations on thing that the callback can do is to call JS_TraceChildren or +// JS_GetTraceThingInfo. +// +// If eagerlyTraceWeakMaps is true, when we trace a WeakMap visit all +// of its mappings. This should be used in cases where the tracer +// wants to use the existing liveness of entries. +typedef void +(* JSTraceCallback)(JSTracer *trc, void **thingp, JSGCTraceKind kind); + +// Callback that JSTraceOp implementation can provide to return a string +// describing the reference traced with JS_CallTracer. +typedef void +(* JSTraceNamePrinter)(JSTracer *trc, char *buf, size_t bufsize); + +enum WeakMapTraceKind { + DoNotTraceWeakMaps = 0, + TraceWeakMapValues = 1, + TraceWeakMapKeysValues = 2 +}; + +struct JSTracer { + JSRuntime *runtime; + JSTraceCallback callback; + JSTraceNamePrinter debugPrinter; + const void *debugPrintArg; + size_t debugPrintIndex; + WeakMapTraceKind eagerlyTraceWeakMaps; +#ifdef JS_GC_ZEAL + void *realLocation; +#endif +}; + +// Set debugging information about a reference to a traceable thing to prepare +// for the following call to JS_CallTracer. +// +// When printer is null, arg must be const char * or char * C string naming +// the reference and index must be either (size_t)-1 indicating that the name +// alone describes the reference or it must be an index into some array vector +// that stores the reference. +// +// When printer callback is not null, the arg and index arguments are +// available to the callback as debugPrintArg and debugPrintIndex fields +// of JSTracer. +// +// The storage for name or callback's arguments needs to live only until +// the following call to JS_CallTracer returns. +// +# define JS_SET_TRACING_DETAILS(trc, printer, arg, index) \ + JS_BEGIN_MACRO \ + (trc)->debugPrinter = (printer); \ + (trc)->debugPrintArg = (arg); \ + (trc)->debugPrintIndex = (index); \ + JS_END_MACRO + +// Sets the real location for a marked reference, when passing the address +// directly is not feasable. +// +// FIXME: This is currently overcomplicated by our need to nest calls for Values +// stored as keys in hash tables, but will get simplified once we can rekey +// in-place. +// +#ifdef JS_GC_ZEAL +# define JS_SET_TRACING_LOCATION(trc, location) \ + JS_BEGIN_MACRO \ + if (!(trc)->realLocation || !(location)) \ + (trc)->realLocation = (location); \ + JS_END_MACRO +# define JS_UNSET_TRACING_LOCATION(trc) \ + JS_BEGIN_MACRO \ + (trc)->realLocation = nullptr; \ + JS_END_MACRO +#else +# define JS_SET_TRACING_LOCATION(trc, location) \ + JS_BEGIN_MACRO \ + JS_END_MACRO +# define JS_UNSET_TRACING_LOCATION(trc) \ + JS_BEGIN_MACRO \ + JS_END_MACRO +#endif + +// Convenience macro to describe the argument of JS_CallTracer using C string +// and index. +# define JS_SET_TRACING_INDEX(trc, name, index) \ + JS_SET_TRACING_DETAILS(trc, nullptr, name, index) + +// Convenience macro to describe the argument of JS_CallTracer using C string. +# define JS_SET_TRACING_NAME(trc, name) \ + JS_SET_TRACING_DETAILS(trc, nullptr, name, (size_t)-1) + +// The JS_Call*Tracer family of functions traces the given GC thing reference. +// This performs the tracing action configured on the given JSTracer: +// typically calling the JSTracer::callback or marking the thing as live. +// +// The argument to JS_Call*Tracer is an in-out param: when the function +// returns, the garbage collector might have moved the GC thing. In this case, +// the reference passed to JS_Call*Tracer will be updated to the object's new +// location. Callers of this method are responsible for updating any state +// that is dependent on the object's address. For example, if the object's +// address is used as a key in a hashtable, then the object must be removed +// and re-inserted with the correct hash. +// +extern JS_PUBLIC_API(void) +JS_CallValueTracer(JSTracer *trc, JS::Value *valuep, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallIdTracer(JSTracer *trc, jsid *idp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallObjectTracer(JSTracer *trc, JSObject **objp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallStringTracer(JSTracer *trc, JSString **strp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallScriptTracer(JSTracer *trc, JSScript **scriptp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapValueTracer(JSTracer *trc, JS::Heap *valuep, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapIdTracer(JSTracer *trc, JS::Heap *idp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapObjectTracer(JSTracer *trc, JS::Heap *objp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapStringTracer(JSTracer *trc, JS::Heap *strp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapScriptTracer(JSTracer *trc, JS::Heap *scriptp, const char *name); + +template +inline void +JS_CallHashSetObjectTracer(JSTracer *trc, HashSetEnum &e, JSObject *const &key, const char *name) +{ + JSObject *updated = key; + JS_SET_TRACING_LOCATION(trc, reinterpret_cast(&const_cast(key))); + JS_CallObjectTracer(trc, &updated, name); + if (updated != key) + e.rekeyFront(key, updated); +} + +// Trace an object that is known to always be tenured. No post barriers are +// required in this case. +extern JS_PUBLIC_API(void) +JS_CallTenuredObjectTracer(JSTracer *trc, JS::TenuredHeap *objp, const char *name); + +// API for JSTraceCallback implementations. +extern JS_PUBLIC_API(void) +JS_TracerInit(JSTracer *trc, JSRuntime *rt, JSTraceCallback callback); + +extern JS_PUBLIC_API(void) +JS_TraceChildren(JSTracer *trc, void *thing, JSGCTraceKind kind); + +extern JS_PUBLIC_API(void) +JS_TraceRuntime(JSTracer *trc); + +extern JS_PUBLIC_API(void) +JS_GetTraceThingInfo(char *buf, size_t bufsize, JSTracer *trc, + void *thing, JSGCTraceKind kind, bool includeDetails); + +extern JS_PUBLIC_API(const char *) +JS_GetTraceEdgeName(JSTracer *trc, char *buffer, int bufferSize); + +#endif /* js_Tracer_h */ diff --git a/external/spidermonkey/include/android/js/TypeDecls.h b/external/spidermonkey/include/android/js/TypeDecls.h new file mode 100644 index 0000000000..ec944d374c --- /dev/null +++ b/external/spidermonkey/include/android/js/TypeDecls.h @@ -0,0 +1,81 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +// This file contains public type declarations that are used *frequently*. If +// it doesn't occur at least 10 times in Gecko, it probably shouldn't be in +// here. +// +// It includes only: +// - forward declarations of structs and classes; +// - typedefs; +// - enums (maybe). +// It does *not* contain any struct or class definitions. + +#ifndef js_TypeDecls_h +#define js_TypeDecls_h + +#include +#include + +struct JSContext; +class JSFunction; +class JSObject; +class JSScript; +class JSString; + +// In release builds, jsid is defined to be an integral type. This +// prevents many bugs from being caught at compile time. E.g.: +// +// jsid id = ... +// if (id) // error +// ... +// +// size_t n = id; // error +// +// To catch more errors, jsid is given a struct type in C++ debug builds. +// Struct assignment and (in C++) operator== allow correct code to be mostly +// oblivious to the change. This feature can be explicitly disabled in debug +// builds by defining JS_NO_JSVAL_JSID_STRUCT_TYPES. +// + +// Needed for cocos2d-js +#define JS_NO_JSVAL_JSID_STRUCT_TYPES + +#if defined(DEBUG) && !defined(JS_NO_JSVAL_JSID_STRUCT_TYPES) +# define JS_USE_JSID_STRUCT_TYPES +#endif + +#ifdef JS_USE_JSID_STRUCT_TYPES +struct jsid; +#else +typedef ptrdiff_t jsid; +#endif + +typedef char16_t jschar; + +namespace JS { + +class Value; +template class Handle; +template class MutableHandle; + +typedef Handle HandleFunction; +typedef Handle HandleId; +typedef Handle HandleObject; +typedef Handle HandleScript; +typedef Handle HandleString; +typedef Handle HandleValue; + +typedef MutableHandle MutableHandleFunction; +typedef MutableHandle MutableHandleId; +typedef MutableHandle MutableHandleObject; +typedef MutableHandle MutableHandleScript; +typedef MutableHandle MutableHandleString; +typedef MutableHandle MutableHandleValue; + +} // namespace JS + +#endif /* js_TypeDecls_h */ diff --git a/external/spidermonkey/include/android/js/Utility.h b/external/spidermonkey/include/android/js/Utility.h index 9d391e5c8a..cdaf19ba5f 100644 --- a/external/spidermonkey/include/android/js/Utility.h +++ b/external/spidermonkey/include/android/js/Utility.h @@ -11,6 +11,7 @@ #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" #include "mozilla/Move.h" +#include "mozilla/NullPtr.h" #include "mozilla/Scoped.h" #include "mozilla/TemplateLib.h" @@ -18,8 +19,8 @@ #include #ifdef JS_OOM_DO_BACKTRACES -#include #include +#include #endif #include "jstypes.h" @@ -44,16 +45,6 @@ namespace js {} #define JS_ALWAYS_TRUE(expr) MOZ_ALWAYS_TRUE(expr) #define JS_ALWAYS_FALSE(expr) MOZ_ALWAYS_FALSE(expr) -#ifdef DEBUG -# ifdef JS_THREADSAFE -# define JS_THREADSAFE_ASSERT(expr) JS_ASSERT(expr) -# else -# define JS_THREADSAFE_ASSERT(expr) ((void) 0) -# endif -#else -# define JS_THREADSAFE_ASSERT(expr) ((void) 0) -#endif - #if defined(DEBUG) # define JS_DIAGNOSTICS_ASSERT(expr) MOZ_ASSERT(expr) #elif defined(JS_CRASH_DIAGNOSTICS) @@ -96,7 +87,7 @@ static JS_ALWAYS_INLINE void PrintBacktrace() { void* OOM_trace[JS_OOM_BACKTRACE_SIZE]; - char** OOM_traceSymbols = NULL; + char** OOM_traceSymbols = nullptr; int32_t OOM_traceSize = 0; int32_t OOM_traceIdx = 0; OOM_traceSize = backtrace(OOM_trace, JS_OOM_BACKTRACE_SIZE); @@ -126,7 +117,7 @@ PrintBacktrace() { \ if (++OOM_counter > OOM_maxAllocations) { \ JS_OOM_EMIT_BACKTRACE();\ - return NULL; \ + return nullptr; \ } \ } while (0) @@ -136,7 +127,7 @@ PrintBacktrace() if (++OOM_counter > OOM_maxAllocations) { \ JS_OOM_EMIT_BACKTRACE();\ js_ReportOutOfMemory(cx);\ - return NULL; \ + return nullptr; \ } \ } while (0) @@ -145,31 +136,31 @@ PrintBacktrace() # define JS_OOM_POSSIBLY_FAIL_REPORT(cx) do {} while(0) # endif /* DEBUG */ -static JS_INLINE void* js_malloc(size_t bytes) +static inline void* js_malloc(size_t bytes) { JS_OOM_POSSIBLY_FAIL(); return malloc(bytes); } -static JS_INLINE void* js_calloc(size_t bytes) +static inline void* js_calloc(size_t bytes) { JS_OOM_POSSIBLY_FAIL(); return calloc(bytes, 1); } -static JS_INLINE void* js_calloc(size_t nmemb, size_t size) +static inline void* js_calloc(size_t nmemb, size_t size) { JS_OOM_POSSIBLY_FAIL(); return calloc(nmemb, size); } -static JS_INLINE void* js_realloc(void* p, size_t bytes) +static inline void* js_realloc(void* p, size_t bytes) { JS_OOM_POSSIBLY_FAIL(); return realloc(p, bytes); } -static JS_INLINE void js_free(void* p) +static inline void js_free(void* p) { free(p); } @@ -241,7 +232,7 @@ static JS_INLINE void js_free(void* p) #define JS_NEW_BODY(allocator, t, parms) \ void *memory = allocator(sizeof(t)); \ - return memory ? new(memory) t parms : NULL; + return memory ? new(memory) t parms : nullptr; /* * Given a class which should provide 'new' methods, add @@ -360,7 +351,7 @@ static JS_ALWAYS_INLINE T * js_pod_malloc(size_t numElems) { if (numElems & mozilla::tl::MulOverflowMask::value) - return NULL; + return nullptr; return (T *)js_malloc(numElems * sizeof(T)); } @@ -369,7 +360,7 @@ static JS_ALWAYS_INLINE T * js_pod_calloc(size_t numElems) { if (numElems & mozilla::tl::MulOverflowMask::value) - return NULL; + return nullptr; return (T *)js_calloc(numElems * sizeof(T)); } @@ -379,7 +370,7 @@ template struct ScopedFreePtrTraits { typedef T* type; - static T* empty() { return NULL; } + static T* empty() { return nullptr; } static void release(T* ptr) { js_free(ptr); } }; SCOPED_TEMPLATE(ScopedJSFreePtr, ScopedFreePtrTraits) diff --git a/external/spidermonkey/include/android/js/Value.h b/external/spidermonkey/include/android/js/Value.h index 9b2c5dd6f9..7a772bcfba 100644 --- a/external/spidermonkey/include/android/js/Value.h +++ b/external/spidermonkey/include/android/js/Value.h @@ -15,6 +15,8 @@ #include /* for std::numeric_limits */ +#include "jstypes.h" + #include "js/Anchor.h" #include "js/RootingAPI.h" #include "js/Utility.h" @@ -248,7 +250,7 @@ typedef union jsval_layout union { int32_t i32; uint32_t u32; - JSBool boo; + uint32_t boo; // Don't use |bool| -- it must be four bytes. JSString *str; JSObject *obj; void *ptr; @@ -295,7 +297,7 @@ typedef union jsval_layout union { int32_t i32; uint32_t u32; - JSBool boo; + uint32_t boo; // Don't use |bool| -- it must be four bytes. JSString *str; JSObject *obj; void *ptr; @@ -333,6 +335,49 @@ typedef union jsval_layout JS_STATIC_ASSERT(sizeof(jsval_layout) == 8); +/* + * For codesize purposes on some platforms, it's important that the + * compiler know that JS::Values constructed from constant values can be + * folded to constant bit patterns at compile time, rather than + * constructed at runtime. Doing this requires a fair amount of C++11 + * features, which are not supported on all of our compilers. Set up + * some defines and helper macros in an attempt to confine the ugliness + * here, rather than scattering it all about the file. The important + * features are: + * + * - constexpr; + * - defaulted functions; + * - C99-style designated initializers. + */ +#if defined(__clang__) +# if __has_feature(cxx_constexpr) && __has_feature(cxx_defaulted_functions) +# define JS_VALUE_IS_CONSTEXPR +# endif +#elif defined(__GNUC__) +/* + * We need 4.5 for defaulted functions, 4.6 for constexpr, 4.7 because 4.6 + * doesn't understand |(X) { .field = ... }| syntax, and 4.7.3 because + * versions prior to that have bugs in the C++ front-end that cause crashes. + */ +# if MOZ_GCC_VERSION_AT_LEAST(4, 7, 3) +# define JS_VALUE_IS_CONSTEXPR +# endif +#endif + +#if defined(JS_VALUE_IS_CONSTEXPR) +# define JS_RETURN_LAYOUT_FROM_BITS(BITS) \ + return (jsval_layout) { .asBits = (BITS) } +# define JS_VALUE_CONSTEXPR MOZ_CONSTEXPR +# define JS_VALUE_CONSTEXPR_VAR MOZ_CONSTEXPR_VAR +#else +# define JS_RETURN_LAYOUT_FROM_BITS(BITS) \ + jsval_layout l; \ + l.asBits = (BITS); \ + return l; +# define JS_VALUE_CONSTEXPR +# define JS_VALUE_CONSTEXPR_VAR const +#endif + #if JS_BITS_PER_WORD == 32 /* @@ -341,15 +386,13 @@ JS_STATIC_ASSERT(sizeof(jsval_layout) == 8); * Thus, all comparisons should explicitly cast operands to uint32_t. */ -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout BUILD_JSVAL(JSValueTag tag, uint32_t payload) { - jsval_layout l; - l.asBits = (((uint64_t)(uint32_t)tag) << 32) | payload; - return l; + JS_RETURN_LAYOUT_FROM_BITS((((uint64_t)(uint32_t)tag) << 32) | payload); } -static inline JSBool +static inline bool JSVAL_IS_DOUBLE_IMPL(jsval_layout l) { return (uint32_t)l.s.tag <= (uint32_t)JSVAL_TAG_CLEAR; @@ -364,7 +407,7 @@ DOUBLE_TO_JSVAL_IMPL(double d) return l; } -static inline JSBool +static inline bool JSVAL_IS_INT32_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_INT32; @@ -376,16 +419,20 @@ JSVAL_TO_INT32_IMPL(jsval_layout l) return l.s.payload.i32; } -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout INT32_TO_JSVAL_IMPL(int32_t i) { +#if defined(JS_VALUE_IS_CONSTEXPR) + return BUILD_JSVAL(JSVAL_TAG_INT32, i); +#else jsval_layout l; l.s.tag = JSVAL_TAG_INT32; l.s.payload.i32 = i; return l; +#endif } -static inline JSBool +static inline bool JSVAL_IS_NUMBER_IMPL(jsval_layout l) { JSValueTag tag = l.s.tag; @@ -393,13 +440,13 @@ JSVAL_IS_NUMBER_IMPL(jsval_layout l) return (uint32_t)tag <= (uint32_t)JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET; } -static inline JSBool +static inline bool JSVAL_IS_UNDEFINED_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_UNDEFINED; } -static inline JSBool +static inline bool JSVAL_IS_STRING_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_STRING; @@ -421,47 +468,46 @@ JSVAL_TO_STRING_IMPL(jsval_layout l) return l.s.payload.str; } -static inline JSBool +static inline bool JSVAL_IS_BOOLEAN_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_BOOLEAN; } -static inline JSBool +static inline bool JSVAL_TO_BOOLEAN_IMPL(jsval_layout l) { return l.s.payload.boo; } static inline jsval_layout -BOOLEAN_TO_JSVAL_IMPL(JSBool b) +BOOLEAN_TO_JSVAL_IMPL(bool b) { jsval_layout l; - MOZ_ASSERT(b == JS_TRUE || b == JS_FALSE); l.s.tag = JSVAL_TAG_BOOLEAN; l.s.payload.boo = b; return l; } -static inline JSBool +static inline bool JSVAL_IS_MAGIC_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_MAGIC; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_OBJECT; } -static inline JSBool +static inline bool JSVAL_IS_PRIMITIVE_IMPL(jsval_layout l) { return (uint32_t)l.s.tag < (uint32_t)JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_OR_NULL_IMPL(jsval_layout l) { MOZ_ASSERT((uint32_t)l.s.tag <= (uint32_t)JSVAL_TAG_OBJECT); @@ -484,7 +530,7 @@ OBJECT_TO_JSVAL_IMPL(JSObject *obj) return l; } -static inline JSBool +static inline bool JSVAL_IS_NULL_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_NULL; @@ -507,7 +553,7 @@ JSVAL_TO_PRIVATE_PTR_IMPL(jsval_layout l) return l.s.payload.ptr; } -static inline JSBool +static inline bool JSVAL_IS_GCTHING_IMPL(jsval_layout l) { /* gcc sometimes generates signed < without explicit casts. */ @@ -520,7 +566,7 @@ JSVAL_TO_GCTHING_IMPL(jsval_layout l) return l.s.payload.ptr; } -static inline JSBool +static inline bool JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_STRING || l.s.tag == JSVAL_TAG_OBJECT; @@ -529,19 +575,19 @@ JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) static inline uint32_t JSVAL_TRACE_KIND_IMPL(jsval_layout l) { - return (uint32_t)(JSBool)JSVAL_IS_STRING_IMPL(l); + return (uint32_t)(bool)JSVAL_IS_STRING_IMPL(l); } -static inline JSBool +static inline bool JSVAL_IS_SPECIFIC_INT32_IMPL(jsval_layout l, int32_t i32) { return l.s.tag == JSVAL_TAG_INT32 && l.s.payload.i32 == i32; } -static inline JSBool -JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, JSBool b) +static inline bool +JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, bool b) { - return (l.s.tag == JSVAL_TAG_BOOLEAN) && (l.s.payload.boo == b); + return (l.s.tag == JSVAL_TAG_BOOLEAN) && (l.s.payload.boo == uint32_t(b)); } static inline jsval_layout @@ -553,7 +599,7 @@ MAGIC_TO_JSVAL_IMPL(JSWhyMagic why) return l; } -static inline JSBool +static inline bool JSVAL_SAME_TYPE_IMPL(jsval_layout lhs, jsval_layout rhs) { JSValueTag ltag = lhs.s.tag, rtag = rhs.s.tag; @@ -570,15 +616,13 @@ JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(jsval_layout l) #elif JS_BITS_PER_WORD == 64 -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout BUILD_JSVAL(JSValueTag tag, uint64_t payload) { - jsval_layout l; - l.asBits = (((uint64_t)(uint32_t)tag) << JSVAL_TAG_SHIFT) | payload; - return l; + JS_RETURN_LAYOUT_FROM_BITS((((uint64_t)(uint32_t)tag) << JSVAL_TAG_SHIFT) | payload); } -static inline JSBool +static inline bool JSVAL_IS_DOUBLE_IMPL(jsval_layout l) { return l.asBits <= JSVAL_SHIFTED_TAG_MAX_DOUBLE; @@ -593,7 +637,7 @@ DOUBLE_TO_JSVAL_IMPL(double d) return l; } -static inline JSBool +static inline bool JSVAL_IS_INT32_IMPL(jsval_layout l) { return (uint32_t)(l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_INT32; @@ -605,27 +649,25 @@ JSVAL_TO_INT32_IMPL(jsval_layout l) return (int32_t)l.asBits; } -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout INT32_TO_JSVAL_IMPL(int32_t i32) { - jsval_layout l; - l.asBits = ((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32; - return l; + JS_RETURN_LAYOUT_FROM_BITS(((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32); } -static inline JSBool +static inline bool JSVAL_IS_NUMBER_IMPL(jsval_layout l) { return l.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET; } -static inline JSBool +static inline bool JSVAL_IS_UNDEFINED_IMPL(jsval_layout l) { return l.asBits == JSVAL_SHIFTED_TAG_UNDEFINED; } -static inline JSBool +static inline bool JSVAL_IS_STRING_IMPL(jsval_layout l) { return (uint32_t)(l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_STRING; @@ -648,47 +690,46 @@ JSVAL_TO_STRING_IMPL(jsval_layout l) return (JSString *)(l.asBits & JSVAL_PAYLOAD_MASK); } -static inline JSBool +static inline bool JSVAL_IS_BOOLEAN_IMPL(jsval_layout l) { return (uint32_t)(l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_BOOLEAN; } -static inline JSBool +static inline bool JSVAL_TO_BOOLEAN_IMPL(jsval_layout l) { - return (JSBool)l.asBits; + return (bool)(l.asBits & JSVAL_PAYLOAD_MASK); } static inline jsval_layout -BOOLEAN_TO_JSVAL_IMPL(JSBool b) +BOOLEAN_TO_JSVAL_IMPL(bool b) { jsval_layout l; - MOZ_ASSERT(b == JS_TRUE || b == JS_FALSE); l.asBits = ((uint64_t)(uint32_t)b) | JSVAL_SHIFTED_TAG_BOOLEAN; return l; } -static inline JSBool +static inline bool JSVAL_IS_MAGIC_IMPL(jsval_layout l) { return (l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_MAGIC; } -static inline JSBool +static inline bool JSVAL_IS_PRIMITIVE_IMPL(jsval_layout l) { return l.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_IMPL(jsval_layout l) { MOZ_ASSERT((l.asBits >> JSVAL_TAG_SHIFT) <= JSVAL_SHIFTED_TAG_OBJECT); return l.asBits >= JSVAL_SHIFTED_TAG_OBJECT; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_OR_NULL_IMPL(jsval_layout l) { MOZ_ASSERT((l.asBits >> JSVAL_TAG_SHIFT) <= JSVAL_TAG_OBJECT); @@ -714,13 +755,13 @@ OBJECT_TO_JSVAL_IMPL(JSObject *obj) return l; } -static inline JSBool +static inline bool JSVAL_IS_NULL_IMPL(jsval_layout l) { return l.asBits == JSVAL_SHIFTED_TAG_NULL; } -static inline JSBool +static inline bool JSVAL_IS_GCTHING_IMPL(jsval_layout l) { return l.asBits >= JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET; @@ -734,7 +775,7 @@ JSVAL_TO_GCTHING_IMPL(jsval_layout l) return (void *)ptrBits; } -static inline JSBool +static inline bool JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) { return JSVAL_IS_GCTHING_IMPL(l) && !JSVAL_IS_NULL_IMPL(l); @@ -743,7 +784,7 @@ JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) static inline uint32_t JSVAL_TRACE_KIND_IMPL(jsval_layout l) { - return (uint32_t)(JSBool)!(JSVAL_IS_OBJECT_IMPL(l)); + return (uint32_t)(bool)!(JSVAL_IS_OBJECT_IMPL(l)); } static inline jsval_layout @@ -764,14 +805,14 @@ JSVAL_TO_PRIVATE_PTR_IMPL(jsval_layout l) return (void *)(l.asBits << 1); } -static inline JSBool +static inline bool JSVAL_IS_SPECIFIC_INT32_IMPL(jsval_layout l, int32_t i32) { return l.asBits == (((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32); } -static inline JSBool -JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, JSBool b) +static inline bool +JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, bool b) { return l.asBits == (((uint64_t)(uint32_t)b) | JSVAL_SHIFTED_TAG_BOOLEAN); } @@ -784,7 +825,7 @@ MAGIC_TO_JSVAL_IMPL(JSWhyMagic why) return l; } -static inline JSBool +static inline bool JSVAL_SAME_TYPE_IMPL(jsval_layout lhs, jsval_layout rhs) { uint64_t lbits = lhs.asBits, rbits = rhs.asBits; @@ -803,10 +844,12 @@ JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(jsval_layout l) #endif /* JS_BITS_PER_WORD */ static inline jsval_layout JSVAL_TO_IMPL(JS::Value v); -static inline JS::Value IMPL_TO_JSVAL(jsval_layout l); +static inline JS_VALUE_CONSTEXPR JS::Value IMPL_TO_JSVAL(jsval_layout l); namespace JS { +static inline JS_VALUE_CONSTEXPR JS::Value UndefinedValue(); + /** * Returns a generic quiet NaN value, with all payload bits set to zero. * @@ -816,7 +859,7 @@ namespace JS { static MOZ_ALWAYS_INLINE double GenericNaN() { - return mozilla::SpecificNaN(0, 0x8000000000000ULL); + return mozilla::SpecificNaN(0, 0x8000000000000ULL); } static inline double @@ -869,6 +912,10 @@ class Value * N.B. the default constructor leaves Value unitialized. Adding a default * constructor prevents Value from being stored in a union. */ +#if defined(JS_VALUE_IS_CONSTEXPR) + Value() = default; + Value(const Value& v) = default; +#endif /*** Mutators ***/ @@ -893,6 +940,10 @@ class Value data = DOUBLE_TO_JSVAL_IMPL(d); } + void setNaN() { + setDouble(GenericNaN()); + } + double &getDoubleRef() { MOZ_ASSERT(isDouble()); return data.asDouble; @@ -1173,16 +1224,20 @@ class Value jsval_layout data; private: +#if defined(JS_VALUE_IS_CONSTEXPR) + JS_VALUE_CONSTEXPR Value(jsval_layout layout) : data(layout) {} +#endif + void staticAssertions() { JS_STATIC_ASSERT(sizeof(JSValueType) == 1); JS_STATIC_ASSERT(sizeof(JSValueTag) == 4); - JS_STATIC_ASSERT(sizeof(JSBool) == 4); JS_STATIC_ASSERT(sizeof(JSWhyMagic) <= 4); JS_STATIC_ASSERT(sizeof(Value) == 8); } friend jsval_layout (::JSVAL_TO_IMPL)(Value); - friend Value (::IMPL_TO_JSVAL)(jsval_layout l); + friend Value JS_VALUE_CONSTEXPR (::IMPL_TO_JSVAL)(jsval_layout l); + friend Value JS_VALUE_CONSTEXPR (JS::UndefinedValue)(); }; inline bool @@ -1205,12 +1260,16 @@ NullValue() return v; } -static inline Value +static inline JS_VALUE_CONSTEXPR Value UndefinedValue() { - Value v; +#if defined(JS_VALUE_IS_CONSTEXPR) + return Value(BUILD_JSVAL(JSVAL_TAG_UNDEFINED, 0)); +#else + JS::Value v; v.setUndefined(); return v; +#endif } static inline Value @@ -1229,6 +1288,22 @@ DoubleValue(double dbl) return v; } +static inline Value +DoubleNaNValue() +{ + Value v; + v.setNaN(); + return v; +} + +static inline Value +Float32Value(float f) +{ + Value v; + v.setDouble(f); + return v; +} + static inline Value StringValue(JSString *str) { @@ -1499,6 +1574,7 @@ class UnbarrieredMutableValueOperations : public ValueOperations void setUndefined() { value()->setUndefined(); } void setInt32(int32_t i) { value()->setInt32(i); } void setDouble(double d) { value()->setDouble(d); } + void setNaN() { setDouble(JS::GenericNaN()); } void setBoolean(bool b) { value()->setBoolean(b); } void setMagic(JSWhyMagic why) { value()->setMagic(why); } bool setNumber(uint32_t ui) { return value()->setNumber(ui); } @@ -1620,12 +1696,16 @@ JSVAL_TO_IMPL(JS::Value v) return v.data; } -inline JS::Value +inline JS_VALUE_CONSTEXPR JS::Value IMPL_TO_JSVAL(jsval_layout l) { +#if defined(JS_VALUE_IS_CONSTEXPR) + return JS::Value(l); +#else JS::Value v; v.data = l; return v; +#endif } namespace JS { @@ -1678,19 +1758,19 @@ static_assert(sizeof(jsval_layout) == sizeof(JS::Value), /************************************************************************/ -static inline JSBool +static inline bool JSVAL_IS_NULL(jsval v) { return JSVAL_IS_NULL_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_VOID(jsval v) { return JSVAL_IS_UNDEFINED_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_INT(jsval v) { return JSVAL_IS_INT32_IMPL(JSVAL_TO_IMPL(v)); @@ -1703,13 +1783,13 @@ JSVAL_TO_INT(jsval v) return JSVAL_TO_INT32_IMPL(JSVAL_TO_IMPL(v)); } -static inline jsval +static inline JS_VALUE_CONSTEXPR jsval INT_TO_JSVAL(int32_t i) { return IMPL_TO_JSVAL(INT32_TO_JSVAL_IMPL(i)); } -static inline JSBool +static inline bool JSVAL_IS_DOUBLE(jsval v) { return JSVAL_IS_DOUBLE_IMPL(JSVAL_TO_IMPL(v)); @@ -1724,7 +1804,7 @@ JSVAL_TO_DOUBLE(jsval v) return l.asDouble; } -static inline jsval +static inline JS_VALUE_CONSTEXPR jsval DOUBLE_TO_JSVAL(double d) { /* @@ -1733,29 +1813,35 @@ DOUBLE_TO_JSVAL(double d) * return IMPL_TO_JSVAL(DOUBLE_TO_JSVAL_IMPL(d)); * because GCC from XCode 3.1.4 miscompiles the above code. */ +#if defined(JS_VALUE_IS_CONSTEXPR) + return IMPL_TO_JSVAL(MOZ_UNLIKELY(d != d) + ? (jsval_layout) { .asBits = 0x7FF8000000000000LL } + : (jsval_layout) { .asDouble = d }); +#else jsval_layout l; if (MOZ_UNLIKELY(d != d)) l.asBits = 0x7FF8000000000000LL; else l.asDouble = d; return IMPL_TO_JSVAL(l); +#endif } -static inline jsval +static inline JS_VALUE_CONSTEXPR jsval UINT_TO_JSVAL(uint32_t i) { - if (i <= JSVAL_INT_MAX) - return INT_TO_JSVAL((int32_t)i); - return DOUBLE_TO_JSVAL((double)i); + return (i <= JSVAL_INT_MAX + ? INT_TO_JSVAL((int32_t)i) + : DOUBLE_TO_JSVAL((double)i)); } -static inline JSBool +static inline bool JSVAL_IS_NUMBER(jsval v) { return JSVAL_IS_NUMBER_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_STRING(jsval v) { return JSVAL_IS_STRING_IMPL(JSVAL_TO_IMPL(v)); @@ -1789,13 +1875,13 @@ OBJECT_TO_JSVAL(JSObject *obj) return IMPL_TO_JSVAL(BUILD_JSVAL(JSVAL_TAG_NULL, 0)); } -static inline JSBool +static inline bool JSVAL_IS_BOOLEAN(jsval v) { return JSVAL_IS_BOOLEAN_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_TO_BOOLEAN(jsval v) { MOZ_ASSERT(JSVAL_IS_BOOLEAN(v)); @@ -1803,18 +1889,18 @@ JSVAL_TO_BOOLEAN(jsval v) } static inline jsval -BOOLEAN_TO_JSVAL(JSBool b) +BOOLEAN_TO_JSVAL(bool b) { return IMPL_TO_JSVAL(BOOLEAN_TO_JSVAL_IMPL(b)); } -static inline JSBool +static inline bool JSVAL_IS_PRIMITIVE(jsval v) { return JSVAL_IS_PRIMITIVE_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_GCTHING(jsval v) { return JSVAL_IS_GCTHING_IMPL(JSVAL_TO_IMPL(v)); @@ -1842,4 +1928,25 @@ JSVAL_TO_PRIVATE(jsval v) return JSVAL_TO_PRIVATE_PTR_IMPL(JSVAL_TO_IMPL(v)); } +// JS constants. For efficiency, prefer predicates (e.g. v.isNull()) and +// constructing values from scratch (e.g. Int32Value(0)). These constants are +// stored in memory and initialized at startup, so testing against them and +// using them requires memory loads and will be correspondingly slow. +extern JS_PUBLIC_DATA(const jsval) JSVAL_NULL; +extern JS_PUBLIC_DATA(const jsval) JSVAL_ZERO; +extern JS_PUBLIC_DATA(const jsval) JSVAL_ONE; +extern JS_PUBLIC_DATA(const jsval) JSVAL_FALSE; +extern JS_PUBLIC_DATA(const jsval) JSVAL_TRUE; +extern JS_PUBLIC_DATA(const jsval) JSVAL_VOID; + +namespace JS { + +extern JS_PUBLIC_DATA(const Handle) NullHandleValue; +extern JS_PUBLIC_DATA(const Handle) UndefinedHandleValue; + +} + +#undef JS_VALUE_IS_CONSTEXPR +#undef JS_RETURN_LAYOUT_FROM_BITS + #endif /* js_Value_h */ diff --git a/external/spidermonkey/include/android/jsalloc.h b/external/spidermonkey/include/android/jsalloc.h index 3abc4966d1..03b6b569e1 100644 --- a/external/spidermonkey/include/android/jsalloc.h +++ b/external/spidermonkey/include/android/jsalloc.h @@ -9,12 +9,9 @@ #ifndef jsalloc_h #define jsalloc_h -#include "mozilla/AllocPolicy.h" - +#include "js/TypeDecls.h" #include "js/Utility.h" -struct JSContext; - namespace js { class ContextFriendFields; @@ -56,14 +53,14 @@ class TempAllocPolicy void *malloc_(size_t bytes) { void *p = js_malloc(bytes); if (JS_UNLIKELY(!p)) - p = onOutOfMemory(NULL, bytes); + p = onOutOfMemory(nullptr, bytes); return p; } void *calloc_(size_t bytes) { void *p = js_calloc(bytes); if (JS_UNLIKELY(!p)) - p = onOutOfMemory(NULL, bytes); + p = onOutOfMemory(nullptr, bytes); return p; } diff --git a/external/spidermonkey/include/android/jsapi.h.REMOVED.git-id b/external/spidermonkey/include/android/jsapi.h.REMOVED.git-id index 27b6bbed78..f73a8c745e 100644 --- a/external/spidermonkey/include/android/jsapi.h.REMOVED.git-id +++ b/external/spidermonkey/include/android/jsapi.h.REMOVED.git-id @@ -1 +1 @@ -e14ea931f699b1808c06886e55e977c9819f3774 \ No newline at end of file +38fc2004d49d7c513aff0f7f43d79524ec667c2c \ No newline at end of file diff --git a/external/spidermonkey/include/android/jsbytecode.h b/external/spidermonkey/include/android/jsbytecode.h new file mode 100644 index 0000000000..8e4f4cf90b --- /dev/null +++ b/external/spidermonkey/include/android/jsbytecode.h @@ -0,0 +1,14 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef jsbytecode_h +#define jsbytecode_h + +#include + +typedef uint8_t jsbytecode; + +#endif /* jsbytecode_h */ diff --git a/external/spidermonkey/include/android/jsclass.h b/external/spidermonkey/include/android/jsclass.h deleted file mode 100644 index def641715d..0000000000 --- a/external/spidermonkey/include/android/jsclass.h +++ /dev/null @@ -1,405 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -#ifndef jsclass_h -#define jsclass_h -/* - * A JSClass acts as a vtable for JS objects that allows JSAPI clients to - * control various aspects of the behavior of an object like property lookup. - * js::Class is an engine-private extension that allows more control over - * object behavior and, e.g., allows custom slow layout. - */ - -#include "jsapi.h" -#include "jsprvtd.h" - -namespace js { - -class PropertyName; -class SpecialId; -class PropertyId; - -// This is equal to JSFunction::class_. Use it in places where you don't want -// to #include jsfun.h. -extern JS_FRIEND_DATA(js::Class* const) FunctionClassPtr; - -static JS_ALWAYS_INLINE jsid -SPECIALID_TO_JSID(const SpecialId &sid); - -/* - * We partition the ways to refer to a property into three: by an index - * (uint32_t); by a string whose characters do not represent an index - * (PropertyName, see vm/String.h); and by various special values. - * - * Special values are encoded using SpecialId, which is layout-compatible but - * non-interconvertible with jsid. A SpecialId is used for JSID_VOID, which - * does not occur in JS scripts but may be used to indicate the absence of a - * valid identifier. In the future, a SpecialId may also be an object used by - * Harmony-proposed private names. - */ -class SpecialId -{ - uintptr_t bits_; - - /* Needs access to raw bits. */ - friend JS_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid); - friend class PropertyId; - - static const uintptr_t TYPE_VOID = JSID_TYPE_VOID; - static const uintptr_t TYPE_OBJECT = JSID_TYPE_OBJECT; - static const uintptr_t TYPE_MASK = JSID_TYPE_MASK; - - SpecialId(uintptr_t bits) : bits_(bits) { } - - public: - SpecialId() : bits_(TYPE_VOID) { } - - /* Object-valued */ - - SpecialId(JSObject &obj) - : bits_(uintptr_t(&obj) | TYPE_OBJECT) - { - JS_ASSERT(&obj != NULL); - JS_ASSERT((uintptr_t(&obj) & TYPE_MASK) == 0); - } - - bool isObject() const { - return (bits_ & TYPE_MASK) == TYPE_OBJECT && bits_ != TYPE_OBJECT; - } - - JSObject *toObject() const { - JS_ASSERT(isObject()); - return reinterpret_cast(bits_ & ~TYPE_MASK); - } - - /* Empty */ - - static SpecialId empty() { - SpecialId sid(TYPE_OBJECT); - JS_ASSERT(sid.isEmpty()); - return sid; - } - - bool isEmpty() const { - return bits_ == TYPE_OBJECT; - } - - /* Void */ - - static SpecialId voidId() { - SpecialId sid(TYPE_VOID); - JS_ASSERT(sid.isVoid()); - return sid; - } - - bool isVoid() const { - return bits_ == TYPE_VOID; - } -}; - -static JS_ALWAYS_INLINE jsid -SPECIALID_TO_JSID(const SpecialId &sid) -{ - jsid id; - JSID_BITS(id) = sid.bits_; - JS_ASSERT_IF(sid.isObject(), JSID_IS_OBJECT(id) && JSID_TO_OBJECT(id) == sid.toObject()); - JS_ASSERT_IF(sid.isVoid(), JSID_IS_VOID(id)); - JS_ASSERT_IF(sid.isEmpty(), JSID_IS_EMPTY(id)); - return id; -} - -static JS_ALWAYS_INLINE bool -JSID_IS_SPECIAL(jsid id) -{ - return JSID_IS_OBJECT(id) || JSID_IS_EMPTY(id) || JSID_IS_VOID(id); -} - -static JS_ALWAYS_INLINE SpecialId -JSID_TO_SPECIALID(jsid id) -{ - JS_ASSERT(JSID_IS_SPECIAL(id)); - if (JSID_IS_OBJECT(id)) - return SpecialId(*JSID_TO_OBJECT(id)); - if (JSID_IS_EMPTY(id)) - return SpecialId::empty(); - JS_ASSERT(JSID_IS_VOID(id)); - return SpecialId::voidId(); -} - -typedef JS::Handle HandleSpecialId; - -/* js::Class operation signatures. */ - -typedef JSBool -(* LookupGenericOp)(JSContext *cx, HandleObject obj, HandleId id, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* LookupPropOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* LookupElementOp)(JSContext *cx, HandleObject obj, uint32_t index, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* LookupSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* DefineGenericOp)(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* DefinePropOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* DefineElementOp)(JSContext *cx, HandleObject obj, uint32_t index, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* DefineSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* GenericIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandleId id, MutableHandleValue vp); -typedef JSBool -(* PropertyIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandlePropertyName name, MutableHandleValue vp); -typedef JSBool -(* ElementIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, uint32_t index, MutableHandleValue vp); -typedef JSBool -(* ElementIfPresentOp)(JSContext *cx, HandleObject obj, HandleObject receiver, uint32_t index, MutableHandleValue vp, bool* present); -typedef JSBool -(* SpecialIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandleSpecialId sid, MutableHandleValue vp); -typedef JSBool -(* StrictGenericIdOp)(JSContext *cx, HandleObject obj, HandleId id, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* StrictPropertyIdOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* StrictElementIdOp)(JSContext *cx, HandleObject obj, uint32_t index, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* StrictSpecialIdOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* GenericAttributesOp)(JSContext *cx, HandleObject obj, HandleId id, unsigned *attrsp); -typedef JSBool -(* PropertyAttributesOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, unsigned *attrsp); -typedef JSBool -(* ElementAttributesOp)(JSContext *cx, HandleObject obj, uint32_t index, unsigned *attrsp); -typedef JSBool -(* SpecialAttributesOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, unsigned *attrsp); -typedef JSBool -(* DeletePropertyOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, JSBool *succeeded); -typedef JSBool -(* DeleteElementOp)(JSContext *cx, HandleObject obj, uint32_t index, JSBool *succeeded); -typedef JSBool -(* DeleteSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, JSBool *succeeded); - - -typedef JSObject * -(* ObjectOp)(JSContext *cx, HandleObject obj); -typedef void -(* FinalizeOp)(FreeOp *fop, JSObject *obj); - -#define JS_CLASS_MEMBERS \ - const char *name; \ - uint32_t flags; \ - \ - /* Mandatory function pointer members. */ \ - JSPropertyOp addProperty; \ - JSDeletePropertyOp delProperty; \ - JSPropertyOp getProperty; \ - JSStrictPropertyOp setProperty; \ - JSEnumerateOp enumerate; \ - JSResolveOp resolve; \ - JSConvertOp convert; \ - \ - /* Optional members (may be null). */ \ - FinalizeOp finalize; \ - JSCheckAccessOp checkAccess; \ - JSNative call; \ - JSHasInstanceOp hasInstance; \ - JSNative construct; \ - JSTraceOp trace - -/* - * The helper struct to measure the size of JS_CLASS_MEMBERS to know how much - * we have to pad js::Class to match the size of JSClass. - */ -struct ClassSizeMeasurement -{ - JS_CLASS_MEMBERS; -}; - -struct ClassExtension -{ - JSObjectOp outerObject; - JSObjectOp innerObject; - JSIteratorOp iteratorObject; - - /* - * isWrappedNative is true only if the class is an XPCWrappedNative. - * WeakMaps use this to override the wrapper disposal optimization. - */ - bool isWrappedNative; - - /* - * If an object is used as a key in a weakmap, it may be desirable for the - * garbage collector to keep that object around longer than it otherwise - * would. A common case is when the key is a wrapper around an object in - * another compartment, and we want to avoid collecting the wrapper (and - * removing the weakmap entry) as long as the wrapped object is alive. In - * that case, the wrapped object is returned by the wrapper's - * weakmapKeyDelegateOp hook. As long as the wrapper is used as a weakmap - * key, it will not be collected (and remain in the weakmap) until the - * wrapped object is collected. - */ - JSWeakmapKeyDelegateOp weakmapKeyDelegateOp; -}; - -#define JS_NULL_CLASS_EXT {NULL,NULL,NULL,false,NULL} - -struct ObjectOps -{ - LookupGenericOp lookupGeneric; - LookupPropOp lookupProperty; - LookupElementOp lookupElement; - LookupSpecialOp lookupSpecial; - DefineGenericOp defineGeneric; - DefinePropOp defineProperty; - DefineElementOp defineElement; - DefineSpecialOp defineSpecial; - GenericIdOp getGeneric; - PropertyIdOp getProperty; - ElementIdOp getElement; - ElementIfPresentOp getElementIfPresent; /* can be null */ - SpecialIdOp getSpecial; - StrictGenericIdOp setGeneric; - StrictPropertyIdOp setProperty; - StrictElementIdOp setElement; - StrictSpecialIdOp setSpecial; - GenericAttributesOp getGenericAttributes; - PropertyAttributesOp getPropertyAttributes; - ElementAttributesOp getElementAttributes; - SpecialAttributesOp getSpecialAttributes; - GenericAttributesOp setGenericAttributes; - PropertyAttributesOp setPropertyAttributes; - ElementAttributesOp setElementAttributes; - SpecialAttributesOp setSpecialAttributes; - DeletePropertyOp deleteProperty; - DeleteElementOp deleteElement; - DeleteSpecialOp deleteSpecial; - - JSNewEnumerateOp enumerate; - ObjectOp thisObject; -}; - -#define JS_NULL_OBJECT_OPS \ - {NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, \ - NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, \ - NULL,NULL,NULL} - -struct Class -{ - JS_CLASS_MEMBERS; - ClassExtension ext; - ObjectOps ops; - uint8_t pad[sizeof(JSClass) - sizeof(ClassSizeMeasurement) - - sizeof(ClassExtension) - sizeof(ObjectOps)]; - - /* Class is not native and its map is not a scope. */ - static const uint32_t NON_NATIVE = JSCLASS_INTERNAL_FLAG2; - - bool isNative() const { - return !(flags & NON_NATIVE); - } - - bool hasPrivate() const { - return !!(flags & JSCLASS_HAS_PRIVATE); - } - - bool emulatesUndefined() const { - return flags & JSCLASS_EMULATES_UNDEFINED; - } - - bool isCallable() const { - return this == js::FunctionClassPtr || call; - } - - static size_t offsetOfFlags() { return offsetof(Class, flags); } -}; - -JS_STATIC_ASSERT(offsetof(JSClass, name) == offsetof(Class, name)); -JS_STATIC_ASSERT(offsetof(JSClass, flags) == offsetof(Class, flags)); -JS_STATIC_ASSERT(offsetof(JSClass, addProperty) == offsetof(Class, addProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, delProperty) == offsetof(Class, delProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, getProperty) == offsetof(Class, getProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, setProperty) == offsetof(Class, setProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, enumerate) == offsetof(Class, enumerate)); -JS_STATIC_ASSERT(offsetof(JSClass, resolve) == offsetof(Class, resolve)); -JS_STATIC_ASSERT(offsetof(JSClass, convert) == offsetof(Class, convert)); -JS_STATIC_ASSERT(offsetof(JSClass, finalize) == offsetof(Class, finalize)); -JS_STATIC_ASSERT(offsetof(JSClass, checkAccess) == offsetof(Class, checkAccess)); -JS_STATIC_ASSERT(offsetof(JSClass, call) == offsetof(Class, call)); -JS_STATIC_ASSERT(offsetof(JSClass, construct) == offsetof(Class, construct)); -JS_STATIC_ASSERT(offsetof(JSClass, hasInstance) == offsetof(Class, hasInstance)); -JS_STATIC_ASSERT(offsetof(JSClass, trace) == offsetof(Class, trace)); -JS_STATIC_ASSERT(sizeof(JSClass) == sizeof(Class)); - -static JS_ALWAYS_INLINE JSClass * -Jsvalify(Class *c) -{ - return (JSClass *)c; -} -static JS_ALWAYS_INLINE const JSClass * -Jsvalify(const Class *c) -{ - return (const JSClass *)c; -} - -static JS_ALWAYS_INLINE Class * -Valueify(JSClass *c) -{ - return (Class *)c; -} -static JS_ALWAYS_INLINE const Class * -Valueify(const JSClass *c) -{ - return (const Class *)c; -} - -/* - * Enumeration describing possible values of the [[Class]] internal property - * value of objects. - */ -enum ESClassValue { - ESClass_Array, ESClass_Number, ESClass_String, ESClass_Boolean, - ESClass_RegExp, ESClass_ArrayBuffer, ESClass_Date -}; - -/* - * Return whether the given object has the given [[Class]] internal property - * value. Beware, this query says nothing about the js::Class of the JSObject - * so the caller must not assume anything about obj's representation (e.g., obj - * may be a proxy). - */ -inline bool -ObjectClassIs(JSObject &obj, ESClassValue classValue, JSContext *cx); - -/* Just a helper that checks v.isObject before calling ObjectClassIs. */ -inline bool -IsObjectWithClass(const Value &v, ESClassValue classValue, JSContext *cx); - -inline bool -IsPoisonedSpecialId(js::SpecialId iden) -{ - if (iden.isObject()) - return IsPoisonedPtr(iden.toObject()); - return false; -} - -template <> struct GCMethods -{ - static SpecialId initial() { return SpecialId(); } - static ThingRootKind kind() { return THING_ROOT_ID; } - static bool poisoned(SpecialId id) { return IsPoisonedSpecialId(id); } -}; - -} /* namespace js */ - -#endif /* jsclass_h */ diff --git a/external/spidermonkey/include/android/jscpucfg.h b/external/spidermonkey/include/android/jscpucfg.h index c79bd7ad14..ccacab3482 100644 --- a/external/spidermonkey/include/android/jscpucfg.h +++ b/external/spidermonkey/include/android/jscpucfg.h @@ -14,8 +14,6 @@ # if defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_) # define IS_LITTLE_ENDIAN 1 # undef IS_BIG_ENDIAN -# define JS_BYTES_PER_WORD 8 -# define JS_BITS_PER_WORD_LOG2 6 # else /* !(defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)) */ # error "CPU type is unknown" # endif /* !(defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)) */ @@ -28,8 +26,6 @@ # define IS_LITTLE_ENDIAN 1 # undef IS_BIG_ENDIAN -# define JS_BYTES_PER_WORD 4 -# define JS_BITS_PER_WORD_LOG2 5 #elif defined(__APPLE__) # if __LITTLE_ENDIAN__ @@ -57,8 +53,8 @@ /* BSDs */ #elif defined(JS_HAVE_MACHINE_ENDIAN_H) -# include # include +# include # if defined(_BYTE_ORDER) # if _BYTE_ORDER == _LITTLE_ENDIAN diff --git a/external/spidermonkey/include/android/jsfriendapi.h b/external/spidermonkey/include/android/jsfriendapi.h index a1c3024fed..811275d332 100644 --- a/external/spidermonkey/include/android/jsfriendapi.h +++ b/external/spidermonkey/include/android/jsfriendapi.h @@ -9,11 +9,12 @@ #include "mozilla/MemoryReporting.h" -#include "jsclass.h" -#include "jsprvtd.h" +#include "jsbytecode.h" #include "jspubtd.h" #include "js/CallArgs.h" +#include "js/CallNonGenericMethod.h" +#include "js/Class.h" /* * This macro checks if the stack pointer has exceeded a given limit. If @@ -30,6 +31,12 @@ #define JS_CHECK_STACK_SIZE(limit, lval) JS_CHECK_STACK_SIZE_WITH_TOLERANCE(limit, lval, 0) +class JSAtom; +struct JSErrorFormatString; +class JSLinearString; +struct JSJitInfo; +class JSErrorReport; + namespace JS { template class Heap; @@ -47,11 +54,11 @@ JS_FindCompilationScope(JSContext *cx, JSObject *obj); extern JS_FRIEND_API(JSFunction *) JS_GetObjectFunction(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_SplicePrototype(JSContext *cx, JSObject *obj, JSObject *proto); extern JS_FRIEND_API(JSObject *) -JS_NewObjectWithUniqueType(JSContext *cx, JSClass *clasp, JSObject *proto, JSObject *parent); +JS_NewObjectWithUniqueType(JSContext *cx, const JSClass *clasp, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(uint32_t) JS_ObjectCountDynamicSlots(JS::HandleObject obj); @@ -62,7 +69,7 @@ JS_SetProtoCalled(JSContext *cx); extern JS_FRIEND_API(size_t) JS_GetCustomIteratorCount(JSContext *cx); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_NondeterministicGetWeakMapKeys(JSContext *cx, JSObject *obj, JSObject **ret); /* @@ -71,7 +78,7 @@ JS_NondeterministicGetWeakMapKeys(JSContext *cx, JSObject *obj, JSObject **ret); * Such objects hold no other objects (they have no outgoing reference edges) * and will throw if you touch them (e.g. by reading/writing a property). */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsDeadWrapper(JSObject *obj); /* @@ -112,11 +119,11 @@ JS_GetCompartmentPrincipals(JSCompartment *compartment); extern JS_FRIEND_API(void) JS_SetCompartmentPrincipals(JSCompartment *compartment, JSPrincipals *principals); -/* Safe to call with input obj == NULL. Returns non-NULL iff obj != NULL. */ +/* Safe to call with input obj == nullptr. Returns non-nullptr iff obj != nullptr. */ extern JS_FRIEND_API(JSObject *) JS_ObjectToInnerObject(JSContext *cx, JSObject *obj); -/* Requires obj != NULL. */ +/* Requires obj != nullptr. */ extern JS_FRIEND_API(JSObject *) JS_ObjectToOuterObject(JSContext *cx, JSObject *obj); @@ -126,8 +133,8 @@ JS_CloneObject(JSContext *cx, JSObject *obj, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(JSString *) JS_BasicObjectToString(JSContext *cx, JS::HandleObject obj); -extern JS_FRIEND_API(JSBool) -js_GetterOnlyPropertyStub(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JSBool strict, +extern JS_FRIEND_API(bool) +js_GetterOnlyPropertyStub(JSContext *cx, JS::HandleObject obj, JS::HandleId id, bool strict, JS::MutableHandleValue vp); JS_FRIEND_API(void) @@ -166,18 +173,32 @@ extern JS_FRIEND_API(void) js_DumpChars(const jschar *s, size_t n); #endif +/* + * Copies all own properties from |obj| to |target|. |obj| must be a "native" + * object (that is to say, normal-ish - not an Array or a Proxy). + * + * On entry, |cx| must be in the compartment of |target|. + */ extern JS_FRIEND_API(bool) JS_CopyPropertiesFrom(JSContext *cx, JSObject *target, JSObject *obj); -extern JS_FRIEND_API(JSBool) -JS_WrapPropertyDescriptor(JSContext *cx, js::PropertyDescriptor *desc); +/* + * Single-property version of the above. This function asserts that an |own| + * property of the given name exists on |obj|. + */ +extern JS_FRIEND_API(bool) +JS_CopyPropertyFrom(JSContext *cx, JS::HandleId id, JS::HandleObject target, + JS::HandleObject obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) +JS_WrapPropertyDescriptor(JSContext *cx, JS::MutableHandle desc); + +extern JS_FRIEND_API(bool) JS_WrapAutoIdVector(JSContext *cx, JS::AutoIdVector &props); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_EnumerateState(JSContext *cx, JS::HandleObject obj, JSIterateOp enum_op, - js::MutableHandleValue statep, js::MutableHandleId idp); + JS::MutableHandleValue statep, JS::MutableHandleId idp); struct JSFunctionSpecWithHelp { const char *name; @@ -191,19 +212,49 @@ struct JSFunctionSpecWithHelp { #define JS_FN_HELP(name,call,nargs,flags,usage,help) \ {name, call, nargs, (flags) | JSPROP_ENUMERATE | JSFUN_STUB_GSOPS, usage, help} #define JS_FS_HELP_END \ - {NULL, NULL, 0, 0, NULL, NULL} + {nullptr, nullptr, 0, 0, nullptr, nullptr} extern JS_FRIEND_API(bool) JS_DefineFunctionsWithHelp(JSContext *cx, JSObject *obj, const JSFunctionSpecWithHelp *fs); -typedef bool (* JS_SourceHook)(JSContext *cx, JS::Handle script, - jschar **src, uint32_t *length); - -extern JS_FRIEND_API(void) -JS_SetSourceHook(JSRuntime *rt, JS_SourceHook hook); - namespace js { +/* + * A class of objects that return source code on demand. + * + * When code is compiled with CompileOptions::LAZY_SOURCE, SpiderMonkey + * doesn't retain the source code (and doesn't do lazy bytecode + * generation). If we ever need the source code, say, in response to a call + * to Function.prototype.toSource or Debugger.Source.prototype.text, then + * we call the 'load' member function of the instance of this class that + * has hopefully been registered with the runtime, passing the code's URL, + * and hope that it will be able to find the source. + */ +class SourceHook { + public: + virtual ~SourceHook() { } + + /* + * Set |*src| and |*length| to refer to the source code for |filename|. + * On success, the caller owns the buffer to which |*src| points, and + * should use JS_free to free it. + */ + virtual bool load(JSContext *cx, const char *filename, jschar **src, size_t *length) = 0; +}; + +/* + * Have |rt| use |hook| to retrieve LAZY_SOURCE source code. See the + * comments for SourceHook. The runtime takes ownership of the hook, and + * will delete it when the runtime itself is deleted, or when a new hook is + * set. + */ +extern JS_FRIEND_API(void) +SetSourceHook(JSRuntime *rt, SourceHook *hook); + +/* Remove |rt|'s source hook, and return it. The caller now owns the hook. */ +extern JS_FRIEND_API(SourceHook *) +ForgetSourceHook(JSRuntime *rt); + inline JSRuntime * GetRuntime(const JSContext *cx) { @@ -228,16 +279,21 @@ GetCompartmentZone(JSCompartment *comp); typedef bool (* PreserveWrapperCallback)(JSContext *cx, JSObject *obj); +typedef enum { + CollectNurseryBeforeDump, + IgnoreNurseryObjects +} DumpHeapNurseryBehaviour; + /* * Dump the complete object graph of heap-allocated things. * fp is the file for the dump output. */ extern JS_FRIEND_API(void) -DumpHeapComplete(JSRuntime *rt, FILE *fp); +DumpHeapComplete(JSRuntime *rt, FILE *fp, DumpHeapNurseryBehaviour nurseryBehaviour); -#ifdef OLD_GETTER_SETTER_METHODS -JS_FRIEND_API(JSBool) obj_defineGetter(JSContext *cx, unsigned argc, js::Value *vp); -JS_FRIEND_API(JSBool) obj_defineSetter(JSContext *cx, unsigned argc, js::Value *vp); +#ifdef JS_OLD_GETTER_SETTER_METHODS +JS_FRIEND_API(bool) obj_defineGetter(JSContext *cx, unsigned argc, JS::Value *vp); +JS_FRIEND_API(bool) obj_defineSetter(JSContext *cx, unsigned argc, JS::Value *vp); #endif extern JS_FRIEND_API(bool) @@ -257,7 +313,7 @@ IsAtomsCompartment(JSCompartment *comp); * particularly, always reports when it returns false). */ extern JS_FRIEND_API(bool) -ReportIfUndeclaredVarAssignment(JSContext *cx, HandleString propname); +ReportIfUndeclaredVarAssignment(JSContext *cx, JS::HandleString propname); /* * Returns whether we're in a non-strict property set (in that we're in a @@ -274,7 +330,7 @@ struct WeakMapTracer; * Weak map tracer callback, called once for every binding of every * weak map that was live at the time of the last garbage collection. * - * m will be NULL if the weak map is not contained in a JS Object. + * m will be nullptr if the weak map is not contained in a JS Object. */ typedef void (* WeakMapTraceCallback)(WeakMapTracer *trc, JSObject *m, @@ -330,12 +386,12 @@ GetAnyCompartmentInZone(JS::Zone *zone); namespace shadow { struct TypeObject { - Class *clasp; + const Class *clasp; JSObject *proto; }; struct BaseShape { - js::Class *clasp; + const js::Class *clasp; JSObject *parent; JSObject *_1; JSCompartment *compartment; @@ -353,15 +409,15 @@ public: struct Object { shadow::Shape *shape; shadow::TypeObject *type; - js::Value *slots; - js::Value *_1; + JS::Value *slots; + JS::Value *_1; size_t numFixedSlots() const { return shape->slotInfo >> Shape::FIXED_SLOTS_SHIFT; } - Value *fixedSlots() const { - return (Value *)(uintptr_t(this) + sizeof(shadow::Object)); + JS::Value *fixedSlots() const { + return (JS::Value *)(uintptr_t(this) + sizeof(shadow::Object)); } - js::Value &slotRef(size_t slot) const { + JS::Value &slotRef(size_t slot) const { size_t nfixed = numFixedSlots(); if (slot < nfixed) return fixedSlots()[slot]; @@ -374,7 +430,7 @@ struct Function { uint16_t nargs; uint16_t flags; /* Used only for natives */ - Native native; + JSNative native; const JSJitInfo *jitinfo; void *_1; }; @@ -387,23 +443,17 @@ struct Atom { } /* namespace shadow */ -// These are equal to |&{Function,Object,OuterWindow}ProxyObject::class_|. Use -// them in places where you don't want to #include vm/ProxyObject.h. -extern JS_FRIEND_DATA(js::Class* const) FunctionProxyClassPtr; -extern JS_FRIEND_DATA(js::Class* const) ObjectProxyClassPtr; -extern JS_FRIEND_DATA(js::Class* const) OuterWindowProxyClassPtr; - // This is equal to |&JSObject::class_|. Use it in places where you don't want // to #include jsobj.h. -extern JS_FRIEND_DATA(js::Class* const) ObjectClassPtr; +extern JS_FRIEND_DATA(const js::Class* const) ObjectClassPtr; -inline js::Class * +inline const js::Class * GetObjectClass(JSObject *obj) { return reinterpret_cast(obj)->type->clasp; } -inline JSClass * +inline const JSClass * GetObjectJSClass(JSObject *obj) { return js::Jsvalify(GetObjectClass(obj)); @@ -447,6 +497,16 @@ GetObjectParentMaybeScope(JSObject *obj); JS_FRIEND_API(JSObject *) GetGlobalForObjectCrossCompartment(JSObject *obj); +JS_FRIEND_API(void) +AssertSameCompartment(JSContext *cx, JSObject *obj); + +#ifdef DEBUG +JS_FRIEND_API(void) +AssertSameCompartment(JSObject *objA, JSObject *objB); +#else +inline void AssertSameCompartment(JSObject *objA, JSObject *objB) {} +#endif + // For legacy consumers only. This whole concept is going away soon. JS_FRIEND_API(JSObject *) DefaultObjectForContextOrNull(JSContext *cx); @@ -462,7 +522,7 @@ IsOriginalScriptFunction(JSFunction *fun); /* * Return the outermost enclosing function (script) of the scripted caller. - * This function returns NULL in several cases: + * This function returns nullptr in several cases: * - no script is running on the context * - the caller is in global or eval code * In particular, this function will "stop" its outermost search at eval() and @@ -486,30 +546,18 @@ NewFunctionByIdWithReserved(JSContext *cx, JSNative native, unsigned nargs, unsi JS_FRIEND_API(JSObject *) InitClassWithReserved(JSContext *cx, JSObject *obj, JSObject *parent_proto, - JSClass *clasp, JSNative constructor, unsigned nargs, + const JSClass *clasp, JSNative constructor, unsigned nargs, const JSPropertySpec *ps, const JSFunctionSpec *fs, const JSPropertySpec *static_ps, const JSFunctionSpec *static_fs); -JS_FRIEND_API(const Value &) +JS_FRIEND_API(const JS::Value &) GetFunctionNativeReserved(JSObject *fun, size_t which); JS_FRIEND_API(void) -SetFunctionNativeReserved(JSObject *fun, size_t which, const Value &val); +SetFunctionNativeReserved(JSObject *fun, size_t which, const JS::Value &val); -inline bool -GetObjectProto(JSContext *cx, JS::Handle obj, JS::MutableHandle proto) -{ - js::Class *clasp = GetObjectClass(obj); - if (clasp == js::ObjectProxyClassPtr || - clasp == js::OuterWindowProxyClassPtr || - clasp == js::FunctionProxyClassPtr) - { - return JS_GetPrototype(cx, obj, proto); - } - - proto.set(reinterpret_cast(obj.get())->type->proto); - return true; -} +JS_FRIEND_API(bool) +GetObjectProto(JSContext *cx, JS::Handle obj, JS::MutableHandle proto); inline void * GetObjectPrivate(JSObject *obj) @@ -523,7 +571,7 @@ GetObjectPrivate(JSObject *obj) * Get a slot that is both reserved for object's clasp *and* is fixed (fits * within the maximum capacity for the object's fixed slots). */ -inline const Value & +inline const JS::Value & GetReservedSlot(JSObject *obj, size_t slot) { JS_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); @@ -531,10 +579,10 @@ GetReservedSlot(JSObject *obj, size_t slot) } JS_FRIEND_API(void) -SetReservedSlotWithBarrier(JSObject *obj, size_t slot, const Value &value); +SetReservedSlotWithBarrier(JSObject *obj, size_t slot, const JS::Value &value); inline void -SetReservedSlot(JSObject *obj, size_t slot, const Value &value) +SetReservedSlot(JSObject *obj, size_t slot, const JS::Value &value) { JS_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); shadow::Object *sobj = reinterpret_cast(obj); @@ -553,7 +601,7 @@ SetReservedSlot(JSObject *obj, size_t slot, const Value &value) JS_FRIEND_API(uint32_t) GetObjectSlotSpan(JSObject *obj); -inline const Value & +inline const JS::Value & GetObjectSlot(JSObject *obj, size_t slot) { JS_ASSERT(slot < GetObjectSlotSpan(obj)); @@ -579,26 +627,14 @@ AtomToLinearString(JSAtom *atom) return reinterpret_cast(atom); } -static inline js::PropertyOp -CastAsJSPropertyOp(JSObject *object) -{ - return JS_DATA_TO_FUNC_PTR(js::PropertyOp, object); -} - -static inline js::StrictPropertyOp -CastAsJSStrictPropertyOp(JSObject *object) -{ - return JS_DATA_TO_FUNC_PTR(js::StrictPropertyOp, object); -} +JS_FRIEND_API(bool) +GetPropertyNames(JSContext *cx, JSObject *obj, unsigned flags, JS::AutoIdVector *props); JS_FRIEND_API(bool) -GetPropertyNames(JSContext *cx, JSObject *obj, unsigned flags, js::AutoIdVector *props); +AppendUnique(JSContext *cx, JS::AutoIdVector &base, JS::AutoIdVector &others); JS_FRIEND_API(bool) -AppendUnique(JSContext *cx, AutoIdVector &base, AutoIdVector &others); - -JS_FRIEND_API(bool) -GetGeneric(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id, Value *vp); +GetGeneric(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id, JS::Value *vp); JS_FRIEND_API(bool) StringIsArrayIndex(JSLinearString *str, uint32_t *indexp); @@ -609,6 +645,14 @@ SetPreserveWrapperCallback(JSRuntime *rt, PreserveWrapperCallback callback); JS_FRIEND_API(bool) IsObjectInContextCompartment(JSObject *obj, const JSContext *cx); +/* + * ErrorFromException takes a raw Value so that it's possible to call it during + * GC/CC/whatever, when it may not be possible to get a JSContext to create a + * Rooted. It promises to never ever GC. + */ +JS_FRIEND_API(JSErrorReport*) +ErrorFromException(JS::Value val); + /* * NB: these flag bits are encoded into the bytecode stream in the immediate * operand of JSOP_ITER, so don't change them without advancing vm/Xdr.h's @@ -619,18 +663,18 @@ IsObjectInContextCompartment(JSObject *obj, const JSContext *cx); #define JSITER_KEYVALUE 0x4 /* destructuring for-in wants [key, value] */ #define JSITER_OWNONLY 0x8 /* iterate over obj's own properties only */ #define JSITER_HIDDEN 0x10 /* also enumerate non-enumerable properties */ -#define JSITER_FOR_OF 0x20 /* harmony for-of loop */ -inline uintptr_t -GetNativeStackLimit(const JSRuntime *rt) -{ - return PerThreadDataFriendFields::getMainThread(rt)->nativeStackLimit; -} +JS_FRIEND_API(bool) +RunningWithTrustedPrincipals(JSContext *cx); inline uintptr_t GetNativeStackLimit(JSContext *cx) { - return GetNativeStackLimit(GetRuntime(cx)); + StackKind kind = RunningWithTrustedPrincipals(cx) ? StackForTrustedScript + : StackForUntrustedScript; + PerThreadDataFriendFields *mainThread = + PerThreadDataFriendFields::getMainThread(GetRuntime(cx)); + return mainThread->nativeStackLimit[kind]; } /* @@ -655,6 +699,14 @@ GetNativeStackLimit(JSContext *cx) } \ JS_END_MACRO +#define JS_CHECK_RECURSION_WITH_SP(cx, sp, onerror) \ + JS_BEGIN_MACRO \ + if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ + js_ReportOverRecursed(cx); \ + onerror; \ + } \ + JS_END_MACRO + #define JS_CHECK_CHROME_RECURSION(cx, onerror) \ JS_BEGIN_MACRO \ int stackDummy_; \ @@ -685,94 +737,13 @@ GetPCCountScriptSummary(JSContext *cx, size_t script); JS_FRIEND_API(JSString *) GetPCCountScriptContents(JSContext *cx, size_t script); -/* - * A call stack can be specified to the JS engine such that all JS entry/exits - * to functions push/pop an entry to/from the specified stack. - * - * For more detailed information, see vm/SPSProfiler.h - */ -class ProfileEntry -{ - /* - * All fields are marked volatile to prevent the compiler from re-ordering - * instructions. Namely this sequence: - * - * entry[size] = ...; - * size++; - * - * If the size modification were somehow reordered before the stores, then - * if a sample were taken it would be examining bogus information. - * - * A ProfileEntry represents both a C++ profile entry and a JS one. Both use - * the string as a description, but JS uses the sp as NULL to indicate that - * it is a JS entry. The script_ is then only ever examined for a JS entry, - * and the idx is used by both, but with different meanings. - */ - const char * volatile string; // Descriptive string of this entry - void * volatile sp; // Relevant stack pointer for the entry - JSScript * volatile script_; // if js(), non-null script which is running - int32_t volatile idx; // if js(), idx of pc, otherwise line number - - public: - /* - * All of these methods are marked with the 'volatile' keyword because SPS's - * representation of the stack is stored such that all ProfileEntry - * instances are volatile. These methods would not be available unless they - * were marked as volatile as well - */ - - bool js() volatile { - JS_ASSERT_IF(sp == NULL, script_ != NULL); - return sp == NULL; - } - - uint32_t line() volatile { JS_ASSERT(!js()); return idx; } - JSScript *script() volatile { JS_ASSERT(js()); return script_; } - void *stackAddress() volatile { return sp; } - const char *label() volatile { return string; } - - void setLine(uint32_t aLine) volatile { JS_ASSERT(!js()); idx = aLine; } - void setLabel(const char *aString) volatile { string = aString; } - void setStackAddress(void *aSp) volatile { sp = aSp; } - void setScript(JSScript *aScript) volatile { script_ = aScript; } - - /* we can't know the layout of JSScript, so look in vm/SPSProfiler.cpp */ - JS_FRIEND_API(jsbytecode *) pc() volatile; - JS_FRIEND_API(void) setPC(jsbytecode *pc) volatile; - - static size_t offsetOfString() { return offsetof(ProfileEntry, string); } - static size_t offsetOfStackAddress() { return offsetof(ProfileEntry, sp); } - static size_t offsetOfPCIdx() { return offsetof(ProfileEntry, idx); } - static size_t offsetOfScript() { return offsetof(ProfileEntry, script_); } - - /* - * The index used in the entry can either be a line number or the offset of - * a pc into a script's code. To signify a NULL pc, use a -1 index. This is - * checked against in pc() and setPC() to set/get the right pc. - */ - static const int32_t NullPCIndex = -1; -}; - -JS_FRIEND_API(void) -SetRuntimeProfilingStack(JSRuntime *rt, ProfileEntry *stack, uint32_t *size, - uint32_t max); - -JS_FRIEND_API(void) -EnableRuntimeProfilingStack(JSRuntime *rt, bool enabled); - -JS_FRIEND_API(jsbytecode*) -ProfilingGetPC(JSRuntime *rt, JSScript *script, void *ip); - #ifdef JS_THREADSAFE JS_FRIEND_API(bool) ContextHasOutstandingRequests(const JSContext *cx); #endif -JS_FRIEND_API(bool) -HasUnrootedGlobal(const JSContext *cx); - typedef void -(* ActivityCallback)(void *arg, JSBool active); +(* ActivityCallback)(void *arg, bool active); /* * Sets a callback that is run whenever the runtime goes idle - the @@ -785,22 +756,10 @@ SetActivityCallback(JSRuntime *rt, ActivityCallback cb, void *arg); extern JS_FRIEND_API(const JSStructuredCloneCallbacks *) GetContextStructuredCloneCallbacks(JSContext *cx); -extern JS_FRIEND_API(bool) -CanCallContextDebugHandler(JSContext *cx); - -extern JS_FRIEND_API(JSTrapStatus) -CallContextDebugHandler(JSContext *cx, JSScript *script, jsbytecode *bc, Value *rval); - extern JS_FRIEND_API(bool) IsContextRunningJS(JSContext *cx); -typedef void -(* AnalysisPurgeCallback)(JSRuntime *rt, JS::Handle desc); - -extern JS_FRIEND_API(AnalysisPurgeCallback) -SetAnalysisPurgeCallback(JSRuntime *rt, AnalysisPurgeCallback callback); - -typedef JSBool +typedef bool (* DOMInstanceClassMatchesProto)(JS::HandleObject protoObject, uint32_t protoID, uint32_t depth); struct JSDOMCallbacks { @@ -832,10 +791,10 @@ CastToJSFreeOp(FreeOp *fop) /* * Get an error type name from a JSExnType constant. - * Returns NULL for invalid arguments and JSEXN_INTERNALERR + * Returns nullptr for invalid arguments and JSEXN_INTERNALERR */ extern JS_FRIEND_API(const jschar*) -GetErrorTypeName(JSContext* cx, int16_t exnType); +GetErrorTypeName(JSRuntime* rt, int16_t exnType); #ifdef DEBUG extern JS_FRIEND_API(unsigned) @@ -886,7 +845,7 @@ struct CompartmentsWithPrincipals : public CompartmentFilter { } }; -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) NukeCrossCompartmentWrappers(JSContext* cx, const CompartmentFilter& sourceFilter, const CompartmentFilter& targetFilter, @@ -910,7 +869,7 @@ NukeCrossCompartmentWrappers(JSContext* cx, struct ExpandoAndGeneration { ExpandoAndGeneration() - : expando(UndefinedValue()), + : expando(JS::UndefinedValue()), generation(0) {} @@ -933,10 +892,10 @@ typedef enum DOMProxyShadowsResult { typedef DOMProxyShadowsResult (* DOMProxyShadowsCheck)(JSContext* cx, JS::HandleObject object, JS::HandleId id); JS_FRIEND_API(void) -SetDOMProxyInformation(void *domProxyHandlerFamily, uint32_t domProxyExpandoSlot, +SetDOMProxyInformation(const void *domProxyHandlerFamily, uint32_t domProxyExpandoSlot, DOMProxyShadowsCheck domProxyShadowsCheck); -void *GetDOMProxyHandlerFamily(); +const void *GetDOMProxyHandlerFamily(); uint32_t GetDOMProxyExpandoSlot(); DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); @@ -948,7 +907,7 @@ DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); * Detect whether the internal date value is NaN. (Because failure is * out-of-band for js_DateGet*) */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_DateIsValid(JSObject* obj); extern JS_FRIEND_API(double) @@ -1008,136 +967,6 @@ enum ViewType { } /* namespace ArrayBufferView */ -/* - * A helper for building up an ArrayBuffer object's data - * before creating the ArrayBuffer itself. Will do doubling - * based reallocation, up to an optional maximum growth given. - * - * When all the data has been appended, call getArrayBuffer, - * passing in the JSContext* for which the ArrayBuffer object - * is to be created. This also implicitly resets the builder, - * or it can be reset explicitly at any point by calling reset(). - */ -class ArrayBufferBuilder -{ - void *rawcontents_; - uint8_t *dataptr_; - uint32_t capacity_; - uint32_t length_; - public: - ArrayBufferBuilder() - : rawcontents_(NULL), - dataptr_(NULL), - capacity_(0), - length_(0) - { - } - - ~ArrayBufferBuilder() { - reset(); - } - - void reset() { - if (rawcontents_) - JS_free(NULL, rawcontents_); - rawcontents_ = dataptr_ = NULL; - capacity_ = length_ = 0; - } - - // will truncate if newcap is < length() - bool setCapacity(uint32_t newcap) { - if (!JS_ReallocateArrayBufferContents(NULL, newcap, &rawcontents_, &dataptr_)) - return false; - - capacity_ = newcap; - if (length_ > newcap) - length_ = newcap; - - return true; - } - - // Append datalen bytes from data to the current buffer. If we - // need to grow the buffer, grow by doubling the size up to a - // maximum of maxgrowth (if given). If datalen is greater than - // what the new capacity would end up as, then grow by datalen. - // - // The data parameter must not overlap with anything beyond the - // builder's current valid contents [0..length) - bool append(const uint8_t *newdata, uint32_t datalen, uint32_t maxgrowth = 0) { - if (length_ + datalen > capacity_) { - uint32_t newcap; - // double while under maxgrowth or if not specified - if (!maxgrowth || capacity_ < maxgrowth) - newcap = capacity_ * 2; - else - newcap = capacity_ + maxgrowth; - - // but make sure there's always enough to satisfy our request - if (newcap < length_ + datalen) - newcap = length_ + datalen; - - // did we overflow? - if (newcap < capacity_) - return false; - - if (!setCapacity(newcap)) - return false; - } - - // assert that the region isn't overlapping so we can memcpy; - JS_ASSERT(!areOverlappingRegions(newdata, datalen, dataptr_ + length_, datalen)); - - memcpy(dataptr_ + length_, newdata, datalen); - length_ += datalen; - - return true; - } - - uint8_t *data() { - return dataptr_; - } - - uint32_t length() { - return length_; - } - - uint32_t capacity() { - return capacity_; - } - - JSObject* getArrayBuffer(JSContext *cx) { - // we need to check for length_ == 0, because nothing may have been - // added - if (capacity_ > length_ || length_ == 0) { - if (!setCapacity(length_)) - return NULL; - } - - JSObject* obj = JS_NewArrayBufferWithContents(cx, rawcontents_); - if (!obj) - return NULL; - - rawcontents_ = dataptr_ = NULL; - length_ = capacity_ = 0; - - return obj; - } - -protected: - - static bool areOverlappingRegions(const uint8_t *start1, uint32_t length1, - const uint8_t *start2, uint32_t length2) - { - const uint8_t *end1 = start1 + length1; - const uint8_t *end2 = start2 + length2; - - const uint8_t *max_start = start1 > start2 ? start1 : start2; - const uint8_t *min_end = end1 < end2 ? end1 : end2; - - return max_start < min_end; - } -}; - } /* namespace js */ typedef js::ArrayBufferView::ViewType JSArrayBufferViewType; @@ -1241,7 +1070,7 @@ JS_NewArrayBuffer(JSContext *cx, uint32_t nbytes); * this test or one of the JS_Is*Array tests succeeds, then it is safe to call * the various accessor JSAPI calls defined below. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsTypedArrayObject(JSObject *obj); /* @@ -1251,36 +1080,36 @@ JS_IsTypedArrayObject(JSObject *obj); * is safe to call the various ArrayBufferView accessor JSAPI calls defined * below. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsArrayBufferViewObject(JSObject *obj); /* * Test for specific typed array types (ArrayBufferView subtypes) */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsInt8Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint8Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint8ClampedArray(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsInt16Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint16Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsInt32Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint32Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsFloat32Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsFloat64Array(JSObject *obj); /* - * Unwrap Typed arrays all at once. Return NULL without throwing if the object - * cannot be viewed as the correct typed array, or the typed array object on - * success, filling both outparameters. + * Unwrap Typed arrays all at once. Return nullptr without throwing if the + * object cannot be viewed as the correct typed array, or the typed array + * object on success, filling both outparameters. */ extern JS_FRIEND_API(JSObject *) JS_GetObjectAsInt8Array(JSObject *obj, uint32_t *length, int8_t **data); @@ -1321,7 +1150,7 @@ JS_GetArrayBufferViewType(JSObject *obj); * unwrapping. If this test succeeds, then it is safe to call the various * accessor JSAPI calls defined below. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsArrayBufferObject(JSObject *obj); /* @@ -1382,7 +1211,7 @@ JS_GetTypedArrayByteLength(JSObject *obj); * return false if a security wrapper is encountered that denies the * unwrapping. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsArrayBufferViewObject(JSObject *obj); /* @@ -1435,10 +1264,16 @@ JS_GetArrayBufferViewData(JSObject *obj); extern JS_FRIEND_API(JSObject *) JS_GetArrayBufferViewBuffer(JSObject *obj); +/* + * Set an ArrayBuffer's length to 0 and neuter all of its views. + */ +extern JS_FRIEND_API(void) +JS_NeuterArrayBuffer(JSObject *obj, JSContext *cx); + /* * Check whether obj supports JS_GetDataView* APIs. */ -JS_FRIEND_API(JSBool) +JS_FRIEND_API(bool) JS_IsDataViewObject(JSObject *obj); /* @@ -1457,7 +1292,7 @@ JS_GetDataViewByteOffset(JSObject *obj); * * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is NULL, then DEBUG builds may be + * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be * unable to assert when unwrapping should be disallowed. */ JS_FRIEND_API(uint32_t) @@ -1468,12 +1303,39 @@ JS_GetDataViewByteLength(JSObject *obj); * * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is NULL, then DEBUG builds may be + * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be * unable to assert when unwrapping should be disallowed. */ JS_FRIEND_API(void *) JS_GetDataViewData(JSObject *obj); +namespace js { + +/* + * Add a watchpoint -- in the Object.prototype.watch sense -- to |obj| for the + * property |id|, using the callable object |callable| as the function to be + * called for notifications. + * + * This is an internal function exposed -- temporarily -- only so that DOM + * proxies can be watchable. Don't use it! We'll soon kill off the + * Object.prototype.{,un}watch functions, at which point this will go too. + */ +extern JS_FRIEND_API(bool) +WatchGuts(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); + +/* + * Remove a watchpoint -- in the Object.prototype.watch sense -- from |obj| for + * the property |id|. + * + * This is an internal function exposed -- temporarily -- only so that DOM + * proxies can be watchable. Don't use it! We'll soon kill off the + * Object.prototype.{,un}watch functions, at which point this will go too. + */ +extern JS_FRIEND_API(bool) +UnwatchGuts(JSContext *cx, JS::HandleObject obj, JS::HandleId id); + +} // namespace js + /* * A class, expected to be passed by value, which represents the CallArgs for a * JSJitGetterOp. @@ -1599,7 +1461,7 @@ struct JSJitInfo { }; #define JS_JITINFO_NATIVE_PARALLEL(op) \ - {{NULL},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} + {{nullptr},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} static JS_ALWAYS_INLINE const JSJitInfo * FUNCTION_VALUE_TO_JITINFO(const JS::Value& v) @@ -1632,6 +1494,12 @@ JSID_FROM_BITS(size_t bits) return id; } +namespace js { +namespace detail { +bool IdMatchesAtom(jsid id, JSAtom *atom); +} +} + /* * Must not be used on atoms that are representable as integer jsids. * Prefer NameToId or AtomToId over this function: @@ -1658,18 +1526,18 @@ NON_INTEGER_ATOM_TO_JSID(JSAtom *atom) { JS_ASSERT(((size_t)atom & 0x7) == 0); jsid id = JSID_FROM_BITS((size_t)atom); - JS_ASSERT(id == INTERNED_STRING_TO_JSID(NULL, (JSString*)atom)); + JS_ASSERT(js::detail::IdMatchesAtom(id, atom)); return id; } /* All strings stored in jsids are atomized, but are not necessarily property names. */ -static JS_ALWAYS_INLINE JSBool +static JS_ALWAYS_INLINE bool JSID_IS_ATOM(jsid id) { return JSID_IS_STRING(id); } -static JS_ALWAYS_INLINE JSBool +static JS_ALWAYS_INLINE bool JSID_IS_ATOM(jsid id, JSAtom *atom) { return id == JSID_FROM_BITS((size_t)atom); @@ -1681,21 +1549,21 @@ JSID_TO_ATOM(jsid id) return (JSAtom *)JSID_TO_STRING(id); } -JS_STATIC_ASSERT(sizeof(jsid) == JS_BYTES_PER_WORD); +JS_STATIC_ASSERT(sizeof(jsid) == sizeof(void*)); namespace js { -static JS_ALWAYS_INLINE Value +static JS_ALWAYS_INLINE JS::Value IdToValue(jsid id) { if (JSID_IS_STRING(id)) - return StringValue(JSID_TO_STRING(id)); + return JS::StringValue(JSID_TO_STRING(id)); if (JS_LIKELY(JSID_IS_INT(id))) - return Int32Value(JSID_TO_INT(id)); + return JS::Int32Value(JSID_TO_INT(id)); if (JS_LIKELY(JSID_IS_OBJECT(id))) - return ObjectValue(*JSID_TO_OBJECT(id)); + return JS::ObjectValue(*JSID_TO_OBJECT(id)); JS_ASSERT(JSID_IS_VOID(id)); - return UndefinedValue(); + return JS::UndefinedValue(); } static JS_ALWAYS_INLINE jsval @@ -1710,6 +1578,20 @@ IsReadOnlyDateMethod(JS::IsAcceptableThis test, JS::NativeImpl method); extern JS_FRIEND_API(bool) IsTypedArrayThisCheck(JS::IsAcceptableThis test); +/* + * If the embedder has registered a default JSContext callback, returns the + * result of the callback. Otherwise, asserts that |rt| has exactly one + * JSContext associated with it, and returns that context. + */ +extern JS_FRIEND_API(JSContext *) +DefaultJSContext(JSRuntime *rt); + +typedef JSContext* +(* DefaultJSContextCallback)(JSRuntime *rt); + +JS_FRIEND_API(void) +SetDefaultJSContextCallback(JSRuntime *rt, DefaultJSContextCallback cb); + enum CTypesActivityType { CTYPES_CALL_BEGIN, CTYPES_CALL_END, @@ -1744,7 +1626,7 @@ class JS_FRIEND_API(AutoCTypesActivityCallback) { void DoEndCallback() { if (callback) { callback(cx, endType); - callback = NULL; + callback = nullptr; } } }; @@ -1777,8 +1659,8 @@ JS_FRIEND_API(JSObject *) GetObjectMetadata(JSObject *obj); /* ES5 8.12.8. */ -extern JS_FRIEND_API(JSBool) -DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, MutableHandleValue vp); +extern JS_FRIEND_API(bool) +DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, JS::MutableHandleValue vp); /* * Helper function. To approximate a call to the [[DefineOwnProperty]] internal @@ -1794,16 +1676,16 @@ DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, MutableHandleValu * js::ProxyHandler, or the JSAPI with precisely the right semantics for it. */ extern JS_FRIEND_API(bool) -CheckDefineProperty(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); +CheckDefineProperty(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue value, + JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs); } /* namespace js */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_DefineOwnProperty(JSContext *cx, JSObject *objArg, jsid idArg, - const js::PropertyDescriptor& descriptor, JSBool *bp); + JS::Handle descriptor, bool *bp); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_ReportIsNotFunction(JSContext *cx, const JS::Value& v); #ifdef JSGC_GENERATIONAL diff --git a/external/spidermonkey/include/android/jslock.h b/external/spidermonkey/include/android/jslock.h deleted file mode 100644 index 522034ad68..0000000000 --- a/external/spidermonkey/include/android/jslock.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -#ifndef jslock_h -#define jslock_h - -#ifdef JS_THREADSAFE - -# include "jsapi.h" -# include "pratom.h" -# include "prcvar.h" -# include "prinit.h" -# include "prlock.h" -# include "prthread.h" - -# define JS_ATOMIC_INCREMENT(p) PR_ATOMIC_INCREMENT((int32_t *)(p)) -# define JS_ATOMIC_DECREMENT(p) PR_ATOMIC_DECREMENT((int32_t *)(p)) -# define JS_ATOMIC_ADD(p,v) PR_ATOMIC_ADD((int32_t *)(p), (int32_t)(v)) -# define JS_ATOMIC_SET(p,v) PR_ATOMIC_SET((int32_t *)(p), (int32_t)(v)) - -namespace js { - // Defined in jsgc.cpp. - unsigned GetCPUCount(); -} - -#else /* JS_THREADSAFE */ - -typedef struct PRThread PRThread; -typedef struct PRCondVar PRCondVar; -typedef struct PRLock PRLock; - -# define JS_ATOMIC_INCREMENT(p) (++*(p)) -# define JS_ATOMIC_DECREMENT(p) (--*(p)) -# define JS_ATOMIC_ADD(p,v) (*(p) += (v)) -# define JS_ATOMIC_SET(p,v) (*(p) = (v)) - -#endif /* JS_THREADSAFE */ - -#endif /* jslock_h */ diff --git a/external/spidermonkey/include/android/jsperf.h b/external/spidermonkey/include/android/jsperf.h index 468ce8609c..e3cbc23143 100644 --- a/external/spidermonkey/include/android/jsperf.h +++ b/external/spidermonkey/include/android/jsperf.h @@ -6,7 +6,10 @@ #ifndef perf_jsperf_h #define perf_jsperf_h -#include "jsapi.h" +#include "jstypes.h" + +#include "js/TypeDecls.h" +#include "js/Utility.h" namespace JS { @@ -118,12 +121,12 @@ extern JS_FRIEND_API(JSObject*) RegisterPerfMeasurement(JSContext *cx, JSObject *global); /* - * Given a jsval which contains an instance of the aforementioned - * wrapper class, extract the C++ object. Returns NULL if the - * jsval is not an instance of the wrapper. + * Given a Value which contains an instance of the aforementioned + * wrapper class, extract the C++ object. Returns nullptr if the + * Value is not an instance of the wrapper. */ extern JS_FRIEND_API(PerfMeasurement*) - ExtractPerfMeasurement(jsval wrapper); + ExtractPerfMeasurement(Value wrapper); } // namespace JS diff --git a/external/spidermonkey/include/android/jsprf.h b/external/spidermonkey/include/android/jsprf.h index ce159d8115..b235f0b4fb 100644 --- a/external/spidermonkey/include/android/jsprf.h +++ b/external/spidermonkey/include/android/jsprf.h @@ -26,7 +26,6 @@ */ #include -#include #include "jstypes.h" @@ -39,7 +38,7 @@ extern JS_PUBLIC_API(uint32_t) JS_snprintf(char *out, uint32_t outlen, const cha /* ** sprintf into a malloc'd buffer. Return a pointer to the malloc'd -** buffer on success, NULL on failure. Call "JS_smprintf_free" to release +** buffer on success, nullptr on failure. Call "JS_smprintf_free" to release ** the memory returned. */ extern JS_PUBLIC_API(char*) JS_smprintf(const char *fmt, ...); @@ -52,9 +51,9 @@ extern JS_PUBLIC_API(void) JS_smprintf_free(char *mem); /* ** "append" sprintf into a malloc'd buffer. "last" is the last value of ** the malloc'd buffer. sprintf will append data to the end of last, -** growing it as necessary using realloc. If last is NULL, JS_sprintf_append +** growing it as necessary using realloc. If last is nullptr, JS_sprintf_append ** will allocate the initial string. The return value is the new value of -** last for subsequent calls, or NULL if there is a malloc failure. +** last for subsequent calls, or nullptr if there is a malloc failure. */ extern JS_PUBLIC_API(char*) JS_sprintf_append(char *last, const char *fmt, ...); diff --git a/external/spidermonkey/include/android/jsprototypes.h b/external/spidermonkey/include/android/jsprototypes.h index f9bacac409..b0fee8c468 100644 --- a/external/spidermonkey/include/android/jsprototypes.h +++ b/external/spidermonkey/include/android/jsprototypes.h @@ -9,8 +9,6 @@ #ifndef jsprototypes_h #define jsprototypes_h -#include "jsversion.h" - /* * Enumerator codes in the second column must not change -- they are part of * the JS XDR API. Also note the symbols in the third column are extern "C"; @@ -56,20 +54,7 @@ macro(DataView, 35, js_InitTypedArrayClasses) \ macro(ParallelArray, 36, js_InitParallelArrayClass) \ macro(Intl, 37, js_InitIntlClass) \ - macro(Type, 38, js_InitBinaryDataClasses) \ - macro(Data, 39, js_InitBinaryDataClasses) \ - macro(uint8, 40, js_InitBinaryDataClasses) \ - macro(uint16, 41, js_InitBinaryDataClasses) \ - macro(uint32, 42, js_InitBinaryDataClasses) \ - macro(uint64, 43, js_InitBinaryDataClasses) \ - macro(int8, 44, js_InitBinaryDataClasses) \ - macro(int16, 45, js_InitBinaryDataClasses) \ - macro(int32, 46, js_InitBinaryDataClasses) \ - macro(int64, 47, js_InitBinaryDataClasses) \ - macro(float32, 48, js_InitBinaryDataClasses) \ - macro(float64, 49, js_InitBinaryDataClasses) \ - macro(ArrayType, 50, js_InitBinaryDataClasses) \ - macro(StructType, 51, js_InitBinaryDataClasses) \ - macro(ArrayTypeObject, 52, js_InitBinaryDataClasses) \ + macro(TypedObject, 38, js_InitTypedObjectDummy) \ + macro(GeneratorFunction, 39, js_InitIteratorClasses) \ #endif /* jsprototypes_h */ diff --git a/external/spidermonkey/include/android/jsproxy.h b/external/spidermonkey/include/android/jsproxy.h index 56868a05c3..c54e300d73 100644 --- a/external/spidermonkey/include/android/jsproxy.h +++ b/external/spidermonkey/include/android/jsproxy.h @@ -7,11 +7,29 @@ #ifndef jsproxy_h #define jsproxy_h -#include "jsapi.h" +#include "mozilla/Maybe.h" + #include "jsfriendapi.h" +#include "js/CallNonGenericMethod.h" +#include "js/Class.h" + namespace js { +using JS::AutoIdVector; +using JS::CallArgs; +using JS::HandleId; +using JS::HandleObject; +using JS::HandleValue; +using JS::IsAcceptableThis; +using JS::MutableHandle; +using JS::MutableHandleObject; +using JS::MutableHandleValue; +using JS::NativeImpl; +using JS::PrivateValue; +using JS::Value; + +class RegExpGuard; class JS_FRIEND_API(Wrapper); /* @@ -49,7 +67,7 @@ class JS_FRIEND_API(Wrapper); */ class JS_FRIEND_API(BaseProxyHandler) { - void *mFamily; + const void *mFamily; bool mHasPrototype; bool mHasPolicy; protected: @@ -58,7 +76,7 @@ class JS_FRIEND_API(BaseProxyHandler) void setHasPolicy(bool aHasPolicy) { mHasPolicy = aHasPolicy; } public: - explicit BaseProxyHandler(void *family); + explicit BaseProxyHandler(const void *family); virtual ~BaseProxyHandler(); bool hasPrototype() { @@ -69,9 +87,12 @@ class JS_FRIEND_API(BaseProxyHandler) return mHasPolicy; } - inline void *family() { + inline const void *family() { return mFamily; } + static size_t offsetOfFamily() { + return offsetof(BaseProxyHandler, mFamily); + } virtual bool isOuterWindow() { return false; @@ -106,12 +127,13 @@ class JS_FRIEND_API(BaseProxyHandler) /* ES5 Harmony fundamental proxy traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject proxy) = 0; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags) = 0; + MutableHandle desc, + unsigned flags) = 0; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, - HandleId id, PropertyDescriptor *desc, + HandleId id, MutableHandle desc, unsigned flags) = 0; virtual bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc) = 0; + MutableHandle desc) = 0; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props) = 0; virtual bool delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) = 0; @@ -144,7 +166,13 @@ class JS_FRIEND_API(BaseProxyHandler) uint32_t index, MutableHandleValue vp, bool *present); virtual bool getPrototypeOf(JSContext *cx, HandleObject proxy, MutableHandleObject protop); - /* See comment for weakmapKeyDelegateOp in jsclass.h. */ + // These two hooks must be overridden, or not overridden, in tandem -- no + // overriding just one! + virtual bool watch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id, + JS::HandleObject callable); + virtual bool unwatch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id); + + /* See comment for weakmapKeyDelegateOp in js/Class.h. */ virtual JSObject *weakmapKeyDelegate(JSObject *proxy); }; @@ -157,17 +185,17 @@ class JS_FRIEND_API(BaseProxyHandler) class JS_PUBLIC_API(DirectProxyHandler) : public BaseProxyHandler { public: - explicit DirectProxyHandler(void *family); + explicit DirectProxyHandler(const void *family); /* ES5 Harmony fundamental proxy traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject proxy) MOZ_OVERRIDE; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, unsigned flags) MOZ_OVERRIDE; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, - HandleId id, PropertyDescriptor *desc, + HandleId id, MutableHandle desc, unsigned flags) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props) MOZ_OVERRIDE; virtual bool delete_(JSContext *cx, HandleObject proxy, HandleId id, @@ -204,8 +232,6 @@ class JS_PUBLIC_API(DirectProxyHandler) : public BaseProxyHandler unsigned indent) MOZ_OVERRIDE; virtual bool regexp_toShared(JSContext *cx, HandleObject proxy, RegExpGuard *g) MOZ_OVERRIDE; - virtual bool defaultValue(JSContext *cx, HandleObject obj, JSType hint, - MutableHandleValue vp) MOZ_OVERRIDE; virtual JSObject *weakmapKeyDelegate(JSObject *proxy); }; @@ -216,14 +242,15 @@ class Proxy /* ES5 Harmony fundamental proxy traps. */ static bool preventExtensions(JSContext *cx, HandleObject proxy); static bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags); + MutableHandle desc, unsigned flags); static bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, unsigned flags, HandleId id, MutableHandleValue vp); static bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags); + MutableHandle desc, unsigned flags); static bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, unsigned flags, HandleId id, MutableHandleValue vp); - static bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, PropertyDescriptor *desc); + static bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, + MutableHandle desc); static bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, HandleValue v); static bool getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props); static bool delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp); @@ -254,32 +281,27 @@ class Proxy static bool defaultValue(JSContext *cx, HandleObject obj, JSType hint, MutableHandleValue vp); static bool getPrototypeOf(JSContext *cx, HandleObject proxy, MutableHandleObject protop); + static bool watch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id, + JS::HandleObject callable); + static bool unwatch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id); + + /* IC entry path for handling __noSuchMethod__ on access. */ + static bool callProp(JSContext *cx, HandleObject proxy, HandleObject reveiver, HandleId id, + MutableHandleValue vp); + static JSObject * const LazyProto; }; -inline bool IsObjectProxyClass(const Class *clasp) -{ - return clasp == js::ObjectProxyClassPtr || clasp == js::OuterWindowProxyClassPtr; -} - -inline bool IsFunctionProxyClass(const Class *clasp) -{ - return clasp == js::FunctionProxyClassPtr; -} +// Use these in places where you don't want to #include vm/ProxyObject.h. +extern JS_FRIEND_DATA(const js::Class* const) CallableProxyClassPtr; +extern JS_FRIEND_DATA(const js::Class* const) UncallableProxyClassPtr; +extern JS_FRIEND_DATA(const js::Class* const) OuterWindowProxyClassPtr; inline bool IsProxyClass(const Class *clasp) { - return IsObjectProxyClass(clasp) || IsFunctionProxyClass(clasp); -} - -inline bool IsObjectProxy(JSObject *obj) -{ - return IsObjectProxyClass(GetObjectClass(obj)); -} - -inline bool IsFunctionProxy(JSObject *obj) -{ - return IsFunctionProxyClass(GetObjectClass(obj)); + return clasp == CallableProxyClassPtr || + clasp == UncallableProxyClassPtr || + clasp == OuterWindowProxyClassPtr; } inline bool IsProxy(JSObject *obj) @@ -342,14 +364,42 @@ SetProxyExtra(JSObject *obj, size_t n, const Value &extra) SetReservedSlot(obj, PROXY_EXTRA_SLOT + n, extra); } -enum ProxyCallable { - ProxyNotCallable = false, - ProxyIsCallable = true +class MOZ_STACK_CLASS ProxyOptions { + public: + ProxyOptions() : callable_(false), + singleton_(false), + forceForegroundFinalization_(false) + {} + + bool callable() const { return callable_; } + ProxyOptions &setCallable(bool flag) { + callable_ = flag; + return *this; + } + + bool singleton() const { return singleton_; } + ProxyOptions &setSingleton(bool flag) { + singleton_ = flag; + return *this; + } + + bool forceForegroundFinalization() const { + return forceForegroundFinalization_; + } + ProxyOptions &setForceForegroundFinalization(bool flag) { + forceForegroundFinalization_ = true; + return *this; + } + + private: + bool callable_; + bool singleton_; + bool forceForegroundFinalization_; }; JS_FRIEND_API(JSObject *) NewProxyObject(JSContext *cx, BaseProxyHandler *handler, HandleValue priv, - JSObject *proto, JSObject *parent, ProxyCallable callable = ProxyNotCallable); + JSObject *proto, JSObject *parent, const ProxyOptions &options = ProxyOptions()); JSObject * RenewProxyObject(JSContext *cx, JSObject *obj, BaseProxyHandler *handler, Value priv); @@ -361,7 +411,7 @@ class JS_FRIEND_API(AutoEnterPolicy) AutoEnterPolicy(JSContext *cx, BaseProxyHandler *handler, HandleObject wrapper, HandleId id, Action act, bool mayThrow) #ifdef DEBUG - : context(NULL) + : context(nullptr) #endif { allow = handler->hasPolicy() ? handler->enter(cx, wrapper, id, act, &rv) @@ -372,8 +422,8 @@ class JS_FRIEND_API(AutoEnterPolicy) // * The policy set rv to false, indicating that we should throw. // * The caller did not instruct us to ignore exceptions. // * The policy did not throw itself. - if (!allow && !rv && mayThrow && !JS_IsExceptionPending(cx)) - reportError(cx, id); + if (!allow && !rv && mayThrow) + reportErrorIfExceptionIsNotPending(cx, id); } virtual ~AutoEnterPolicy() { recordLeave(); } @@ -384,10 +434,10 @@ class JS_FRIEND_API(AutoEnterPolicy) // no-op constructor for subclass AutoEnterPolicy() #ifdef DEBUG - : context(NULL) + : context(nullptr) #endif {}; - void reportError(JSContext *cx, jsid id); + void reportErrorIfExceptionIsNotPending(JSContext *cx, jsid id); bool allow; bool rv; diff --git a/external/spidermonkey/include/android/jsprvtd.h b/external/spidermonkey/include/android/jsprvtd.h deleted file mode 100644 index 1fbc086a7c..0000000000 --- a/external/spidermonkey/include/android/jsprvtd.h +++ /dev/null @@ -1,297 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -#ifndef jsprvtd_h -#define jsprvtd_h -/* - * JS private typename definitions. - * - * This header is included only in other .h files, for convenience and for - * simplicity of type naming. The alternative for structures is to use tags, - * which are named the same as their typedef names (legal in C/C++, and less - * noisy than suffixing the typedef name with "Struct" or "Str"). Instead, - * all .h files that include this file may use the same typedef name, whether - * declaring a pointer to struct type, or defining a member of struct type. - * - * A few fundamental scalar types are defined here too. Neither the scalar - * nor the struct typedefs should change much, therefore the nearly-global - * make dependency induced by this file should not prove painful. - */ - -#include "jsapi.h" -#include "jsutil.h" - -#include "js/HashTable.h" -#include "js/Vector.h" - -/* - * Convenience constants. - */ -#define JS_BITS_PER_UINT32_LOG2 5 -#define JS_BITS_PER_UINT32 32 - -/* The alignment required of objects stored in GC arenas. */ -static const unsigned JS_GCTHING_ALIGN = 8; -static const unsigned JS_GCTHING_ZEROBITS = 3; - -/* Scalar typedefs. */ -typedef uint8_t jsbytecode; -typedef uint8_t jssrcnote; -typedef uintptr_t jsatomid; - -/* Struct typedefs. */ -typedef struct JSGCThing JSGCThing; -typedef struct JSGenerator JSGenerator; -typedef struct JSNativeEnumerator JSNativeEnumerator; -typedef struct JSTryNote JSTryNote; - -/* Friend "Advanced API" typedefs. */ -typedef struct JSAtomState JSAtomState; -typedef struct JSCodeSpec JSCodeSpec; -typedef struct JSPrinter JSPrinter; -typedef struct JSStackHeader JSStackHeader; -typedef struct JSSubString JSSubString; -typedef struct JSSpecializedNative JSSpecializedNative; - -/* String typedefs. */ -class JSDependentString; -class JSExtensibleString; -class JSExternalString; -class JSLinearString; -class JSRope; -class JSAtom; -class JSWrapper; - -namespace js { - -struct ArgumentsData; -struct Class; - -class AutoNameVector; -class RegExpGuard; -class RegExpObject; -class RegExpObjectBuilder; -class RegExpShared; -class RegExpStatics; -class MatchPairs; -class PropertyName; -class LazyScript; - -enum RegExpFlag -{ - IgnoreCaseFlag = 0x01, - GlobalFlag = 0x02, - MultilineFlag = 0x04, - StickyFlag = 0x08, - - NoFlags = 0x00, - AllFlags = 0x0f -}; - -class StringBuffer; - -class FrameRegs; -class StackFrame; -class ScriptFrameIter; - -class Proxy; -class JS_FRIEND_API(AutoEnterPolicy); -class JS_FRIEND_API(BaseProxyHandler); -class JS_FRIEND_API(Wrapper); -class JS_FRIEND_API(CrossCompartmentWrapper); - -class TempAllocPolicy; -class RuntimeAllocPolicy; - -class GlobalObject; - -template -class InlineMap; - -class LifoAlloc; - -class Shape; - -class Breakpoint; -class BreakpointSite; -class Debugger; -class WatchpointMap; - -/* - * Env is the type of what ES5 calls "lexical environments" (runtime - * activations of lexical scopes). This is currently just JSObject, and is - * implemented by Call, Block, With, and DeclEnv objects, among others--but - * environments and objects are really two different concepts. - */ -typedef JSObject Env; - -typedef JSNative Native; -typedef JSParallelNative ParallelNative; -typedef JSThreadSafeNative ThreadSafeNative; -typedef JSPropertyOp PropertyOp; -typedef JSStrictPropertyOp StrictPropertyOp; -typedef JSPropertyDescriptor PropertyDescriptor; - -struct SourceCompressionToken; - -namespace frontend { - -struct BytecodeEmitter; -struct Definition; -class FullParseHandler; -class FunctionBox; -class ObjectBox; -struct Token; -struct TokenPos; -class TokenStream; -class ParseMapPool; -class ParseNode; - -template -class Parser; - -} /* namespace frontend */ - -namespace analyze { - -struct LifetimeVariable; -class LoopAnalysis; -class ScriptAnalysis; -class SlotValue; -class SSAValue; -class SSAUseChain; - -} /* namespace analyze */ - -namespace types { - -class TypeSet; -struct TypeCallsite; -struct TypeObject; -struct TypeCompartment; - -} /* namespace types */ - -typedef JS::Handle HandleShape; -typedef JS::Handle HandleTypeObject; -typedef JS::Handle HandleAtom; -typedef JS::Handle HandlePropertyName; - -typedef JS::MutableHandle MutableHandleShape; -typedef JS::MutableHandle MutableHandleAtom; - -typedef JS::Rooted RootedShape; -typedef JS::Rooted RootedTypeObject; -typedef JS::Rooted RootedAtom; -typedef JS::Rooted RootedPropertyName; - -enum XDRMode { - XDR_ENCODE, - XDR_DECODE -}; - -template -class XDRState; - -class FreeOp; - -struct IdValuePair -{ - jsid id; - Value value; - - IdValuePair() {} - IdValuePair(jsid idArg) - : id(idArg), value(UndefinedValue()) - {} -}; - -} /* namespace js */ - -namespace JSC { - -class ExecutableAllocator; - -} /* namespace JSC */ - -namespace WTF { - -class BumpPointerAllocator; - -} /* namespace WTF */ - -/* "Friend" types used by jscntxt.h and jsdbgapi.h. */ -typedef enum JSTrapStatus { - JSTRAP_ERROR, - JSTRAP_CONTINUE, - JSTRAP_RETURN, - JSTRAP_THROW, - JSTRAP_LIMIT -} JSTrapStatus; - -typedef JSTrapStatus -(* JSTrapHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - jsval closure); - -typedef JSTrapStatus -(* JSInterruptHook)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - void *closure); - -typedef JSTrapStatus -(* JSDebuggerHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - void *closure); - -typedef JSTrapStatus -(* JSThrowHook)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - void *closure); - -typedef JSBool -(* JSWatchPointHandler)(JSContext *cx, JSObject *obj, jsid id, jsval old, - jsval *newp, void *closure); - -/* called just after script creation */ -typedef void -(* JSNewScriptHook)(JSContext *cx, - const char *filename, /* URL of script */ - unsigned lineno, /* first line */ - JSScript *script, - JSFunction *fun, - void *callerdata); - -/* called just before script destruction */ -typedef void -(* JSDestroyScriptHook)(JSFreeOp *fop, - JSScript *script, - void *callerdata); - -typedef void -(* JSSourceHandler)(const char *filename, unsigned lineno, const jschar *str, - size_t length, void **listenerTSData, void *closure); - -/* js::ObjectOps function pointer typedefs. */ - -/* - * A generic type for functions mapping an object to another object, or null - * if an error or exception was thrown on cx. - */ -typedef JSObject * -(* JSObjectOp)(JSContext *cx, JS::Handle obj); - -/* Signature for class initialization ops. */ -typedef JSObject * -(* JSClassInitializerOp)(JSContext *cx, JS::HandleObject obj); - -/* - * Hook that creates an iterator object for a given object. Returns the - * iterator object or null if an error or exception was thrown on cx. - */ -typedef JSObject * -(* JSIteratorOp)(JSContext *cx, JS::HandleObject obj, JSBool keysonly); - - -#endif /* jsprvtd_h */ diff --git a/external/spidermonkey/include/android/jspubtd.h b/external/spidermonkey/include/android/jspubtd.h index 96f5dd8297..4aa922eb84 100644 --- a/external/spidermonkey/include/android/jspubtd.h +++ b/external/spidermonkey/include/android/jspubtd.h @@ -11,72 +11,35 @@ * JS public API typedefs. */ +#include "mozilla/NullPtr.h" #include "mozilla/PodOperations.h" #include "jsprototypes.h" #include "jstypes.h" +#include "js/TypeDecls.h" + #if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) || defined(DEBUG) # define JSGC_TRACK_EXACT_ROOTS #endif namespace JS { -/* - * Allow headers to reference JS::Value without #including the whole jsapi.h. - * Unfortunately, typedefs (hence jsval) cannot be declared. - */ -class Value; +class AutoIdVector; +class CallArgs; template class Rooted; class JS_PUBLIC_API(AutoGCRooter); +class JS_PUBLIC_API(CompileOptions); +class JS_PUBLIC_API(CompartmentOptions); + struct Zone; } /* namespace JS */ -/* - * In release builds, jsid is defined to be an integral type. This - * prevents many bugs from being caught at compile time. E.g.: - * - * jsid id = ... - * if (id == JS_TRUE) // error - * ... - * - * size_t n = id; // error - * - * To catch more errors, jsid is given a struct type in C++ debug builds. - * Struct assignment and (in C++) operator== allow correct code to be mostly - * oblivious to the change. This feature can be explicitly disabled in debug - * builds by defining JS_NO_JSVAL_JSID_STRUCT_TYPES. - */ -// Needed for cocos2d-js -#define JS_NO_JSVAL_JSID_STRUCT_TYPES -# if defined(DEBUG) && !defined(JS_NO_JSVAL_JSID_STRUCT_TYPES) -# define JS_USE_JSID_STRUCT_TYPES -# endif - -# ifdef JS_USE_JSID_STRUCT_TYPES -struct jsid -{ - size_t asBits; - bool operator==(jsid rhs) const { return asBits == rhs.asBits; } - bool operator!=(jsid rhs) const { return asBits != rhs.asBits; } -}; -# define JSID_BITS(id) (id.asBits) -# else /* defined(JS_USE_JSID_STRUCT_TYPES) */ -typedef ptrdiff_t jsid; -# define JSID_BITS(id) (id) -# endif /* defined(JS_USE_JSID_STRUCT_TYPES) */ - -#ifdef WIN32 -typedef wchar_t jschar; -#else -typedef uint16_t jschar; -#endif - /* * Run-time version enumeration. For compile-time version checking, please use * the JS_HAS_* macros in jsversion.h, or use MOZJS_MAJOR_VERSION, @@ -109,7 +72,7 @@ typedef enum JSType { typedef enum JSProtoKey { #define PROTOKEY_AND_INITIALIZER(name,code,init) JSProto_##name = code, JS_FOR_EACH_PROTOTYPE(PROTOKEY_AND_INITIALIZER) -#undef JS_PROTO +#undef PROTOKEY_AND_INITIALIZER JSProto_LIMIT } JSProtoKey; @@ -175,7 +138,6 @@ typedef enum { typedef struct JSClass JSClass; typedef struct JSCompartment JSCompartment; typedef struct JSConstDoubleSpec JSConstDoubleSpec; -typedef struct JSContext JSContext; typedef struct JSCrossCompartmentCall JSCrossCompartmentCall; typedef struct JSErrorReport JSErrorReport; typedef struct JSExceptionState JSExceptionState; @@ -195,20 +157,32 @@ typedef struct JSStructuredCloneWriter JSStructuredCloneWriter; typedef struct JSTracer JSTracer; class JSFlatString; -class JSFunction; -class JSObject; -class JSScript; class JSStableString; // long story -class JSString; #ifdef JS_THREADSAFE -typedef struct PRCallOnceType JSCallOnceType; +typedef struct PRCallOnceType JSCallOnceType; #else -typedef JSBool JSCallOnceType; +typedef bool JSCallOnceType; #endif -typedef JSBool (*JSInitCallback)(void); +typedef bool (*JSInitCallback)(void); + +/* + * Generic trace operation that calls JS_CallTracer on each traceable thing + * stored in data. + */ +typedef void +(* JSTraceDataOp)(JSTracer *trc, void *data); + +namespace js { +namespace gc { +class StoreBuffer; +} +} namespace JS { + +typedef void (*OffThreadCompileCallback)(void *token, void *callbackData); + namespace shadow { struct Runtime @@ -220,15 +194,36 @@ struct Runtime /* Allow inlining of Nursery::isInside. */ uintptr_t gcNurseryStart_; uintptr_t gcNurseryEnd_; + + private: + js::gc::StoreBuffer *gcStoreBufferPtr_; #endif - Runtime() + public: + Runtime( +#ifdef JSGC_GENERATIONAL + js::gc::StoreBuffer *storeBuffer +#endif + ) : needsBarrier_(false) #ifdef JSGC_GENERATIONAL , gcNurseryStart_(0) , gcNurseryEnd_(0) + , gcStoreBufferPtr_(storeBuffer) #endif {} + + bool needsBarrier() const { + return needsBarrier_; + } + +#ifdef JSGC_GENERATIONAL + js::gc::StoreBuffer *gcStoreBufferPtr() { return gcStoreBufferPtr_; } +#endif + + static JS::shadow::Runtime *asShadowRuntime(JSRuntime *rt) { + return reinterpret_cast(rt); + } }; } /* namespace shadow */ @@ -270,6 +265,19 @@ enum ThingRootKind THING_ROOT_LIMIT }; +/* + * This list enumerates the different types of conceptual stacks we have in + * SpiderMonkey. In reality, they all share the C stack, but we allow different + * stack limits depending on the type of code running. + */ +enum StackKind +{ + StackForSystemCode, // C++, such as the GC, running on behalf of the VM. + StackForTrustedScript, // Script running with trusted principals. + StackForUntrustedScript, // Script running with untrusted principals. + StackKindCount +}; + template struct RootKind; @@ -305,13 +313,13 @@ struct ContextFriendFields public: explicit ContextFriendFields(JSRuntime *rt) - : runtime_(rt), compartment_(NULL), zone_(NULL), autoGCRooters(NULL) + : runtime_(rt), compartment_(nullptr), zone_(nullptr), autoGCRooters(nullptr) { #ifdef JSGC_TRACK_EXACT_ROOTS mozilla::PodArrayZero(thingGCRooters); #endif #if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) - skipGCRooters = NULL; + skipGCRooters = nullptr; #endif } @@ -395,7 +403,7 @@ struct PerThreadDataFriendFields #endif /* Limit pointer for checking native stack consumption. */ - uintptr_t nativeStackLimit; + uintptr_t nativeStackLimit[StackKindCount]; static const size_t RuntimeMainThreadOffset = offsetof(RuntimeDummy, mainThread); diff --git a/external/spidermonkey/include/android/jstypes.h b/external/spidermonkey/include/android/jstypes.h index 17f67f70e1..d5b15ccb1d 100644 --- a/external/spidermonkey/include/android/jstypes.h +++ b/external/spidermonkey/include/android/jstypes.h @@ -22,9 +22,16 @@ #define jstypes_h #include "mozilla/Attributes.h" -#include "mozilla/Util.h" +#include "mozilla/Types.h" +// jstypes.h is (or should be!) included by every file in SpiderMonkey. +// js-config.h and jsversion.h also should be included by every file. +// So include them here. +// XXX: including them in js/RequiredDefines.h should be a better option, since +// that is by definition the header file that should be included in all +// SpiderMonkey code. However, Gecko doesn't do this! See bug 909576. #include "js-config.h" +#include "jsversion.h" /*********************************************************************** ** MACROS: JS_EXTERN_API @@ -82,10 +89,6 @@ #define JS_NO_FASTCALL #endif -#ifndef JS_INLINE -#define JS_INLINE MOZ_INLINE -#endif - #ifndef JS_ALWAYS_INLINE #define JS_ALWAYS_INLINE MOZ_ALWAYS_INLINE #endif @@ -180,19 +183,6 @@ # error "Implement me" #endif - -/************************************************************************ -** TYPES: JSBool -** DESCRIPTION: -** Use JSBool for variables and parameter types. Use JS_FALSE and JS_TRUE -** for clarity of target type in assignments and actual arguments. Use -** 'if (bool)', 'while (!bool)', '(bool) ? x : y' etc., to test booleans -** just as you would C int-valued conditions. -************************************************************************/ -typedef int JSBool; -#define JS_TRUE (int)1 -#define JS_FALSE (int)0 - /*********************************************************************** ** MACROS: JS_LIKELY ** JS_UNLIKELY @@ -244,7 +234,11 @@ typedef int JSBool; #define JS_BITS_PER_BYTE 8 #define JS_BITS_PER_BYTE_LOG2 3 -#define JS_BITS_PER_WORD (JS_BITS_PER_BYTE * JS_BYTES_PER_WORD) +#if defined(JS_64BIT) +# define JS_BITS_PER_WORD 64 +#else +# define JS_BITS_PER_WORD 32 +#endif /*********************************************************************** ** MACROS: JS_FUNC_TO_DATA_PTR diff --git a/external/spidermonkey/include/android/jsutil.h b/external/spidermonkey/include/android/jsutil.h deleted file mode 100644 index 4020822be1..0000000000 --- a/external/spidermonkey/include/android/jsutil.h +++ /dev/null @@ -1,385 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -/* - * PR assertion checker. - */ - -#ifndef jsutil_h -#define jsutil_h - -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/GuardObjects.h" - -#ifdef USE_ZLIB -#include -#endif - -#include "js/Utility.h" - -/* Forward declarations. */ -struct JSContext; - -static JS_ALWAYS_INLINE void * -js_memcpy(void *dst_, const void *src_, size_t len) -{ - char *dst = (char *) dst_; - const char *src = (const char *) src_; - JS_ASSERT_IF(dst >= src, (size_t) (dst - src) >= len); - JS_ASSERT_IF(src >= dst, (size_t) (src - dst) >= len); - - return memcpy(dst, src, len); -} - -namespace js { - -template -struct AlignmentTestStruct -{ - char c; - T t; -}; - -/* This macro determines the alignment requirements of a type. */ -#define JS_ALIGNMENT_OF(t_) \ - (sizeof(js::AlignmentTestStruct) - sizeof(t_)) - -template -class AlignedPtrAndFlag -{ - uintptr_t bits; - - public: - AlignedPtrAndFlag(T *t, bool aFlag) { - JS_ASSERT((uintptr_t(t) & 1) == 0); - bits = uintptr_t(t) | uintptr_t(aFlag); - } - - T *ptr() const { - return (T *)(bits & ~uintptr_t(1)); - } - - bool flag() const { - return (bits & 1) != 0; - } - - void setPtr(T *t) { - JS_ASSERT((uintptr_t(t) & 1) == 0); - bits = uintptr_t(t) | uintptr_t(flag()); - } - - void setFlag() { - bits |= 1; - } - - void unsetFlag() { - bits &= ~uintptr_t(1); - } - - void set(T *t, bool aFlag) { - JS_ASSERT((uintptr_t(t) & 1) == 0); - bits = uintptr_t(t) | aFlag; - } -}; - -template -static inline void -Reverse(T *beg, T *end) -{ - while (beg != end) { - if (--end == beg) - return; - T tmp = *beg; - *beg = *end; - *end = tmp; - ++beg; - } -} - -template -static inline T * -Find(T *beg, T *end, const T &v) -{ - for (T *p = beg; p != end; ++p) { - if (*p == v) - return p; - } - return end; -} - -template -static inline typename Container::ElementType * -Find(Container &c, const typename Container::ElementType &v) -{ - return Find(c.begin(), c.end(), v); -} - -template -void -ForEach(InputIterT begin, InputIterT end, CallableT f) -{ - for (; begin != end; ++begin) - f(*begin); -} - -template -static inline T -Min(T t1, T t2) -{ - return t1 < t2 ? t1 : t2; -} - -template -static inline T -Max(T t1, T t2) -{ - return t1 > t2 ? t1 : t2; -} - -/* Allows a const variable to be initialized after its declaration. */ -template -static T& -InitConst(const T &t) -{ - return const_cast(t); -} - -template -JS_ALWAYS_INLINE T & -ImplicitCast(U &u) -{ - T &t = u; - return t; -} - -template -class AutoScopedAssign -{ - public: - AutoScopedAssign(T *addr, const T &value - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : addr_(addr), old(*addr_) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - *addr_ = value; - } - - ~AutoScopedAssign() { *addr_ = old; } - - private: - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - T *addr_; - T old; -}; - -template -static inline bool -IsPowerOfTwo(T t) -{ - return t && !(t & (t - 1)); -} - -template -static inline U -ComputeByteAlignment(T bytes, U alignment) -{ - JS_ASSERT(IsPowerOfTwo(alignment)); - return (alignment - (bytes % alignment)) % alignment; -} - -template -static inline T -AlignBytes(T bytes, U alignment) -{ - return bytes + ComputeByteAlignment(bytes, alignment); -} - -JS_ALWAYS_INLINE static size_t -UnsignedPtrDiff(const void *bigger, const void *smaller) -{ - return size_t(bigger) - size_t(smaller); -} - -/*****************************************************************************/ - -/* A bit array is an array of bits represented by an array of words (size_t). */ - -static inline unsigned -NumWordsForBitArrayOfLength(size_t length) -{ - return (length + (JS_BITS_PER_WORD - 1)) / JS_BITS_PER_WORD; -} - -static inline unsigned -BitArrayIndexToWordIndex(size_t length, size_t bitIndex) -{ - unsigned wordIndex = bitIndex / JS_BITS_PER_WORD; - JS_ASSERT(wordIndex < length); - return wordIndex; -} - -static inline size_t -BitArrayIndexToWordMask(size_t i) -{ - return size_t(1) << (i % JS_BITS_PER_WORD); -} - -static inline bool -IsBitArrayElementSet(size_t *array, size_t length, size_t i) -{ - return array[BitArrayIndexToWordIndex(length, i)] & BitArrayIndexToWordMask(i); -} - -static inline bool -IsAnyBitArrayElementSet(size_t *array, size_t length) -{ - unsigned numWords = NumWordsForBitArrayOfLength(length); - for (unsigned i = 0; i < numWords; ++i) { - if (array[i]) - return true; - } - return false; -} - -static inline void -SetBitArrayElement(size_t *array, size_t length, size_t i) -{ - array[BitArrayIndexToWordIndex(length, i)] |= BitArrayIndexToWordMask(i); -} - -static inline void -ClearBitArrayElement(size_t *array, size_t length, size_t i) -{ - array[BitArrayIndexToWordIndex(length, i)] &= ~BitArrayIndexToWordMask(i); -} - -static inline void -ClearAllBitArrayElements(size_t *array, size_t length) -{ - for (unsigned i = 0; i < length; ++i) - array[i] = 0; -} - -#ifdef USE_ZLIB -class Compressor -{ - /* Number of bytes we should hand to zlib each compressMore() call. */ - static const size_t CHUNKSIZE = 2048; - z_stream zs; - const unsigned char *inp; - size_t inplen; - size_t outbytes; - - public: - enum Status { - MOREOUTPUT, - DONE, - CONTINUE, - OOM - }; - - Compressor(const unsigned char *inp, size_t inplen); - ~Compressor(); - bool init(); - void setOutput(unsigned char *out, size_t outlen); - size_t outWritten() const { return outbytes; } - /* Compress some of the input. Return true if it should be called again. */ - Status compressMore(); -}; - -/* - * Decompress a string. The caller must know the length of the output and - * allocate |out| to a string of that length. - */ -bool DecompressString(const unsigned char *inp, size_t inplen, - unsigned char *out, size_t outlen); -#endif - -} /* namespace js */ - -/* Crash diagnostics */ -#ifdef DEBUG -# define JS_CRASH_DIAGNOSTICS 1 -#endif -#ifdef JS_CRASH_DIAGNOSTICS -# define JS_POISON(p, val, size) memset((p), (val), (size)) -#else -# define JS_POISON(p, val, size) ((void) 0) -#endif - -/* Basic stats */ -#ifdef DEBUG -# define JS_BASIC_STATS 1 -#endif -#ifdef JS_BASIC_STATS -# include -typedef struct JSBasicStats { - uint32_t num; - uint32_t max; - double sum; - double sqsum; - uint32_t logscale; /* logarithmic scale: 0 (linear), 2, 10 */ - uint32_t hist[11]; -} JSBasicStats; -# define JS_INIT_STATIC_BASIC_STATS {0,0,0,0,0,{0,0,0,0,0,0,0,0,0,0,0}} -# define JS_BASIC_STATS_INIT(bs) memset((bs), 0, sizeof(JSBasicStats)) -# define JS_BASIC_STATS_ACCUM(bs,val) \ - JS_BasicStatsAccum(bs, val) -# define JS_MeanAndStdDevBS(bs,sigma) \ - JS_MeanAndStdDev((bs)->num, (bs)->sum, (bs)->sqsum, sigma) -extern void -JS_BasicStatsAccum(JSBasicStats *bs, uint32_t val); -extern double -JS_MeanAndStdDev(uint32_t num, double sum, double sqsum, double *sigma); -extern void -JS_DumpBasicStats(JSBasicStats *bs, const char *title, FILE *fp); -extern void -JS_DumpHistogram(JSBasicStats *bs, FILE *fp); -#else -# define JS_BASIC_STATS_ACCUM(bs,val) -#endif - -/* A jsbitmap_t is a long integer that can be used for bitmaps. */ -typedef size_t jsbitmap; -#define JS_TEST_BIT(_map,_bit) ((_map)[(_bit)>>JS_BITS_PER_WORD_LOG2] & \ - ((jsbitmap)1<<((_bit)&(JS_BITS_PER_WORD-1)))) -#define JS_SET_BIT(_map,_bit) ((_map)[(_bit)>>JS_BITS_PER_WORD_LOG2] |= \ - ((jsbitmap)1<<((_bit)&(JS_BITS_PER_WORD-1)))) -#define JS_CLEAR_BIT(_map,_bit) ((_map)[(_bit)>>JS_BITS_PER_WORD_LOG2] &= \ - ~((jsbitmap)1<<((_bit)&(JS_BITS_PER_WORD-1)))) - -/* Wrapper for various macros to stop warnings coming from their expansions. */ -#if defined(__clang__) -# define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \ - JS_BEGIN_MACRO \ - _Pragma("clang diagnostic push") \ - /* If these _Pragmas cause warnings for you, try disabling ccache. */ \ - _Pragma("clang diagnostic ignored \"-Wunused-value\"") \ - { expr; } \ - _Pragma("clang diagnostic pop") \ - JS_END_MACRO -#elif MOZ_IS_GCC - -#if MOZ_GCC_VERSION_AT_LEAST(4, 6, 0) -# define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \ - JS_BEGIN_MACRO \ - _Pragma("GCC diagnostic push") \ - _Pragma("GCC diagnostic ignored \"-Wunused-but-set-variable\"") \ - expr; \ - _Pragma("GCC diagnostic pop") \ - JS_END_MACRO -#endif -#endif - -#if !defined(JS_SILENCE_UNUSED_VALUE_IN_EXPR) -# define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \ - JS_BEGIN_MACRO \ - expr; \ - JS_END_MACRO -#endif - -#endif /* jsutil_h */ diff --git a/external/spidermonkey/include/android/jsversion.h b/external/spidermonkey/include/android/jsversion.h index 1780616a32..827a56981d 100644 --- a/external/spidermonkey/include/android/jsversion.h +++ b/external/spidermonkey/include/android/jsversion.h @@ -7,19 +7,6 @@ #ifndef jsversion_h #define jsversion_h -/* - * Deprecated JS_VERSION handler. - */ -#ifdef JS_VERSION -# if JS_VERSION == 185 -# warning "JS_VERSION defined but unsupported (legacy)" -# elif JS_VERSION < 185 -# error "Unsupported JS_VERSION" -# else -# error "Unknown JS_VERSION" -# endif -#endif - /* * JS Capability Macros. */ @@ -52,15 +39,15 @@ * Feature for Object.prototype.__{define,lookup}{G,S}etter__ legacy support; * support likely to be made opt-in at some future time. */ -#define OLD_GETTER_SETTER_METHODS 1 +#define JS_OLD_GETTER_SETTER_METHODS 1 /* A kill-switch for bug 586842. Embedders shouldn't touch this! */ -#define USE_NEW_OBJECT_REPRESENTATION 0 +#define JS_USE_NEW_OBJECT_REPRESENTATION 0 -#if USE_NEW_OBJECT_REPRESENTATION -# define NEW_OBJECT_REPRESENTATION_ONLY() ((void)0) +#if JS_USE_NEW_OBJECT_REPRESENTATION +# define JS_NEW_OBJECT_REPRESENTATION_ONLY() ((void)0) #else -# define NEW_OBJECT_REPRESENTATION_ONLY() \ +# define JS_NEW_OBJECT_REPRESENTATION_ONLY() \ MOZ_ASSUME_UNREACHABLE("don't call this! to be used in the new object representation") #endif diff --git a/external/spidermonkey/include/android/jswrapper.h b/external/spidermonkey/include/android/jswrapper.h index f78df7db60..938db73ec8 100644 --- a/external/spidermonkey/include/android/jswrapper.h +++ b/external/spidermonkey/include/android/jswrapper.h @@ -9,7 +9,6 @@ #include "mozilla/Attributes.h" -#include "jsapi.h" #include "jsproxy.h" namespace js { @@ -38,6 +37,9 @@ class JS_FRIEND_API(Wrapper) : public DirectProxyHandler LAST_USED_FLAG = CROSS_COMPARTMENT }; + virtual bool defaultValue(JSContext *cx, HandleObject obj, JSType hint, + MutableHandleValue vp) MOZ_OVERRIDE; + /* * Wrappers can explicitly specify that they are unsafe to unwrap from a * security perspective (as is the case for SecurityWrappers). If a wrapper @@ -64,6 +66,8 @@ class JS_FRIEND_API(Wrapper) : public DirectProxyHandler virtual ~Wrapper(); + virtual bool finalizeInBackground(Value priv) MOZ_OVERRIDE; + static Wrapper singleton; static Wrapper singletonWithPrototype; }; @@ -76,16 +80,16 @@ class JS_FRIEND_API(CrossCompartmentWrapper) : public Wrapper virtual ~CrossCompartmentWrapper(); - virtual bool finalizeInBackground(Value priv) MOZ_OVERRIDE; - /* ES5 Harmony fundamental wrapper traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject wrapper) MOZ_OVERRIDE; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject wrapper, AutoIdVector &props) MOZ_OVERRIDE; virtual bool delete_(JSContext *cx, HandleObject wrapper, HandleId id, bool *bp) MOZ_OVERRIDE; @@ -149,7 +153,7 @@ class JS_FRIEND_API(SecurityWrapper) : public Base JSContext *cx) MOZ_OVERRIDE; virtual bool regexp_toShared(JSContext *cx, HandleObject proxy, RegExpGuard *g) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; /* * Allow our subclasses to select the superclass behavior they want without @@ -165,18 +169,21 @@ typedef SecurityWrapper CrossCompartmentSecurityWrapper class JS_FRIEND_API(DeadObjectProxy) : public BaseProxyHandler { public: - static int sDeadObjectFamily; + // This variable exists solely to provide a unique address for use as an identifier. + static const char sDeadObjectFamily; explicit DeadObjectProxy(); /* ES5 Harmony fundamental wrapper traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject proxy) MOZ_OVERRIDE; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject wrapper, AutoIdVector &props) MOZ_OVERRIDE; virtual bool delete_(JSContext *cx, HandleObject wrapper, HandleId id, bool *bp) MOZ_OVERRIDE; @@ -213,7 +220,8 @@ TransparentObjectWrapper(JSContext *cx, HandleObject existing, HandleObject obj, // Proxy family for wrappers. Public so that IsWrapper() can be fully inlined by // jsfriendapi users. -extern JS_FRIEND_DATA(int) sWrapperFamily; +// This variable exists solely to provide a unique address for use as an identifier. +extern JS_FRIEND_DATA(const char) sWrapperFamily; inline bool IsWrapper(JSObject *obj) @@ -226,7 +234,7 @@ IsWrapper(JSObject *obj) // previously wrapped. Otherwise, this returns the first object for // which JSObject::isWrapper returns false. JS_FRIEND_API(JSObject *) -UncheckedUnwrap(JSObject *obj, bool stopAtOuter = true, unsigned *flagsp = NULL); +UncheckedUnwrap(JSObject *obj, bool stopAtOuter = true, unsigned *flagsp = nullptr); // Given a JSObject, returns that object stripped of wrappers. At each stage, // the security wrapper has the opportunity to veto the unwrap. Since checked @@ -247,7 +255,8 @@ bool IsDeadProxyObject(JSObject *obj); JSObject * -NewDeadProxyObject(JSContext *cx, JSObject *parent); +NewDeadProxyObject(JSContext *cx, JSObject *parent, + const ProxyOptions &options = ProxyOptions()); void NukeCrossCompartmentWrapper(JSContext *cx, JSObject *wrapper); diff --git a/external/spidermonkey/include/android/mozilla/Alignment.h b/external/spidermonkey/include/android/mozilla/Alignment.h new file mode 100644 index 0000000000..29599d0ef1 --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/Alignment.h @@ -0,0 +1,137 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=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/. */ + +/* Functionality related to memory alignment. */ + +#ifndef mozilla_Alignment_h +#define mozilla_Alignment_h + +#include +#include + +namespace mozilla { + +/* + * This class, and the corresponding macro MOZ_ALIGNOF, figures out how many + * bytes of alignment a given type needs. + */ +template +class AlignmentFinder +{ + struct Aligner + { + char c; + T t; + }; + + public: + static const size_t alignment = sizeof(Aligner) - sizeof(T); +}; + +#define MOZ_ALIGNOF(T) mozilla::AlignmentFinder::alignment + +/* + * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types. + * + * For instance, + * + * MOZ_ALIGNED_DECL(char arr[2], 8); + * + * will declare a two-character array |arr| aligned to 8 bytes. + */ + +#if defined(__GNUC__) +# define MOZ_ALIGNED_DECL(_type, _align) \ + _type __attribute__((aligned(_align))) +#elif defined(_MSC_VER) +# define MOZ_ALIGNED_DECL(_type, _align) \ + __declspec(align(_align)) _type +#else +# warning "We don't know how to align variables on this compiler." +# define MOZ_ALIGNED_DECL(_type, _align) _type +#endif + +/* + * AlignedElem is a structure whose alignment is guaranteed to be at least N + * bytes. + * + * We support 1, 2, 4, 8, and 16-bit alignment. + */ +template +struct AlignedElem; + +/* + * We have to specialize this template because GCC doesn't like __attribute__((aligned(foo))) where + * foo is a template parameter. + */ + +template<> +struct AlignedElem<1> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 1); +}; + +template<> +struct AlignedElem<2> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 2); +}; + +template<> +struct AlignedElem<4> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 4); +}; + +template<> +struct AlignedElem<8> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 8); +}; + +template<> +struct AlignedElem<16> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 16); +}; + +/* + * This utility pales in comparison to Boost's aligned_storage. The utility + * simply assumes that uint64_t is enough alignment for anyone. This may need + * to be extended one day... + * + * As an important side effect, pulling the storage into this template is + * enough obfuscation to confuse gcc's strict-aliasing analysis into not giving + * false negatives when we cast from the char buffer to whatever type we've + * constructed using the bytes. + */ +template +struct AlignedStorage +{ + union U { + char bytes[Nbytes]; + uint64_t _; + } u; + + const void* addr() const { return u.bytes; } + void* addr() { return u.bytes; } +}; + +template +struct AlignedStorage2 +{ + union U { + char bytes[sizeof(T)]; + uint64_t _; + } u; + + const T* addr() const { return reinterpret_cast(u.bytes); } + T* addr() { return static_cast(static_cast(u.bytes)); } +}; + +} /* namespace mozilla */ + +#endif /* mozilla_Alignment_h */ diff --git a/external/spidermonkey/include/android/mozilla/Assertions.h b/external/spidermonkey/include/android/mozilla/Assertions.h index 00b7037802..f902199051 100644 --- a/external/spidermonkey/include/android/mozilla/Assertions.h +++ b/external/spidermonkey/include/android/mozilla/Assertions.h @@ -180,7 +180,7 @@ __declspec(noreturn) __inline void MOZ_NoReturn() {} # ifdef __cplusplus # define MOZ_REALLY_CRASH() \ do { \ - __debugbreak(); \ + ::__debugbreak(); \ *((volatile int*) NULL) = 123; \ ::TerminateProcess(::GetCurrentProcess(), 3); \ ::MOZ_NoReturn(); \ diff --git a/external/spidermonkey/include/android/mozilla/Atomics.h b/external/spidermonkey/include/android/mozilla/Atomics.h index f876683c3e..31e6a7daec 100644 --- a/external/spidermonkey/include/android/mozilla/Atomics.h +++ b/external/spidermonkey/include/android/mozilla/Atomics.h @@ -17,6 +17,8 @@ #define mozilla_Atomics_h #include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" +#include "mozilla/Compiler.h" #include "mozilla/TypeTraits.h" #include @@ -26,34 +28,16 @@ * does not have . So be sure to check for support * along with C++0x support. */ -#if defined(__clang__) +#if defined(__clang__) || defined(__GNUC__) /* - * clang doesn't like libstdc++'s version of before GCC 4.7, - * due to the loose typing of the __sync_* family of functions done by - * GCC. We do not have a particularly good way to detect this sort of - * case at this point, so just assume that if we're on a Linux system, - * we can't use the system's . - * - * OpenBSD uses an old libstdc++ 4.2.1 and thus doesnt have . + * Clang doesn't like from libstdc++ before 4.7 due to the + * loose typing of the atomic builtins. GCC 4.5 and 4.6 lacks inline + * definitions for unspecialized std::atomic and causes linking errors. + * Therefore, we require at least 4.7.0 for using libstdc++. */ -# if !defined(__linux__) && !defined(__OpenBSD__) && \ - (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) && \ - __has_include() +# if MOZ_USING_LIBSTDCXX && MOZ_LIBSTDCXX_VERSION_AT_LEAST(4, 7, 0) # define MOZ_HAVE_CXX11_ATOMICS -# endif -/* - * Android uses a different C++ standard library that does not provide - * support for . - * - * GCC 4.5.x and 4.6.x's unspecialized std::atomic template doesn't include - * inline definitions for the functions declared therein. This oversight - * leads to linking errors when using atomic enums. We therefore require - * GCC 4.7 or higher. - */ -#elif defined(__GNUC__) && !defined(__ANDROID__) -# include "mozilla/Compiler.h" -# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) && \ - MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) +# elif MOZ_USING_LIBCXX # define MOZ_HAVE_CXX11_ATOMICS # endif #elif defined(_MSC_VER) && _MSC_VER >= 1700 @@ -845,8 +829,8 @@ class AtomicBase typename Intrinsics::ValueType mValue; public: - AtomicBase() : mValue() {} - AtomicBase(T aInit) { Intrinsics::store(mValue, aInit); } + MOZ_CONSTEXPR AtomicBase() : mValue() {} + MOZ_CONSTEXPR AtomicBase(T aInit) : mValue(aInit) {} operator T() const { return Intrinsics::load(mValue); } @@ -889,8 +873,8 @@ class AtomicBaseIncDec : public AtomicBase typedef typename detail::AtomicBase Base; public: - AtomicBaseIncDec() : Base() {} - AtomicBaseIncDec(T aInit) : Base(aInit) {} + MOZ_CONSTEXPR AtomicBaseIncDec() : Base() {} + MOZ_CONSTEXPR AtomicBaseIncDec(T aInit) : Base(aInit) {} using Base::operator=; @@ -943,8 +927,8 @@ class Atomic::value>::Type> typedef typename detail::AtomicBaseIncDec Base; public: - Atomic() : Base() {} - Atomic(T aInit) : Base(aInit) {} + MOZ_CONSTEXPR Atomic() : Base() {} + MOZ_CONSTEXPR Atomic(T aInit) : Base(aInit) {} using Base::operator=; @@ -972,8 +956,8 @@ class Atomic : public detail::AtomicBaseIncDec typedef typename detail::AtomicBaseIncDec Base; public: - Atomic() : Base() {} - Atomic(T* aInit) : Base(aInit) {} + MOZ_CONSTEXPR Atomic() : Base() {} + MOZ_CONSTEXPR Atomic(T* aInit) : Base(aInit) {} using Base::operator=; @@ -1000,8 +984,8 @@ class Atomic::value>::Type> typedef typename detail::AtomicBase Base; public: - Atomic() : Base() {} - Atomic(T aInit) : Base(aInit) {} + MOZ_CONSTEXPR Atomic() : Base() {} + MOZ_CONSTEXPR Atomic(T aInit) : Base(aInit) {} using Base::operator=; diff --git a/external/spidermonkey/include/android/mozilla/Attributes.h b/external/spidermonkey/include/android/mozilla/Attributes.h index 6ea9776fbf..0786cb2fe5 100644 --- a/external/spidermonkey/include/android/mozilla/Attributes.h +++ b/external/spidermonkey/include/android/mozilla/Attributes.h @@ -11,26 +11,10 @@ #include "mozilla/Compiler.h" -/* - * MOZ_INLINE is a macro which expands to tell the compiler that the method - * decorated with it should be inlined. This macro is usable from C and C++ - * code, even though C89 does not support the |inline| keyword. The compiler - * may ignore this directive if it chooses. - */ -#if defined(__cplusplus) -# define MOZ_INLINE inline -#elif defined(_MSC_VER) -# define MOZ_INLINE __inline -#elif defined(__GNUC__) -# define MOZ_INLINE __inline__ -#else -# define MOZ_INLINE inline -#endif - /* * MOZ_ALWAYS_INLINE is a macro which expands to tell the compiler that the * method decorated with it must be inlined, even if the compiler thinks - * otherwise. This is only a (much) stronger version of the MOZ_INLINE hint: + * otherwise. This is only a (much) stronger version of the inline hint: * compilers are not guaranteed to respect it (although they're much more likely * to do so). * @@ -40,15 +24,17 @@ #if defined(_MSC_VER) # define MOZ_ALWAYS_INLINE_EVEN_DEBUG __forceinline #elif defined(__GNUC__) -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __attribute__((always_inline)) MOZ_INLINE +# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __attribute__((always_inline)) inline #else -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_INLINE +# define MOZ_ALWAYS_INLINE_EVEN_DEBUG inline #endif -#if defined(DEBUG) -# define MOZ_ALWAYS_INLINE MOZ_INLINE -#else +#if !defined(DEBUG) # define MOZ_ALWAYS_INLINE MOZ_ALWAYS_INLINE_EVEN_DEBUG +#elif defined(_MSC_VER) && !defined(__cplusplus) +# define MOZ_ALWAYS_INLINE __inline +#else +# define MOZ_ALWAYS_INLINE inline #endif /* @@ -170,12 +156,31 @@ * Furthermore, it will prevent the compiler from inlining the function because * inlining currently breaks the blacklisting mechanism of AddressSanitizer. */ -#if defined(MOZ_ASAN) -# define MOZ_ASAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_address_safety_analysis)) -# else -# define MOZ_ASAN_BLACKLIST +#if defined(__has_feature) +# if __has_feature(address_sanitizer) +# define MOZ_ASAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_address)) +# else +# define MOZ_ASAN_BLACKLIST /* nothing */ +# endif +#else +# define MOZ_ASAN_BLACKLIST /* nothing */ #endif +/* + * MOZ_TSAN_BLACKLIST is a macro to tell ThreadSanitizer (a compile-time + * instrumentation shipped with Clang) to not instrument the annotated function. + * Furthermore, it will prevent the compiler from inlining the function because + * inlining currently breaks the blacklisting mechanism of ThreadSanitizer. + */ +#if defined(__has_feature) +# if __has_feature(thread_sanitizer) +# define MOZ_TSAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_thread)) +# else +# define MOZ_TSAN_BLACKLIST /* nothing */ +# endif +#else +# define MOZ_TSAN_BLACKLIST /* nothing */ +#endif #ifdef __cplusplus diff --git a/external/spidermonkey/include/android/mozilla/Char16.h b/external/spidermonkey/include/android/mozilla/Char16.h index e4b184f950..fb182dfde2 100644 --- a/external/spidermonkey/include/android/mozilla/Char16.h +++ b/external/spidermonkey/include/android/mozilla/Char16.h @@ -9,16 +9,11 @@ #ifndef mozilla_Char16_h #define mozilla_Char16_h -#include "mozilla/Assertions.h" - /* * C11 and C++11 introduce a char16_t type and support for UTF-16 string and * character literals. C++11's char16_t is a distinct builtin type. C11's * char16_t is a typedef for uint_least16_t. Technically, char16_t is a 16-bit * code unit of a Unicode code point, not a "character". - * - * For now, Char16.h only supports C++ because we don't want mix different C - * and C++ definitions of char16_t in the same code base. */ #ifdef _MSC_VER @@ -26,20 +21,52 @@ * C++11 says char16_t is a distinct builtin type, but Windows's yvals.h * typedefs char16_t as an unsigned short. We would like to alias char16_t * to Windows's 16-bit wchar_t so we can declare UTF-16 literals as constant - * expressions (and pass char16_t pointers to Windows APIs). We #define our - * char16_t as a macro to override yval.h's typedef of the same name. + * expressions (and pass char16_t pointers to Windows APIs). We #define + * _CHAR16T here in order to prevent yvals.h from overriding our char16_t + * typedefs, which we set to wchar_t for C++ code and to unsigned short for + * C code. + * + * In addition, #defining _CHAR16T will prevent yvals.h from defining a + * char32_t type, so we have to undo that damage here and provide our own, + * which is identical to the yvals.h type. */ # define MOZ_UTF16_HELPER(s) L##s -# include -# define char16_t wchar_t +# define _CHAR16T +# ifdef __cplusplus + typedef wchar_t char16_t; +# else + typedef unsigned short char16_t; +# endif + typedef unsigned int char32_t; #elif defined(__cplusplus) && \ (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) /* C++11 has a builtin char16_t type. */ # define MOZ_UTF16_HELPER(s) u##s + /** + * This macro is used to distinguish when char16_t would be a distinct + * typedef from wchar_t. + */ +# define MOZ_CHAR16_IS_NOT_WCHAR +#elif !defined(__cplusplus) +# if defined(WIN32) +# include + typedef wchar_t char16_t; +# else + /** + * We can't use the stdint.h uint16_t type here because including + * stdint.h will break building some of our C libraries, such as + * sqlite. + */ + typedef unsigned short char16_t; +# endif #else # error "Char16.h requires C++11 (or something like it) for UTF-16 support." #endif +/* This is a temporary hack until bug 927728 is fixed. */ +#define __PRUNICHAR__ +typedef char16_t PRUnichar; + /* * Macro arguments used in concatenation or stringification won't be expanded. * Therefore, in order for |MOZ_UTF16(FOO)| to work as expected (which is to @@ -50,8 +77,12 @@ */ #define MOZ_UTF16(s) MOZ_UTF16_HELPER(s) +#if defined(__cplusplus) && \ + (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) static_assert(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); +static_assert(char16_t(-1) > char16_t(0), "Is char16_t type unsigned?"); static_assert(sizeof(MOZ_UTF16('A')) == 2, "Is char literal 16 bits?"); static_assert(sizeof(MOZ_UTF16("")[0]) == 2, "Is string char 16 bits?"); +#endif #endif /* mozilla_Char16_h */ diff --git a/external/spidermonkey/include/android/mozilla/Compiler.h b/external/spidermonkey/include/android/mozilla/Compiler.h index d1ef1e79aa..fd5c98c98d 100644 --- a/external/spidermonkey/include/android/mozilla/Compiler.h +++ b/external/spidermonkey/include/android/mozilla/Compiler.h @@ -29,4 +29,77 @@ #endif +/* + * The situation with standard libraries is a lot worse than with compilers, + * particularly as clang and gcc could end up using one of three or so standard + * libraries, and they may not be up-to-snuff with newer C++11 versions. To + * detect the library, we're going to include cstddef (which is a small header + * which will be transitively included by everybody else at some point) to grab + * the version macros and deduce macros from there. + */ +#ifdef __cplusplus +# include +# ifdef _STLPORT_MAJOR +# define MOZ_USING_STLPORT 1 +# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) \ + (_STLPORT_VERSION >= ((major) << 8 | (minor) << 4 | (patch))) +# elif defined(_LIBCPP_VERSION) + /* + * libc++, unfortunately, doesn't appear to have useful versioning macros. + * Hopefully, the recommendations of N3694 with respect to standard libraries + * will get applied instead and we won't need to worry about version numbers + * here. + */ +# define MOZ_USING_LIBCXX 1 +# elif defined(__GLIBCXX__) +# define MOZ_USING_LIBSTDCXX 1 + /* + * libstdc++ is also annoying and doesn't give us useful versioning macros + * for the library. If we're using gcc, then assume that libstdc++ matches + * the compiler version. If we're using clang, we're going to have to fake + * major/minor combinations by looking for newly-defined config macros. + */ +# if MOZ_IS_GCC +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + MOZ_GCC_VERSION_AT_LEAST(major, minor, patch) +# elif defined(_GLIBCXX_THROW_OR_ABORT) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 8)) +# elif defined(_GLIBCXX_NOEXCEPT) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 7)) +# elif defined(_GLIBCXX_USE_DEPRECATED) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 6)) +# elif defined(_GLIBCXX_PSEUDO_VISIBILITY) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 5)) +# elif defined(_GLIBCXX_BEGIN_EXTERN_C) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 4)) +# elif defined(_GLIBCXX_VISIBILITY_ATTR) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 3)) +# elif defined(_GLIBCXX_VISIBILITY) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 2)) +# else +# error "Your version of libstdc++ is unknown to us and is likely too old." +# endif +# endif + + // Flesh out the defines for everyone else +# ifndef MOZ_USING_STLPORT +# define MOZ_USING_STLPORT 0 +# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) 0 +# endif +# ifndef MOZ_USING_LIBCXX +# define MOZ_USING_LIBCXX 0 +# endif +# ifndef MOZ_USING_LIBSTDCXX +# define MOZ_USING_LIBSTDCXX 0 +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) 0 +# endif +#endif /* __cplusplus */ + #endif /* mozilla_Compiler_h */ diff --git a/external/spidermonkey/include/android/mozilla/Compression.h b/external/spidermonkey/include/android/mozilla/Compression.h new file mode 100644 index 0000000000..da77fa895f --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/Compression.h @@ -0,0 +1,116 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* 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/. */ + +/* Various simple compression/decompression functions. */ + +#ifndef mozilla_Compression_h_ +#define mozilla_Compression_h_ + +#include "mozilla/Types.h" +#include "mozilla/Assertions.h" + +namespace mozilla { +namespace Compression { + +/** + * LZ4 is a very fast byte-wise compression algorithm. + * + * Compared to Google's Snappy it is faster to compress and decompress and + * generally produces output of about the same size. + * + * Compared to zlib it compresses at about 10x the speed, decompresses at about + * 4x the speed and produces output of about 1.5x the size. + * + */ + +class LZ4 +{ + +public: + + /** + * Compresses 'inputSize' bytes from 'source' into 'dest'. + * Destination buffer must be already allocated, + * and must be sized to handle worst cases situations (input data not compressible) + * Worst case size evaluation is provided by function LZ4_compressBound() + * + * @param inputSize is the input size. Max supported value is ~1.9GB + * @param return the number of bytes written in buffer dest + */ + static MFBT_API size_t compress(const char* source, size_t inputSize, char* dest); + + /** + * Compress 'inputSize' bytes from 'source' into an output buffer + * 'dest' of maximum size 'maxOutputSize'. If it cannot achieve it, + * compression will stop, and result of the function will be zero, + * 'dest' will still be written to, but since the number of input + * bytes consumed is not returned the result is not usable. + * + * This function never writes outside of provided output buffer. + * + * @param inputSize is the input size. Max supported value is ~1.9GB + * @param maxOutputSize is the size of the destination buffer (which must be already allocated) + * @return the number of bytes written in buffer 'dest' + or 0 if the compression fails + */ + static MFBT_API size_t compressLimitedOutput(const char* source, size_t inputSize, char* dest, + size_t maxOutputSize); + + /** + * If the source stream is malformed, the function will stop decoding + * and return a negative result, indicating the byte position of the + * faulty instruction + * + * This function never writes outside of provided buffers, and never + * modifies input buffer. + * + * note : destination buffer must be already allocated. + * its size must be a minimum of 'outputSize' bytes. + * @param outputSize is the output size, therefore the original size + * @return the number of bytes read in the source buffer + */ + static MFBT_API bool decompress(const char* source, char* dest, size_t outputSize); + + /** + * If the source stream is malformed, the function will stop decoding + * and return false. + * + * This function never writes beyond dest + maxOutputSize, and is + * therefore protected against malicious data packets. + * + * note : Destination buffer must be already allocated. + * This version is slightly slower than the decompress + * without the maxOutputSize + * + * @param inputSize is the length of the input compressed data + * @param maxOutputSize is the size of the destination buffer (which must be already allocated) + * @param outputSize the actual number of bytes decoded in the destination buffer (necessarily <= maxOutputSize) + + */ + static MFBT_API bool decompress(const char* source, size_t inputSize, char* dest, + size_t maxOutputSize, size_t *outputSize); + + /* + Provides the maximum size that LZ4 may output in a "worst case" + scenario (input data not compressible) primarily useful for memory + allocation of output buffer. + note : this function is limited by "int" range (2^31-1) + + @param inputSize is the input size. Max supported value is ~1.9GB + @return maximum output size in a "worst case" scenario + */ + static MFBT_API size_t maxCompressedSize(size_t inputSize) + { + size_t max = ((inputSize) + ((inputSize)/255) + 16); + MOZ_ASSERT(max > inputSize); + return max; + } + +}; + +} /* namespace Compression */ +} /* namespace mozilla */ + +#endif /* mozilla_Compression_h_ */ diff --git a/external/spidermonkey/include/android/mozilla/Endian.h b/external/spidermonkey/include/android/mozilla/Endian.h index dc6d11d3ba..cb6bd27c05 100644 --- a/external/spidermonkey/include/android/mozilla/Endian.h +++ b/external/spidermonkey/include/android/mozilla/Endian.h @@ -238,9 +238,9 @@ class EndianUtils { DebugOnly byteDestPtr = static_cast(dest); DebugOnly byteSrcPtr = static_cast(src); - MOZ_ASSERT((byteDestPtr < byteSrcPtr && + MOZ_ASSERT((byteDestPtr <= byteSrcPtr && byteDestPtr + count <= byteSrcPtr) || - (byteSrcPtr < byteDestPtr && + (byteSrcPtr <= byteDestPtr && byteSrcPtr + count <= byteDestPtr)); } diff --git a/external/spidermonkey/include/android/mozilla/FloatingPoint.h b/external/spidermonkey/include/android/mozilla/FloatingPoint.h index d80f6a7234..eff26b4bb8 100644 --- a/external/spidermonkey/include/android/mozilla/FloatingPoint.h +++ b/external/spidermonkey/include/android/mozilla/FloatingPoint.h @@ -12,6 +12,7 @@ #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Casting.h" +#include "mozilla/Types.h" #include @@ -58,6 +59,30 @@ static_assert((DoubleSignBit | DoubleExponentBits | DoubleSignificandBits) == ~uint64_t(0), "all bits accounted for"); +/* + * Ditto for |float| that must be a 32-bit double format number type, compatible + * with the IEEE-754 standard. + */ +static_assert(sizeof(float) == sizeof(uint32_t), "float must be 32bits"); + +const unsigned FloatExponentBias = 127; +const unsigned FloatExponentShift = 23; + +const uint32_t FloatSignBit = 0x80000000UL; +const uint32_t FloatExponentBits = 0x7F800000UL; +const uint32_t FloatSignificandBits = 0x007FFFFFUL; + +static_assert((FloatSignBit & FloatExponentBits) == 0, + "sign bit doesn't overlap exponent bits"); +static_assert((FloatSignBit & FloatSignificandBits) == 0, + "sign bit doesn't overlap significand bits"); +static_assert((FloatExponentBits & FloatSignificandBits) == 0, + "exponent bits don't overlap significand bits"); + +static_assert((FloatSignBit | FloatExponentBits | FloatSignificandBits) == + ~uint32_t(0), + "all bits accounted for"); + /** Determines whether a double is NaN. */ static MOZ_ALWAYS_INLINE bool IsNaN(double d) @@ -115,7 +140,12 @@ IsNegativeZero(double d) return bits == DoubleSignBit; } -/** Returns the exponent portion of the double. */ +/** + * Returns the exponent portion of the double. + * + * Zero is not special-cased, so ExponentComponent(0.0) is + * -int_fast16_t(DoubleExponentBias). + */ static MOZ_ALWAYS_INLINE int_fast16_t ExponentComponent(double d) { @@ -190,7 +220,13 @@ DoubleIsInt32(double d, int32_t* i) static MOZ_ALWAYS_INLINE double UnspecifiedNaN() { - return SpecificNaN(0, 0xfffffffffffffULL); + /* + * If we can use any quiet NaN, we might as well use the all-ones NaN, + * since it's cheap to materialize on common platforms (such as x64, where + * this value can be represented in a 32-bit signed immediate field, allowing + * it to be stored to memory in a single instruction). + */ + return SpecificNaN(1, 0xfffffffffffffULL); } /** @@ -206,6 +242,46 @@ DoublesAreIdentical(double d1, double d2) return BitwiseCast(d1) == BitwiseCast(d2); } +/** Determines whether a float is NaN. */ +static MOZ_ALWAYS_INLINE bool +IsFloatNaN(float f) +{ + /* + * A float is NaN if all exponent bits are 1 and the significand contains at + * least one non-zero bit. + */ + uint32_t bits = BitwiseCast(f); + return (bits & FloatExponentBits) == FloatExponentBits && + (bits & FloatSignificandBits) != 0; +} + +/** Constructs a NaN value with the specified sign bit and significand bits. */ +static MOZ_ALWAYS_INLINE float +SpecificFloatNaN(int signbit, uint32_t significand) +{ + MOZ_ASSERT(signbit == 0 || signbit == 1); + MOZ_ASSERT((significand & ~FloatSignificandBits) == 0); + MOZ_ASSERT(significand & FloatSignificandBits); + + float f = BitwiseCast((signbit ? FloatSignBit : 0) | + FloatExponentBits | + significand); + MOZ_ASSERT(IsFloatNaN(f)); + return f; +} + +/** + * Returns true if the given value can be losslessly represented as an IEEE-754 + * single format number, false otherwise. All NaN values are considered + * representable (notwithstanding that the exact bit pattern of a double format + * NaN value can't be exactly represented in single format). + * + * This function isn't inlined to avoid buggy optimizations by MSVC. + */ +MOZ_WARN_UNUSED_RESULT +extern MFBT_API bool +IsFloat32Representable(double x); + } /* namespace mozilla */ #endif /* mozilla_FloatingPoint_h */ diff --git a/external/spidermonkey/include/android/mozilla/HashFunctions.h b/external/spidermonkey/include/android/mozilla/HashFunctions.h index 6d0d24e7b1..b228955ce5 100644 --- a/external/spidermonkey/include/android/mozilla/HashFunctions.h +++ b/external/spidermonkey/include/android/mozilla/HashFunctions.h @@ -48,6 +48,7 @@ #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/Char16.h" #include "mozilla/Types.h" #include @@ -326,6 +327,22 @@ HashString(const uint16_t* str, size_t length) return detail::HashKnownLength(str, length); } +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +MOZ_WARN_UNUSED_RESULT +inline uint32_t +HashString(const char16_t* str) +{ + return detail::HashUntilZero(str); +} + +MOZ_WARN_UNUSED_RESULT +inline uint32_t +HashString(const char16_t* str, size_t length) +{ + return detail::HashKnownLength(str, length); +} +#endif + /* * On Windows, wchar_t (PRUnichar) is not the same as uint16_t, even though it's * the same width! diff --git a/external/spidermonkey/include/android/mozilla/IntegerPrintfMacros.h b/external/spidermonkey/include/android/mozilla/IntegerPrintfMacros.h new file mode 100644 index 0000000000..1ae60d618e --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/IntegerPrintfMacros.h @@ -0,0 +1,40 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* 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/. */ + +/* Implements the C99 interface, minus the SCN* format macros. */ + +#ifndef mozilla_IntegerPrintfMacros_h_ +#define mozilla_IntegerPrintfMacros_h_ + +/* + * MSVC++ doesn't include , even in versions shipping , so + * we have to reimplement it there. Note: #includes . + * + * Note that this header DOES NOT implement 's scanf macros. MSVC's + * scanf doesn't have sufficient format specifier support to implement them + * (specifically, to implement scanning into an 8-bit location). + * + * http://stackoverflow.com/questions/3036396/scanfd-char-char-as-int-format-string + * + * Moreover, scanf is a footgun: if the input number exceeds the bounds of the + * target type, behavior is undefined (in the compiler sense: that is, this code + * could overwrite your hard drive with zeroes): + * + * uint8_t u; + * sscanf("256", "%" SCNu8, &u); // BAD + * + * This header will sometimes provide SCN* macros, by dint of being implemented + * using . But for these reasons, *never* use them! + */ + +#if defined(MOZ_CUSTOM_INTTYPES_H) +# include MOZ_CUSTOM_INTTYPES_H +#elif defined(_MSC_VER) +# include "mozilla/MSIntTypes.h" +#else +# include +#endif + +#endif /* mozilla_IntegerPrintfMacros_h_ */ diff --git a/external/spidermonkey/include/android/mozilla/LinkedList.h b/external/spidermonkey/include/android/mozilla/LinkedList.h index c29760b3e7..f35e7d56ab 100644 --- a/external/spidermonkey/include/android/mozilla/LinkedList.h +++ b/external/spidermonkey/include/android/mozilla/LinkedList.h @@ -58,6 +58,7 @@ #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/Move.h" #include "mozilla/NullPtr.h" #ifdef __cplusplus @@ -116,6 +117,36 @@ class LinkedListElement isSentinel(false) { } + LinkedListElement(LinkedListElement&& other) + : isSentinel(other.isSentinel) + { + if (!other.isInList()) { + next = this; + prev = this; + return; + } + + MOZ_ASSERT(other.next->prev == &other); + MOZ_ASSERT(other.prev->next == &other); + + /* + * Initialize |this| with |other|'s prev/next pointers, and adjust those + * element to point to this one. + */ + next = other.next; + prev = other.prev; + + next->prev = this; + prev->next = this; + + /* + * Adjust |other| so it doesn't think it's in a list. This makes it + * safely destructable. + */ + other.next = &other; + other.prev = &other; + } + ~LinkedListElement() { if (!isSentinel && isInList()) remove(); @@ -148,8 +179,8 @@ class LinkedListElement * linked list when you call setNext(); otherwise, this method will assert. */ void setNext(T* elem) { - MOZ_ASSERT(isInList()); - setNextUnsafe(elem); + MOZ_ASSERT(isInList()); + setNextUnsafe(elem); } /* @@ -252,8 +283,8 @@ class LinkedListElement } private: - LinkedListElement& operator=(const LinkedList& other) MOZ_DELETE; - LinkedListElement(const LinkedList& other) MOZ_DELETE; + LinkedListElement& operator=(const LinkedListElement& other) MOZ_DELETE; + LinkedListElement(const LinkedListElement& other) MOZ_DELETE; }; template @@ -265,6 +296,10 @@ class LinkedList public: LinkedList() : sentinel(LinkedListElement::NODE_KIND_SENTINEL) { } + LinkedList(LinkedList&& other) + : sentinel(mozilla::Move(other.sentinel)) + { } + ~LinkedList() { MOZ_ASSERT(isEmpty()); } @@ -361,7 +396,7 @@ class LinkedList for (slow = sentinel.next, fast1 = sentinel.next->next, fast2 = sentinel.next->next->next; - slow != sentinel && fast1 != sentinel && fast2 != sentinel; + slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; slow = slow->next, fast1 = fast2->next, fast2 = fast1->next) { MOZ_ASSERT(slow != fast1); @@ -372,7 +407,7 @@ class LinkedList for (slow = sentinel.prev, fast1 = sentinel.prev->prev, fast2 = sentinel.prev->prev->prev; - slow != sentinel && fast1 != sentinel && fast2 != sentinel; + slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; slow = slow->prev, fast1 = fast2->prev, fast2 = fast1->prev) { MOZ_ASSERT(slow != fast1); @@ -384,14 +419,14 @@ class LinkedList * isSentinel == true. */ for (const LinkedListElement* elem = sentinel.next; - elem != sentinel; + elem != &sentinel; elem = elem->next) { MOZ_ASSERT(!elem->isSentinel); } /* Check that the next/prev pointers match up. */ - const LinkedListElement* prev = sentinel; + const LinkedListElement* prev = &sentinel; const LinkedListElement* cur = sentinel.next; do { MOZ_ASSERT(cur->prev == prev); @@ -399,7 +434,7 @@ class LinkedList prev = cur; cur = cur->next; - } while (cur != sentinel); + } while (cur != &sentinel); #endif /* ifdef DEBUG */ } diff --git a/external/spidermonkey/include/android/mozilla/MSIntTypes.h b/external/spidermonkey/include/android/mozilla/MSIntTypes.h new file mode 100644 index 0000000000..3dfba55f58 --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/MSIntTypes.h @@ -0,0 +1,198 @@ +// ISO C9x compliant inttypes.h for Microsoft Visual Studio +// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 +// +// Copyright (c) 2006 Alexander Chemeris +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// 3. The name of the author may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef _MSC_VER // [ +#error "Use this header only with Microsoft Visual C++ compilers!" +#endif // _MSC_VER ] + +#ifndef _MSC_INTTYPES_H_ // [ +#define _MSC_INTTYPES_H_ + +#if _MSC_VER > 1000 +#pragma once +#endif + +#include + +// 7.8 Format conversion of integer types + +typedef struct { + intmax_t quot; + intmax_t rem; +} imaxdiv_t; + +// 7.8.1 Macros for format specifiers + +#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 + +// The fprintf macros for signed integers are: +#define PRId8 "d" +#define PRIi8 "i" +#define PRIdLEAST8 "d" +#define PRIiLEAST8 "i" +#define PRIdFAST8 "d" +#define PRIiFAST8 "i" + +#define PRId16 "hd" +#define PRIi16 "hi" +#define PRIdLEAST16 "hd" +#define PRIiLEAST16 "hi" +#define PRIdFAST16 "hd" +#define PRIiFAST16 "hi" + +#define PRId32 "I32d" +#define PRIi32 "I32i" +#define PRIdLEAST32 "I32d" +#define PRIiLEAST32 "I32i" +#define PRIdFAST32 "I32d" +#define PRIiFAST32 "I32i" + +#define PRId64 "I64d" +#define PRIi64 "I64i" +#define PRIdLEAST64 "I64d" +#define PRIiLEAST64 "I64i" +#define PRIdFAST64 "I64d" +#define PRIiFAST64 "I64i" + +#define PRIdMAX "I64d" +#define PRIiMAX "I64i" + +#define PRIdPTR "Id" +#define PRIiPTR "Ii" + +// The fprintf macros for unsigned integers are: +#define PRIo8 "o" +#define PRIu8 "u" +#define PRIx8 "x" +#define PRIX8 "X" +#define PRIoLEAST8 "o" +#define PRIuLEAST8 "u" +#define PRIxLEAST8 "x" +#define PRIXLEAST8 "X" +#define PRIoFAST8 "o" +#define PRIuFAST8 "u" +#define PRIxFAST8 "x" +#define PRIXFAST8 "X" + +#define PRIo16 "ho" +#define PRIu16 "hu" +#define PRIx16 "hx" +#define PRIX16 "hX" +#define PRIoLEAST16 "ho" +#define PRIuLEAST16 "hu" +#define PRIxLEAST16 "hx" +#define PRIXLEAST16 "hX" +#define PRIoFAST16 "ho" +#define PRIuFAST16 "hu" +#define PRIxFAST16 "hx" +#define PRIXFAST16 "hX" + +#define PRIo32 "I32o" +#define PRIu32 "I32u" +#define PRIx32 "I32x" +#define PRIX32 "I32X" +#define PRIoLEAST32 "I32o" +#define PRIuLEAST32 "I32u" +#define PRIxLEAST32 "I32x" +#define PRIXLEAST32 "I32X" +#define PRIoFAST32 "I32o" +#define PRIuFAST32 "I32u" +#define PRIxFAST32 "I32x" +#define PRIXFAST32 "I32X" + +#define PRIo64 "I64o" +#define PRIu64 "I64u" +#define PRIx64 "I64x" +#define PRIX64 "I64X" +#define PRIoLEAST64 "I64o" +#define PRIuLEAST64 "I64u" +#define PRIxLEAST64 "I64x" +#define PRIXLEAST64 "I64X" +#define PRIoFAST64 "I64o" +#define PRIuFAST64 "I64u" +#define PRIxFAST64 "I64x" +#define PRIXFAST64 "I64X" + +#define PRIoMAX "I64o" +#define PRIuMAX "I64u" +#define PRIxMAX "I64x" +#define PRIXMAX "I64X" + +#define PRIoPTR "Io" +#define PRIuPTR "Iu" +#define PRIxPTR "Ix" +#define PRIXPTR "IX" + +// DO NOT SUPPORT THE scanf MACROS! See the comment at the top of +// IntegerPrintfMacros.h. + +#endif // __STDC_FORMAT_MACROS ] + +// 7.8.2 Functions for greatest-width integer types + +// 7.8.2.1 The imaxabs function +#define imaxabs _abs64 + +// 7.8.2.2 The imaxdiv function + +// This is modified version of div() function from Microsoft's div.c found +// in %MSVC.NET%\crt\src\div.c +#ifdef STATIC_IMAXDIV // [ +static +#else // STATIC_IMAXDIV ][ +_inline +#endif // STATIC_IMAXDIV ] +imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) +{ + imaxdiv_t result; + + result.quot = numer / denom; + result.rem = numer % denom; + + if (numer < 0 && result.rem > 0) { + // did division wrong; must fix up + ++result.quot; + result.rem -= denom; + } + + return result; +} + +// 7.8.2.3 The strtoimax and strtoumax functions +#define strtoimax _strtoi64 +#define strtoumax _strtoui64 + +// 7.8.2.4 The wcstoimax and wcstoumax functions +#define wcstoimax _wcstoi64 +#define wcstoumax _wcstoui64 + + +#endif // _MSC_INTTYPES_H_ ] diff --git a/external/spidermonkey/include/android/mozilla/MathAlgorithms.h b/external/spidermonkey/include/android/mozilla/MathAlgorithms.h index 6d58691e06..941ac81271 100644 --- a/external/spidermonkey/include/android/mozilla/MathAlgorithms.h +++ b/external/spidermonkey/include/android/mozilla/MathAlgorithms.h @@ -186,6 +186,16 @@ namespace detail { return uint_fast8_t(index); } + inline uint_fast8_t + CountPopulation32(uint32_t u) + { + uint32_t sum2 = (u & 0x55555555) + ((u & 0xaaaaaaaa) >> 1); + uint32_t sum4 = (sum2 & 0x33333333) + ((sum2 & 0xcccccccc) >> 2); + uint32_t sum8 = (sum4 & 0x0f0f0f0f) + ((sum4 & 0xf0f0f0f0) >> 4); + uint32_t sum16 = (sum8 & 0x00ff00ff) + ((sum8 & 0xff00ff00) >> 8); + return sum16; + } + inline uint_fast8_t CountLeadingZeroes64(uint64_t u) { @@ -242,6 +252,12 @@ namespace detail { return __builtin_ctz(u); } + inline uint_fast8_t + CountPopulation32(uint32_t u) + { + return __builtin_popcount(u); + } + inline uint_fast8_t CountLeadingZeroes64(uint64_t u) { @@ -258,6 +274,7 @@ namespace detail { # error "Implement these!" inline uint_fast8_t CountLeadingZeroes32(uint32_t u) MOZ_DELETE; inline uint_fast8_t CountTrailingZeroes32(uint32_t u) MOZ_DELETE; + inline uint_fast8_t CountPopulation32(uint32_t u) MOZ_DELETE; inline uint_fast8_t CountLeadingZeroes64(uint64_t u) MOZ_DELETE; inline uint_fast8_t CountTrailingZeroes64(uint64_t u) MOZ_DELETE; #endif @@ -300,6 +317,15 @@ CountTrailingZeroes32(uint32_t u) return detail::CountTrailingZeroes32(u); } +/** + * Compute the number of one bits in the number |u|, + */ +inline uint_fast8_t +CountPopulation32(uint32_t u) +{ + return detail::CountPopulation32(u); +} + /** Analogous to CountLeadingZeroes32, but for 64-bit numbers. */ inline uint_fast8_t CountLeadingZeroes64(uint64_t u) diff --git a/external/spidermonkey/include/android/mozilla/Maybe.h b/external/spidermonkey/include/android/mozilla/Maybe.h new file mode 100644 index 0000000000..25683a28ab --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/Maybe.h @@ -0,0 +1,163 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=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/. */ + +/* A class for lazily constructing an object without sticking it on the heap. */ + +#ifndef mozilla_Maybe_h +#define mozilla_Maybe_h + +#include "mozilla/Alignment.h" +#include "mozilla/Assertions.h" + +// For placement new +#include + +namespace mozilla { + +/* + * Small utility for lazily constructing objects without using dynamic storage. + * When a Maybe is constructed, it is |empty()|, i.e., no value of T has + * been constructed and no T destructor will be called when the Maybe is + * destroyed. Upon calling |construct|, a T object will be constructed with the + * given arguments and that object will be destroyed when the owning Maybe + * is destroyed. + * + * N.B. GCC seems to miss some optimizations with Maybe and may generate extra + * branches/loads/stores. Use with caution on hot paths. + */ +template +class Maybe +{ + AlignedStorage2 storage; + bool constructed; + + T& asT() { return *storage.addr(); } + + public: + Maybe() { constructed = false; } + ~Maybe() { if (constructed) asT().~T(); } + + bool empty() const { return !constructed; } + + void construct() { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(); + constructed = true; + } + + template + void construct(const T1& t1) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); + constructed = true; + } + + T* addr() { + MOZ_ASSERT(constructed); + return &asT(); + } + + T& ref() { + MOZ_ASSERT(constructed); + return asT(); + } + + const T& ref() const { + MOZ_ASSERT(constructed); + return const_cast(this)->asT(); + } + + void destroy() { + ref().~T(); + constructed = false; + } + + void destroyIfConstructed() { + if (!empty()) + destroy(); + } + + private: + Maybe(const Maybe& other) MOZ_DELETE; + const Maybe& operator=(const Maybe& other) MOZ_DELETE; +}; + +} // namespace mozilla + +#endif /* mozilla_Maybe_h */ diff --git a/external/spidermonkey/include/android/mozilla/Move.h b/external/spidermonkey/include/android/mozilla/Move.h index 97178daaa6..a18da32ad8 100644 --- a/external/spidermonkey/include/android/mozilla/Move.h +++ b/external/spidermonkey/include/android/mozilla/Move.h @@ -9,11 +9,21 @@ #ifndef mozilla_Move_h #define mozilla_Move_h +#include "mozilla/TypeTraits.h" + namespace mozilla { /* * "Move" References * + * [Once upon a time, C++11 rvalue references were not implemented by all the + * compilers we cared about, so we invented mozilla::Move() (now called + * OldMove()), which does something similar. We're in the process of + * transitioning away from this to pure stl (bug 896100). Until that bug is + * completed, this header will provide both mozilla::OldMove() and + * mozilla::Move().] + * + * * Some types can be copied much more efficiently if we know the original's * value need not be preserved --- that is, if we are doing a "move", not a * "copy". For example, if we have: @@ -48,18 +58,28 @@ namespace mozilla { * efficiently than it can be copied, and provide an implementation of that * move operation. * - * The Move(T&) function takes a reference to a T, and returns a MoveRef - * referring to the same value; that's 1). A MoveRef is simply a reference + * The OldMove(T&) function takes a reference to a T, and returns a MoveRef + * referring to the same value; that's (1). A MoveRef is simply a reference * to a T, annotated to say that a copy constructor applied to it may move that * T, instead of copying it. Finally, a constructor that accepts an MoveRef - * should perform a more efficient move, instead of a copy, providing 2). + * should perform a more efficient move, instead of a copy, providing (2). * - * So, where we might define a copy constructor for a class C like this: + * The Move(T&) function takes a reference to a T and returns a T&&. It acts + * just like std::move(), which is not available on all our platforms. + * + * In new code, you should use Move(T&) and T&& instead of OldMove(T&) and + * MoveRef, where possible. + * + * Where we might define a copy constructor for a class C like this: * * C(const C& rhs) { ... copy rhs to this ... } * * we would declare a move constructor like this: * + * C(C&& rhs) { .. move rhs to this ... } + * + * or, in the deprecated OldMove style: + * * C(MoveRef rhs) { ... move rhs to this ... } * * And where we might perform a copy like this: @@ -68,7 +88,11 @@ namespace mozilla { * * we would perform a move like this: * - * C c2(Move(c1)) + * C c2(Move(c1)); + * + * or, in the deprecated OldMove style: + * + * C c2(OldMove(c1)); * * Note that MoveRef implicitly converts to T&, so you can pass a MoveRef * to an ordinary copy constructor for a type that doesn't support a special @@ -82,7 +106,7 @@ namespace mozilla { * which runs this's destructor, and then applies the move constructor to * *this's memory. A typical definition: * - * C& operator=(MoveRef rhs) { + * C& operator=(C&& rhs) { // or |MoveRef rhs| * this->~C(); * new(this) C(rhs); * return *this; @@ -90,14 +114,14 @@ namespace mozilla { * * With that in place, one can write move assignments like this: * - * c2 = Move(c1); + * c2 = Move(c1); // or OldMove() * * This destroys c1, moves c1's value to c2, and leaves c1 in an undefined but * destructible state. * - * This header file defines MoveRef and Move in the mozilla namespace. It's up - * to individual containers to annotate moves as such, by calling Move; and it's - * up to individual types to define move constructors. + * This header file defines MoveRef, Move, and OldMove in the mozilla namespace. + * It's up to individual containers to annotate moves as such, by calling Move + * or OldMove; and it's up to individual types to define move constructors. * * One hint: if you're writing a move constructor where the type has members * that should be moved themselves, it's much nicer to write this: @@ -125,14 +149,14 @@ class MoveRef template inline MoveRef -Move(T& t) +OldMove(T& t) { return MoveRef(t); } template inline MoveRef -Move(const T& t) +OldMove(const T& t) { // With some versions of gcc, for a class C, there's an (incorrect) ambiguity // between the C(const C&) constructor and the default C(C&&) C++11 move @@ -151,14 +175,45 @@ Move(const T& t) return MoveRef(const_cast(t)); } +/** + * Identical to std::Move(); this is necessary until our stlport supports + * std::move(). + */ +template +inline typename RemoveReference::Type&& +Move(T&& a) +{ + return static_cast::Type&&>(a); +} + +/** + * These two overloads are identidal to std::Forward(); they are necessary until + * our stlport supports std::forward(). + */ +template +inline T&& +Forward(typename RemoveReference::Type& a) +{ + return static_cast(a); +} + +template +inline T&& +Forward(typename RemoveReference::Type&& t) +{ + static_assert(!IsLvalueReference::value, + "misuse of Forward detected! try the other overload"); + return static_cast(t); +} + /** Swap |t| and |u| using move-construction if possible. */ template inline void Swap(T& t, T& u) { - T tmp(Move(t)); - t = Move(u); - u = Move(tmp); + T tmp(OldMove(t)); + t = OldMove(u); + u = OldMove(tmp); } } // namespace mozilla diff --git a/external/spidermonkey/include/android/mozilla/NullPtr.h b/external/spidermonkey/include/android/mozilla/NullPtr.h index 14c0f07df2..35faadc4c3 100644 --- a/external/spidermonkey/include/android/mozilla/NullPtr.h +++ b/external/spidermonkey/include/android/mozilla/NullPtr.h @@ -12,8 +12,6 @@ #ifndef mozilla_NullPtr_h #define mozilla_NullPtr_h -#include "mozilla/Compiler.h" - #if defined(__clang__) # ifndef __has_extension # define __has_extension __has_feature @@ -23,6 +21,7 @@ # endif #elif defined(__GNUC__) # if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L +# include "mozilla/Compiler.h" # if MOZ_GCC_VERSION_AT_LEAST(4, 6, 0) # define MOZ_HAVE_CXX11_NULLPTR # endif diff --git a/external/spidermonkey/include/android/mozilla/NumericLimits.h b/external/spidermonkey/include/android/mozilla/NumericLimits.h new file mode 100644 index 0000000000..d2ee29813e --- /dev/null +++ b/external/spidermonkey/include/android/mozilla/NumericLimits.h @@ -0,0 +1,40 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=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/. */ + +/* Compatibility with std::numeric_limits. */ + +#ifndef mozilla_NumericLimits_h +#define mozilla_NumericLimits_h + +#include "mozilla/Char16.h" + +#include +#include + +namespace mozilla { + +/** + * The NumericLimits class provides a compatibility layer with std::numeric_limits + * for char16_t, otherwise it is exactly the same as std::numeric_limits. + * Code which does not need std::numeric_limits should avoid using + * NumericLimits. + */ +template +class NumericLimits : public std::numeric_limits +{ +}; + +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> +class NumericLimits : public std::numeric_limits +{ + // char16_t and uint16_t numeric limits should be exactly the same. +}; +#endif + +} // namespace mozilla + +#endif /* mozilla_NumericLimits_h */ diff --git a/external/spidermonkey/include/android/mozilla/PodOperations.h b/external/spidermonkey/include/android/mozilla/PodOperations.h index bec89fa928..668197cdc1 100644 --- a/external/spidermonkey/include/android/mozilla/PodOperations.h +++ b/external/spidermonkey/include/android/mozilla/PodOperations.h @@ -24,7 +24,7 @@ namespace mozilla { /** Set the contents of |t| to 0. */ template -static void +static MOZ_ALWAYS_INLINE void PodZero(T* t) { memset(t, 0, sizeof(T)); @@ -32,7 +32,7 @@ PodZero(T* t) /** Set the contents of |nelem| elements starting at |t| to 0. */ template -static void +static MOZ_ALWAYS_INLINE void PodZero(T* t, size_t nelem) { /* @@ -58,7 +58,7 @@ static void PodZero(T (&t)[N], size_t nelem) MOZ_DELETE; /** Set the contents of the array |t| to zero. */ template -static void +static MOZ_ALWAYS_INLINE void PodArrayZero(T (&t)[N]) { memset(t, 0, N * sizeof(T)); @@ -69,7 +69,7 @@ PodArrayZero(T (&t)[N]) * overlap. */ template -static void +static MOZ_ALWAYS_INLINE void PodAssign(T* dst, const T* src) { MOZ_ASSERT(dst != src); @@ -83,7 +83,7 @@ PodAssign(T* dst, const T* src) * overlap! */ template -MOZ_ALWAYS_INLINE static void +static MOZ_ALWAYS_INLINE void PodCopy(T* dst, const T* src, size_t nelem) { MOZ_ASSERT(dst != src); @@ -103,7 +103,7 @@ PodCopy(T* dst, const T* src, size_t nelem) } template -MOZ_ALWAYS_INLINE static void +static MOZ_ALWAYS_INLINE void PodCopy(volatile T* dst, const volatile T* src, size_t nelem) { MOZ_ASSERT(dst != src); @@ -127,7 +127,7 @@ PodCopy(volatile T* dst, const volatile T* src, size_t nelem) * The arrays must not overlap! */ template -static void +static MOZ_ALWAYS_INLINE void PodArrayCopy(T (&dst)[N], const T (&src)[N]) { PodCopy(dst, src, N); @@ -138,7 +138,7 @@ PodArrayCopy(T (&dst)[N], const T (&src)[N]) * |len| elements at |two|. */ template -MOZ_ALWAYS_INLINE static bool +static MOZ_ALWAYS_INLINE bool PodEqual(const T* one, const T* two, size_t len) { if (len < 128) { diff --git a/external/spidermonkey/include/android/mozilla/RefPtr.h b/external/spidermonkey/include/android/mozilla/RefPtr.h index 3c275afdc7..72c7904554 100644 --- a/external/spidermonkey/include/android/mozilla/RefPtr.h +++ b/external/spidermonkey/include/android/mozilla/RefPtr.h @@ -68,18 +68,18 @@ class RefCounted public: // Compatibility with nsRefPtr. - void AddRef() { + void AddRef() const { MOZ_ASSERT(refCnt >= 0); ++refCnt; } - void Release() { + void Release() const { MOZ_ASSERT(refCnt > 0); if (0 == --refCnt) { #ifdef DEBUG refCnt = detail::DEAD; #endif - delete static_cast(this); + delete static_cast(this); } } @@ -93,7 +93,7 @@ class RefCounted } private: - typename Conditional, int>::Type refCnt; + mutable typename Conditional, int>::Type refCnt; }; } diff --git a/external/spidermonkey/include/android/mozilla/TypeTraits.h b/external/spidermonkey/include/android/mozilla/TypeTraits.h index 53c0b5c2f6..1ccd0c85d1 100644 --- a/external/spidermonkey/include/android/mozilla/TypeTraits.h +++ b/external/spidermonkey/include/android/mozilla/TypeTraits.h @@ -63,6 +63,9 @@ template<> struct IsIntegralHelper : TrueType {}; template<> struct IsIntegralHelper : TrueType {}; template<> struct IsIntegralHelper : TrueType {}; template<> struct IsIntegralHelper : TrueType {}; +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> struct IsIntegralHelper : TrueType {}; +#endif } /* namespace detail */ @@ -218,6 +221,9 @@ template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> struct IsPod : TrueType {}; +#endif template struct IsPod : TrueType {}; namespace detail { @@ -418,6 +424,16 @@ struct IsConvertible : IntegralConstant::value> {}; +/** + * Is IsLvalueReference is true if its template param is T& and is false if + * its type is T or T&&. + */ +template +struct IsLvalueReference : FalseType {}; + +template +struct IsLvalueReference : TrueType {}; + /* 20.9.7 Transformations between types [meta.trans] */ /* 20.9.7.1 Const-volatile modifications [meta.trans.cv] */ @@ -478,6 +494,32 @@ struct RemoveCV /* 20.9.7.2 Reference modifications [meta.trans.ref] */ +/** + * Converts reference types to the underlying types. + * + * mozilla::RemoveReference::Type is T; + * mozilla::RemoveReference::Type is T; + * mozilla::RemoveReference::Type is T; + */ + +template +struct RemoveReference +{ + typedef T Type; +}; + +template +struct RemoveReference +{ + typedef T Type; +}; + +template +struct RemoveReference +{ + typedef T Type; +}; + /* 20.9.7.3 Sign modifications [meta.trans.sign] */ template diff --git a/external/spidermonkey/include/android/mozilla/TypedEnum.h b/external/spidermonkey/include/android/mozilla/TypedEnum.h index 6f595cb4c5..9c7590deff 100644 --- a/external/spidermonkey/include/android/mozilla/TypedEnum.h +++ b/external/spidermonkey/include/android/mozilla/TypedEnum.h @@ -28,7 +28,7 @@ # endif #elif defined(__GNUC__) # if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L -# if MOZ_GCC_VERSION_AT_LEAST(4, 5, 1) +# if MOZ_GCC_VERSION_AT_LEAST(4, 6, 3) # define MOZ_HAVE_CXX11_ENUM_TYPE # define MOZ_HAVE_CXX11_STRONG_ENUMS # endif @@ -72,7 +72,7 @@ * strongly-typed enumeration feature of C++11 ("enum class"). If supported * by the compiler, an enum defined using these macros will not be implicitly * converted to any other type, and its enumerators will be scoped using the - * enumeration name. Place MOZ_BEGIN_ENUM_CLASS(EnumName, type) in place of + * enumeration name. Place MOZ_BEGIN_ENUM_CLASS(EnumName [, type]) in place of * "enum EnumName {", and MOZ_END_ENUM_CLASS(EnumName) in place of the closing * "};". For example, * @@ -87,10 +87,9 @@ * fail. In other compilers, Enum itself will actually be defined as a class, * and some implicit conversions will fail while others will succeed. * - * The type argument specifies the underlying type for the enum where - * supported, as with MOZ_ENUM_TYPE(). For simplicity, it is currently - * mandatory. As with MOZ_ENUM_TYPE(), it will do nothing on compilers that do - * not support it. + * The optional type argument specifies the underlying type for the enum where + * supported, as with MOZ_ENUM_TYPE(). As with MOZ_ENUM_TYPE(), it will do + * nothing on compilers that do not support it. * * MOZ_{BEGIN,END}_ENUM_CLASS doesn't work for defining enum classes nested * inside classes. To define an enum class nested inside another class, use @@ -114,7 +113,12 @@ * All compilers that support strong enums also support an explicit * underlying type, so no extra check is needed. */ -# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ + + /* Single-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER1(Name) \ + enum class Name { + /* Two-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER2(Name, type) \ enum class Name : type { # define MOZ_END_NESTED_ENUM_CLASS(Name) \ }; @@ -154,8 +158,17 @@ * { * return Enum::A; * } - */\ -# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ + */ + + /* Single-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER1(Name) \ + class Name \ + { \ + public: \ + enum Enum \ + { + /* Two-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER2(Name, type) \ class Name \ { \ public: \ @@ -226,7 +239,36 @@ inline int& operator<<=(int&, const Name::Enum&) MOZ_DELETE; \ inline int& operator>>=(int&, const Name::Enum&) MOZ_DELETE; #endif -# define MOZ_BEGIN_ENUM_CLASS(Name, type) MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) + + /* + * Count the number of arguments passed to MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS, + * very carefully tiptoeing around an MSVC bug where it improperly expands + * __VA_ARGS__ as a single token in argument lists. See these URLs for + * details: + * + * http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement + * http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/#comment-644 + */ +# define MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL2(_1, _2, count, ...) \ + count +# define MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL(args) \ + MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL2 args +# define MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS(...) \ + MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL((__VA_ARGS__, 2, 1, 0)) + /* Pick the right helper macro to invoke. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER2(count) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER##count +# define MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER1(count) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER2(count) +# define MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER(count) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER1(count) + /* The actual macro. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_GLUE(x, y) x y +# define MOZ_BEGIN_NESTED_ENUM_CLASS(...) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_GLUE(MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER(MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS(__VA_ARGS__)), \ + (__VA_ARGS__)) + +# define MOZ_BEGIN_ENUM_CLASS(...) MOZ_BEGIN_NESTED_ENUM_CLASS(__VA_ARGS__) # define MOZ_END_ENUM_CLASS(Name) \ MOZ_END_NESTED_ENUM_CLASS(Name) \ MOZ_FINISH_NESTED_ENUM_CLASS(Name) diff --git a/external/spidermonkey/include/android/mozilla/Util.h b/external/spidermonkey/include/android/mozilla/Util.h index 4f1c634a59..b4cf2e425b 100644 --- a/external/spidermonkey/include/android/mozilla/Util.h +++ b/external/spidermonkey/include/android/mozilla/Util.h @@ -18,267 +18,10 @@ #ifdef __cplusplus +#include "mozilla/Alignment.h" + namespace mozilla { -/* - * This class, and the corresponding macro MOZ_ALIGNOF, figure out how many - * bytes of alignment a given type needs. - */ -template -class AlignmentFinder -{ - struct Aligner - { - char c; - T t; - }; - - public: - static const size_t alignment = sizeof(Aligner) - sizeof(T); -}; - -#define MOZ_ALIGNOF(T) mozilla::AlignmentFinder::alignment - -/* - * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types. - * - * For instance, - * - * MOZ_ALIGNED_DECL(char arr[2], 8); - * - * will declare a two-character array |arr| aligned to 8 bytes. - */ - -#if defined(__GNUC__) -# define MOZ_ALIGNED_DECL(_type, _align) \ - _type __attribute__((aligned(_align))) -#elif defined(_MSC_VER) -# define MOZ_ALIGNED_DECL(_type, _align) \ - __declspec(align(_align)) _type -#else -# warning "We don't know how to align variables on this compiler." -# define MOZ_ALIGNED_DECL(_type, _align) _type -#endif - -/* - * AlignedElem is a structure whose alignment is guaranteed to be at least N - * bytes. - * - * We support 1, 2, 4, 8, and 16-bit alignment. - */ -template -struct AlignedElem; - -/* - * We have to specialize this template because GCC doesn't like __attribute__((aligned(foo))) where - * foo is a template parameter. - */ - -template<> -struct AlignedElem<1> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 1); -}; - -template<> -struct AlignedElem<2> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 2); -}; - -template<> -struct AlignedElem<4> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 4); -}; - -template<> -struct AlignedElem<8> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 8); -}; - -template<> -struct AlignedElem<16> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 16); -}; - -/* - * This utility pales in comparison to Boost's aligned_storage. The utility - * simply assumes that uint64_t is enough alignment for anyone. This may need - * to be extended one day... - * - * As an important side effect, pulling the storage into this template is - * enough obfuscation to confuse gcc's strict-aliasing analysis into not giving - * false negatives when we cast from the char buffer to whatever type we've - * constructed using the bytes. - */ -template -struct AlignedStorage -{ - union U { - char bytes[nbytes]; - uint64_t _; - } u; - - const void* addr() const { return u.bytes; } - void* addr() { return u.bytes; } -}; - -template -struct AlignedStorage2 -{ - union U { - char bytes[sizeof(T)]; - uint64_t _; - } u; - - const T* addr() const { return reinterpret_cast(u.bytes); } - T* addr() { return static_cast(static_cast(u.bytes)); } -}; - -/* - * Small utility for lazily constructing objects without using dynamic storage. - * When a Maybe is constructed, it is |empty()|, i.e., no value of T has - * been constructed and no T destructor will be called when the Maybe is - * destroyed. Upon calling |construct|, a T object will be constructed with the - * given arguments and that object will be destroyed when the owning Maybe - * is destroyed. - * - * N.B. GCC seems to miss some optimizations with Maybe and may generate extra - * branches/loads/stores. Use with caution on hot paths. - */ -template -class Maybe -{ - AlignedStorage2 storage; - bool constructed; - - T& asT() { return *storage.addr(); } - - public: - Maybe() { constructed = false; } - ~Maybe() { if (constructed) asT().~T(); } - - bool empty() const { return !constructed; } - - void construct() { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(); - constructed = true; - } - - template - void construct(const T1& t1) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7, const T8& t8) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7, const T8& t8, const T9& t9) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); - constructed = true; - } - - T* addr() { - MOZ_ASSERT(constructed); - return &asT(); - } - - T& ref() { - MOZ_ASSERT(constructed); - return asT(); - } - - const T& ref() const { - MOZ_ASSERT(constructed); - return const_cast(this)->asT(); - } - - void destroy() { - ref().~T(); - constructed = false; - } - - void destroyIfConstructed() { - if (!empty()) - destroy(); - } - - private: - Maybe(const Maybe& other) MOZ_DELETE; - const Maybe& operator=(const Maybe& other) MOZ_DELETE; -}; - /* * Safely subtract two pointers when it is known that end >= begin. This avoids * the common compiler bug that if (size_t(end) - size_t(begin)) has the MSB diff --git a/external/spidermonkey/include/android/mozilla/Vector.h b/external/spidermonkey/include/android/mozilla/Vector.h index 8759df8c06..54e266eeb7 100644 --- a/external/spidermonkey/include/android/mozilla/Vector.h +++ b/external/spidermonkey/include/android/mozilla/Vector.h @@ -9,6 +9,7 @@ #ifndef mozilla_Vector_h #define mozilla_Vector_h +#include "mozilla/Alignment.h" #include "mozilla/AllocPolicy.h" #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" @@ -19,7 +20,7 @@ #include "mozilla/ReentrancyGuard.h" #include "mozilla/TemplateLib.h" #include "mozilla/TypeTraits.h" -#include "mozilla/Util.h" +#include "mozilla/Util.h" // for PointerRangeSize #include // for placement new @@ -85,7 +86,7 @@ struct VectorImpl template static inline void moveConstruct(T* dst, const U* srcbeg, const U* srcend) { for (const U* p = srcbeg; p < srcend; ++p, ++dst) - new(dst) T(Move(*p)); + new(dst) T(OldMove(*p)); } /* @@ -114,7 +115,7 @@ struct VectorImpl T* dst = newbuf; T* src = v.beginNoCheck(); for (; src < v.endNoCheck(); ++dst, ++src) - new(dst) T(Move(*src)); + new(dst) T(OldMove(*src)); VectorImpl::destroy(v.beginNoCheck(), v.endNoCheck()); v.free_(v.mBegin); v.mBegin = newbuf; @@ -547,8 +548,8 @@ class VectorBase : private AllocPolicy void swap(ThisVector& other); private: - VectorBase(const ThisVector&) MOZ_DELETE; - void operator=(const ThisVector&) MOZ_DELETE; + VectorBase(const VectorBase&) MOZ_DELETE; + void operator=(const VectorBase&) MOZ_DELETE; }; /* This does the re-entrancy check plus several other sanity checks. */ @@ -565,14 +566,15 @@ template MOZ_ALWAYS_INLINE VectorBase::VectorBase(AP ap) : AP(ap), - mBegin(static_cast(storage.addr())), mLength(0), mCapacity(sInlineCapacity) #ifdef DEBUG , mReserved(sInlineCapacity), entered(false) #endif -{} +{ + mBegin = static_cast(storage.addr()); +} /* Move constructor. */ template diff --git a/external/spidermonkey/include/android/mozilla/WeakPtr.h b/external/spidermonkey/include/android/mozilla/WeakPtr.h index c714ebf565..0165e3a017 100644 --- a/external/spidermonkey/include/android/mozilla/WeakPtr.h +++ b/external/spidermonkey/include/android/mozilla/WeakPtr.h @@ -14,9 +14,6 @@ * the WeakPtrs to it and allows the WeakReference to live beyond the lifetime * of 'Foo'. * - * AtomicSupportsWeakPtr can be used for a variant with an atomically updated - * reference counter. - * * The overhead of WeakPtr is that accesses to 'Foo' becomes an additional * dereference, and an additional heap allocated pointer sized object shared * between all of the WeakPtrs. @@ -63,7 +60,6 @@ #define mozilla_WeakPtr_h #include "mozilla/Assertions.h" -#include "mozilla/Atomics.h" #include "mozilla/NullPtr.h" #include "mozilla/RefPtr.h" #include "mozilla/TypeTraits.h" @@ -76,8 +72,8 @@ template class SupportsWeakPtrBase; namespace detail { // This can live beyond the lifetime of the class derived from SupportsWeakPtrBase. -template -class WeakReference : public RefCounted, Atomicity> +template +class WeakReference : public ::mozilla::RefCounted > { public: explicit WeakReference(T* p) : ptr(p) {} @@ -86,8 +82,8 @@ class WeakReference : public RefCounted, Atomicity> } private: - friend class WeakPtrBase; - friend class SupportsWeakPtrBase; + friend class WeakPtrBase >; + friend class SupportsWeakPtrBase >; void detach() { ptr = nullptr; } @@ -121,30 +117,10 @@ class SupportsWeakPtrBase }; template -class SupportsWeakPtr - : public SupportsWeakPtrBase > +class SupportsWeakPtr : public SupportsWeakPtrBase > { }; -template -class AtomicSupportsWeakPtr - : public SupportsWeakPtrBase > -{ -}; - -namespace detail { - -template -struct WeakReferenceCount -{ - static const RefCountAtomicity atomicity = - IsBaseOf, T>::value - ? AtomicRefCount - : NonAtomicRefCount; -}; - -} - template class WeakPtrBase { @@ -177,9 +153,9 @@ class WeakPtrBase }; template -class WeakPtr : public WeakPtrBase::atomicity> > +class WeakPtr : public WeakPtrBase > { - typedef WeakPtrBase::atomicity> > Base; + typedef WeakPtrBase > Base; public: WeakPtr(const WeakPtr& o) : Base(o) {} WeakPtr(const Base& o) : Base(o) {} diff --git a/external/spidermonkey/include/ios/js-config.h b/external/spidermonkey/include/ios/js-config.h index 4b893482f4..b1563e37e9 100644 --- a/external/spidermonkey/include/ios/js-config.h +++ b/external/spidermonkey/include/ios/js-config.h @@ -5,8 +5,8 @@ * 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/. */ -#ifndef js_config_h___ -#define js_config_h___ +#ifndef js_config_h +#define js_config_h /* Definitions set at build time that affect SpiderMonkey's public API. This header file is generated by the SpiderMonkey configure script, @@ -34,12 +34,8 @@ useable. See jscpucfg.h. */ /* #undef JS_HAVE_SYS_ISA_DEFS_H */ -/* The configure script defines these if it doesn't #define - JS_HAVE_STDINT_H. */ -#define JS_BYTES_PER_WORD 4 - /* MOZILLA JSAPI version number components */ -#define MOZJS_MAJOR_VERSION 25 +#define MOZJS_MAJOR_VERSION 27 #define MOZJS_MINOR_VERSION 0 -#endif /* js_config_h___ */ +#endif /* js_config_h */ diff --git a/external/spidermonkey/include/ios/js.msg b/external/spidermonkey/include/ios/js.msg index 3f665d8d54..da7361d5df 100644 --- a/external/spidermonkey/include/ios/js.msg +++ b/external/spidermonkey/include/ios/js.msg @@ -221,8 +221,8 @@ MSG_DEF(JSMSG_CANT_DECODE_PRINCIPALS, 167, 0, JSEXN_INTERNALERR, "can't decode J MSG_DEF(JSMSG_CANT_SEAL_OBJECT, 168, 1, JSEXN_ERR, "can't seal {0} objects") MSG_DEF(JSMSG_TOO_MANY_CATCH_VARS, 169, 0, JSEXN_SYNTAXERR, "too many catch variables") MSG_DEF(JSMSG_NEGATIVE_REPETITION_COUNT, 170, 0, JSEXN_RANGEERR, "repeat count must be non-negative") -MSG_DEF(JSMSG_UNUSED171, 171, 0, JSEXN_NONE, "") -MSG_DEF(JSMSG_UNUSED172, 172, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_INVALID_FOR_OF_INIT, 171, 0, JSEXN_SYNTAXERR, "for-of loop variable declaration may not have an initializer") +MSG_DEF(JSMSG_INVALID_MAP_ITERABLE, 172, 0, JSEXN_TYPEERR, "iterable for map should have array-like objects") MSG_DEF(JSMSG_UNUSED173, 173, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED174, 174, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_NESTING_GENERATOR, 175, 0, JSEXN_TYPEERR, "already executing generator") @@ -233,8 +233,8 @@ MSG_DEF(JSMSG_UNUSED179, 179, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED180, 180, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED181, 181, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_BAD_GENERATOR_SEND, 182, 1, JSEXN_TYPEERR, "attempt to send {0} to newborn generator") -MSG_DEF(JSMSG_UNUSED183, 183, 0, JSEXN_NONE, "") -MSG_DEF(JSMSG_UNUSED184, 184, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_SC_NOT_TRANSFERABLE, 183, 0, JSEXN_TYPEERR, "invalid transferable array for structured clone") +MSG_DEF(JSMSG_SC_DUP_TRANSFERABLE, 184, 0, JSEXN_TYPEERR, "duplicate transferable for structured clone") MSG_DEF(JSMSG_CANT_REPORT_AS_NON_EXTENSIBLE, 185, 0, JSEXN_TYPEERR, "proxy can't report an extensible object as non-extensible") MSG_DEF(JSMSG_UNUSED186, 186, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED187, 187, 0, JSEXN_NONE, "") @@ -260,7 +260,7 @@ MSG_DEF(JSMSG_USER_DEFINED_ERROR, 206, 0, JSEXN_ERR, "JS_ReportError was cal MSG_DEF(JSMSG_WRONG_CONSTRUCTOR, 207, 1, JSEXN_TYPEERR, "wrong constructor called for {0}") MSG_DEF(JSMSG_BAD_GENERATOR_RETURN, 208, 1, JSEXN_TYPEERR, "generator function {0} returns a value") MSG_DEF(JSMSG_BAD_ANON_GENERATOR_RETURN, 209, 0, JSEXN_TYPEERR, "anonymous generator function returns a value") -MSG_DEF(JSMSG_NAME_AFTER_FOR_PAREN, 210, 0, JSEXN_SYNTAXERR, "missing name after for (") +MSG_DEF(JSMSG_UNUSED210, 210, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_IN_AFTER_FOR_NAME, 211, 0, JSEXN_SYNTAXERR, "missing 'in' or 'of' after for") MSG_DEF(JSMSG_BAD_TRAP_RETURN_VALUE, 212, 2, JSEXN_TYPEERR,"trap {1} for {0} returned a primitive value") MSG_DEF(JSMSG_UNUSED213, 213, 0, JSEXN_NONE, "") @@ -269,7 +269,7 @@ MSG_DEF(JSMSG_BAD_GENERATOR_SYNTAX, 215, 1, JSEXN_SYNTAXERR, "{0} expression m MSG_DEF(JSMSG_ARRAY_COMP_LEFTSIDE, 216, 0, JSEXN_SYNTAXERR, "invalid array comprehension left-hand side") MSG_DEF(JSMSG_UNUSED217, 217, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_EMPTY_ARRAY_REDUCE, 218, 0, JSEXN_TYPEERR, "reduce of empty array with no initial value") -MSG_DEF(JSMSG_UNUSED219, 219, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_BAD_SYMBOL, 219, 1, JSEXN_TYPEERR, "{0} is not a well-known @@-symbol") MSG_DEF(JSMSG_BAD_DELETE_OPERAND, 220, 0, JSEXN_REFERENCEERR, "invalid delete operand") MSG_DEF(JSMSG_BAD_INCOP_OPERAND, 221, 0, JSEXN_REFERENCEERR, "invalid increment/decrement operand") MSG_DEF(JSMSG_UNEXPECTED_TYPE, 222, 2, JSEXN_TYPEERR, "{0} is {1}") @@ -353,7 +353,7 @@ MSG_DEF(JSMSG_REST_WITH_DEFAULT, 299, 0, JSEXN_SYNTAXERR, "rest parameter m MSG_DEF(JSMSG_NONDEFAULT_FORMAL_AFTER_DEFAULT, 300, 0, JSEXN_SYNTAXERR, "parameter(s) with default followed by parameter without default") MSG_DEF(JSMSG_YIELD_IN_DEFAULT, 301, 0, JSEXN_SYNTAXERR, "yield in default expression") MSG_DEF(JSMSG_INTRINSIC_NOT_DEFINED, 302, 1, JSEXN_REFERENCEERR, "no intrinsic function {0}") -MSG_DEF(JSMSG_ALREADY_HAS_SOURCEMAP, 303, 1, JSEXN_ERR, "{0} is being assigned a source map, yet already has one") +MSG_DEF(JSMSG_ALREADY_HAS_PRAGMA, 303, 2, JSEXN_ERR, "{0} is being assigned a {1}, but already has one") MSG_DEF(JSMSG_PAR_ARRAY_BAD_ARG, 304, 1, JSEXN_RANGEERR, "invalid ParallelArray{0} argument") MSG_DEF(JSMSG_PAR_ARRAY_BAD_PARTITION, 305, 0, JSEXN_ERR, "argument must be divisible by outermost dimension") MSG_DEF(JSMSG_PAR_ARRAY_REDUCE_EMPTY, 306, 0, JSEXN_ERR, "cannot reduce ParallelArray object whose outermost dimension is empty") @@ -375,7 +375,7 @@ MSG_DEF(JSMSG_MUST_REPORT_UNDEFINED, 321, 0, JSEXN_TYPEERR, "proxy must report MSG_DEF(JSMSG_CANT_SET_NW_NC, 322, 0, JSEXN_TYPEERR, "proxy can't successfully set a non-writable, non-configurable property") MSG_DEF(JSMSG_CANT_SET_WO_SETTER, 323, 0, JSEXN_TYPEERR, "proxy can't succesfully set an accessor property without a setter") MSG_DEF(JSMSG_DEBUG_BAD_REFERENT, 324, 2, JSEXN_TYPEERR, "{0} does not refer to {1}") -MSG_DEF(JSMSG_DEBUG_WRAPPER_IN_WAY, 325, 2, JSEXN_TYPEERR, "{0} is a wrapper around {1}, but a direct reference is required") +MSG_DEF(JSMSG_DEBUG_WRAPPER_IN_WAY, 325, 3, JSEXN_TYPEERR, "{0} is {1}{2}a global object, but a direct reference is required") MSG_DEF(JSMSG_UNWRAP_DENIED, 326, 0, JSEXN_ERR, "permission denied to unwrap object") MSG_DEF(JSMSG_INTL_OBJECT_NOT_INITED, 327, 3, JSEXN_TYPEERR, "Intl.{0}.prototype.{1} called on value that's not an object initialized as a {2}") MSG_DEF(JSMSG_INVALID_LOCALES_ELEMENT,328, 0, JSEXN_TYPEERR, "invalid element in locales argument") @@ -400,12 +400,23 @@ MSG_DEF(JSMSG_YIELD_IN_ARROW, 346, 0, JSEXN_SYNTAXERR, "arrow function m MSG_DEF(JSMSG_WRONG_VALUE, 347, 2, JSEXN_ERR, "expected {0} but found {1}") MSG_DEF(JSMSG_PAR_ARRAY_SCATTER_BAD_TARGET, 348, 1, JSEXN_ERR, "target for index {0} is not an integer") MSG_DEF(JSMSG_SELFHOSTED_UNBOUND_NAME,349, 0, JSEXN_TYPEERR, "self-hosted code may not contain unbound name lookups") -MSG_DEF(JSMSG_DEPRECATED_SOURCE_MAP, 350, 0, JSEXN_SYNTAXERR, "Using //@ to indicate source map URL pragmas is deprecated. Use //# instead") +MSG_DEF(JSMSG_DEPRECATED_PRAGMA, 350, 1, JSEXN_SYNTAXERR, "Using //@ to indicate {0} pragmas is deprecated. Use //# instead") MSG_DEF(JSMSG_BAD_DESTRUCT_ASSIGN, 351, 1, JSEXN_SYNTAXERR, "can't assign to {0} using destructuring assignment") -MSG_DEF(JSMSG_BINARYDATA_ARRAYTYPE_BAD_ARGS, 352, 0, JSEXN_ERR, "Invalid arguments") -MSG_DEF(JSMSG_BINARYDATA_BINARYARRAY_BAD_INDEX, 353, 0, JSEXN_RANGEERR, "invalid or out-of-range index") -MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_ARGS, 354, 0, JSEXN_RANGEERR, "invalid field descriptor") -MSG_DEF(JSMSG_BINARYDATA_NOT_BINARYSTRUCT, 355, 1, JSEXN_TYPEERR, "{0} is not a BinaryStruct") -MSG_DEF(JSMSG_BINARYDATA_SUBARRAY_INTEGER_ARG, 356, 1, JSEXN_ERR, "argument {0} must be an integer") -MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_EMPTY_DESCRIPTOR, 357, 0, JSEXN_ERR, "field descriptor cannot be empty") -MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_FIELD, 358, 1, JSEXN_ERR, "field {0} is not a valid BinaryData Type descriptor") +MSG_DEF(JSMSG_TYPEDOBJECT_ARRAYTYPE_BAD_ARGS, 352, 0, JSEXN_ERR, "Invalid arguments") +MSG_DEF(JSMSG_TYPEDOBJECT_BINARYARRAY_BAD_INDEX, 353, 0, JSEXN_RANGEERR, "invalid or out-of-range index") +MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_BAD_ARGS, 354, 0, JSEXN_RANGEERR, "invalid field descriptor") +MSG_DEF(JSMSG_TYPEDOBJECT_NOT_BINARYSTRUCT, 355, 1, JSEXN_TYPEERR, "{0} is not a BinaryStruct") +MSG_DEF(JSMSG_TYPEDOBJECT_SUBARRAY_INTEGER_ARG, 356, 1, JSEXN_ERR, "argument {0} must be an integer") +MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_EMPTY_DESCRIPTOR, 357, 0, JSEXN_ERR, "field descriptor cannot be empty") +MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_BAD_FIELD, 358, 1, JSEXN_ERR, "field {0} is not a valid BinaryData Type descriptor") +MSG_DEF(JSMSG_GENERATOR_FINISHED, 359, 0, JSEXN_TYPEERR, "generator has already finished") +MSG_DEF(JSMSG_TYPEDOBJECT_TOO_BIG, 360, 0, JSEXN_ERR, "Type is too large to allocate") +MSG_DEF(JSMSG_TYPEDOBJECT_NOT_TYPE_OBJECT, 361, 0, JSEXN_ERR, "Expected a type object") +MSG_DEF(JSMSG_TOO_MANY_CON_SPREADARGS, 362, 0, JSEXN_RANGEERR, "too many constructor arguments") +MSG_DEF(JSMSG_TOO_MANY_FUN_SPREADARGS, 363, 0, JSEXN_RANGEERR, "too many function arguments") +MSG_DEF(JSMSG_DEBUG_NOT_DEBUGGEE, 364, 2, JSEXN_ERR, "{0} is not a debuggee {1}") +MSG_DEF(JSMSG_TYPEDOBJECT_NOT_TYPED_OBJECT, 365, 0, JSEXN_ERR, "Expected a typed object") +MSG_DEF(JSMSG_TYPEDOBJECT_NO_SUCH_PROP, 366, 1, JSEXN_TYPEERR, "No such property: {0}") +MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_BAD_ARGS, 367, 2, JSEXN_TYPEERR, "argument {0} invalid: expected {1}") +MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_UNATTACHED, 368, 0, JSEXN_TYPEERR, "handle unattached") +MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_BAD_TYPE, 369, 0, JSEXN_TYPEERR, "handle moved to destination of incorrect type") diff --git a/external/spidermonkey/include/ios/js/Anchor.h b/external/spidermonkey/include/ios/js/Anchor.h index 0d458e6fb6..c2324fb2e9 100644 --- a/external/spidermonkey/include/ios/js/Anchor.h +++ b/external/spidermonkey/include/ios/js/Anchor.h @@ -11,12 +11,7 @@ #include "mozilla/Attributes.h" -class JSFunction; -class JSObject; -class JSScript; -class JSString; - -namespace JS { class Value; } +#include "js/TypeDecls.h" namespace JS { diff --git a/external/spidermonkey/include/ios/js/CallArgs.h b/external/spidermonkey/include/ios/js/CallArgs.h index 8027ffc71a..5c7a201101 100644 --- a/external/spidermonkey/include/ios/js/CallArgs.h +++ b/external/spidermonkey/include/ios/js/CallArgs.h @@ -38,22 +38,19 @@ #include "js/RootingAPI.h" #include "js/Value.h" -struct JSContext; -class JSObject; - /* Typedef for native functions called by the JS VM. */ -typedef JSBool +typedef bool (* JSNative)(JSContext *cx, unsigned argc, JS::Value *vp); /* Typedef for native functions that may be called in parallel. */ -typedef js::ParallelResult +typedef bool (* JSParallelNative)(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); /* * Typedef for native functions that may be called either in parallel or * sequential execution. */ -typedef JSBool +typedef bool (* JSThreadSafeNative)(js::ThreadSafeContext *cx, unsigned argc, JS::Value *vp); /* @@ -61,11 +58,11 @@ typedef JSBool * a JSNative or a JSParallelNative. */ template -inline JSBool +inline bool JSNativeThreadSafeWrapper(JSContext *cx, unsigned argc, JS::Value *vp); template -inline js::ParallelResult +inline bool JSParallelNativeThreadSafeWrapper(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); /* @@ -89,7 +86,7 @@ extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; * return value for a function call. The principal way to create a * CallReceiver is using JS::CallReceiverFromVp: * - * static JSBool + * static bool * FunctionReturningThis(JSContext *cx, unsigned argc, JS::Value *vp) * { * JS::CallReceiver rec = JS::CallReceiverFromVp(vp); @@ -282,7 +279,7 @@ CallReceiverFromVp(Value *vp) * the function call's arguments. The principal way to create a CallArgs is * like so, using JS::CallArgsFromVp: * - * static JSBool + * static bool * FunctionReturningArgcTimesArg0(JSContext *cx, unsigned argc, JS::Value *vp) * { * JS::CallArgs args = JS::CallArgsFromVp(argc, vp); diff --git a/external/spidermonkey/include/ios/js/CallNonGenericMethod.h b/external/spidermonkey/include/ios/js/CallNonGenericMethod.h new file mode 100644 index 0000000000..05097f0294 --- /dev/null +++ b/external/spidermonkey/include/ios/js/CallNonGenericMethod.h @@ -0,0 +1,117 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_CallNonGenericMethod_h +#define js_CallNonGenericMethod_h + +#include "jstypes.h" + +#include "js/CallArgs.h" + +namespace JS { + +// Returns true if |v| is considered an acceptable this-value. +typedef bool (*IsAcceptableThis)(Handle v); + +// Implements the guts of a method; guaranteed to be provided an acceptable +// this-value, as determined by a corresponding IsAcceptableThis method. +typedef bool (*NativeImpl)(JSContext *cx, CallArgs args); + +namespace detail { + +// DON'T CALL THIS DIRECTLY. It's for use only by CallNonGenericMethod! +extern JS_PUBLIC_API(bool) +CallMethodIfWrapped(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args); + +} // namespace detail + +// Methods usually act upon |this| objects only from a single global object and +// compartment. Sometimes, however, a method must act upon |this| values from +// multiple global objects or compartments. In such cases the |this| value a +// method might see will be wrapped, such that various access to the object -- +// to its class, its private data, its reserved slots, and so on -- will not +// work properly without entering that object's compartment. This method +// implements a solution to this problem. +// +// To implement a method that accepts |this| values from multiple compartments, +// define two functions. The first function matches the IsAcceptableThis type +// and indicates whether the provided value is an acceptable |this| for the +// method; it must be a pure function only of its argument. +// +// static const JSClass AnswerClass = { ... }; +// +// static bool +// IsAnswerObject(const Value &v) +// { +// if (!v.isObject()) +// return false; +// return JS_GetClass(&v.toObject()) == &AnswerClass; +// } +// +// The second function implements the NativeImpl signature and defines the +// behavior of the method when it is provided an acceptable |this| value. +// Aside from some typing niceties -- see the CallArgs interface for details -- +// its interface is the same as that of JSNative. +// +// static bool +// answer_getAnswer_impl(JSContext *cx, JS::CallArgs args) +// { +// args.rval().setInt32(42); +// return true; +// } +// +// The implementation function is guaranteed to be called *only* with a |this| +// value which is considered acceptable. +// +// Now to implement the actual method, write a JSNative that calls the method +// declared below, passing the appropriate template and runtime arguments. +// +// static bool +// answer_getAnswer(JSContext *cx, unsigned argc, JS::Value *vp) +// { +// JS::CallArgs args = JS::CallArgsFromVp(argc, vp); +// return JS::CallNonGenericMethod(cx, args); +// } +// +// Note that, because they are used as template arguments, the predicate +// and implementation functions must have external linkage. (This is +// unfortunate, but GCC wasn't inlining things as one would hope when we +// passed them as function arguments.) +// +// JS::CallNonGenericMethod will test whether |args.thisv()| is acceptable. If +// it is, it will call the provided implementation function, which will return +// a value and indicate success. If it is not, it will attempt to unwrap +// |this| and call the implementation function on the unwrapped |this|. If +// that succeeds, all well and good. If it doesn't succeed, a TypeError will +// be thrown. +// +// Note: JS::CallNonGenericMethod will only work correctly if it's called in +// tail position in a JSNative. Do not call it from any other place. +// +template +JS_ALWAYS_INLINE bool +CallNonGenericMethod(JSContext *cx, CallArgs args) +{ + HandleValue thisv = args.thisv(); + if (Test(thisv)) + return Impl(cx, args); + + return detail::CallMethodIfWrapped(cx, Test, Impl, args); +} + +JS_ALWAYS_INLINE bool +CallNonGenericMethod(JSContext *cx, IsAcceptableThis Test, NativeImpl Impl, CallArgs args) +{ + HandleValue thisv = args.thisv(); + if (Test(thisv)) + return Impl(cx, args); + + return detail::CallMethodIfWrapped(cx, Test, Impl, args); +} + +} // namespace JS + +#endif /* js_CallNonGenericMethod_h */ diff --git a/external/spidermonkey/include/ios/js/CharacterEncoding.h b/external/spidermonkey/include/ios/js/CharacterEncoding.h index e88e08e1be..7918b83484 100644 --- a/external/spidermonkey/include/ios/js/CharacterEncoding.h +++ b/external/spidermonkey/include/ios/js/CharacterEncoding.h @@ -7,11 +7,15 @@ #ifndef js_CharacterEncoding_h #define js_CharacterEncoding_h +#include "mozilla/NullPtr.h" #include "mozilla/Range.h" +#include "js/TypeDecls.h" #include "js/Utility.h" -#include "jspubtd.h" +namespace js { +struct ThreadSafeContext; +} namespace JS { @@ -41,7 +45,7 @@ class Latin1CharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: - Latin1CharsZ() : Base(NULL, 0) {} + Latin1CharsZ() : Base(nullptr, 0) {} Latin1CharsZ(char *aBytes, size_t aLength) : Base(reinterpret_cast(aBytes), aLength) @@ -80,7 +84,7 @@ class UTF8CharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: - UTF8CharsZ() : Base(NULL, 0) {} + UTF8CharsZ() : Base(nullptr, 0) {} UTF8CharsZ(char *aBytes, size_t aLength) : Base(reinterpret_cast(aBytes), aLength) @@ -138,7 +142,7 @@ class TwoByteCharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: - TwoByteCharsZ() : Base(NULL, 0) {} + TwoByteCharsZ() : Base(nullptr, 0) {} TwoByteCharsZ(jschar *chars, size_t length) : Base(chars, length) @@ -154,7 +158,7 @@ class TwoByteCharsZ : public mozilla::RangedPtr * output. The returned string is zero terminated. The returned string or the * returned string's |start()| must be freed with JS_free or js_free, * respectively. If allocation fails, an OOM error will be set and the method - * will return a NULL chars (which can be tested for with the ! operator). + * will return a nullptr chars (which can be tested for with the ! operator). * This method cannot trigger GC. */ extern Latin1CharsZ diff --git a/external/spidermonkey/include/ios/js/Class.h b/external/spidermonkey/include/ios/js/Class.h new file mode 100644 index 0000000000..4058688e99 --- /dev/null +++ b/external/spidermonkey/include/ios/js/Class.h @@ -0,0 +1,699 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +/* JSClass definition and its component types, plus related interfaces. */ + +#ifndef js_Class_h +#define js_Class_h + +#include "mozilla/NullPtr.h" + +#include "jstypes.h" + +#include "js/CallArgs.h" +#include "js/Id.h" +#include "js/TypeDecls.h" + +/* + * A JSClass acts as a vtable for JS objects that allows JSAPI clients to + * control various aspects of the behavior of an object like property lookup. + * js::Class is an engine-private extension that allows more control over + * object behavior and, e.g., allows custom slow layout. + */ + +class JSFreeOp; + +namespace js { + +class Class; +class FreeOp; +class PropertyId; +class PropertyName; +class Shape; +class SpecialId; + +// This is equal to JSFunction::class_. Use it in places where you don't want +// to #include jsfun.h. +extern JS_FRIEND_DATA(const js::Class* const) FunctionClassPtr; + +static JS_ALWAYS_INLINE jsid +SPECIALID_TO_JSID(const SpecialId &sid); + +/* + * We partition the ways to refer to a property into three: by an index + * (uint32_t); by a string whose characters do not represent an index + * (PropertyName, see vm/String.h); and by various special values. + * + * Special values are encoded using SpecialId, which is layout-compatible but + * non-interconvertible with jsid. A SpecialId is used for JSID_VOID, which + * does not occur in JS scripts but may be used to indicate the absence of a + * valid identifier. In the future, a SpecialId may also be an object used by + * Harmony-proposed private names. + */ +class SpecialId +{ + uintptr_t bits_; + + /* Needs access to raw bits. */ + friend JS_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid); + friend class PropertyId; + + static const uintptr_t TYPE_VOID = JSID_TYPE_VOID; + static const uintptr_t TYPE_OBJECT = JSID_TYPE_OBJECT; + static const uintptr_t TYPE_MASK = JSID_TYPE_MASK; + + SpecialId(uintptr_t bits) : bits_(bits) { } + + public: + SpecialId() : bits_(TYPE_VOID) { } + + /* Object-valued */ + + SpecialId(JSObject &obj) + : bits_(uintptr_t(&obj) | TYPE_OBJECT) + { + JS_ASSERT(&obj != nullptr); + JS_ASSERT((uintptr_t(&obj) & TYPE_MASK) == 0); + } + + bool isObject() const { + return (bits_ & TYPE_MASK) == TYPE_OBJECT && bits_ != TYPE_OBJECT; + } + + JSObject *toObject() const { + JS_ASSERT(isObject()); + return reinterpret_cast(bits_ & ~TYPE_MASK); + } + + /* Empty */ + + static SpecialId empty() { + SpecialId sid(TYPE_OBJECT); + JS_ASSERT(sid.isEmpty()); + return sid; + } + + bool isEmpty() const { + return bits_ == TYPE_OBJECT; + } + + /* Void */ + + static SpecialId voidId() { + SpecialId sid(TYPE_VOID); + JS_ASSERT(sid.isVoid()); + return sid; + } + + bool isVoid() const { + return bits_ == TYPE_VOID; + } +}; + +static JS_ALWAYS_INLINE jsid +SPECIALID_TO_JSID(const SpecialId &sid) +{ + jsid id; + JSID_BITS(id) = sid.bits_; + JS_ASSERT_IF(sid.isObject(), JSID_IS_OBJECT(id) && JSID_TO_OBJECT(id) == sid.toObject()); + JS_ASSERT_IF(sid.isVoid(), JSID_IS_VOID(id)); + JS_ASSERT_IF(sid.isEmpty(), JSID_IS_EMPTY(id)); + return id; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_SPECIAL(jsid id) +{ + return JSID_IS_OBJECT(id) || JSID_IS_EMPTY(id) || JSID_IS_VOID(id); +} + +static JS_ALWAYS_INLINE SpecialId +JSID_TO_SPECIALID(jsid id) +{ + JS_ASSERT(JSID_IS_SPECIAL(id)); + if (JSID_IS_OBJECT(id)) + return SpecialId(*JSID_TO_OBJECT(id)); + if (JSID_IS_EMPTY(id)) + return SpecialId::empty(); + JS_ASSERT(JSID_IS_VOID(id)); + return SpecialId::voidId(); +} + +typedef JS::Handle HandleSpecialId; + +} // namespace js + +// JSClass operation signatures. + +// Add or get a property named by id in obj. Note the jsid id type -- id may +// be a string (Unicode property identifier) or an int (element index). The +// *vp out parameter, on success, is the new property value after the action. +typedef bool +(* JSPropertyOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + JS::MutableHandle vp); + +// Set a property named by id in obj, treating the assignment as strict +// mode code if strict is true. Note the jsid id type -- id may be a string +// (Unicode property identifier) or an int (element index). The *vp out +// parameter, on success, is the new property value after the +// set. +typedef bool +(* JSStrictPropertyOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + bool strict, JS::MutableHandle vp); + +// Delete a property named by id in obj. +// +// If an error occurred, return false as per normal JSAPI error practice. +// +// If no error occurred, but the deletion attempt wasn't allowed (perhaps +// because the property was non-configurable), set *succeeded to false and +// return true. This will cause |delete obj[id]| to evaluate to false in +// non-strict mode code, and to throw a TypeError in strict mode code. +// +// If no error occurred and the deletion wasn't disallowed (this is *not* the +// same as saying that a deletion actually occurred -- deleting a non-existent +// property, or an inherited property, is allowed -- it's just pointless), +// set *succeeded to true and return true. +typedef bool +(* JSDeletePropertyOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + bool *succeeded); + +// This function type is used for callbacks that enumerate the properties of +// a JSObject. The behavior depends on the value of enum_op: +// +// JSENUMERATE_INIT +// A new, opaque iterator state should be allocated and stored in *statep. +// (You can use PRIVATE_TO_JSVAL() to tag the pointer to be stored). +// +// The number of properties that will be enumerated should be returned as +// an integer jsval in *idp, if idp is non-null, and provided the number of +// enumerable properties is known. If idp is non-null and the number of +// enumerable properties can't be computed in advance, *idp should be set +// to JSVAL_ZERO. +// +// JSENUMERATE_INIT_ALL +// Used identically to JSENUMERATE_INIT, but exposes all properties of the +// object regardless of enumerability. +// +// JSENUMERATE_NEXT +// A previously allocated opaque iterator state is passed in via statep. +// Return the next jsid in the iteration using *idp. The opaque iterator +// state pointed at by statep is destroyed and *statep is set to JSVAL_NULL +// if there are no properties left to enumerate. +// +// JSENUMERATE_DESTROY +// Destroy the opaque iterator state previously allocated in *statep by a +// call to this function when enum_op was JSENUMERATE_INIT or +// JSENUMERATE_INIT_ALL. +// +// The return value is used to indicate success, with a value of false +// indicating failure. +typedef bool +(* JSNewEnumerateOp)(JSContext *cx, JS::Handle obj, JSIterateOp enum_op, + JS::MutableHandle statep, JS::MutableHandle idp); + +// The old-style JSClass.enumerate op should define all lazy properties not +// yet reflected in obj. +typedef bool +(* JSEnumerateOp)(JSContext *cx, JS::Handle obj); + +// Resolve a lazy property named by id in obj by defining it directly in obj. +// Lazy properties are those reflected from some peer native property space +// (e.g., the DOM attributes for a given node reflected as obj) on demand. +// +// JS looks for a property in an object, and if not found, tries to resolve +// the given id. If resolve succeeds, the engine looks again in case resolve +// defined obj[id]. If no such property exists directly in obj, the process +// is repeated with obj's prototype, etc. +// +// NB: JSNewResolveOp provides a cheaper way to resolve lazy properties. +typedef bool +(* JSResolveOp)(JSContext *cx, JS::Handle obj, JS::Handle id); + +// Like JSResolveOp, but flags provide contextual information as follows: +// +// JSRESOLVE_ASSIGNING obj[id] is on the left-hand side of an assignment +// +// The *objp out parameter, on success, should be null to indicate that id +// was not resolved; and non-null, referring to obj or one of its prototypes, +// if id was resolved. The hook may assume *objp is null on entry. +// +// This hook instead of JSResolveOp is called via the JSClass.resolve member +// if JSCLASS_NEW_RESOLVE is set in JSClass.flags. +typedef bool +(* JSNewResolveOp)(JSContext *cx, JS::Handle obj, JS::Handle id, unsigned flags, + JS::MutableHandle objp); + +// Convert obj to the given type, returning true with the resulting value in +// *vp on success, and returning false on error or exception. +typedef bool +(* JSConvertOp)(JSContext *cx, JS::Handle obj, JSType type, + JS::MutableHandle vp); + +// Finalize obj, which the garbage collector has determined to be unreachable +// from other live objects or from GC roots. Obviously, finalizers must never +// store a reference to obj. +typedef void +(* JSFinalizeOp)(JSFreeOp *fop, JSObject *obj); + +// Finalizes external strings created by JS_NewExternalString. +struct JSStringFinalizer { + void (*finalize)(const JSStringFinalizer *fin, jschar *chars); +}; + +// JSClass.checkAccess type: check whether obj[id] may be accessed per mode, +// returning false on error/exception, true on success with obj[id]'s last-got +// value in *vp, and its attributes in *attrsp. As for JSPropertyOp above, id +// is either a string or an int jsval. +typedef bool +(* JSCheckAccessOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + JSAccessMode mode, JS::MutableHandle vp); + +// Return whether the first principal subsumes the second. The exact meaning of +// 'subsumes' is left up to the browser. Subsumption is checked inside the JS +// engine when determining, e.g., which stack frames to display in a backtrace. +typedef bool +(* JSSubsumesOp)(JSPrincipals *first, JSPrincipals *second); + +// Check whether v is an instance of obj. Return false on error or exception, +// true on success with true in *bp if v is an instance of obj, false in +// *bp otherwise. +typedef bool +(* JSHasInstanceOp)(JSContext *cx, JS::Handle obj, JS::MutableHandle vp, + bool *bp); + +// Function type for trace operation of the class called to enumerate all +// traceable things reachable from obj's private data structure. For each such +// thing, a trace implementation must call one of the JS_Call*Tracer variants +// on the thing. +// +// JSTraceOp implementation can assume that no other threads mutates object +// state. It must not change state of the object or corresponding native +// structures. The only exception for this rule is the case when the embedding +// needs a tight integration with GC. In that case the embedding can check if +// the traversal is a part of the marking phase through calling +// JS_IsGCMarkingTracer and apply a special code like emptying caches or +// marking its native structures. +typedef void +(* JSTraceOp)(JSTracer *trc, JSObject *obj); + +// A generic type for functions mapping an object to another object, or null +// if an error or exception was thrown on cx. +typedef JSObject * +(* JSObjectOp)(JSContext *cx, JS::Handle obj); + +// Hook that creates an iterator object for a given object. Returns the +// iterator object or null if an error or exception was thrown on cx. +typedef JSObject * +(* JSIteratorOp)(JSContext *cx, JS::HandleObject obj, bool keysonly); + +typedef JSObject * +(* JSWeakmapKeyDelegateOp)(JSObject *obj); + +/* js::Class operation signatures. */ + +namespace js { + +typedef bool +(* LookupGenericOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* LookupPropOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* LookupElementOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* LookupSpecialOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* DefineGenericOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue value, + JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs); +typedef bool +(* DefinePropOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + JS::HandleValue value, JSPropertyOp getter, JSStrictPropertyOp setter, + unsigned attrs); +typedef bool +(* DefineElementOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, JS::HandleValue value, + JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs); +typedef bool +(* DefineSpecialOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, + JS::HandleValue value, JSPropertyOp getter, JSStrictPropertyOp setter, + unsigned attrs); +typedef bool +(* GenericIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, JS::HandleId id, + JS::MutableHandleValue vp); +typedef bool +(* PropertyIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, + JS::Handle name, JS::MutableHandleValue vp); +typedef bool +(* ElementIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, uint32_t index, + JS::MutableHandleValue vp); +typedef bool +(* ElementIfPresentOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, + uint32_t index, JS::MutableHandleValue vp, bool* present); +typedef bool +(* SpecialIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, + HandleSpecialId sid, JS::MutableHandleValue vp); +typedef bool +(* StrictGenericIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* StrictPropertyIdOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* StrictElementIdOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* StrictSpecialIdOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* GenericAttributesOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, unsigned *attrsp); +typedef bool +(* PropertyAttributesOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + unsigned *attrsp); +typedef bool +(* DeletePropertyOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + bool *succeeded); +typedef bool +(* DeleteElementOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, bool *succeeded); +typedef bool +(* DeleteSpecialOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, bool *succeeded); + +typedef bool +(* WatchOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); + +typedef bool +(* UnwatchOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id); + +typedef JSObject * +(* ObjectOp)(JSContext *cx, JS::HandleObject obj); +typedef void +(* FinalizeOp)(FreeOp *fop, JSObject *obj); + +#define JS_CLASS_MEMBERS \ + const char *name; \ + uint32_t flags; \ + \ + /* Mandatory function pointer members. */ \ + JSPropertyOp addProperty; \ + JSDeletePropertyOp delProperty; \ + JSPropertyOp getProperty; \ + JSStrictPropertyOp setProperty; \ + JSEnumerateOp enumerate; \ + JSResolveOp resolve; \ + JSConvertOp convert; \ + \ + /* Optional members (may be null). */ \ + FinalizeOp finalize; \ + JSCheckAccessOp checkAccess; \ + JSNative call; \ + JSHasInstanceOp hasInstance; \ + JSNative construct; \ + JSTraceOp trace + +/* + * The helper struct to measure the size of JS_CLASS_MEMBERS to know how much + * we have to pad js::Class to match the size of JSClass. + */ +struct ClassSizeMeasurement +{ + JS_CLASS_MEMBERS; +}; + +struct ClassExtension +{ + JSObjectOp outerObject; + JSObjectOp innerObject; + JSIteratorOp iteratorObject; + + /* + * isWrappedNative is true only if the class is an XPCWrappedNative. + * WeakMaps use this to override the wrapper disposal optimization. + */ + bool isWrappedNative; + + /* + * If an object is used as a key in a weakmap, it may be desirable for the + * garbage collector to keep that object around longer than it otherwise + * would. A common case is when the key is a wrapper around an object in + * another compartment, and we want to avoid collecting the wrapper (and + * removing the weakmap entry) as long as the wrapped object is alive. In + * that case, the wrapped object is returned by the wrapper's + * weakmapKeyDelegateOp hook. As long as the wrapper is used as a weakmap + * key, it will not be collected (and remain in the weakmap) until the + * wrapped object is collected. + */ + JSWeakmapKeyDelegateOp weakmapKeyDelegateOp; +}; + +#define JS_NULL_CLASS_EXT {nullptr,nullptr,nullptr,false,nullptr} + +struct ObjectOps +{ + LookupGenericOp lookupGeneric; + LookupPropOp lookupProperty; + LookupElementOp lookupElement; + LookupSpecialOp lookupSpecial; + DefineGenericOp defineGeneric; + DefinePropOp defineProperty; + DefineElementOp defineElement; + DefineSpecialOp defineSpecial; + GenericIdOp getGeneric; + PropertyIdOp getProperty; + ElementIdOp getElement; + ElementIfPresentOp getElementIfPresent; /* can be null */ + SpecialIdOp getSpecial; + StrictGenericIdOp setGeneric; + StrictPropertyIdOp setProperty; + StrictElementIdOp setElement; + StrictSpecialIdOp setSpecial; + GenericAttributesOp getGenericAttributes; + GenericAttributesOp setGenericAttributes; + DeletePropertyOp deleteProperty; + DeleteElementOp deleteElement; + DeleteSpecialOp deleteSpecial; + WatchOp watch; + UnwatchOp unwatch; + + JSNewEnumerateOp enumerate; + ObjectOp thisObject; +}; + +#define JS_NULL_OBJECT_OPS \ + {nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr, \ + nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr, \ + nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr} + +} // namespace js + +// Classes, objects, and properties. + +typedef void (*JSClassInternal)(); + +struct JSClass { + const char *name; + uint32_t flags; + + // Mandatory function pointer members. + JSPropertyOp addProperty; + JSDeletePropertyOp delProperty; + JSPropertyOp getProperty; + JSStrictPropertyOp setProperty; + JSEnumerateOp enumerate; + JSResolveOp resolve; + JSConvertOp convert; + + // Optional members (may be null). + JSFinalizeOp finalize; + JSCheckAccessOp checkAccess; + JSNative call; + JSHasInstanceOp hasInstance; + JSNative construct; + JSTraceOp trace; + + void *reserved[42]; +}; + +#define JSCLASS_HAS_PRIVATE (1<<0) // objects have private slot +#define JSCLASS_NEW_ENUMERATE (1<<1) // has JSNewEnumerateOp hook +#define JSCLASS_NEW_RESOLVE (1<<2) // has JSNewResolveOp hook +#define JSCLASS_PRIVATE_IS_NSISUPPORTS (1<<3) // private is (nsISupports *) +#define JSCLASS_IS_DOMJSCLASS (1<<4) // objects are DOM +#define JSCLASS_IMPLEMENTS_BARRIERS (1<<5) // Correctly implements GC read + // and write barriers +#define JSCLASS_EMULATES_UNDEFINED (1<<6) // objects of this class act + // like the value undefined, + // in some contexts +#define JSCLASS_USERBIT1 (1<<7) // Reserved for embeddings. + +// To reserve slots fetched and stored via JS_Get/SetReservedSlot, bitwise-or +// JSCLASS_HAS_RESERVED_SLOTS(n) into the initializer for JSClass.flags, where +// n is a constant in [1, 255]. Reserved slots are indexed from 0 to n-1. +#define JSCLASS_RESERVED_SLOTS_SHIFT 8 // room for 8 flags below */ +#define JSCLASS_RESERVED_SLOTS_WIDTH 8 // and 16 above this field */ +#define JSCLASS_RESERVED_SLOTS_MASK JS_BITMASK(JSCLASS_RESERVED_SLOTS_WIDTH) +#define JSCLASS_HAS_RESERVED_SLOTS(n) (((n) & JSCLASS_RESERVED_SLOTS_MASK) \ + << JSCLASS_RESERVED_SLOTS_SHIFT) +#define JSCLASS_RESERVED_SLOTS(clasp) (((clasp)->flags \ + >> JSCLASS_RESERVED_SLOTS_SHIFT) \ + & JSCLASS_RESERVED_SLOTS_MASK) + +#define JSCLASS_HIGH_FLAGS_SHIFT (JSCLASS_RESERVED_SLOTS_SHIFT + \ + JSCLASS_RESERVED_SLOTS_WIDTH) + +#define JSCLASS_IS_ANONYMOUS (1<<(JSCLASS_HIGH_FLAGS_SHIFT+0)) +#define JSCLASS_IS_GLOBAL (1<<(JSCLASS_HIGH_FLAGS_SHIFT+1)) +#define JSCLASS_INTERNAL_FLAG2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+2)) +#define JSCLASS_INTERNAL_FLAG3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+3)) + +// Indicate whether the proto or ctor should be frozen. +#define JSCLASS_FREEZE_PROTO (1<<(JSCLASS_HIGH_FLAGS_SHIFT+4)) +#define JSCLASS_FREEZE_CTOR (1<<(JSCLASS_HIGH_FLAGS_SHIFT+5)) + +// Reserved for embeddings. +#define JSCLASS_USERBIT2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+6)) +#define JSCLASS_USERBIT3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+7)) + +#define JSCLASS_BACKGROUND_FINALIZE (1<<(JSCLASS_HIGH_FLAGS_SHIFT+8)) + +// Bits 26 through 31 are reserved for the CACHED_PROTO_KEY mechanism, see +// below. + +// ECMA-262 requires that most constructors used internally create objects +// with "the original Foo.prototype value" as their [[Prototype]] (__proto__) +// member initial value. The "original ... value" verbiage is there because +// in ECMA-262, global properties naming class objects are read/write and +// deleteable, for the most part. +// +// Implementing this efficiently requires that global objects have classes +// with the following flags. Failure to use JSCLASS_GLOBAL_FLAGS was +// previously allowed, but is now an ES5 violation and thus unsupported. +// +#define JSCLASS_GLOBAL_SLOT_COUNT (3 + JSProto_LIMIT * 3 + 28) +#define JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(n) \ + (JSCLASS_IS_GLOBAL | JSCLASS_HAS_RESERVED_SLOTS(JSCLASS_GLOBAL_SLOT_COUNT + (n))) +#define JSCLASS_GLOBAL_FLAGS \ + JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(0) +#define JSCLASS_HAS_GLOBAL_FLAG_AND_SLOTS(clasp) \ + (((clasp)->flags & JSCLASS_IS_GLOBAL) \ + && JSCLASS_RESERVED_SLOTS(clasp) >= JSCLASS_GLOBAL_SLOT_COUNT) + +// Fast access to the original value of each standard class's prototype. +#define JSCLASS_CACHED_PROTO_SHIFT (JSCLASS_HIGH_FLAGS_SHIFT + 10) +#define JSCLASS_CACHED_PROTO_WIDTH 6 +#define JSCLASS_CACHED_PROTO_MASK JS_BITMASK(JSCLASS_CACHED_PROTO_WIDTH) +#define JSCLASS_HAS_CACHED_PROTO(key) (uint32_t(key) << JSCLASS_CACHED_PROTO_SHIFT) +#define JSCLASS_CACHED_PROTO_KEY(clasp) ((JSProtoKey) \ + (((clasp)->flags \ + >> JSCLASS_CACHED_PROTO_SHIFT) \ + & JSCLASS_CACHED_PROTO_MASK)) + +// Initializer for unused members of statically initialized JSClass structs. +#define JSCLASS_NO_INTERNAL_MEMBERS {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} +#define JSCLASS_NO_OPTIONAL_MEMBERS 0,0,0,0,0,JSCLASS_NO_INTERNAL_MEMBERS + +namespace js { + +struct Class +{ + JS_CLASS_MEMBERS; + ClassExtension ext; + ObjectOps ops; + uint8_t pad[sizeof(JSClass) - sizeof(ClassSizeMeasurement) - + sizeof(ClassExtension) - sizeof(ObjectOps)]; + + /* Class is not native and its map is not a scope. */ + static const uint32_t NON_NATIVE = JSCLASS_INTERNAL_FLAG2; + + bool isNative() const { + return !(flags & NON_NATIVE); + } + + bool hasPrivate() const { + return !!(flags & JSCLASS_HAS_PRIVATE); + } + + bool emulatesUndefined() const { + return flags & JSCLASS_EMULATES_UNDEFINED; + } + + bool isCallable() const { + return this == js::FunctionClassPtr || call; + } + + static size_t offsetOfFlags() { return offsetof(Class, flags); } +}; + +JS_STATIC_ASSERT(offsetof(JSClass, name) == offsetof(Class, name)); +JS_STATIC_ASSERT(offsetof(JSClass, flags) == offsetof(Class, flags)); +JS_STATIC_ASSERT(offsetof(JSClass, addProperty) == offsetof(Class, addProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, delProperty) == offsetof(Class, delProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, getProperty) == offsetof(Class, getProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, setProperty) == offsetof(Class, setProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, enumerate) == offsetof(Class, enumerate)); +JS_STATIC_ASSERT(offsetof(JSClass, resolve) == offsetof(Class, resolve)); +JS_STATIC_ASSERT(offsetof(JSClass, convert) == offsetof(Class, convert)); +JS_STATIC_ASSERT(offsetof(JSClass, finalize) == offsetof(Class, finalize)); +JS_STATIC_ASSERT(offsetof(JSClass, checkAccess) == offsetof(Class, checkAccess)); +JS_STATIC_ASSERT(offsetof(JSClass, call) == offsetof(Class, call)); +JS_STATIC_ASSERT(offsetof(JSClass, construct) == offsetof(Class, construct)); +JS_STATIC_ASSERT(offsetof(JSClass, hasInstance) == offsetof(Class, hasInstance)); +JS_STATIC_ASSERT(offsetof(JSClass, trace) == offsetof(Class, trace)); +JS_STATIC_ASSERT(sizeof(JSClass) == sizeof(Class)); + +static JS_ALWAYS_INLINE const JSClass * +Jsvalify(const Class *c) +{ + return (const JSClass *)c; +} + +static JS_ALWAYS_INLINE const Class * +Valueify(const JSClass *c) +{ + return (const Class *)c; +} + +/* + * Enumeration describing possible values of the [[Class]] internal property + * value of objects. + */ +enum ESClassValue { + ESClass_Array, ESClass_Number, ESClass_String, ESClass_Boolean, + ESClass_RegExp, ESClass_ArrayBuffer, ESClass_Date +}; + +/* + * Return whether the given object has the given [[Class]] internal property + * value. Beware, this query says nothing about the js::Class of the JSObject + * so the caller must not assume anything about obj's representation (e.g., obj + * may be a proxy). + */ +inline bool +ObjectClassIs(JSObject &obj, ESClassValue classValue, JSContext *cx); + +/* Just a helper that checks v.isObject before calling ObjectClassIs. */ +inline bool +IsObjectWithClass(const JS::Value &v, ESClassValue classValue, JSContext *cx); + +inline bool +IsPoisonedSpecialId(js::SpecialId iden) +{ + if (iden.isObject()) + return JS::IsPoisonedPtr(iden.toObject()); + return false; +} + +template <> struct GCMethods +{ + static SpecialId initial() { return SpecialId(); } + static ThingRootKind kind() { return THING_ROOT_ID; } + static bool poisoned(SpecialId id) { return IsPoisonedSpecialId(id); } +}; + +} /* namespace js */ + +#endif /* js_Class_h */ diff --git a/external/spidermonkey/include/ios/js/GCAPI.h b/external/spidermonkey/include/ios/js/GCAPI.h index a9bef77c09..9cdf56bcce 100644 --- a/external/spidermonkey/include/ios/js/GCAPI.h +++ b/external/spidermonkey/include/ios/js/GCAPI.h @@ -7,7 +7,11 @@ #ifndef js_GCAPI_h #define js_GCAPI_h +#include "mozilla/NullPtr.h" + #include "js/HeapAPI.h" +#include "js/RootingAPI.h" +#include "js/Value.h" namespace JS { @@ -15,13 +19,12 @@ namespace JS { /* Reasons internal to the JS engine */ \ D(API) \ D(MAYBEGC) \ - D(LAST_CONTEXT) \ + D(DESTROY_RUNTIME) \ D(DESTROY_CONTEXT) \ D(LAST_DITCH) \ D(TOO_MUCH_MALLOC) \ D(ALLOC_TRIGGER) \ D(DEBUG_GC) \ - D(DEBUG_MODE_GC) \ D(TRANSPLANT) \ D(RESET) \ D(OUT_OF_NURSERY) \ @@ -206,12 +209,25 @@ PokeGC(JSRuntime *rt); extern JS_FRIEND_API(bool) WasIncrementalGC(JSRuntime *rt); -class ObjectPtr +extern JS_FRIEND_API(size_t) +GetGCNumber(); + +class AutoAssertNoGC { +#ifdef DEBUG + size_t gcNumber; + + public: + AutoAssertNoGC(); + ~AutoAssertNoGC(); +#endif +}; + +class JS_PUBLIC_API(ObjectPtr) { Heap value; public: - ObjectPtr() : value(NULL) {} + ObjectPtr() : value(nullptr) {} ObjectPtr(JSObject *obj) : value(obj) {} @@ -221,7 +237,7 @@ class ObjectPtr void finalize(JSRuntime *rt) { if (IsIncrementalBarrierNeeded(rt)) IncrementalObjectBarrier(value); - value = NULL; + value = nullptr; } void init(JSObject *obj) { value = obj; } @@ -232,9 +248,7 @@ class ObjectPtr IncrementalObjectBarrier(value); } - bool isAboutToBeFinalized() { - return JS_IsAboutToBeFinalized(&value); - } + bool isAboutToBeFinalized(); ObjectPtr &operator=(JSObject *obj) { IncrementalObjectBarrier(value); @@ -242,9 +256,7 @@ class ObjectPtr return *this; } - void trace(JSTracer *trc, const char *name) { - JS_CallHeapObjectTracer(trc, &value, name); - } + void trace(JSTracer *trc, const char *name); JSObject &operator*() const { return *value; } JSObject *operator->() const { return value; } @@ -255,7 +267,7 @@ class ObjectPtr * Unsets the gray bit for anything reachable from |thing|. |kind| should not be * JSTRACE_SHAPE. |thing| should be non-null. */ -extern JS_FRIEND_API(void) +extern JS_FRIEND_API(bool) UnmarkGrayGCThingRecursively(void *thing, JSGCTraceKind kind); /* @@ -276,7 +288,7 @@ ExposeGCThingToActiveJS(void *thing, JSGCTraceKind kind) * All live objects in the nursery are moved to tenured at the beginning of * each GC slice, so the gray marker never sees nursery things. */ - if (uintptr_t(thing) >= rt->gcNurseryStart_ && uintptr_t(thing) < rt->gcNurseryEnd_) + if (js::gc::IsInsideNursery(rt, thing)) return; #endif if (IsIncrementalBarrierNeededOnGCThing(rt, thing, kind)) @@ -292,6 +304,37 @@ ExposeValueToActiveJS(const Value &v) ExposeGCThingToActiveJS(v.toGCThing(), v.gcKind()); } +static JS_ALWAYS_INLINE void +ExposeObjectToActiveJS(JSObject *obj) +{ + ExposeGCThingToActiveJS(obj, JSTRACE_OBJECT); +} + +/* + * If a GC is currently marking, mark the object black. + */ +static JS_ALWAYS_INLINE void +MarkGCThingAsLive(JSRuntime *rt_, void *thing, JSGCTraceKind kind) +{ + shadow::Runtime *rt = shadow::Runtime::asShadowRuntime(rt_); +#ifdef JSGC_GENERATIONAL + /* + * Any object in the nursery will not be freed during any GC running at that time. + */ + if (js::gc::IsInsideNursery(rt, thing)) + return; +#endif + if (IsIncrementalBarrierNeededOnGCThing(rt, thing, kind)) + IncrementalReferenceBarrier(thing, kind); +} + +static JS_ALWAYS_INLINE void +MarkStringAsLive(Zone *zone, JSString *string) +{ + JSRuntime *rt = JS::shadow::Zone::asShadowZone(zone)->runtimeFromMainThread(); + MarkGCThingAsLive(rt, string, JSTRACE_STRING); +} + } /* namespace JS */ #endif /* js_GCAPI_h */ diff --git a/external/spidermonkey/include/ios/js/HashTable.h b/external/spidermonkey/include/ios/js/HashTable.h index aa05b71472..a6b4361dea 100644 --- a/external/spidermonkey/include/ios/js/HashTable.h +++ b/external/spidermonkey/include/ios/js/HashTable.h @@ -7,17 +7,18 @@ #ifndef js_HashTable_h #define js_HashTable_h +#include "mozilla/Alignment.h" #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Casting.h" #include "mozilla/DebugOnly.h" #include "mozilla/MemoryReporting.h" #include "mozilla/Move.h" +#include "mozilla/NullPtr.h" #include "mozilla/PodOperations.h" #include "mozilla/ReentrancyGuard.h" #include "mozilla/TemplateLib.h" #include "mozilla/TypeTraits.h" -#include "mozilla/Util.h" #include "js/Utility.h" @@ -60,7 +61,7 @@ class HashMap { typedef Key KeyType; static const Key &getKey(TableEntry &e) { return e.key; } - static void setKey(TableEntry &e, Key &k) { const_cast(e.key) = k; } + static void setKey(TableEntry &e, Key &k) { HashPolicy::rekey(const_cast(e.key), k); } }; typedef detail::HashTable Impl; @@ -138,18 +139,18 @@ class HashMap template bool add(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.add(p, mozilla::Move(e)); + return impl.add(p, mozilla::OldMove(e)); } bool add(AddPtr &p, const Key &k) { Entry e(k, Value()); - return impl.add(p, mozilla::Move(e)); + return impl.add(p, mozilla::OldMove(e)); } template bool relookupOrAdd(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.relookupOrAdd(p, k, mozilla::Move(e)); + return impl.relookupOrAdd(p, k, mozilla::OldMove(e)); } // |all()| returns a Range containing |count()| elements. E.g.: @@ -213,7 +214,7 @@ class HashMap /************************************************** Shorthand operations */ bool has(const Lookup &l) const { - return impl.lookup(l) != NULL; + return impl.lookup(l) != nullptr; } // Overwrite existing value with v. Return false on oom. @@ -231,7 +232,7 @@ class HashMap template bool putNew(const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.putNew(k, mozilla::Move(e)); + return impl.putNew(k, mozilla::OldMove(e)); } // Add (k,defaultValue) if |k| is not found. Return a false-y Ptr on oom. @@ -249,17 +250,22 @@ class HashMap remove(p); } + // Infallibly rekey one entry, if necessary. + // Requires template parameters Key and HashPolicy::Lookup to be the same type. + void rekeyIfMoved(const Key &old_key, const Key &new_key) { + if (old_key != new_key) + rekeyAs(old_key, new_key, new_key); + } + // Infallibly rekey one entry, if present. - void rekey(const Lookup &old_key, const Key &new_key) { - if (old_key != new_key) { - if (Ptr p = lookup(old_key)) - impl.rekey(p, new_key, new_key); - } + void rekeyAs(const Lookup &old_lookup, const Lookup &new_lookup, const Key &new_key) { + if (Ptr p = lookup(old_lookup)) + impl.rekeyAndMaybeRehash(p, new_lookup, new_key); } // HashMap is movable - HashMap(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} - void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } + HashMap(mozilla::MoveRef rhs) : impl(mozilla::OldMove(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::OldMove(rhs->impl); } private: // HashMap is not copyable or assignable @@ -295,7 +301,7 @@ class HashSet { typedef T KeyType; static const KeyType &getKey(const T &t) { return t; } - static void setKey(T &t, KeyType &k) { t = k; } + static void setKey(T &t, KeyType &k) { HashPolicy::rekey(t, k); } }; typedef detail::HashTable Impl; @@ -323,6 +329,10 @@ class HashSet typedef typename Impl::Ptr Ptr; Ptr lookup(const Lookup &l) const { return impl.lookup(l); } + // Like lookup, but does not assert if two threads call lookup at the same + // time. Only use this method when none of the threads will modify the map. + Ptr readonlyThreadsafeLookup(const Lookup &l) const { return impl.readonlyThreadsafeLookup(l); } + // Assuming |p.found()|, remove |*p|. void remove(Ptr p) { impl.remove(p); } @@ -425,7 +435,7 @@ class HashSet /************************************************** Shorthand operations */ bool has(const Lookup &l) const { - return impl.lookup(l) != NULL; + return impl.lookup(l) != nullptr; } // Overwrite existing value with v. Return false on oom. @@ -449,16 +459,21 @@ class HashSet } // Infallibly rekey one entry, if present. - void rekey(const Lookup &old_key, const T &new_key) { - if (old_key != new_key) { - if (Ptr p = lookup(old_key)) - impl.rekey(p, new_key, new_key); - } + // Requires template parameters T and HashPolicy::Lookup to be the same type. + void rekeyIfMoved(const Lookup &old_value, const T &new_value) { + if (old_value != new_value) + rekeyAs(old_value, new_value, new_value); + } + + // Infallibly rekey one entry, if present. + void rekeyAs(const Lookup &old_lookup, const Lookup &new_lookup, const T &new_value) { + if (Ptr p = lookup(old_lookup)) + impl.rekeyAndMaybeRehash(p, new_lookup, new_value); } // HashSet is movable - HashSet(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} - void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } + HashSet(mozilla::MoveRef rhs) : impl(mozilla::OldMove(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::OldMove(rhs->impl); } private: // HashSet is not copyable or assignable @@ -505,7 +520,7 @@ struct PointerHasher JS_ASSERT(!JS::IsPoisonedPtr(l)); size_t word = reinterpret_cast(l) >> zeroBits; JS_STATIC_ASSERT(sizeof(HashNumber) == 4); -#if JS_BYTES_PER_WORD == 4 +#if JS_BITS_PER_WORD == 32 return HashNumber(word); #else JS_STATIC_ASSERT(sizeof word == 8); @@ -517,6 +532,9 @@ struct PointerHasher JS_ASSERT(!JS::IsPoisonedPtr(l)); return k == l; } + static void rekey(Key &k, const Key& newKey) { + k = newKey; + } }; // Default hash policy: just use the 'lookup' value. This of course only @@ -535,6 +553,9 @@ struct DefaultHasher // Use builtin or overloaded operator==. return k == l; } + static void rekey(Key &k, const Key& newKey) { + k = newKey; + } }; // Specialize hashing policy for pointer types. It assumes that the type is @@ -558,6 +579,19 @@ struct DefaultHasher } }; +template <> +struct DefaultHasher +{ + typedef float Lookup; + static HashNumber hash(float f) { + JS_STATIC_ASSERT(sizeof(HashNumber) == 4); + return HashNumber(mozilla::BitwiseCast(f)); + } + static bool match(float lhs, float rhs) { + return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); + } +}; + /*****************************************************************************/ // Both HashMap and HashSet are implemented by a single HashTable that is even @@ -579,7 +613,7 @@ class HashMapEntry HashMapEntry(const KeyInput &k, const ValueInput &v) : key(k), value(v) {} HashMapEntry(mozilla::MoveRef rhs) - : key(mozilla::Move(rhs->key)), value(mozilla::Move(rhs->value)) { } + : key(mozilla::OldMove(rhs->key)), value(mozilla::OldMove(rhs->value)) { } typedef Key KeyType; typedef Value ValueType; @@ -750,7 +784,7 @@ class HashTable : private AllocPolicy mozilla::DebugOnly validEntry; public: - Range() : cur(NULL), end(NULL), validEntry(false) {} + Range() : cur(nullptr), end(nullptr), validEntry(false) {} bool empty() const { return cur == end; @@ -808,7 +842,7 @@ class HashTable : private AllocPolicy // a new key at the new Lookup position. |front()| is invalid after // this operation until the next call to |popFront()|. void rekeyFront(const Lookup &l, const Key &k) { - table.rekey(*this->cur, l, k); + table.rekeyWithoutRehash(*this->cur, l, k); rekeyed = true; this->validEntry = false; } @@ -834,13 +868,13 @@ class HashTable : private AllocPolicy : AllocPolicy(*rhs) { mozilla::PodAssign(this, &*rhs); - rhs->table = NULL; + rhs->table = nullptr; } void operator=(mozilla::MoveRef rhs) { if (table) destroyTable(*this, table, capacity()); mozilla::PodAssign(this, &*rhs); - rhs->table = NULL; + rhs->table = nullptr; } private: @@ -941,7 +975,7 @@ class HashTable : private AllocPolicy entryCount(0), gen(0), removedCount(0), - table(NULL), + table(nullptr), entered(false), mutationCount(0) {} @@ -1067,7 +1101,7 @@ class HashTable : private AllocPolicy DoubleHash dh = hash2(keyHash); // Save the first removed entry pointer so we can recycle later. - Entry *firstRemoved = NULL; + Entry *firstRemoved = nullptr; while(true) { if (JS_UNLIKELY(entry->isRemoved())) { @@ -1163,7 +1197,7 @@ class HashTable : private AllocPolicy for (Entry *src = oldTable, *end = src + oldCap; src < end; ++src) { if (src->isLive()) { HashNumber hn = src->getKeyHash(); - findFreeEntry(hn).setLive(hn, mozilla::Move(src->get())); + findFreeEntry(hn).setLive(hn, mozilla::OldMove(src->get())); src->destroy(); } } @@ -1307,7 +1341,7 @@ class HashTable : private AllocPolicy return; destroyTable(*this, table, capacity()); - table = NULL; + table = nullptr; gen++; entryCount = 0; removedCount = 0; @@ -1456,15 +1490,21 @@ class HashTable : private AllocPolicy checkUnderloaded(); } - void rekey(Ptr p, const Lookup &l, const Key &k) + void rekeyWithoutRehash(Ptr p, const Lookup &l, const Key &k) { JS_ASSERT(table); mozilla::ReentrancyGuard g(*this); JS_ASSERT(p.found()); - typename HashTableEntry::NonConstT t(mozilla::Move(*p)); + typename HashTableEntry::NonConstT t(mozilla::OldMove(*p)); HashPolicy::setKey(t, const_cast(k)); remove(*p.entry_); - putNewInfallible(l, mozilla::Move(t)); + putNewInfallible(l, mozilla::OldMove(t)); + } + + void rekeyAndMaybeRehash(Ptr p, const Lookup &l, const Key &k) + { + rekeyWithoutRehash(p, l, k); + checkOverRemoved(); } #undef METER diff --git a/external/spidermonkey/include/ios/js/HeapAPI.h b/external/spidermonkey/include/ios/js/HeapAPI.h index 4d739304bc..438c23c05f 100644 --- a/external/spidermonkey/include/ios/js/HeapAPI.h +++ b/external/spidermonkey/include/ios/js/HeapAPI.h @@ -7,12 +7,23 @@ #ifndef js_HeapAPI_h #define js_HeapAPI_h +#include + #include "jspubtd.h" #include "js/Utility.h" /* These values are private to the JS engine. */ namespace js { + +// Whether the current thread is permitted access to any part of the specified +// runtime or zone. +JS_FRIEND_API(bool) +CurrentThreadCanAccessRuntime(JSRuntime *rt); + +JS_FRIEND_API(bool) +CurrentThreadCanAccessZone(JS::Zone *zone); + namespace gc { const size_t ArenaShift = 12; @@ -57,9 +68,43 @@ struct ArenaHeader struct Zone { + protected: + JSRuntime *const runtime_; + JSTracer *const barrierTracer_; // A pointer to the JSRuntime's |gcMarker|. + + public: bool needsBarrier_; - Zone() : needsBarrier_(false) {} + Zone(JSRuntime *runtime, JSTracer *barrierTracerArg) + : runtime_(runtime), + barrierTracer_(barrierTracerArg), + needsBarrier_(false) + {} + + bool needsBarrier() const { + return needsBarrier_; + } + + JSTracer *barrierTracer() { + JS_ASSERT(needsBarrier_); + JS_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); + return barrierTracer_; + } + + JSRuntime *runtimeFromMainThread() const { + JS_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); + return runtime_; + } + + // Note: Unrestricted access to the zone's runtime from an arbitrary + // thread can easily lead to races. Use this method very carefully. + JSRuntime *runtimeFromAnyThread() const { + return runtime_; + } + + static JS::shadow::Zone *asShadowZone(JS::Zone *zone) { + return reinterpret_cast(zone); + } }; } /* namespace shadow */ @@ -94,8 +139,9 @@ GetGCThingMarkWordAndMask(const void *thing, uint32_t color, size_t bit = (addr & js::gc::ChunkMask) / js::gc::CellSize + color; JS_ASSERT(bit < js::gc::ChunkMarkBitmapBits); uintptr_t *bitmap = GetGCThingMarkBitmap(thing); - *maskp = uintptr_t(1) << (bit % JS_BITS_PER_WORD); - *wordp = &bitmap[bit / JS_BITS_PER_WORD]; + const uintptr_t nbits = sizeof(*bitmap) * CHAR_BIT; + *maskp = uintptr_t(1) << (bit % nbits); + *wordp = &bitmap[bit / nbits]; } static JS_ALWAYS_INLINE JS::shadow::ArenaHeader * @@ -106,6 +152,16 @@ GetGCThingArena(void *thing) return reinterpret_cast(addr); } +JS_ALWAYS_INLINE bool +IsInsideNursery(const JS::shadow::Runtime *runtime, const void *p) +{ +#ifdef JSGC_GENERATIONAL + return uintptr_t(p) >= runtime->gcNurseryStart_ && uintptr_t(p) < runtime->gcNurseryEnd_; +#else + return false; +#endif +} + } /* namespace gc */ } /* namespace js */ @@ -128,6 +184,16 @@ GetObjectZone(JSObject *obj) static JS_ALWAYS_INLINE bool GCThingIsMarkedGray(void *thing) { +#ifdef JSGC_GENERATIONAL + /* + * GC things residing in the nursery cannot be gray: they have no mark bits. + * All live objects in the nursery are moved to tenured at the beginning of + * each GC slice, so the gray marker never sees nursery things. + */ + JS::shadow::Runtime *rt = js::gc::GetGCThingRuntime(thing); + if (js::gc::IsInsideNursery(rt, thing)) + return false; +#endif uintptr_t *word, mask; js::gc::GetGCThingMarkWordAndMask(thing, js::gc::GRAY, &word, &mask); return *word & mask; diff --git a/external/spidermonkey/include/ios/js/Id.h b/external/spidermonkey/include/ios/js/Id.h new file mode 100644 index 0000000000..447deb62e6 --- /dev/null +++ b/external/spidermonkey/include/ios/js/Id.h @@ -0,0 +1,192 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_Id_h +#define js_Id_h + +// A jsid is an identifier for a property or method of an object which is +// either a 31-bit signed integer, interned string or object. +// +// Also, there is an additional jsid value, JSID_VOID, which does not occur in +// JS scripts but may be used to indicate the absence of a valid jsid. A void +// jsid is not a valid id and only arises as an exceptional API return value, +// such as in JS_NextProperty. Embeddings must not pass JSID_VOID into JSAPI +// entry points expecting a jsid and do not need to handle JSID_VOID in hooks +// receiving a jsid except when explicitly noted in the API contract. +// +// A jsid is not implicitly convertible to or from a jsval; JS_ValueToId or +// JS_IdToValue must be used instead. + +#include "mozilla/NullPtr.h" + +#include "jstypes.h" + +#include "js/RootingAPI.h" +#include "js/TypeDecls.h" +#include "js/Utility.h" + +#ifdef JS_USE_JSID_STRUCT_TYPES +struct jsid +{ + size_t asBits; + bool operator==(jsid rhs) const { return asBits == rhs.asBits; } + bool operator!=(jsid rhs) const { return asBits != rhs.asBits; } +}; +# define JSID_BITS(id) (id.asBits) +#else +# define JSID_BITS(id) (id) +#endif + +#define JSID_TYPE_STRING 0x0 +#define JSID_TYPE_INT 0x1 +#define JSID_TYPE_VOID 0x2 +#define JSID_TYPE_OBJECT 0x4 +#define JSID_TYPE_MASK 0x7 + +// Avoid using canonical 'id' for jsid parameters since this is a magic word in +// Objective-C++ which, apparently, wants to be able to #include jsapi.h. +#define id iden + +static JS_ALWAYS_INLINE bool +JSID_IS_STRING(jsid id) +{ + return (JSID_BITS(id) & JSID_TYPE_MASK) == 0; +} + +static JS_ALWAYS_INLINE JSString * +JSID_TO_STRING(jsid id) +{ + JS_ASSERT(JSID_IS_STRING(id)); + return (JSString *)JSID_BITS(id); +} + +static JS_ALWAYS_INLINE bool +JSID_IS_ZERO(jsid id) +{ + return JSID_BITS(id) == 0; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_INT(jsid id) +{ + return !!(JSID_BITS(id) & JSID_TYPE_INT); +} + +static JS_ALWAYS_INLINE int32_t +JSID_TO_INT(jsid id) +{ + JS_ASSERT(JSID_IS_INT(id)); + return ((uint32_t)JSID_BITS(id)) >> 1; +} + +#define JSID_INT_MIN 0 +#define JSID_INT_MAX INT32_MAX + +static JS_ALWAYS_INLINE bool +INT_FITS_IN_JSID(int32_t i) +{ + return i >= 0; +} + +static JS_ALWAYS_INLINE jsid +INT_TO_JSID(int32_t i) +{ + jsid id; + JS_ASSERT(INT_FITS_IN_JSID(i)); + JSID_BITS(id) = ((i << 1) | JSID_TYPE_INT); + return id; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_OBJECT(jsid id) +{ + return (JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_OBJECT && + (size_t)JSID_BITS(id) != JSID_TYPE_OBJECT; +} + +static JS_ALWAYS_INLINE JSObject * +JSID_TO_OBJECT(jsid id) +{ + JS_ASSERT(JSID_IS_OBJECT(id)); + return (JSObject *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); +} + +static JS_ALWAYS_INLINE jsid +OBJECT_TO_JSID(JSObject *obj) +{ + jsid id; + JS_ASSERT(obj != nullptr); + JS_ASSERT(((size_t)obj & JSID_TYPE_MASK) == 0); + JSID_BITS(id) = ((size_t)obj | JSID_TYPE_OBJECT); + return id; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_GCTHING(jsid id) +{ + return JSID_IS_STRING(id) || JSID_IS_OBJECT(id); +} + +static JS_ALWAYS_INLINE void * +JSID_TO_GCTHING(jsid id) +{ + return (void *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); +} + +static JS_ALWAYS_INLINE bool +JSID_IS_VOID(const jsid id) +{ + JS_ASSERT_IF(((size_t)JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_VOID, + JSID_BITS(id) == JSID_TYPE_VOID); + return ((size_t)JSID_BITS(id) == JSID_TYPE_VOID); +} + +static JS_ALWAYS_INLINE bool +JSID_IS_EMPTY(const jsid id) +{ + return ((size_t)JSID_BITS(id) == JSID_TYPE_OBJECT); +} + +#undef id + +#ifdef JS_USE_JSID_STRUCT_TYPES +extern JS_PUBLIC_DATA(const jsid) JSID_VOID; +extern JS_PUBLIC_DATA(const jsid) JSID_EMPTY; +#else +# define JSID_VOID ((jsid)JSID_TYPE_VOID) +# define JSID_EMPTY ((jsid)JSID_TYPE_OBJECT) +#endif + +extern JS_PUBLIC_DATA(const JS::Handle) JSID_VOIDHANDLE; +extern JS_PUBLIC_DATA(const JS::Handle) JSID_EMPTYHANDLE; + +namespace js { + +inline bool +IsPoisonedId(jsid iden) +{ + if (JSID_IS_STRING(iden)) + return JS::IsPoisonedPtr(JSID_TO_STRING(iden)); + if (JSID_IS_OBJECT(iden)) + return JS::IsPoisonedPtr(JSID_TO_OBJECT(iden)); + return false; +} + +template <> struct GCMethods +{ + static jsid initial() { return JSID_VOID; } + static ThingRootKind kind() { return THING_ROOT_ID; } + static bool poisoned(jsid id) { return IsPoisonedId(id); } + static bool needsPostBarrier(jsid id) { return false; } +#ifdef JSGC_GENERATIONAL + static void postBarrier(jsid *idp) {} + static void relocate(jsid *idp) {} +#endif +}; + +} + +#endif /* js_Id_h */ diff --git a/external/spidermonkey/include/ios/js/MemoryMetrics.h b/external/spidermonkey/include/ios/js/MemoryMetrics.h index ed61e1c427..2336e35624 100644 --- a/external/spidermonkey/include/ios/js/MemoryMetrics.h +++ b/external/spidermonkey/include/ios/js/MemoryMetrics.h @@ -7,20 +7,54 @@ #ifndef js_MemoryMetrics_h #define js_MemoryMetrics_h -// These declarations are not within jsapi.h because they are highly likely to -// change in the future. Depend on them at your own risk. +// These declarations are highly likely to change in the future. Depend on them +// at your own risk. #include "mozilla/MemoryReporting.h" +#include "mozilla/NullPtr.h" +#include "mozilla/PodOperations.h" #include #include "jsalloc.h" #include "jspubtd.h" +#include "js/HashTable.h" #include "js/Utility.h" #include "js/Vector.h" -class nsISupports; // This is needed for ObjectPrivateVisitor. +class nsISupports; // Needed for ObjectPrivateVisitor. + +namespace JS { + +struct TabSizes +{ + enum Kind { + Objects, + Strings, + Private, + Other + }; + + TabSizes() { mozilla::PodZero(this); } + + void add(Kind kind, size_t n) { + switch (kind) { + case Objects: objects += n; break; + case Strings: strings += n; break; + case Private: private_ += n; break; + case Other: other += n; break; + default: MOZ_CRASH("bad TabSizes kind"); + } + } + + size_t objects; + size_t strings; + size_t private_; + size_t other; +}; + +} // namespace JS namespace js { @@ -30,9 +64,86 @@ namespace js { // MemoryReportingSundriesThreshold() bytes. // // We need to define this value here, rather than in the code which actually -// generates the memory reports, because HugeStringInfo uses this value. +// generates the memory reports, because NotableStringInfo uses this value. JS_FRIEND_API(size_t) MemoryReportingSundriesThreshold(); +// This hash policy avoids flattening ropes (which perturbs the site being +// measured and requires a JSContext) at the expense of doing a FULL ROPE COPY +// on every hash and match! Beware. +struct InefficientNonFlatteningStringHashPolicy +{ + typedef JSString *Lookup; + static HashNumber hash(const Lookup &l); + static bool match(const JSString *const &k, const Lookup &l); +}; + +// This file features many classes with numerous size_t fields, and each such +// class has one or more methods that need to operate on all of these fields. +// Writing these individually is error-prone -- it's easy to add a new field +// without updating all the required methods. So we define a single macro list +// in each class to name the fields (and notable characteristics of them), and +// then use the following macros to transform those lists into the required +// methods. +// +// In some classes, one or more of the macro arguments aren't used. We use '_' +// for those. +// +#define DECL_SIZE(kind, gc, mSize) size_t mSize; +#define ZERO_SIZE(kind, gc, mSize) mSize(0), +#define COPY_OTHER_SIZE(kind, gc, mSize) mSize(other.mSize), +#define ADD_OTHER_SIZE(kind, gc, mSize) mSize += other.mSize; +#define ADD_SIZE_TO_N_IF_LIVE_GC_THING(kind, gc, mSize) n += (js::gc == js::IsLiveGCThing) ? mSize : 0; +#define ADD_TO_TAB_SIZES(kind, gc, mSize) sizes->add(JS::TabSizes::kind, mSize); + +// Used to annotate which size_t fields measure live GC things and which don't. +enum { + NotLiveGCThing = false, + IsLiveGCThing = true +}; + +struct ZoneStatsPod +{ +#define FOR_EACH_SIZE(macro) \ + macro(Other, NotLiveGCThing, gcHeapArenaAdmin) \ + macro(Other, NotLiveGCThing, unusedGCThings) \ + macro(Other, IsLiveGCThing, lazyScriptsGCHeap) \ + macro(Other, NotLiveGCThing, lazyScriptsMallocHeap) \ + macro(Other, IsLiveGCThing, ionCodesGCHeap) \ + macro(Other, IsLiveGCThing, typeObjectsGCHeap) \ + macro(Other, NotLiveGCThing, typeObjectsMallocHeap) \ + macro(Other, NotLiveGCThing, typePool) \ + macro(Strings, IsLiveGCThing, stringsShortGCHeap) \ + macro(Strings, IsLiveGCThing, stringsNormalGCHeap) \ + macro(Strings, NotLiveGCThing, stringsNormalMallocHeap) + + ZoneStatsPod() + : FOR_EACH_SIZE(ZERO_SIZE) + extra() + {} + + void add(const ZoneStatsPod &other) { + FOR_EACH_SIZE(ADD_OTHER_SIZE) + // Do nothing with |extra|. + } + + size_t sizeOfLiveGCThings() const { + size_t n = 0; + FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) + // Do nothing with |extra|. + return n; + } + + void addToTabSizes(JS::TabSizes *sizes) const { + FOR_EACH_SIZE(ADD_TO_TAB_SIZES) + // Do nothing with |extra|. + } + + FOR_EACH_SIZE(DECL_SIZE) + void *extra; // This field can be used by embedders. + +#undef FOR_EACH_SIZE +}; + } // namespace js namespace JS { @@ -40,352 +151,320 @@ namespace JS { // Data for tracking memory usage of things hanging off objects. struct ObjectsExtraSizes { - size_t slots; - size_t elementsNonAsmJS; - size_t elementsAsmJSHeap; - size_t elementsAsmJSNonHeap; - size_t argumentsData; - size_t regExpStatics; - size_t propertyIteratorData; - size_t ctypesData; - size_t private_; // The '_' suffix is required because |private| is a keyword. - // Note that this field is measured separately from the others. +#define FOR_EACH_SIZE(macro) \ + macro(Objects, NotLiveGCThing, mallocHeapSlots) \ + macro(Objects, NotLiveGCThing, mallocHeapElementsNonAsmJS) \ + macro(Objects, NotLiveGCThing, mallocHeapElementsAsmJS) \ + macro(Objects, NotLiveGCThing, nonHeapElementsAsmJS) \ + macro(Objects, NotLiveGCThing, nonHeapCodeAsmJS) \ + macro(Objects, NotLiveGCThing, mallocHeapAsmJSModuleData) \ + macro(Objects, NotLiveGCThing, mallocHeapArgumentsData) \ + macro(Objects, NotLiveGCThing, mallocHeapRegExpStatics) \ + macro(Objects, NotLiveGCThing, mallocHeapPropertyIteratorData) \ + macro(Objects, NotLiveGCThing, mallocHeapCtypesData) - ObjectsExtraSizes() { memset(this, 0, sizeof(ObjectsExtraSizes)); } + ObjectsExtraSizes() + : FOR_EACH_SIZE(ZERO_SIZE) + dummy() + {} - void add(ObjectsExtraSizes &sizes) { - this->slots += sizes.slots; - this->elementsNonAsmJS += sizes.elementsNonAsmJS; - this->elementsAsmJSHeap += sizes.elementsAsmJSHeap; - this->elementsAsmJSNonHeap += sizes.elementsAsmJSNonHeap; - this->argumentsData += sizes.argumentsData; - this->regExpStatics += sizes.regExpStatics; - this->propertyIteratorData += sizes.propertyIteratorData; - this->ctypesData += sizes.ctypesData; - this->private_ += sizes.private_; + void add(const ObjectsExtraSizes &other) { + FOR_EACH_SIZE(ADD_OTHER_SIZE) } -}; -// Data for tracking analysis/inference memory usage. -struct TypeInferenceSizes -{ - size_t typeScripts; - size_t typeResults; - size_t analysisPool; - size_t pendingArrays; - size_t allocationSiteTables; - size_t arrayTypeTables; - size_t objectTypeTables; - - TypeInferenceSizes() { memset(this, 0, sizeof(TypeInferenceSizes)); } - - void add(TypeInferenceSizes &sizes) { - this->typeScripts += sizes.typeScripts; - this->typeResults += sizes.typeResults; - this->analysisPool += sizes.analysisPool; - this->pendingArrays += sizes.pendingArrays; - this->allocationSiteTables += sizes.allocationSiteTables; - this->arrayTypeTables += sizes.arrayTypeTables; - this->objectTypeTables += sizes.objectTypeTables; + size_t sizeOfLiveGCThings() const { + size_t n = 0; + FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) + return n; } + + void addToTabSizes(TabSizes *sizes) const { + FOR_EACH_SIZE(ADD_TO_TAB_SIZES) + } + + FOR_EACH_SIZE(DECL_SIZE) + int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) + +#undef FOR_EACH_SIZE }; // Data for tracking JIT-code memory usage. struct CodeSizes { - size_t ion; - size_t asmJS; - size_t baseline; - size_t regexp; - size_t other; - size_t unused; +#define FOR_EACH_SIZE(macro) \ + macro(_, _, ion) \ + macro(_, _, baseline) \ + macro(_, _, regexp) \ + macro(_, _, other) \ + macro(_, _, unused) - CodeSizes() { memset(this, 0, sizeof(CodeSizes)); } + CodeSizes() + : FOR_EACH_SIZE(ZERO_SIZE) + dummy() + {} + + FOR_EACH_SIZE(DECL_SIZE) + int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) + +#undef FOR_EACH_SIZE }; -// Holds data about a huge string (one which uses more HugeStringInfo::MinSize -// bytes of memory), so we can report it individually. -struct HugeStringInfo +// This class holds information about the memory taken up by identical copies of +// a particular string. Multiple JSStrings may have their sizes aggregated +// together into one StringInfo object. +struct StringInfo { - HugeStringInfo() : length(0), size(0) { memset(&buffer, 0, sizeof(buffer)); } + StringInfo() + : length(0), numCopies(0), shortGCHeap(0), normalGCHeap(0), normalMallocHeap(0) + {} + + StringInfo(size_t len, size_t shorts, size_t normals, size_t chars) + : length(len), + numCopies(1), + shortGCHeap(shorts), + normalGCHeap(normals), + normalMallocHeap(chars) + {} + + void add(size_t shorts, size_t normals, size_t chars) { + shortGCHeap += shorts; + normalGCHeap += normals; + normalMallocHeap += chars; + numCopies++; + } + + void add(const StringInfo& info) { + MOZ_ASSERT(length == info.length); + + shortGCHeap += info.shortGCHeap; + normalGCHeap += info.normalGCHeap; + normalMallocHeap += info.normalMallocHeap; + numCopies += info.numCopies; + } + + size_t totalSizeOf() const { + return shortGCHeap + normalGCHeap + normalMallocHeap; + } + + size_t totalGCHeapSizeOf() const { + return shortGCHeap + normalGCHeap; + } + + // The string's length, excluding the null-terminator. + size_t length; + + // How many copies of the string have we seen? + size_t numCopies; + + // These are all totals across all copies of the string we've seen. + size_t shortGCHeap; + size_t normalGCHeap; + size_t normalMallocHeap; +}; + +// Holds data about a notable string (one which uses more than +// NotableStringInfo::notableSize() bytes of memory), so we can report it +// individually. +// +// Essentially the only difference between this class and StringInfo is that +// NotableStringInfo holds a copy of the string's chars. +struct NotableStringInfo : public StringInfo +{ + NotableStringInfo(); + NotableStringInfo(JSString *str, const StringInfo &info); + NotableStringInfo(mozilla::MoveRef info); + NotableStringInfo &operator=(mozilla::MoveRef info); + + ~NotableStringInfo() { + js_free(buffer); + } // A string needs to take up this many bytes of storage before we consider - // it to be "huge". - static size_t MinSize() { + // it to be "notable". + static size_t notableSize() { return js::MemoryReportingSundriesThreshold(); } - // A string's size in memory is not necessarily equal to twice its length - // because the allocator and the JS engine both may round up. - size_t length; - size_t size; + char *buffer; - // We record the first 32 chars of the escaped string here. (We escape the - // string so we can use a char[] instead of a jschar[] here. - char buffer[32]; + private: + NotableStringInfo(const NotableStringInfo& info) MOZ_DELETE; }; -// These measurements relate directly to the JSRuntime, and not to +// These measurements relate directly to the JSRuntime, and not to zones and // compartments within it. struct RuntimeSizes { - RuntimeSizes() { memset(this, 0, sizeof(RuntimeSizes)); } +#define FOR_EACH_SIZE(macro) \ + macro(_, _, object) \ + macro(_, _, atomsTable) \ + macro(_, _, contexts) \ + macro(_, _, dtoa) \ + macro(_, _, temporary) \ + macro(_, _, regexpData) \ + macro(_, _, interpreterStack) \ + macro(_, _, gcMarker) \ + macro(_, _, mathCache) \ + macro(_, _, scriptData) \ + macro(_, _, scriptSources) - size_t object; - size_t atomsTable; - size_t contexts; - size_t dtoa; - size_t temporary; - size_t regexpData; - size_t interpreterStack; - size_t gcMarker; - size_t mathCache; - size_t scriptData; - size_t scriptSources; - - CodeSizes code; -}; - -struct ZoneStats -{ - ZoneStats() - : extra(NULL), - gcHeapArenaAdmin(0), - gcHeapUnusedGcThings(0), - gcHeapStringsNormal(0), - gcHeapStringsShort(0), - gcHeapLazyScripts(0), - gcHeapTypeObjects(0), - gcHeapIonCodes(0), - stringCharsNonHuge(0), - lazyScripts(0), - typeObjects(0), - typePool(0), - hugeStrings() + RuntimeSizes() + : FOR_EACH_SIZE(ZERO_SIZE) + code() {} - ZoneStats(const ZoneStats &other) - : extra(other.extra), - gcHeapArenaAdmin(other.gcHeapArenaAdmin), - gcHeapUnusedGcThings(other.gcHeapUnusedGcThings), - gcHeapStringsNormal(other.gcHeapStringsNormal), - gcHeapStringsShort(other.gcHeapStringsShort), - gcHeapLazyScripts(other.gcHeapLazyScripts), - gcHeapTypeObjects(other.gcHeapTypeObjects), - gcHeapIonCodes(other.gcHeapIonCodes), - stringCharsNonHuge(other.stringCharsNonHuge), - lazyScripts(other.lazyScripts), - typeObjects(other.typeObjects), - typePool(other.typePool), - hugeStrings() - { - hugeStrings.appendAll(other.hugeStrings); + FOR_EACH_SIZE(DECL_SIZE) + CodeSizes code; + +#undef FOR_EACH_SIZE +}; + +struct ZoneStats : js::ZoneStatsPod +{ + ZoneStats() { + strings.init(); } - // Add other's numbers to this object's numbers. - void add(ZoneStats &other) { - #define ADD(x) this->x += other.x + ZoneStats(mozilla::MoveRef other) + : ZoneStatsPod(other), + strings(mozilla::OldMove(other->strings)), + notableStrings(mozilla::OldMove(other->notableStrings)) + {} - ADD(gcHeapArenaAdmin); - ADD(gcHeapUnusedGcThings); + // Add other's numbers to this object's numbers. Both objects' + // notableStrings vectors must be empty at this point, because we can't + // merge them. (A NotableStringInfo contains only a prefix of the string, + // so we can't tell whether two NotableStringInfo objects correspond to the + // same string.) + void add(const ZoneStats &other) { + ZoneStatsPod::add(other); - ADD(gcHeapStringsNormal); - ADD(gcHeapStringsShort); - ADD(gcHeapLazyScripts); - ADD(gcHeapTypeObjects); - ADD(gcHeapIonCodes); + MOZ_ASSERT(notableStrings.empty()); + MOZ_ASSERT(other.notableStrings.empty()); - ADD(stringCharsNonHuge); - ADD(lazyScripts); - ADD(typeObjects); - ADD(typePool); - - #undef ADD - - hugeStrings.appendAll(other.hugeStrings); + for (StringsHashMap::Range r = other.strings.all(); !r.empty(); r.popFront()) { + StringsHashMap::AddPtr p = strings.lookupForAdd(r.front().key); + if (p) { + // We've seen this string before; add its size to our tally. + p->value.add(r.front().value); + } else { + // We haven't seen this string before; add it to the hashtable. + strings.add(p, r.front().key, r.front().value); + } + } } - // This field can be used by embedders. - void *extra; + size_t sizeOfLiveGCThings() const { + size_t n = ZoneStatsPod::sizeOfLiveGCThings(); + for (size_t i = 0; i < notableStrings.length(); i++) { + const JS::NotableStringInfo& info = notableStrings[i]; + n += info.totalGCHeapSizeOf(); + } + return n; + } - size_t gcHeapArenaAdmin; - size_t gcHeapUnusedGcThings; + typedef js::HashMap StringsHashMap; - size_t gcHeapStringsNormal; - size_t gcHeapStringsShort; - - size_t gcHeapLazyScripts; - size_t gcHeapTypeObjects; - size_t gcHeapIonCodes; - - size_t stringCharsNonHuge; - size_t lazyScripts; - size_t typeObjects; - size_t typePool; - - js::Vector hugeStrings; - - // The size of all the live things in the GC heap that don't belong to any - // compartment. - size_t GCHeapThingsSize(); + StringsHashMap strings; + js::Vector notableStrings; }; struct CompartmentStats { +#define FOR_EACH_SIZE(macro) \ + macro(Objects, IsLiveGCThing, objectsGCHeapOrdinary) \ + macro(Objects, IsLiveGCThing, objectsGCHeapFunction) \ + macro(Objects, IsLiveGCThing, objectsGCHeapDenseArray) \ + macro(Objects, IsLiveGCThing, objectsGCHeapSlowArray) \ + macro(Objects, IsLiveGCThing, objectsGCHeapCrossCompartmentWrapper) \ + macro(Private, NotLiveGCThing, objectsPrivate) \ + macro(Other, IsLiveGCThing, shapesGCHeapTreeGlobalParented) \ + macro(Other, IsLiveGCThing, shapesGCHeapTreeNonGlobalParented) \ + macro(Other, IsLiveGCThing, shapesGCHeapDict) \ + macro(Other, IsLiveGCThing, shapesGCHeapBase) \ + macro(Other, NotLiveGCThing, shapesMallocHeapTreeTables) \ + macro(Other, NotLiveGCThing, shapesMallocHeapDictTables) \ + macro(Other, NotLiveGCThing, shapesMallocHeapTreeShapeKids) \ + macro(Other, NotLiveGCThing, shapesMallocHeapCompartmentTables) \ + macro(Other, IsLiveGCThing, scriptsGCHeap) \ + macro(Other, NotLiveGCThing, scriptsMallocHeapData) \ + macro(Other, NotLiveGCThing, baselineData) \ + macro(Other, NotLiveGCThing, baselineStubsFallback) \ + macro(Other, NotLiveGCThing, baselineStubsOptimized) \ + macro(Other, NotLiveGCThing, ionData) \ + macro(Other, NotLiveGCThing, typeInferenceTypeScripts) \ + macro(Other, NotLiveGCThing, typeInferencePendingArrays) \ + macro(Other, NotLiveGCThing, typeInferenceAllocationSiteTables) \ + macro(Other, NotLiveGCThing, typeInferenceArrayTypeTables) \ + macro(Other, NotLiveGCThing, typeInferenceObjectTypeTables) \ + macro(Other, NotLiveGCThing, compartmentObject) \ + macro(Other, NotLiveGCThing, crossCompartmentWrappersTable) \ + macro(Other, NotLiveGCThing, regexpCompartment) \ + macro(Other, NotLiveGCThing, debuggeesSet) + CompartmentStats() - : extra(NULL), - gcHeapObjectsOrdinary(0), - gcHeapObjectsFunction(0), - gcHeapObjectsDenseArray(0), - gcHeapObjectsSlowArray(0), - gcHeapObjectsCrossCompartmentWrapper(0), - gcHeapShapesTreeGlobalParented(0), - gcHeapShapesTreeNonGlobalParented(0), - gcHeapShapesDict(0), - gcHeapShapesBase(0), - gcHeapScripts(0), + : FOR_EACH_SIZE(ZERO_SIZE) objectsExtra(), - shapesExtraTreeTables(0), - shapesExtraDictTables(0), - shapesExtraTreeShapeKids(0), - shapesCompartmentTables(0), - scriptData(0), - baselineData(0), - baselineStubsFallback(0), - baselineStubsOptimized(0), - ionData(0), - compartmentObject(0), - crossCompartmentWrappersTable(0), - regexpCompartment(0), - debuggeesSet(0), - typeInference() + extra() {} CompartmentStats(const CompartmentStats &other) - : extra(other.extra), - gcHeapObjectsOrdinary(other.gcHeapObjectsOrdinary), - gcHeapObjectsFunction(other.gcHeapObjectsFunction), - gcHeapObjectsDenseArray(other.gcHeapObjectsDenseArray), - gcHeapObjectsSlowArray(other.gcHeapObjectsSlowArray), - gcHeapObjectsCrossCompartmentWrapper(other.gcHeapObjectsCrossCompartmentWrapper), - gcHeapShapesTreeGlobalParented(other.gcHeapShapesTreeGlobalParented), - gcHeapShapesTreeNonGlobalParented(other.gcHeapShapesTreeNonGlobalParented), - gcHeapShapesDict(other.gcHeapShapesDict), - gcHeapShapesBase(other.gcHeapShapesBase), - gcHeapScripts(other.gcHeapScripts), + : FOR_EACH_SIZE(COPY_OTHER_SIZE) objectsExtra(other.objectsExtra), - shapesExtraTreeTables(other.shapesExtraTreeTables), - shapesExtraDictTables(other.shapesExtraDictTables), - shapesExtraTreeShapeKids(other.shapesExtraTreeShapeKids), - shapesCompartmentTables(other.shapesCompartmentTables), - scriptData(other.scriptData), - baselineData(other.baselineData), - baselineStubsFallback(other.baselineStubsFallback), - baselineStubsOptimized(other.baselineStubsOptimized), - ionData(other.ionData), - compartmentObject(other.compartmentObject), - crossCompartmentWrappersTable(other.crossCompartmentWrappersTable), - regexpCompartment(other.regexpCompartment), - debuggeesSet(other.debuggeesSet), - typeInference(other.typeInference) - { + extra(other.extra) + {} + + void add(const CompartmentStats &other) { + FOR_EACH_SIZE(ADD_OTHER_SIZE) + objectsExtra.add(other.objectsExtra); + // Do nothing with |extra|. } - // This field can be used by embedders. - void *extra; - - // If you add a new number, remember to update the constructors, add(), and - // maybe gcHeapThingsSize()! - size_t gcHeapObjectsOrdinary; - size_t gcHeapObjectsFunction; - size_t gcHeapObjectsDenseArray; - size_t gcHeapObjectsSlowArray; - size_t gcHeapObjectsCrossCompartmentWrapper; - size_t gcHeapShapesTreeGlobalParented; - size_t gcHeapShapesTreeNonGlobalParented; - size_t gcHeapShapesDict; - size_t gcHeapShapesBase; - size_t gcHeapScripts; - ObjectsExtraSizes objectsExtra; - - size_t shapesExtraTreeTables; - size_t shapesExtraDictTables; - size_t shapesExtraTreeShapeKids; - size_t shapesCompartmentTables; - size_t scriptData; - size_t baselineData; - size_t baselineStubsFallback; - size_t baselineStubsOptimized; - size_t ionData; - size_t compartmentObject; - size_t crossCompartmentWrappersTable; - size_t regexpCompartment; - size_t debuggeesSet; - - TypeInferenceSizes typeInference; - - // Add cStats's numbers to this object's numbers. - void add(CompartmentStats &cStats) { - #define ADD(x) this->x += cStats.x - - ADD(gcHeapObjectsOrdinary); - ADD(gcHeapObjectsFunction); - ADD(gcHeapObjectsDenseArray); - ADD(gcHeapObjectsSlowArray); - ADD(gcHeapObjectsCrossCompartmentWrapper); - ADD(gcHeapShapesTreeGlobalParented); - ADD(gcHeapShapesTreeNonGlobalParented); - ADD(gcHeapShapesDict); - ADD(gcHeapShapesBase); - ADD(gcHeapScripts); - objectsExtra.add(cStats.objectsExtra); - - ADD(shapesExtraTreeTables); - ADD(shapesExtraDictTables); - ADD(shapesExtraTreeShapeKids); - ADD(shapesCompartmentTables); - ADD(scriptData); - ADD(baselineData); - ADD(baselineStubsFallback); - ADD(baselineStubsOptimized); - ADD(ionData); - ADD(compartmentObject); - ADD(crossCompartmentWrappersTable); - ADD(regexpCompartment); - ADD(debuggeesSet); - - #undef ADD - - typeInference.add(cStats.typeInference); + size_t sizeOfLiveGCThings() const { + size_t n = 0; + FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) + n += objectsExtra.sizeOfLiveGCThings(); + // Do nothing with |extra|. + return n; } - // The size of all the live things in the GC heap. - size_t GCHeapThingsSize(); + void addToTabSizes(TabSizes *sizes) const { + FOR_EACH_SIZE(ADD_TO_TAB_SIZES); + objectsExtra.addToTabSizes(sizes); + // Do nothing with |extra|. + } + + FOR_EACH_SIZE(DECL_SIZE) + ObjectsExtraSizes objectsExtra; + void *extra; // This field can be used by embedders. + +#undef FOR_EACH_SIZE }; struct RuntimeStats { +#define FOR_EACH_SIZE(macro) \ + macro(_, _, gcHeapChunkTotal) \ + macro(_, _, gcHeapDecommittedArenas) \ + macro(_, _, gcHeapUnusedChunks) \ + macro(_, _, gcHeapUnusedArenas) \ + macro(_, _, gcHeapChunkAdmin) \ + macro(_, _, gcHeapGCThings) \ + RuntimeStats(mozilla::MallocSizeOf mallocSizeOf) - : runtime(), - gcHeapChunkTotal(0), - gcHeapDecommittedArenas(0), - gcHeapUnusedChunks(0), - gcHeapUnusedArenas(0), - gcHeapUnusedGcThings(0), - gcHeapChunkAdmin(0), - gcHeapGcThings(0), + : FOR_EACH_SIZE(ZERO_SIZE) + runtime(), cTotals(), zTotals(), compartmentStatsVector(), zoneStatsVector(), - currZoneStats(NULL), + currZoneStats(nullptr), mallocSizeOf_(mallocSizeOf) {} - RuntimeSizes runtime; - - // If you add a new number, remember to update the constructor! - // Here's a useful breakdown of the GC heap. // // - rtStats.gcHeapChunkTotal @@ -394,28 +473,24 @@ struct RuntimeStats // - unused bytes // - rtStats.gcHeapUnusedChunks (empty chunks) // - rtStats.gcHeapUnusedArenas (empty arenas within non-empty chunks) - // - rtStats.total.gcHeapUnusedGcThings (empty GC thing slots within non-empty arenas) + // - rtStats.zTotals.unusedGCThings (empty GC thing slots within non-empty arenas) // - used bytes // - rtStats.gcHeapChunkAdmin - // - rtStats.total.gcHeapArenaAdmin - // - rtStats.gcHeapGcThings (in-use GC things) + // - rtStats.zTotals.gcHeapArenaAdmin + // - rtStats.gcHeapGCThings (in-use GC things) + // == rtStats.zTotals.sizeOfLiveGCThings() + rtStats.cTotals.sizeOfLiveGCThings() // // It's possible that some arenas in empty chunks may be decommitted, but // we don't count those under rtStats.gcHeapDecommittedArenas because (a) // it's rare, and (b) this means that rtStats.gcHeapUnusedChunks is a // multiple of the chunk size, which is good. - size_t gcHeapChunkTotal; - size_t gcHeapDecommittedArenas; - size_t gcHeapUnusedChunks; - size_t gcHeapUnusedArenas; - size_t gcHeapUnusedGcThings; - size_t gcHeapChunkAdmin; - size_t gcHeapGcThings; + FOR_EACH_SIZE(DECL_SIZE) - // The sum of all compartment's measurements. - CompartmentStats cTotals; - ZoneStats zTotals; + RuntimeSizes runtime; + + CompartmentStats cTotals; // The sum of this runtime's compartments' measurements. + ZoneStats zTotals; // The sum of this runtime's zones' measurements. js::Vector compartmentStatsVector; js::Vector zoneStatsVector; @@ -426,6 +501,8 @@ struct RuntimeStats virtual void initExtraCompartmentStats(JSCompartment *c, CompartmentStats *cstats) = 0; virtual void initExtraZoneStats(JS::Zone *zone, ZoneStats *zstats) = 0; + +#undef FOR_EACH_SIZE }; class ObjectPrivateVisitor @@ -437,7 +514,7 @@ class ObjectPrivateVisitor // A callback that gets a JSObject's nsISupports pointer, if it has one. // Note: this function does *not* addref |iface|. - typedef JSBool(*GetISupportsFun)(JSObject *obj, nsISupports **iface); + typedef bool(*GetISupportsFun)(JSObject *obj, nsISupports **iface); GetISupportsFun getISupports_; ObjectPrivateVisitor(GetISupportsFun getISupports) @@ -457,6 +534,17 @@ UserCompartmentCount(JSRuntime *rt); extern JS_PUBLIC_API(size_t) PeakSizeOfTemporary(const JSRuntime *rt); +extern JS_PUBLIC_API(bool) +AddSizeOfTab(JSRuntime *rt, JSObject *obj, mozilla::MallocSizeOf mallocSizeOf, + ObjectPrivateVisitor *opv, TabSizes *sizes); + } // namespace JS +#undef DECL_SIZE +#undef ZERO_SIZE +#undef COPY_OTHER_SIZE +#undef ADD_OTHER_SIZE +#undef ADD_SIZE_TO_N_IF_LIVE_GC_THING +#undef ADD_TO_TAB_SIZES + #endif /* js_MemoryMetrics_h */ diff --git a/external/spidermonkey/include/android/jsdbgapi.h b/external/spidermonkey/include/ios/js/OldDebugAPI.h similarity index 77% rename from external/spidermonkey/include/android/jsdbgapi.h rename to external/spidermonkey/include/ios/js/OldDebugAPI.h index 0ce7101337..5e5bdf38d7 100644 --- a/external/spidermonkey/include/android/jsdbgapi.h +++ b/external/spidermonkey/include/ios/js/OldDebugAPI.h @@ -4,13 +4,24 @@ * 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/. */ -#ifndef jsdbgapi_h -#define jsdbgapi_h +#ifndef js_OldDebugAPI_h +#define js_OldDebugAPI_h + /* * JS debugger API. */ -#include "jsprvtd.h" +#include "mozilla/NullPtr.h" + +#include "jsbytecode.h" + +#include "js/CallArgs.h" +#include "js/TypeDecls.h" + +class JSAtom; +class JSFreeOp; + +namespace js { class StackFrame; } namespace JS { @@ -34,21 +45,68 @@ extern JS_PUBLIC_API(void) FreeStackDescription(JSContext *cx, StackDescription *desc); extern JS_PUBLIC_API(char *) -FormatStackDump(JSContext *cx, char *buf, - JSBool showArgs, JSBool showLocals, - JSBool showThisProps); +FormatStackDump(JSContext *cx, char *buf, bool showArgs, bool showLocals, bool showThisProps); } # ifdef DEBUG -JS_FRIEND_API(void) js_DumpValue(const js::Value &val); +JS_FRIEND_API(void) js_DumpValue(const JS::Value &val); JS_FRIEND_API(void) js_DumpId(jsid id); -JS_FRIEND_API(void) js_DumpStackFrame(JSContext *cx, js::StackFrame *start = NULL); +JS_FRIEND_API(void) js_DumpStackFrame(JSContext *cx, js::StackFrame *start = nullptr); # endif JS_FRIEND_API(void) js_DumpBacktrace(JSContext *cx); +typedef enum JSTrapStatus { + JSTRAP_ERROR, + JSTRAP_CONTINUE, + JSTRAP_RETURN, + JSTRAP_THROW, + JSTRAP_LIMIT +} JSTrapStatus; + +typedef JSTrapStatus +(* JSTrapHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + JS::Value closure); + +typedef JSTrapStatus +(* JSInterruptHook)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + void *closure); + +typedef JSTrapStatus +(* JSDebuggerHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + void *closure); + +typedef JSTrapStatus +(* JSThrowHook)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + void *closure); + +typedef bool +(* JSWatchPointHandler)(JSContext *cx, JSObject *obj, jsid id, JS::Value old, + JS::Value *newp, void *closure); + +/* called just after script creation */ +typedef void +(* JSNewScriptHook)(JSContext *cx, + const char *filename, /* URL of script */ + unsigned lineno, /* first line */ + JSScript *script, + JSFunction *fun, + void *callerdata); + +/* called just before script destruction */ +typedef void +(* JSDestroyScriptHook)(JSFreeOp *fop, + JSScript *script, + void *callerdata); + +typedef void +(* JSSourceHandler)(const char *filename, unsigned lineno, const jschar *str, + size_t length, void **listenerTSData, void *closure); + + + extern JS_PUBLIC_API(JSCompartment *) JS_EnterCompartmentOfScript(JSContext *cx, JSScript *target); @@ -60,7 +118,7 @@ JS_DecompileScript(JSContext *cx, JSScript *script, const char *name, unsigned i * be able to support compartment-wide debugging. */ extern JS_PUBLIC_API(void) -JS_SetRuntimeDebugMode(JSRuntime *rt, JSBool debug); +JS_SetRuntimeDebugMode(JSRuntime *rt, bool debug); /* * Debug mode is a compartment-wide mode that enables a debugger to attach @@ -73,42 +131,42 @@ JS_SetRuntimeDebugMode(JSRuntime *rt, JSBool debug); */ /* Get current state of debugging mode. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_GetDebugMode(JSContext *cx); /* * Turn on/off debugging mode for all compartments. This returns false if any code * from any of the runtime's compartments is running or on the stack. */ -JS_FRIEND_API(JSBool) -JS_SetDebugModeForAllCompartments(JSContext *cx, JSBool debug); +JS_FRIEND_API(bool) +JS_SetDebugModeForAllCompartments(JSContext *cx, bool debug); /* * Turn on/off debugging mode for a single compartment. This should only be * used when no code from this compartment is running or on the stack in any * thread. */ -JS_FRIEND_API(JSBool) -JS_SetDebugModeForCompartment(JSContext *cx, JSCompartment *comp, JSBool debug); +JS_FRIEND_API(bool) +JS_SetDebugModeForCompartment(JSContext *cx, JSCompartment *comp, bool debug); /* * Turn on/off debugging mode for a context's compartment. */ -JS_FRIEND_API(JSBool) -JS_SetDebugMode(JSContext *cx, JSBool debug); +JS_FRIEND_API(bool) +JS_SetDebugMode(JSContext *cx, bool debug); /* Turn on single step mode. */ -extern JS_PUBLIC_API(JSBool) -JS_SetSingleStepMode(JSContext *cx, JSScript *script, JSBool singleStep); +extern JS_PUBLIC_API(bool) +JS_SetSingleStepMode(JSContext *cx, JSScript *script, bool singleStep); /* The closure argument will be marked. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetTrap(JSContext *cx, JSScript *script, jsbytecode *pc, - JSTrapHandler handler, jsval closure); + JSTrapHandler handler, JS::Value closure); extern JS_PUBLIC_API(void) JS_ClearTrap(JSContext *cx, JSScript *script, jsbytecode *pc, - JSTrapHandler *handlerp, jsval *closurep); + JSTrapHandler *handlerp, JS::Value *closurep); extern JS_PUBLIC_API(void) JS_ClearScriptTraps(JSRuntime *rt, JSScript *script); @@ -116,28 +174,25 @@ JS_ClearScriptTraps(JSRuntime *rt, JSScript *script); extern JS_PUBLIC_API(void) JS_ClearAllTrapsForCompartment(JSContext *cx); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetInterrupt(JSRuntime *rt, JSInterruptHook handler, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_ClearInterrupt(JSRuntime *rt, JSInterruptHook *handlerp, void **closurep); /************************************************************************/ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetWatchPoint(JSContext *cx, JSObject *obj, jsid id, JSWatchPointHandler handler, JSObject *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_ClearWatchPoint(JSContext *cx, JSObject *obj, jsid id, JSWatchPointHandler *handlerp, JSObject **closurep); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_ClearWatchPointsForObject(JSContext *cx, JSObject *obj); -extern JS_PUBLIC_API(JSBool) -JS_ClearAllWatchPoints(JSContext *cx); - /************************************************************************/ // Raw JSScript* because this needs to be callable from a signal handler. @@ -150,7 +205,7 @@ JS_LineNumberToPC(JSContext *cx, JSScript *script, unsigned lineno); extern JS_PUBLIC_API(jsbytecode *) JS_EndPC(JSContext *cx, JSScript *script); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_GetLinePCs(JSContext *cx, JSScript *script, unsigned startLine, unsigned maxLines, unsigned* count, unsigned** lines, jsbytecode*** pcs); @@ -158,7 +213,7 @@ JS_GetLinePCs(JSContext *cx, JSScript *script, extern JS_PUBLIC_API(unsigned) JS_GetFunctionArgumentCount(JSContext *cx, JSFunction *fun); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_FunctionHasLocalNames(JSContext *cx, JSFunction *fun); /* @@ -230,9 +285,8 @@ JS_GetScriptIsSelfHosted(JSScript *script); /************************************************************************/ /* - * Hook setters for script creation and destruction, see jsprvtd.h for the - * typedefs. These macros provide binary compatibility and newer, shorter - * synonyms. + * Hook setters for script creation and destruction. These macros provide + * binary compatibility and newer, shorter synonyms. */ #define JS_SetNewScriptHook JS_SetNewScriptHookProc #define JS_SetDestroyScriptHook JS_SetDestroyScriptHookProc @@ -247,11 +301,11 @@ JS_SetDestroyScriptHook(JSRuntime *rt, JSDestroyScriptHook hook, /************************************************************************/ typedef struct JSPropertyDesc { - jsval id; /* primary id, atomized string, or int */ - jsval value; /* property value */ + JS::Value id; /* primary id, atomized string, or int */ + JS::Value value; /* property value */ uint8_t flags; /* flags, see below */ uint8_t spare; /* unused */ - jsval alias; /* alias id if JSPD_ALIAS flag */ + JS::Value alias; /* alias id if JSPD_ALIAS flag */ } JSPropertyDesc; #define JSPD_ENUMERATE 0x01 /* visible to for/in loop */ @@ -260,7 +314,7 @@ typedef struct JSPropertyDesc { #define JSPD_ALIAS 0x08 /* property has an alias id */ #define JSPD_EXCEPTION 0x40 /* exception occurred fetching the property, */ /* value is exception */ -#define JSPD_ERROR 0x80 /* native getter returned JS_FALSE without */ +#define JSPD_ERROR 0x80 /* native getter returned false without */ /* throwing an exception */ typedef struct JSPropertyDescArray { @@ -270,7 +324,7 @@ typedef struct JSPropertyDescArray { typedef struct JSScopeProperty JSScopeProperty; -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_GetPropertyDescArray(JSContext *cx, JSObject *obj, JSPropertyDescArray *pda); extern JS_PUBLIC_API(void) @@ -358,8 +412,8 @@ class JS_PUBLIC_API(JSBrokenFrameIterator) * or function call: just before execution begins and just after it finishes. * In both cases the 'current' frame is that of the executing code. * - * The 'before' param is JS_TRUE for the hook invocation before the execution - * and JS_FALSE for the invocation after the code has run. + * The 'before' param is true for the hook invocation before the execution + * and false for the invocation after the code has run. * * The 'ok' param is significant only on the post execution invocation to * signify whether or not the code completed 'normally'. @@ -373,14 +427,14 @@ class JS_PUBLIC_API(JSBrokenFrameIterator) * in 'closure' to cause the 'after' invocation to be called with the same * 'closure' value as the 'before'. * - * Returning NULL in the 'before' hook will cause the 'after' hook *not* to + * Returning nullptr in the 'before' hook will cause the 'after' hook *not* to * be called. */ typedef void * (* JSInterpreterHook)(JSContext *cx, JSAbstractFramePtr frame, bool isConstructing, - JSBool before, JSBool *ok, void *closure); + bool before, bool *ok, void *closure); -typedef JSBool +typedef bool (* JSDebugErrorHook)(JSContext *cx, const char *message, JSErrorReport *report, void *closure); @@ -407,22 +461,22 @@ typedef struct JSDebugHooks { /************************************************************************/ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetDebuggerHandler(JSRuntime *rt, JSDebuggerHandler hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetSourceHandler(JSRuntime *rt, JSSourceHandler handler, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetExecuteHook(JSRuntime *rt, JSInterpreterHook hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetCallHook(JSRuntime *rt, JSInterpreterHook hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetThrowHook(JSRuntime *rt, JSThrowHook hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetDebugErrorHook(JSRuntime *rt, JSDebugErrorHook hook, void *closure); /************************************************************************/ @@ -433,11 +487,11 @@ JS_GetGlobalDebugHooks(JSRuntime *rt); /** * Add various profiling-related functions as properties of the given object. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_DefineProfilingFunctions(JSContext *cx, JSObject *obj); /* Defined in vm/Debugger.cpp. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_DefineDebuggerObject(JSContext *cx, JSObject *obj); extern JS_PUBLIC_API(void) @@ -452,8 +506,13 @@ JS_DumpPCCounts(JSContext *cx, JSScript *script); extern JS_PUBLIC_API(void) JS_DumpCompartmentPCCounts(JSContext *cx); +namespace js { +extern JS_FRIEND_API(bool) +CanCallContextDebugHandler(JSContext *cx); +} + /* Call the context debug handler on the topmost scripted frame. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_CallContextDebugHandler(JSContext *cx); -#endif /* jsdbgapi_h */ +#endif /* js_OldDebugAPI_h */ diff --git a/external/spidermonkey/include/ios/js/ProfilingStack.h b/external/spidermonkey/include/ios/js/ProfilingStack.h new file mode 100644 index 0000000000..c67f98952c --- /dev/null +++ b/external/spidermonkey/include/ios/js/ProfilingStack.h @@ -0,0 +1,95 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_ProfilingStack_h +#define js_ProfilingStack_h + +#include "mozilla/NullPtr.h" + +#include "jsbytecode.h" +#include "jstypes.h" + +#include "js/Utility.h" + +struct JSRuntime; + +namespace js { + +// A call stack can be specified to the JS engine such that all JS entry/exits +// to functions push/pop an entry to/from the specified stack. +// +// For more detailed information, see vm/SPSProfiler.h. +// +class ProfileEntry +{ + // All fields are marked volatile to prevent the compiler from re-ordering + // instructions. Namely this sequence: + // + // entry[size] = ...; + // size++; + // + // If the size modification were somehow reordered before the stores, then + // if a sample were taken it would be examining bogus information. + // + // A ProfileEntry represents both a C++ profile entry and a JS one. Both use + // the string as a description, but JS uses the sp as nullptr to indicate + // that it is a JS entry. The script_ is then only ever examined for a JS + // entry, and the idx is used by both, but with different meanings. + // + const char * volatile string; // Descriptive string of this entry + void * volatile sp; // Relevant stack pointer for the entry + JSScript * volatile script_; // if js(), non-null script which is running + int32_t volatile idx; // if js(), idx of pc, otherwise line number + + public: + // All of these methods are marked with the 'volatile' keyword because SPS's + // representation of the stack is stored such that all ProfileEntry + // instances are volatile. These methods would not be available unless they + // were marked as volatile as well. + + bool js() volatile { + JS_ASSERT_IF(sp == nullptr, script_ != nullptr); + return sp == nullptr; + } + + uint32_t line() volatile { JS_ASSERT(!js()); return idx; } + JSScript *script() volatile { JS_ASSERT(js()); return script_; } + void *stackAddress() volatile { return sp; } + const char *label() volatile { return string; } + + void setLine(uint32_t aLine) volatile { JS_ASSERT(!js()); idx = aLine; } + void setLabel(const char *aString) volatile { string = aString; } + void setStackAddress(void *aSp) volatile { sp = aSp; } + void setScript(JSScript *aScript) volatile { script_ = aScript; } + + // We can't know the layout of JSScript, so look in vm/SPSProfiler.cpp. + JS_FRIEND_API(jsbytecode *) pc() volatile; + JS_FRIEND_API(void) setPC(jsbytecode *pc) volatile; + + static size_t offsetOfString() { return offsetof(ProfileEntry, string); } + static size_t offsetOfStackAddress() { return offsetof(ProfileEntry, sp); } + static size_t offsetOfPCIdx() { return offsetof(ProfileEntry, idx); } + static size_t offsetOfScript() { return offsetof(ProfileEntry, script_); } + + // The index used in the entry can either be a line number or the offset of + // a pc into a script's code. To signify a nullptr pc, use a -1 index. This + // is checked against in pc() and setPC() to set/get the right pc. + static const int32_t NullPCIndex = -1; +}; + +JS_FRIEND_API(void) +SetRuntimeProfilingStack(JSRuntime *rt, ProfileEntry *stack, uint32_t *size, + uint32_t max); + +JS_FRIEND_API(void) +EnableRuntimeProfilingStack(JSRuntime *rt, bool enabled); + +JS_FRIEND_API(jsbytecode*) +ProfilingGetPC(JSRuntime *rt, JSScript *script, void *ip); + +} // namespace js + +#endif /* js_ProfilingStack_h */ diff --git a/external/spidermonkey/include/ios/js/PropertyKey.h b/external/spidermonkey/include/ios/js/PropertyKey.h index c949db13a5..1f90653b40 100644 --- a/external/spidermonkey/include/ios/js/PropertyKey.h +++ b/external/spidermonkey/include/ios/js/PropertyKey.h @@ -9,12 +9,9 @@ #ifndef js_PropertyKey_h #define js_PropertyKey_h -#include "mozilla/Attributes.h" - +#include "js/TypeDecls.h" #include "js/Value.h" -struct JSContext; - namespace JS { class PropertyKey; diff --git a/external/spidermonkey/include/ios/js/RequiredDefines.h b/external/spidermonkey/include/ios/js/RequiredDefines.h index 6af9ca871b..3c8f429132 100644 --- a/external/spidermonkey/include/ios/js/RequiredDefines.h +++ b/external/spidermonkey/include/ios/js/RequiredDefines.h @@ -15,9 +15,17 @@ /* * The c99 defining the limit macros (UINT32_MAX for example), says: - * C++ implementations should define these macros only when __STDC_LIMIT_MACROS - * is defined before is included. + * + * C++ implementations should define these macros only when + * __STDC_LIMIT_MACROS is defined before is included. + * + * The same also occurs with __STDC_CONSTANT_MACROS for the constant macros + * (INT8_C for example) used to specify a literal constant of the proper type, + * and with __STDC_FORMAT_MACROS for the format macros (PRId32 for example) used + * with the fprintf function family. */ #define __STDC_LIMIT_MACROS +#define __STDC_CONSTANT_MACROS +#define __STDC_FORMAT_MACROS #endif /* js_RequiredDefines_h */ diff --git a/external/spidermonkey/include/ios/js/RootingAPI.h b/external/spidermonkey/include/ios/js/RootingAPI.h index c4a5925ae7..82863f020a 100644 --- a/external/spidermonkey/include/ios/js/RootingAPI.h +++ b/external/spidermonkey/include/ios/js/RootingAPI.h @@ -8,12 +8,14 @@ #define js_RootingAPI_h #include "mozilla/GuardObjects.h" +#include "mozilla/NullPtr.h" #include "mozilla/TypeTraits.h" -#include "js/Utility.h" - #include "jspubtd.h" +#include "js/TypeDecls.h" +#include "js/Utility.h" + /* * Moving GC Stack Rooting * @@ -97,7 +99,6 @@ namespace js { -class Module; class ScriptSourceObject; template @@ -116,13 +117,13 @@ template class HeapBase {}; /* - * js::NullPtr acts like a NULL pointer in contexts that require a Handle. + * js::NullPtr acts like a nullptr pointer in contexts that require a Handle. * * Handle provides an implicit constructor for js::NullPtr so that, given: * foo(Handle h); * callers can simply write: * foo(js::NullPtr()); - * which avoids creating a Rooted just to pass NULL. + * which avoids creating a Rooted just to pass nullptr. * * This is the SpiderMonkey internal variant. js::NullPtr should be used in * preference to JS::NullPtr to avoid the GOT access required for JS_PUBLIC_API @@ -143,9 +144,6 @@ namespace JS { template class Rooted; -template class Handle; -template class MutableHandle; - /* This is exposing internal state of the GC for inlining purposes. */ JS_FRIEND_API(bool) isGCEnabled(); @@ -155,13 +153,13 @@ CheckStackRoots(JSContext *cx); #endif /* - * JS::NullPtr acts like a NULL pointer in contexts that require a Handle. + * JS::NullPtr acts like a nullptr pointer in contexts that require a Handle. * * Handle provides an implicit constructor for JS::NullPtr so that, given: * foo(Handle h); * callers can simply write: * foo(JS::NullPtr()); - * which avoids creating a Rooted just to pass NULL. + * which avoids creating a Rooted just to pass nullptr. */ struct JS_PUBLIC_API(NullPtr) { @@ -377,7 +375,7 @@ class TenuredHeap : public js::HeapBase template class MOZ_NONHEAP_CLASS Handle : public js::HandleBase { - friend class MutableHandle; + friend class JS::MutableHandle; public: /* Creates a handle from a handle of a type convertible to T. */ @@ -390,14 +388,14 @@ class MOZ_NONHEAP_CLASS Handle : public js::HandleBase ptr = reinterpret_cast(handle.address()); } - /* Create a handle for a NULL pointer. */ + /* Create a handle for a nullptr pointer. */ Handle(js::NullPtr) { static_assert(mozilla::IsPointer::value, "js::NullPtr overload not valid for non-pointer types"); ptr = reinterpret_cast(&js::NullPtr::constNullValue); } - /* Create a handle for a NULL pointer. */ + /* Create a handle for a nullptr pointer. */ Handle(JS::NullPtr) { static_assert(mozilla::IsPointer::value, "JS::NullPtr overload not valid for non-pointer types"); @@ -457,24 +455,18 @@ class MOZ_NONHEAP_CLASS Handle : public js::HandleBase bool operator!=(const T &other) const { return *ptr != other; } bool operator==(const T &other) const { return *ptr == other; } + /* Change this handle to point to the same rooted location RHS does. */ + void repoint(const Handle &rhs) { ptr = rhs.address(); } + private: Handle() {} const T *ptr; - template - void operator=(S v) MOZ_DELETE; + template void operator=(S) MOZ_DELETE; + void operator=(Handle) MOZ_DELETE; }; -typedef Handle HandleObject; -typedef Handle HandleModule; -typedef Handle HandleScriptSource; -typedef Handle HandleFunction; -typedef Handle HandleScript; -typedef Handle HandleString; -typedef Handle HandleId; -typedef Handle HandleValue; - /* * Similar to a handle, but the underlying storage can be changed. This is * useful for outparams. @@ -488,6 +480,10 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase { public: inline MutableHandle(Rooted *root); + MutableHandle(int) MOZ_DELETE; +#ifdef MOZ_HAVE_CXX11_NULLPTR + MutableHandle(decltype(nullptr)) MOZ_DELETE; +#endif void set(T v) { JS_ASSERT(!js::GCMethods::poisoned(v)); @@ -526,13 +522,6 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase void operator=(MutableHandle other) MOZ_DELETE; }; -typedef MutableHandle MutableHandleObject; -typedef MutableHandle MutableHandleFunction; -typedef MutableHandle MutableHandleScript; -typedef MutableHandle MutableHandleString; -typedef MutableHandle MutableHandleId; -typedef MutableHandle MutableHandleValue; - #ifdef JSGC_GENERATIONAL JS_PUBLIC_API(void) HeapCellPostBarrier(js::gc::Cell **cellp); JS_PUBLIC_API(void) HeapCellRelocate(js::gc::Cell **cellp); @@ -614,7 +603,7 @@ struct RootKind template struct GCMethods { - static T *initial() { return NULL; } + static T *initial() { return nullptr; } static ThingRootKind kind() { return RootKind::rootKind(); } static bool poisoned(T *v) { return JS::IsPoisonedPtr(v); } static bool needsPostBarrier(T *v) { return v; } @@ -628,12 +617,11 @@ struct GCMethods #endif }; -// XXX: Needed for cocos2d JS Bindings -//#if defined(DEBUG) +#if defined(DEBUG) /* This helper allows us to assert that Rooted is scoped within a request. */ extern JS_PUBLIC_API(bool) IsInRequest(JSContext *cx); -//#endif +#endif } /* namespace js */ @@ -730,12 +718,15 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase init(js::PerThreadDataFriendFields::getMainThread(rt)); } - ~Rooted() { + // Note that we need to let the compiler generate the default destructor in + // non-exact-rooting builds because of a bug in the instrumented PGO builds + // using MSVC, see bug 915735 for more details. #ifdef JSGC_TRACK_EXACT_ROOTS + ~Rooted() { JS_ASSERT(*stack == reinterpret_cast*>(this)); *stack = prev; -#endif } +#endif #ifdef JSGC_TRACK_EXACT_ROOTS Rooted *previous() { return prev; } @@ -803,8 +794,6 @@ class Rooted; #endif typedef Rooted RootedObject; -typedef Rooted RootedModule; -typedef Rooted RootedScriptSource; typedef Rooted RootedFunction; typedef Rooted RootedScript; typedef Rooted RootedString; @@ -857,6 +846,10 @@ class SkipRoot void init(js::ContextFriendFields *cx, const T *ptr, size_t count) {} public: + ~SkipRoot() { + // An empty destructor is needed to avoid warnings from clang about + // unused local variables of this type. + } #endif /* DEBUG && JSGC_ROOT_ANALYSIS */ @@ -1063,7 +1056,7 @@ inline void MaybeCheckStackRoots(JSContext *cx) class CompilerRootNode { protected: - CompilerRootNode(js::gc::Cell *ptr) : next(NULL), ptr_(ptr) {} + CompilerRootNode(js::gc::Cell *ptr) : next(nullptr), ptr_(ptr) {} public: void **address() { return (void **)&ptr_; } diff --git a/external/spidermonkey/include/ios/js/StructuredClone.h b/external/spidermonkey/include/ios/js/StructuredClone.h new file mode 100644 index 0000000000..d32bdd8dd6 --- /dev/null +++ b/external/spidermonkey/include/ios/js/StructuredClone.h @@ -0,0 +1,163 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_StructuredClone_h +#define js_StructuredClone_h + +#include "mozilla/NullPtr.h" + +#include + +#include "jstypes.h" + +#include "js/RootingAPI.h" +#include "js/TypeDecls.h" +#include "js/Value.h" + +struct JSRuntime; +struct JSStructuredCloneReader; +struct JSStructuredCloneWriter; + +// API for the HTML5 internal structured cloning algorithm. + +// Read structured data from the reader r. This hook is used to read a value +// previously serialized by a call to the WriteStructuredCloneOp hook. +// +// tag and data are the pair of uint32_t values from the header. The callback +// may use the JS_Read* APIs to read any other relevant parts of the object +// from the reader r. closure is any value passed to the JS_ReadStructuredClone +// function. Return the new object on success, nullptr on error/exception. +typedef JSObject *(*ReadStructuredCloneOp)(JSContext *cx, JSStructuredCloneReader *r, + uint32_t tag, uint32_t data, void *closure); + +// Structured data serialization hook. The engine can write primitive values, +// Objects, Arrays, Dates, RegExps, TypedArrays, and ArrayBuffers. Any other +// type of object requires application support. This callback must first use +// the JS_WriteUint32Pair API to write an object header, passing a value +// greater than JS_SCTAG_USER to the tag parameter. Then it can use the +// JS_Write* APIs to write any other relevant parts of the value v to the +// writer w. closure is any value passed to the JS_WriteStructuredCLone function. +// +// Return true on success, false on error/exception. +typedef bool (*WriteStructuredCloneOp)(JSContext *cx, JSStructuredCloneWriter *w, + JS::Handle obj, void *closure); + +// This is called when JS_WriteStructuredClone is given an invalid transferable. +// To follow HTML5, the application must throw a DATA_CLONE_ERR DOMException +// with error set to one of the JS_SCERR_* values. +typedef void (*StructuredCloneErrorOp)(JSContext *cx, uint32_t errorid); + +// The maximum supported structured-clone serialization format version. Note +// that this does not need to be bumped for Transferable-only changes, since +// they are never saved to persistent storage. +#define JS_STRUCTURED_CLONE_VERSION 2 + +struct JSStructuredCloneCallbacks { + ReadStructuredCloneOp read; + WriteStructuredCloneOp write; + StructuredCloneErrorOp reportError; +}; + +// Note: if the *data contains transferable objects, it can be read only once. +JS_PUBLIC_API(bool) +JS_ReadStructuredClone(JSContext *cx, uint64_t *data, size_t nbytes, uint32_t version, + JS::MutableHandleValue vp, + const JSStructuredCloneCallbacks *optionalCallbacks, void *closure); + +// Note: On success, the caller is responsible for calling +// JS_ClearStructuredClone(*datap, nbytesp). +JS_PUBLIC_API(bool) +JS_WriteStructuredClone(JSContext *cx, JS::HandleValue v, uint64_t **datap, size_t *nbytesp, + const JSStructuredCloneCallbacks *optionalCallbacks, + void *closure, JS::HandleValue transferable); + +JS_PUBLIC_API(bool) +JS_ClearStructuredClone(const uint64_t *data, size_t nbytes); + +JS_PUBLIC_API(bool) +JS_StructuredCloneHasTransferables(const uint64_t *data, size_t nbytes, bool *hasTransferable); + +JS_PUBLIC_API(bool) +JS_StructuredClone(JSContext *cx, JS::HandleValue v, JS::MutableHandleValue vp, + const JSStructuredCloneCallbacks *optionalCallbacks, void *closure); + +// RAII sugar for JS_WriteStructuredClone. +class JS_PUBLIC_API(JSAutoStructuredCloneBuffer) { + uint64_t *data_; + size_t nbytes_; + uint32_t version_; + + public: + JSAutoStructuredCloneBuffer() + : data_(nullptr), nbytes_(0), version_(JS_STRUCTURED_CLONE_VERSION) {} + + ~JSAutoStructuredCloneBuffer() { clear(); } + + uint64_t *data() const { return data_; } + size_t nbytes() const { return nbytes_; } + + void clear(); + + // Copy some memory. It will be automatically freed by the destructor. + bool copy(const uint64_t *data, size_t nbytes, uint32_t version=JS_STRUCTURED_CLONE_VERSION); + + // Adopt some memory. It will be automatically freed by the destructor. + // data must have been allocated by the JS engine (e.g., extracted via + // JSAutoStructuredCloneBuffer::steal). + void adopt(uint64_t *data, size_t nbytes, uint32_t version=JS_STRUCTURED_CLONE_VERSION); + + // Remove the buffer so that it will not be automatically freed. + // After this, the caller is responsible for feeding the memory back to + // JSAutoStructuredCloneBuffer::adopt. + void steal(uint64_t **datap, size_t *nbytesp, uint32_t *versionp=nullptr); + + bool read(JSContext *cx, JS::MutableHandleValue vp, + const JSStructuredCloneCallbacks *optionalCallbacks=nullptr, void *closure=nullptr); + + bool write(JSContext *cx, JS::HandleValue v, + const JSStructuredCloneCallbacks *optionalCallbacks=nullptr, void *closure=nullptr); + + bool write(JSContext *cx, JS::HandleValue v, JS::HandleValue transferable, + const JSStructuredCloneCallbacks *optionalCallbacks=nullptr, void *closure=nullptr); + + // Swap ownership with another JSAutoStructuredCloneBuffer. + void swap(JSAutoStructuredCloneBuffer &other); + + private: + // Copy and assignment are not supported. + JSAutoStructuredCloneBuffer(const JSAutoStructuredCloneBuffer &other); + JSAutoStructuredCloneBuffer &operator=(const JSAutoStructuredCloneBuffer &other); +}; + +// The range of tag values the application may use for its own custom object types. +#define JS_SCTAG_USER_MIN ((uint32_t) 0xFFFF8000) +#define JS_SCTAG_USER_MAX ((uint32_t) 0xFFFFFFFF) + +#define JS_SCERR_RECURSION 0 +#define JS_SCERR_TRANSFERABLE 1 + +JS_PUBLIC_API(void) +JS_SetStructuredCloneCallbacks(JSRuntime *rt, const JSStructuredCloneCallbacks *callbacks); + +JS_PUBLIC_API(bool) +JS_ReadUint32Pair(JSStructuredCloneReader *r, uint32_t *p1, uint32_t *p2); + +JS_PUBLIC_API(bool) +JS_ReadBytes(JSStructuredCloneReader *r, void *p, size_t len); + +JS_PUBLIC_API(bool) +JS_ReadTypedArray(JSStructuredCloneReader *r, JS::Value *vp); + +JS_PUBLIC_API(bool) +JS_WriteUint32Pair(JSStructuredCloneWriter *w, uint32_t tag, uint32_t data); + +JS_PUBLIC_API(bool) +JS_WriteBytes(JSStructuredCloneWriter *w, const void *p, size_t len); + +JS_PUBLIC_API(bool) +JS_WriteTypedArray(JSStructuredCloneWriter *w, JS::Value v); + +#endif /* js_StructuredClone_h */ diff --git a/external/spidermonkey/include/ios/js/Tracer.h b/external/spidermonkey/include/ios/js/Tracer.h new file mode 100644 index 0000000000..89994612f6 --- /dev/null +++ b/external/spidermonkey/include/ios/js/Tracer.h @@ -0,0 +1,193 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_Tracer_h +#define js_Tracer_h + +#include "mozilla/NullPtr.h" + +#include "jspubtd.h" + +struct JSTracer; + +namespace JS { +template class Heap; +template class TenuredHeap; +} + +// Tracer callback, called for each traceable thing directly referenced by a +// particular object or runtime structure. It is the callback responsibility +// to ensure the traversal of the full object graph via calling eventually +// JS_TraceChildren on the passed thing. In this case the callback must be +// prepared to deal with cycles in the traversal graph. +// +// kind argument is one of JSTRACE_OBJECT, JSTRACE_STRING or a tag denoting +// internal implementation-specific traversal kind. In the latter case the only +// operations on thing that the callback can do is to call JS_TraceChildren or +// JS_GetTraceThingInfo. +// +// If eagerlyTraceWeakMaps is true, when we trace a WeakMap visit all +// of its mappings. This should be used in cases where the tracer +// wants to use the existing liveness of entries. +typedef void +(* JSTraceCallback)(JSTracer *trc, void **thingp, JSGCTraceKind kind); + +// Callback that JSTraceOp implementation can provide to return a string +// describing the reference traced with JS_CallTracer. +typedef void +(* JSTraceNamePrinter)(JSTracer *trc, char *buf, size_t bufsize); + +enum WeakMapTraceKind { + DoNotTraceWeakMaps = 0, + TraceWeakMapValues = 1, + TraceWeakMapKeysValues = 2 +}; + +struct JSTracer { + JSRuntime *runtime; + JSTraceCallback callback; + JSTraceNamePrinter debugPrinter; + const void *debugPrintArg; + size_t debugPrintIndex; + WeakMapTraceKind eagerlyTraceWeakMaps; +#ifdef JS_GC_ZEAL + void *realLocation; +#endif +}; + +// Set debugging information about a reference to a traceable thing to prepare +// for the following call to JS_CallTracer. +// +// When printer is null, arg must be const char * or char * C string naming +// the reference and index must be either (size_t)-1 indicating that the name +// alone describes the reference or it must be an index into some array vector +// that stores the reference. +// +// When printer callback is not null, the arg and index arguments are +// available to the callback as debugPrintArg and debugPrintIndex fields +// of JSTracer. +// +// The storage for name or callback's arguments needs to live only until +// the following call to JS_CallTracer returns. +// +# define JS_SET_TRACING_DETAILS(trc, printer, arg, index) \ + JS_BEGIN_MACRO \ + (trc)->debugPrinter = (printer); \ + (trc)->debugPrintArg = (arg); \ + (trc)->debugPrintIndex = (index); \ + JS_END_MACRO + +// Sets the real location for a marked reference, when passing the address +// directly is not feasable. +// +// FIXME: This is currently overcomplicated by our need to nest calls for Values +// stored as keys in hash tables, but will get simplified once we can rekey +// in-place. +// +#ifdef JS_GC_ZEAL +# define JS_SET_TRACING_LOCATION(trc, location) \ + JS_BEGIN_MACRO \ + if (!(trc)->realLocation || !(location)) \ + (trc)->realLocation = (location); \ + JS_END_MACRO +# define JS_UNSET_TRACING_LOCATION(trc) \ + JS_BEGIN_MACRO \ + (trc)->realLocation = nullptr; \ + JS_END_MACRO +#else +# define JS_SET_TRACING_LOCATION(trc, location) \ + JS_BEGIN_MACRO \ + JS_END_MACRO +# define JS_UNSET_TRACING_LOCATION(trc) \ + JS_BEGIN_MACRO \ + JS_END_MACRO +#endif + +// Convenience macro to describe the argument of JS_CallTracer using C string +// and index. +# define JS_SET_TRACING_INDEX(trc, name, index) \ + JS_SET_TRACING_DETAILS(trc, nullptr, name, index) + +// Convenience macro to describe the argument of JS_CallTracer using C string. +# define JS_SET_TRACING_NAME(trc, name) \ + JS_SET_TRACING_DETAILS(trc, nullptr, name, (size_t)-1) + +// The JS_Call*Tracer family of functions traces the given GC thing reference. +// This performs the tracing action configured on the given JSTracer: +// typically calling the JSTracer::callback or marking the thing as live. +// +// The argument to JS_Call*Tracer is an in-out param: when the function +// returns, the garbage collector might have moved the GC thing. In this case, +// the reference passed to JS_Call*Tracer will be updated to the object's new +// location. Callers of this method are responsible for updating any state +// that is dependent on the object's address. For example, if the object's +// address is used as a key in a hashtable, then the object must be removed +// and re-inserted with the correct hash. +// +extern JS_PUBLIC_API(void) +JS_CallValueTracer(JSTracer *trc, JS::Value *valuep, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallIdTracer(JSTracer *trc, jsid *idp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallObjectTracer(JSTracer *trc, JSObject **objp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallStringTracer(JSTracer *trc, JSString **strp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallScriptTracer(JSTracer *trc, JSScript **scriptp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapValueTracer(JSTracer *trc, JS::Heap *valuep, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapIdTracer(JSTracer *trc, JS::Heap *idp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapObjectTracer(JSTracer *trc, JS::Heap *objp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapStringTracer(JSTracer *trc, JS::Heap *strp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapScriptTracer(JSTracer *trc, JS::Heap *scriptp, const char *name); + +template +inline void +JS_CallHashSetObjectTracer(JSTracer *trc, HashSetEnum &e, JSObject *const &key, const char *name) +{ + JSObject *updated = key; + JS_SET_TRACING_LOCATION(trc, reinterpret_cast(&const_cast(key))); + JS_CallObjectTracer(trc, &updated, name); + if (updated != key) + e.rekeyFront(key, updated); +} + +// Trace an object that is known to always be tenured. No post barriers are +// required in this case. +extern JS_PUBLIC_API(void) +JS_CallTenuredObjectTracer(JSTracer *trc, JS::TenuredHeap *objp, const char *name); + +// API for JSTraceCallback implementations. +extern JS_PUBLIC_API(void) +JS_TracerInit(JSTracer *trc, JSRuntime *rt, JSTraceCallback callback); + +extern JS_PUBLIC_API(void) +JS_TraceChildren(JSTracer *trc, void *thing, JSGCTraceKind kind); + +extern JS_PUBLIC_API(void) +JS_TraceRuntime(JSTracer *trc); + +extern JS_PUBLIC_API(void) +JS_GetTraceThingInfo(char *buf, size_t bufsize, JSTracer *trc, + void *thing, JSGCTraceKind kind, bool includeDetails); + +extern JS_PUBLIC_API(const char *) +JS_GetTraceEdgeName(JSTracer *trc, char *buffer, int bufferSize); + +#endif /* js_Tracer_h */ diff --git a/external/spidermonkey/include/ios/js/TypeDecls.h b/external/spidermonkey/include/ios/js/TypeDecls.h new file mode 100644 index 0000000000..ec944d374c --- /dev/null +++ b/external/spidermonkey/include/ios/js/TypeDecls.h @@ -0,0 +1,81 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +// This file contains public type declarations that are used *frequently*. If +// it doesn't occur at least 10 times in Gecko, it probably shouldn't be in +// here. +// +// It includes only: +// - forward declarations of structs and classes; +// - typedefs; +// - enums (maybe). +// It does *not* contain any struct or class definitions. + +#ifndef js_TypeDecls_h +#define js_TypeDecls_h + +#include +#include + +struct JSContext; +class JSFunction; +class JSObject; +class JSScript; +class JSString; + +// In release builds, jsid is defined to be an integral type. This +// prevents many bugs from being caught at compile time. E.g.: +// +// jsid id = ... +// if (id) // error +// ... +// +// size_t n = id; // error +// +// To catch more errors, jsid is given a struct type in C++ debug builds. +// Struct assignment and (in C++) operator== allow correct code to be mostly +// oblivious to the change. This feature can be explicitly disabled in debug +// builds by defining JS_NO_JSVAL_JSID_STRUCT_TYPES. +// + +// Needed for cocos2d-js +#define JS_NO_JSVAL_JSID_STRUCT_TYPES + +#if defined(DEBUG) && !defined(JS_NO_JSVAL_JSID_STRUCT_TYPES) +# define JS_USE_JSID_STRUCT_TYPES +#endif + +#ifdef JS_USE_JSID_STRUCT_TYPES +struct jsid; +#else +typedef ptrdiff_t jsid; +#endif + +typedef char16_t jschar; + +namespace JS { + +class Value; +template class Handle; +template class MutableHandle; + +typedef Handle HandleFunction; +typedef Handle HandleId; +typedef Handle HandleObject; +typedef Handle HandleScript; +typedef Handle HandleString; +typedef Handle HandleValue; + +typedef MutableHandle MutableHandleFunction; +typedef MutableHandle MutableHandleId; +typedef MutableHandle MutableHandleObject; +typedef MutableHandle MutableHandleScript; +typedef MutableHandle MutableHandleString; +typedef MutableHandle MutableHandleValue; + +} // namespace JS + +#endif /* js_TypeDecls_h */ diff --git a/external/spidermonkey/include/ios/js/Utility.h b/external/spidermonkey/include/ios/js/Utility.h index 9d391e5c8a..cdaf19ba5f 100644 --- a/external/spidermonkey/include/ios/js/Utility.h +++ b/external/spidermonkey/include/ios/js/Utility.h @@ -11,6 +11,7 @@ #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" #include "mozilla/Move.h" +#include "mozilla/NullPtr.h" #include "mozilla/Scoped.h" #include "mozilla/TemplateLib.h" @@ -18,8 +19,8 @@ #include #ifdef JS_OOM_DO_BACKTRACES -#include #include +#include #endif #include "jstypes.h" @@ -44,16 +45,6 @@ namespace js {} #define JS_ALWAYS_TRUE(expr) MOZ_ALWAYS_TRUE(expr) #define JS_ALWAYS_FALSE(expr) MOZ_ALWAYS_FALSE(expr) -#ifdef DEBUG -# ifdef JS_THREADSAFE -# define JS_THREADSAFE_ASSERT(expr) JS_ASSERT(expr) -# else -# define JS_THREADSAFE_ASSERT(expr) ((void) 0) -# endif -#else -# define JS_THREADSAFE_ASSERT(expr) ((void) 0) -#endif - #if defined(DEBUG) # define JS_DIAGNOSTICS_ASSERT(expr) MOZ_ASSERT(expr) #elif defined(JS_CRASH_DIAGNOSTICS) @@ -96,7 +87,7 @@ static JS_ALWAYS_INLINE void PrintBacktrace() { void* OOM_trace[JS_OOM_BACKTRACE_SIZE]; - char** OOM_traceSymbols = NULL; + char** OOM_traceSymbols = nullptr; int32_t OOM_traceSize = 0; int32_t OOM_traceIdx = 0; OOM_traceSize = backtrace(OOM_trace, JS_OOM_BACKTRACE_SIZE); @@ -126,7 +117,7 @@ PrintBacktrace() { \ if (++OOM_counter > OOM_maxAllocations) { \ JS_OOM_EMIT_BACKTRACE();\ - return NULL; \ + return nullptr; \ } \ } while (0) @@ -136,7 +127,7 @@ PrintBacktrace() if (++OOM_counter > OOM_maxAllocations) { \ JS_OOM_EMIT_BACKTRACE();\ js_ReportOutOfMemory(cx);\ - return NULL; \ + return nullptr; \ } \ } while (0) @@ -145,31 +136,31 @@ PrintBacktrace() # define JS_OOM_POSSIBLY_FAIL_REPORT(cx) do {} while(0) # endif /* DEBUG */ -static JS_INLINE void* js_malloc(size_t bytes) +static inline void* js_malloc(size_t bytes) { JS_OOM_POSSIBLY_FAIL(); return malloc(bytes); } -static JS_INLINE void* js_calloc(size_t bytes) +static inline void* js_calloc(size_t bytes) { JS_OOM_POSSIBLY_FAIL(); return calloc(bytes, 1); } -static JS_INLINE void* js_calloc(size_t nmemb, size_t size) +static inline void* js_calloc(size_t nmemb, size_t size) { JS_OOM_POSSIBLY_FAIL(); return calloc(nmemb, size); } -static JS_INLINE void* js_realloc(void* p, size_t bytes) +static inline void* js_realloc(void* p, size_t bytes) { JS_OOM_POSSIBLY_FAIL(); return realloc(p, bytes); } -static JS_INLINE void js_free(void* p) +static inline void js_free(void* p) { free(p); } @@ -241,7 +232,7 @@ static JS_INLINE void js_free(void* p) #define JS_NEW_BODY(allocator, t, parms) \ void *memory = allocator(sizeof(t)); \ - return memory ? new(memory) t parms : NULL; + return memory ? new(memory) t parms : nullptr; /* * Given a class which should provide 'new' methods, add @@ -360,7 +351,7 @@ static JS_ALWAYS_INLINE T * js_pod_malloc(size_t numElems) { if (numElems & mozilla::tl::MulOverflowMask::value) - return NULL; + return nullptr; return (T *)js_malloc(numElems * sizeof(T)); } @@ -369,7 +360,7 @@ static JS_ALWAYS_INLINE T * js_pod_calloc(size_t numElems) { if (numElems & mozilla::tl::MulOverflowMask::value) - return NULL; + return nullptr; return (T *)js_calloc(numElems * sizeof(T)); } @@ -379,7 +370,7 @@ template struct ScopedFreePtrTraits { typedef T* type; - static T* empty() { return NULL; } + static T* empty() { return nullptr; } static void release(T* ptr) { js_free(ptr); } }; SCOPED_TEMPLATE(ScopedJSFreePtr, ScopedFreePtrTraits) diff --git a/external/spidermonkey/include/ios/js/Value.h b/external/spidermonkey/include/ios/js/Value.h index 9b2c5dd6f9..7a772bcfba 100644 --- a/external/spidermonkey/include/ios/js/Value.h +++ b/external/spidermonkey/include/ios/js/Value.h @@ -15,6 +15,8 @@ #include /* for std::numeric_limits */ +#include "jstypes.h" + #include "js/Anchor.h" #include "js/RootingAPI.h" #include "js/Utility.h" @@ -248,7 +250,7 @@ typedef union jsval_layout union { int32_t i32; uint32_t u32; - JSBool boo; + uint32_t boo; // Don't use |bool| -- it must be four bytes. JSString *str; JSObject *obj; void *ptr; @@ -295,7 +297,7 @@ typedef union jsval_layout union { int32_t i32; uint32_t u32; - JSBool boo; + uint32_t boo; // Don't use |bool| -- it must be four bytes. JSString *str; JSObject *obj; void *ptr; @@ -333,6 +335,49 @@ typedef union jsval_layout JS_STATIC_ASSERT(sizeof(jsval_layout) == 8); +/* + * For codesize purposes on some platforms, it's important that the + * compiler know that JS::Values constructed from constant values can be + * folded to constant bit patterns at compile time, rather than + * constructed at runtime. Doing this requires a fair amount of C++11 + * features, which are not supported on all of our compilers. Set up + * some defines and helper macros in an attempt to confine the ugliness + * here, rather than scattering it all about the file. The important + * features are: + * + * - constexpr; + * - defaulted functions; + * - C99-style designated initializers. + */ +#if defined(__clang__) +# if __has_feature(cxx_constexpr) && __has_feature(cxx_defaulted_functions) +# define JS_VALUE_IS_CONSTEXPR +# endif +#elif defined(__GNUC__) +/* + * We need 4.5 for defaulted functions, 4.6 for constexpr, 4.7 because 4.6 + * doesn't understand |(X) { .field = ... }| syntax, and 4.7.3 because + * versions prior to that have bugs in the C++ front-end that cause crashes. + */ +# if MOZ_GCC_VERSION_AT_LEAST(4, 7, 3) +# define JS_VALUE_IS_CONSTEXPR +# endif +#endif + +#if defined(JS_VALUE_IS_CONSTEXPR) +# define JS_RETURN_LAYOUT_FROM_BITS(BITS) \ + return (jsval_layout) { .asBits = (BITS) } +# define JS_VALUE_CONSTEXPR MOZ_CONSTEXPR +# define JS_VALUE_CONSTEXPR_VAR MOZ_CONSTEXPR_VAR +#else +# define JS_RETURN_LAYOUT_FROM_BITS(BITS) \ + jsval_layout l; \ + l.asBits = (BITS); \ + return l; +# define JS_VALUE_CONSTEXPR +# define JS_VALUE_CONSTEXPR_VAR const +#endif + #if JS_BITS_PER_WORD == 32 /* @@ -341,15 +386,13 @@ JS_STATIC_ASSERT(sizeof(jsval_layout) == 8); * Thus, all comparisons should explicitly cast operands to uint32_t. */ -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout BUILD_JSVAL(JSValueTag tag, uint32_t payload) { - jsval_layout l; - l.asBits = (((uint64_t)(uint32_t)tag) << 32) | payload; - return l; + JS_RETURN_LAYOUT_FROM_BITS((((uint64_t)(uint32_t)tag) << 32) | payload); } -static inline JSBool +static inline bool JSVAL_IS_DOUBLE_IMPL(jsval_layout l) { return (uint32_t)l.s.tag <= (uint32_t)JSVAL_TAG_CLEAR; @@ -364,7 +407,7 @@ DOUBLE_TO_JSVAL_IMPL(double d) return l; } -static inline JSBool +static inline bool JSVAL_IS_INT32_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_INT32; @@ -376,16 +419,20 @@ JSVAL_TO_INT32_IMPL(jsval_layout l) return l.s.payload.i32; } -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout INT32_TO_JSVAL_IMPL(int32_t i) { +#if defined(JS_VALUE_IS_CONSTEXPR) + return BUILD_JSVAL(JSVAL_TAG_INT32, i); +#else jsval_layout l; l.s.tag = JSVAL_TAG_INT32; l.s.payload.i32 = i; return l; +#endif } -static inline JSBool +static inline bool JSVAL_IS_NUMBER_IMPL(jsval_layout l) { JSValueTag tag = l.s.tag; @@ -393,13 +440,13 @@ JSVAL_IS_NUMBER_IMPL(jsval_layout l) return (uint32_t)tag <= (uint32_t)JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET; } -static inline JSBool +static inline bool JSVAL_IS_UNDEFINED_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_UNDEFINED; } -static inline JSBool +static inline bool JSVAL_IS_STRING_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_STRING; @@ -421,47 +468,46 @@ JSVAL_TO_STRING_IMPL(jsval_layout l) return l.s.payload.str; } -static inline JSBool +static inline bool JSVAL_IS_BOOLEAN_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_BOOLEAN; } -static inline JSBool +static inline bool JSVAL_TO_BOOLEAN_IMPL(jsval_layout l) { return l.s.payload.boo; } static inline jsval_layout -BOOLEAN_TO_JSVAL_IMPL(JSBool b) +BOOLEAN_TO_JSVAL_IMPL(bool b) { jsval_layout l; - MOZ_ASSERT(b == JS_TRUE || b == JS_FALSE); l.s.tag = JSVAL_TAG_BOOLEAN; l.s.payload.boo = b; return l; } -static inline JSBool +static inline bool JSVAL_IS_MAGIC_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_MAGIC; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_OBJECT; } -static inline JSBool +static inline bool JSVAL_IS_PRIMITIVE_IMPL(jsval_layout l) { return (uint32_t)l.s.tag < (uint32_t)JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_OR_NULL_IMPL(jsval_layout l) { MOZ_ASSERT((uint32_t)l.s.tag <= (uint32_t)JSVAL_TAG_OBJECT); @@ -484,7 +530,7 @@ OBJECT_TO_JSVAL_IMPL(JSObject *obj) return l; } -static inline JSBool +static inline bool JSVAL_IS_NULL_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_NULL; @@ -507,7 +553,7 @@ JSVAL_TO_PRIVATE_PTR_IMPL(jsval_layout l) return l.s.payload.ptr; } -static inline JSBool +static inline bool JSVAL_IS_GCTHING_IMPL(jsval_layout l) { /* gcc sometimes generates signed < without explicit casts. */ @@ -520,7 +566,7 @@ JSVAL_TO_GCTHING_IMPL(jsval_layout l) return l.s.payload.ptr; } -static inline JSBool +static inline bool JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_STRING || l.s.tag == JSVAL_TAG_OBJECT; @@ -529,19 +575,19 @@ JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) static inline uint32_t JSVAL_TRACE_KIND_IMPL(jsval_layout l) { - return (uint32_t)(JSBool)JSVAL_IS_STRING_IMPL(l); + return (uint32_t)(bool)JSVAL_IS_STRING_IMPL(l); } -static inline JSBool +static inline bool JSVAL_IS_SPECIFIC_INT32_IMPL(jsval_layout l, int32_t i32) { return l.s.tag == JSVAL_TAG_INT32 && l.s.payload.i32 == i32; } -static inline JSBool -JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, JSBool b) +static inline bool +JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, bool b) { - return (l.s.tag == JSVAL_TAG_BOOLEAN) && (l.s.payload.boo == b); + return (l.s.tag == JSVAL_TAG_BOOLEAN) && (l.s.payload.boo == uint32_t(b)); } static inline jsval_layout @@ -553,7 +599,7 @@ MAGIC_TO_JSVAL_IMPL(JSWhyMagic why) return l; } -static inline JSBool +static inline bool JSVAL_SAME_TYPE_IMPL(jsval_layout lhs, jsval_layout rhs) { JSValueTag ltag = lhs.s.tag, rtag = rhs.s.tag; @@ -570,15 +616,13 @@ JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(jsval_layout l) #elif JS_BITS_PER_WORD == 64 -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout BUILD_JSVAL(JSValueTag tag, uint64_t payload) { - jsval_layout l; - l.asBits = (((uint64_t)(uint32_t)tag) << JSVAL_TAG_SHIFT) | payload; - return l; + JS_RETURN_LAYOUT_FROM_BITS((((uint64_t)(uint32_t)tag) << JSVAL_TAG_SHIFT) | payload); } -static inline JSBool +static inline bool JSVAL_IS_DOUBLE_IMPL(jsval_layout l) { return l.asBits <= JSVAL_SHIFTED_TAG_MAX_DOUBLE; @@ -593,7 +637,7 @@ DOUBLE_TO_JSVAL_IMPL(double d) return l; } -static inline JSBool +static inline bool JSVAL_IS_INT32_IMPL(jsval_layout l) { return (uint32_t)(l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_INT32; @@ -605,27 +649,25 @@ JSVAL_TO_INT32_IMPL(jsval_layout l) return (int32_t)l.asBits; } -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout INT32_TO_JSVAL_IMPL(int32_t i32) { - jsval_layout l; - l.asBits = ((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32; - return l; + JS_RETURN_LAYOUT_FROM_BITS(((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32); } -static inline JSBool +static inline bool JSVAL_IS_NUMBER_IMPL(jsval_layout l) { return l.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET; } -static inline JSBool +static inline bool JSVAL_IS_UNDEFINED_IMPL(jsval_layout l) { return l.asBits == JSVAL_SHIFTED_TAG_UNDEFINED; } -static inline JSBool +static inline bool JSVAL_IS_STRING_IMPL(jsval_layout l) { return (uint32_t)(l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_STRING; @@ -648,47 +690,46 @@ JSVAL_TO_STRING_IMPL(jsval_layout l) return (JSString *)(l.asBits & JSVAL_PAYLOAD_MASK); } -static inline JSBool +static inline bool JSVAL_IS_BOOLEAN_IMPL(jsval_layout l) { return (uint32_t)(l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_BOOLEAN; } -static inline JSBool +static inline bool JSVAL_TO_BOOLEAN_IMPL(jsval_layout l) { - return (JSBool)l.asBits; + return (bool)(l.asBits & JSVAL_PAYLOAD_MASK); } static inline jsval_layout -BOOLEAN_TO_JSVAL_IMPL(JSBool b) +BOOLEAN_TO_JSVAL_IMPL(bool b) { jsval_layout l; - MOZ_ASSERT(b == JS_TRUE || b == JS_FALSE); l.asBits = ((uint64_t)(uint32_t)b) | JSVAL_SHIFTED_TAG_BOOLEAN; return l; } -static inline JSBool +static inline bool JSVAL_IS_MAGIC_IMPL(jsval_layout l) { return (l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_MAGIC; } -static inline JSBool +static inline bool JSVAL_IS_PRIMITIVE_IMPL(jsval_layout l) { return l.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_IMPL(jsval_layout l) { MOZ_ASSERT((l.asBits >> JSVAL_TAG_SHIFT) <= JSVAL_SHIFTED_TAG_OBJECT); return l.asBits >= JSVAL_SHIFTED_TAG_OBJECT; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_OR_NULL_IMPL(jsval_layout l) { MOZ_ASSERT((l.asBits >> JSVAL_TAG_SHIFT) <= JSVAL_TAG_OBJECT); @@ -714,13 +755,13 @@ OBJECT_TO_JSVAL_IMPL(JSObject *obj) return l; } -static inline JSBool +static inline bool JSVAL_IS_NULL_IMPL(jsval_layout l) { return l.asBits == JSVAL_SHIFTED_TAG_NULL; } -static inline JSBool +static inline bool JSVAL_IS_GCTHING_IMPL(jsval_layout l) { return l.asBits >= JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET; @@ -734,7 +775,7 @@ JSVAL_TO_GCTHING_IMPL(jsval_layout l) return (void *)ptrBits; } -static inline JSBool +static inline bool JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) { return JSVAL_IS_GCTHING_IMPL(l) && !JSVAL_IS_NULL_IMPL(l); @@ -743,7 +784,7 @@ JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) static inline uint32_t JSVAL_TRACE_KIND_IMPL(jsval_layout l) { - return (uint32_t)(JSBool)!(JSVAL_IS_OBJECT_IMPL(l)); + return (uint32_t)(bool)!(JSVAL_IS_OBJECT_IMPL(l)); } static inline jsval_layout @@ -764,14 +805,14 @@ JSVAL_TO_PRIVATE_PTR_IMPL(jsval_layout l) return (void *)(l.asBits << 1); } -static inline JSBool +static inline bool JSVAL_IS_SPECIFIC_INT32_IMPL(jsval_layout l, int32_t i32) { return l.asBits == (((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32); } -static inline JSBool -JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, JSBool b) +static inline bool +JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, bool b) { return l.asBits == (((uint64_t)(uint32_t)b) | JSVAL_SHIFTED_TAG_BOOLEAN); } @@ -784,7 +825,7 @@ MAGIC_TO_JSVAL_IMPL(JSWhyMagic why) return l; } -static inline JSBool +static inline bool JSVAL_SAME_TYPE_IMPL(jsval_layout lhs, jsval_layout rhs) { uint64_t lbits = lhs.asBits, rbits = rhs.asBits; @@ -803,10 +844,12 @@ JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(jsval_layout l) #endif /* JS_BITS_PER_WORD */ static inline jsval_layout JSVAL_TO_IMPL(JS::Value v); -static inline JS::Value IMPL_TO_JSVAL(jsval_layout l); +static inline JS_VALUE_CONSTEXPR JS::Value IMPL_TO_JSVAL(jsval_layout l); namespace JS { +static inline JS_VALUE_CONSTEXPR JS::Value UndefinedValue(); + /** * Returns a generic quiet NaN value, with all payload bits set to zero. * @@ -816,7 +859,7 @@ namespace JS { static MOZ_ALWAYS_INLINE double GenericNaN() { - return mozilla::SpecificNaN(0, 0x8000000000000ULL); + return mozilla::SpecificNaN(0, 0x8000000000000ULL); } static inline double @@ -869,6 +912,10 @@ class Value * N.B. the default constructor leaves Value unitialized. Adding a default * constructor prevents Value from being stored in a union. */ +#if defined(JS_VALUE_IS_CONSTEXPR) + Value() = default; + Value(const Value& v) = default; +#endif /*** Mutators ***/ @@ -893,6 +940,10 @@ class Value data = DOUBLE_TO_JSVAL_IMPL(d); } + void setNaN() { + setDouble(GenericNaN()); + } + double &getDoubleRef() { MOZ_ASSERT(isDouble()); return data.asDouble; @@ -1173,16 +1224,20 @@ class Value jsval_layout data; private: +#if defined(JS_VALUE_IS_CONSTEXPR) + JS_VALUE_CONSTEXPR Value(jsval_layout layout) : data(layout) {} +#endif + void staticAssertions() { JS_STATIC_ASSERT(sizeof(JSValueType) == 1); JS_STATIC_ASSERT(sizeof(JSValueTag) == 4); - JS_STATIC_ASSERT(sizeof(JSBool) == 4); JS_STATIC_ASSERT(sizeof(JSWhyMagic) <= 4); JS_STATIC_ASSERT(sizeof(Value) == 8); } friend jsval_layout (::JSVAL_TO_IMPL)(Value); - friend Value (::IMPL_TO_JSVAL)(jsval_layout l); + friend Value JS_VALUE_CONSTEXPR (::IMPL_TO_JSVAL)(jsval_layout l); + friend Value JS_VALUE_CONSTEXPR (JS::UndefinedValue)(); }; inline bool @@ -1205,12 +1260,16 @@ NullValue() return v; } -static inline Value +static inline JS_VALUE_CONSTEXPR Value UndefinedValue() { - Value v; +#if defined(JS_VALUE_IS_CONSTEXPR) + return Value(BUILD_JSVAL(JSVAL_TAG_UNDEFINED, 0)); +#else + JS::Value v; v.setUndefined(); return v; +#endif } static inline Value @@ -1229,6 +1288,22 @@ DoubleValue(double dbl) return v; } +static inline Value +DoubleNaNValue() +{ + Value v; + v.setNaN(); + return v; +} + +static inline Value +Float32Value(float f) +{ + Value v; + v.setDouble(f); + return v; +} + static inline Value StringValue(JSString *str) { @@ -1499,6 +1574,7 @@ class UnbarrieredMutableValueOperations : public ValueOperations void setUndefined() { value()->setUndefined(); } void setInt32(int32_t i) { value()->setInt32(i); } void setDouble(double d) { value()->setDouble(d); } + void setNaN() { setDouble(JS::GenericNaN()); } void setBoolean(bool b) { value()->setBoolean(b); } void setMagic(JSWhyMagic why) { value()->setMagic(why); } bool setNumber(uint32_t ui) { return value()->setNumber(ui); } @@ -1620,12 +1696,16 @@ JSVAL_TO_IMPL(JS::Value v) return v.data; } -inline JS::Value +inline JS_VALUE_CONSTEXPR JS::Value IMPL_TO_JSVAL(jsval_layout l) { +#if defined(JS_VALUE_IS_CONSTEXPR) + return JS::Value(l); +#else JS::Value v; v.data = l; return v; +#endif } namespace JS { @@ -1678,19 +1758,19 @@ static_assert(sizeof(jsval_layout) == sizeof(JS::Value), /************************************************************************/ -static inline JSBool +static inline bool JSVAL_IS_NULL(jsval v) { return JSVAL_IS_NULL_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_VOID(jsval v) { return JSVAL_IS_UNDEFINED_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_INT(jsval v) { return JSVAL_IS_INT32_IMPL(JSVAL_TO_IMPL(v)); @@ -1703,13 +1783,13 @@ JSVAL_TO_INT(jsval v) return JSVAL_TO_INT32_IMPL(JSVAL_TO_IMPL(v)); } -static inline jsval +static inline JS_VALUE_CONSTEXPR jsval INT_TO_JSVAL(int32_t i) { return IMPL_TO_JSVAL(INT32_TO_JSVAL_IMPL(i)); } -static inline JSBool +static inline bool JSVAL_IS_DOUBLE(jsval v) { return JSVAL_IS_DOUBLE_IMPL(JSVAL_TO_IMPL(v)); @@ -1724,7 +1804,7 @@ JSVAL_TO_DOUBLE(jsval v) return l.asDouble; } -static inline jsval +static inline JS_VALUE_CONSTEXPR jsval DOUBLE_TO_JSVAL(double d) { /* @@ -1733,29 +1813,35 @@ DOUBLE_TO_JSVAL(double d) * return IMPL_TO_JSVAL(DOUBLE_TO_JSVAL_IMPL(d)); * because GCC from XCode 3.1.4 miscompiles the above code. */ +#if defined(JS_VALUE_IS_CONSTEXPR) + return IMPL_TO_JSVAL(MOZ_UNLIKELY(d != d) + ? (jsval_layout) { .asBits = 0x7FF8000000000000LL } + : (jsval_layout) { .asDouble = d }); +#else jsval_layout l; if (MOZ_UNLIKELY(d != d)) l.asBits = 0x7FF8000000000000LL; else l.asDouble = d; return IMPL_TO_JSVAL(l); +#endif } -static inline jsval +static inline JS_VALUE_CONSTEXPR jsval UINT_TO_JSVAL(uint32_t i) { - if (i <= JSVAL_INT_MAX) - return INT_TO_JSVAL((int32_t)i); - return DOUBLE_TO_JSVAL((double)i); + return (i <= JSVAL_INT_MAX + ? INT_TO_JSVAL((int32_t)i) + : DOUBLE_TO_JSVAL((double)i)); } -static inline JSBool +static inline bool JSVAL_IS_NUMBER(jsval v) { return JSVAL_IS_NUMBER_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_STRING(jsval v) { return JSVAL_IS_STRING_IMPL(JSVAL_TO_IMPL(v)); @@ -1789,13 +1875,13 @@ OBJECT_TO_JSVAL(JSObject *obj) return IMPL_TO_JSVAL(BUILD_JSVAL(JSVAL_TAG_NULL, 0)); } -static inline JSBool +static inline bool JSVAL_IS_BOOLEAN(jsval v) { return JSVAL_IS_BOOLEAN_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_TO_BOOLEAN(jsval v) { MOZ_ASSERT(JSVAL_IS_BOOLEAN(v)); @@ -1803,18 +1889,18 @@ JSVAL_TO_BOOLEAN(jsval v) } static inline jsval -BOOLEAN_TO_JSVAL(JSBool b) +BOOLEAN_TO_JSVAL(bool b) { return IMPL_TO_JSVAL(BOOLEAN_TO_JSVAL_IMPL(b)); } -static inline JSBool +static inline bool JSVAL_IS_PRIMITIVE(jsval v) { return JSVAL_IS_PRIMITIVE_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_GCTHING(jsval v) { return JSVAL_IS_GCTHING_IMPL(JSVAL_TO_IMPL(v)); @@ -1842,4 +1928,25 @@ JSVAL_TO_PRIVATE(jsval v) return JSVAL_TO_PRIVATE_PTR_IMPL(JSVAL_TO_IMPL(v)); } +// JS constants. For efficiency, prefer predicates (e.g. v.isNull()) and +// constructing values from scratch (e.g. Int32Value(0)). These constants are +// stored in memory and initialized at startup, so testing against them and +// using them requires memory loads and will be correspondingly slow. +extern JS_PUBLIC_DATA(const jsval) JSVAL_NULL; +extern JS_PUBLIC_DATA(const jsval) JSVAL_ZERO; +extern JS_PUBLIC_DATA(const jsval) JSVAL_ONE; +extern JS_PUBLIC_DATA(const jsval) JSVAL_FALSE; +extern JS_PUBLIC_DATA(const jsval) JSVAL_TRUE; +extern JS_PUBLIC_DATA(const jsval) JSVAL_VOID; + +namespace JS { + +extern JS_PUBLIC_DATA(const Handle) NullHandleValue; +extern JS_PUBLIC_DATA(const Handle) UndefinedHandleValue; + +} + +#undef JS_VALUE_IS_CONSTEXPR +#undef JS_RETURN_LAYOUT_FROM_BITS + #endif /* js_Value_h */ diff --git a/external/spidermonkey/include/ios/jsalloc.h b/external/spidermonkey/include/ios/jsalloc.h index 3abc4966d1..03b6b569e1 100644 --- a/external/spidermonkey/include/ios/jsalloc.h +++ b/external/spidermonkey/include/ios/jsalloc.h @@ -9,12 +9,9 @@ #ifndef jsalloc_h #define jsalloc_h -#include "mozilla/AllocPolicy.h" - +#include "js/TypeDecls.h" #include "js/Utility.h" -struct JSContext; - namespace js { class ContextFriendFields; @@ -56,14 +53,14 @@ class TempAllocPolicy void *malloc_(size_t bytes) { void *p = js_malloc(bytes); if (JS_UNLIKELY(!p)) - p = onOutOfMemory(NULL, bytes); + p = onOutOfMemory(nullptr, bytes); return p; } void *calloc_(size_t bytes) { void *p = js_calloc(bytes); if (JS_UNLIKELY(!p)) - p = onOutOfMemory(NULL, bytes); + p = onOutOfMemory(nullptr, bytes); return p; } diff --git a/external/spidermonkey/include/ios/jsapi.h.REMOVED.git-id b/external/spidermonkey/include/ios/jsapi.h.REMOVED.git-id index 27b6bbed78..f73a8c745e 100644 --- a/external/spidermonkey/include/ios/jsapi.h.REMOVED.git-id +++ b/external/spidermonkey/include/ios/jsapi.h.REMOVED.git-id @@ -1 +1 @@ -e14ea931f699b1808c06886e55e977c9819f3774 \ No newline at end of file +38fc2004d49d7c513aff0f7f43d79524ec667c2c \ No newline at end of file diff --git a/external/spidermonkey/include/ios/jsbytecode.h b/external/spidermonkey/include/ios/jsbytecode.h new file mode 100644 index 0000000000..8e4f4cf90b --- /dev/null +++ b/external/spidermonkey/include/ios/jsbytecode.h @@ -0,0 +1,14 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef jsbytecode_h +#define jsbytecode_h + +#include + +typedef uint8_t jsbytecode; + +#endif /* jsbytecode_h */ diff --git a/external/spidermonkey/include/ios/jsclass.h b/external/spidermonkey/include/ios/jsclass.h deleted file mode 100644 index def641715d..0000000000 --- a/external/spidermonkey/include/ios/jsclass.h +++ /dev/null @@ -1,405 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -#ifndef jsclass_h -#define jsclass_h -/* - * A JSClass acts as a vtable for JS objects that allows JSAPI clients to - * control various aspects of the behavior of an object like property lookup. - * js::Class is an engine-private extension that allows more control over - * object behavior and, e.g., allows custom slow layout. - */ - -#include "jsapi.h" -#include "jsprvtd.h" - -namespace js { - -class PropertyName; -class SpecialId; -class PropertyId; - -// This is equal to JSFunction::class_. Use it in places where you don't want -// to #include jsfun.h. -extern JS_FRIEND_DATA(js::Class* const) FunctionClassPtr; - -static JS_ALWAYS_INLINE jsid -SPECIALID_TO_JSID(const SpecialId &sid); - -/* - * We partition the ways to refer to a property into three: by an index - * (uint32_t); by a string whose characters do not represent an index - * (PropertyName, see vm/String.h); and by various special values. - * - * Special values are encoded using SpecialId, which is layout-compatible but - * non-interconvertible with jsid. A SpecialId is used for JSID_VOID, which - * does not occur in JS scripts but may be used to indicate the absence of a - * valid identifier. In the future, a SpecialId may also be an object used by - * Harmony-proposed private names. - */ -class SpecialId -{ - uintptr_t bits_; - - /* Needs access to raw bits. */ - friend JS_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid); - friend class PropertyId; - - static const uintptr_t TYPE_VOID = JSID_TYPE_VOID; - static const uintptr_t TYPE_OBJECT = JSID_TYPE_OBJECT; - static const uintptr_t TYPE_MASK = JSID_TYPE_MASK; - - SpecialId(uintptr_t bits) : bits_(bits) { } - - public: - SpecialId() : bits_(TYPE_VOID) { } - - /* Object-valued */ - - SpecialId(JSObject &obj) - : bits_(uintptr_t(&obj) | TYPE_OBJECT) - { - JS_ASSERT(&obj != NULL); - JS_ASSERT((uintptr_t(&obj) & TYPE_MASK) == 0); - } - - bool isObject() const { - return (bits_ & TYPE_MASK) == TYPE_OBJECT && bits_ != TYPE_OBJECT; - } - - JSObject *toObject() const { - JS_ASSERT(isObject()); - return reinterpret_cast(bits_ & ~TYPE_MASK); - } - - /* Empty */ - - static SpecialId empty() { - SpecialId sid(TYPE_OBJECT); - JS_ASSERT(sid.isEmpty()); - return sid; - } - - bool isEmpty() const { - return bits_ == TYPE_OBJECT; - } - - /* Void */ - - static SpecialId voidId() { - SpecialId sid(TYPE_VOID); - JS_ASSERT(sid.isVoid()); - return sid; - } - - bool isVoid() const { - return bits_ == TYPE_VOID; - } -}; - -static JS_ALWAYS_INLINE jsid -SPECIALID_TO_JSID(const SpecialId &sid) -{ - jsid id; - JSID_BITS(id) = sid.bits_; - JS_ASSERT_IF(sid.isObject(), JSID_IS_OBJECT(id) && JSID_TO_OBJECT(id) == sid.toObject()); - JS_ASSERT_IF(sid.isVoid(), JSID_IS_VOID(id)); - JS_ASSERT_IF(sid.isEmpty(), JSID_IS_EMPTY(id)); - return id; -} - -static JS_ALWAYS_INLINE bool -JSID_IS_SPECIAL(jsid id) -{ - return JSID_IS_OBJECT(id) || JSID_IS_EMPTY(id) || JSID_IS_VOID(id); -} - -static JS_ALWAYS_INLINE SpecialId -JSID_TO_SPECIALID(jsid id) -{ - JS_ASSERT(JSID_IS_SPECIAL(id)); - if (JSID_IS_OBJECT(id)) - return SpecialId(*JSID_TO_OBJECT(id)); - if (JSID_IS_EMPTY(id)) - return SpecialId::empty(); - JS_ASSERT(JSID_IS_VOID(id)); - return SpecialId::voidId(); -} - -typedef JS::Handle HandleSpecialId; - -/* js::Class operation signatures. */ - -typedef JSBool -(* LookupGenericOp)(JSContext *cx, HandleObject obj, HandleId id, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* LookupPropOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* LookupElementOp)(JSContext *cx, HandleObject obj, uint32_t index, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* LookupSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* DefineGenericOp)(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* DefinePropOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* DefineElementOp)(JSContext *cx, HandleObject obj, uint32_t index, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* DefineSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* GenericIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandleId id, MutableHandleValue vp); -typedef JSBool -(* PropertyIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandlePropertyName name, MutableHandleValue vp); -typedef JSBool -(* ElementIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, uint32_t index, MutableHandleValue vp); -typedef JSBool -(* ElementIfPresentOp)(JSContext *cx, HandleObject obj, HandleObject receiver, uint32_t index, MutableHandleValue vp, bool* present); -typedef JSBool -(* SpecialIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandleSpecialId sid, MutableHandleValue vp); -typedef JSBool -(* StrictGenericIdOp)(JSContext *cx, HandleObject obj, HandleId id, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* StrictPropertyIdOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* StrictElementIdOp)(JSContext *cx, HandleObject obj, uint32_t index, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* StrictSpecialIdOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* GenericAttributesOp)(JSContext *cx, HandleObject obj, HandleId id, unsigned *attrsp); -typedef JSBool -(* PropertyAttributesOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, unsigned *attrsp); -typedef JSBool -(* ElementAttributesOp)(JSContext *cx, HandleObject obj, uint32_t index, unsigned *attrsp); -typedef JSBool -(* SpecialAttributesOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, unsigned *attrsp); -typedef JSBool -(* DeletePropertyOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, JSBool *succeeded); -typedef JSBool -(* DeleteElementOp)(JSContext *cx, HandleObject obj, uint32_t index, JSBool *succeeded); -typedef JSBool -(* DeleteSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, JSBool *succeeded); - - -typedef JSObject * -(* ObjectOp)(JSContext *cx, HandleObject obj); -typedef void -(* FinalizeOp)(FreeOp *fop, JSObject *obj); - -#define JS_CLASS_MEMBERS \ - const char *name; \ - uint32_t flags; \ - \ - /* Mandatory function pointer members. */ \ - JSPropertyOp addProperty; \ - JSDeletePropertyOp delProperty; \ - JSPropertyOp getProperty; \ - JSStrictPropertyOp setProperty; \ - JSEnumerateOp enumerate; \ - JSResolveOp resolve; \ - JSConvertOp convert; \ - \ - /* Optional members (may be null). */ \ - FinalizeOp finalize; \ - JSCheckAccessOp checkAccess; \ - JSNative call; \ - JSHasInstanceOp hasInstance; \ - JSNative construct; \ - JSTraceOp trace - -/* - * The helper struct to measure the size of JS_CLASS_MEMBERS to know how much - * we have to pad js::Class to match the size of JSClass. - */ -struct ClassSizeMeasurement -{ - JS_CLASS_MEMBERS; -}; - -struct ClassExtension -{ - JSObjectOp outerObject; - JSObjectOp innerObject; - JSIteratorOp iteratorObject; - - /* - * isWrappedNative is true only if the class is an XPCWrappedNative. - * WeakMaps use this to override the wrapper disposal optimization. - */ - bool isWrappedNative; - - /* - * If an object is used as a key in a weakmap, it may be desirable for the - * garbage collector to keep that object around longer than it otherwise - * would. A common case is when the key is a wrapper around an object in - * another compartment, and we want to avoid collecting the wrapper (and - * removing the weakmap entry) as long as the wrapped object is alive. In - * that case, the wrapped object is returned by the wrapper's - * weakmapKeyDelegateOp hook. As long as the wrapper is used as a weakmap - * key, it will not be collected (and remain in the weakmap) until the - * wrapped object is collected. - */ - JSWeakmapKeyDelegateOp weakmapKeyDelegateOp; -}; - -#define JS_NULL_CLASS_EXT {NULL,NULL,NULL,false,NULL} - -struct ObjectOps -{ - LookupGenericOp lookupGeneric; - LookupPropOp lookupProperty; - LookupElementOp lookupElement; - LookupSpecialOp lookupSpecial; - DefineGenericOp defineGeneric; - DefinePropOp defineProperty; - DefineElementOp defineElement; - DefineSpecialOp defineSpecial; - GenericIdOp getGeneric; - PropertyIdOp getProperty; - ElementIdOp getElement; - ElementIfPresentOp getElementIfPresent; /* can be null */ - SpecialIdOp getSpecial; - StrictGenericIdOp setGeneric; - StrictPropertyIdOp setProperty; - StrictElementIdOp setElement; - StrictSpecialIdOp setSpecial; - GenericAttributesOp getGenericAttributes; - PropertyAttributesOp getPropertyAttributes; - ElementAttributesOp getElementAttributes; - SpecialAttributesOp getSpecialAttributes; - GenericAttributesOp setGenericAttributes; - PropertyAttributesOp setPropertyAttributes; - ElementAttributesOp setElementAttributes; - SpecialAttributesOp setSpecialAttributes; - DeletePropertyOp deleteProperty; - DeleteElementOp deleteElement; - DeleteSpecialOp deleteSpecial; - - JSNewEnumerateOp enumerate; - ObjectOp thisObject; -}; - -#define JS_NULL_OBJECT_OPS \ - {NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, \ - NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, \ - NULL,NULL,NULL} - -struct Class -{ - JS_CLASS_MEMBERS; - ClassExtension ext; - ObjectOps ops; - uint8_t pad[sizeof(JSClass) - sizeof(ClassSizeMeasurement) - - sizeof(ClassExtension) - sizeof(ObjectOps)]; - - /* Class is not native and its map is not a scope. */ - static const uint32_t NON_NATIVE = JSCLASS_INTERNAL_FLAG2; - - bool isNative() const { - return !(flags & NON_NATIVE); - } - - bool hasPrivate() const { - return !!(flags & JSCLASS_HAS_PRIVATE); - } - - bool emulatesUndefined() const { - return flags & JSCLASS_EMULATES_UNDEFINED; - } - - bool isCallable() const { - return this == js::FunctionClassPtr || call; - } - - static size_t offsetOfFlags() { return offsetof(Class, flags); } -}; - -JS_STATIC_ASSERT(offsetof(JSClass, name) == offsetof(Class, name)); -JS_STATIC_ASSERT(offsetof(JSClass, flags) == offsetof(Class, flags)); -JS_STATIC_ASSERT(offsetof(JSClass, addProperty) == offsetof(Class, addProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, delProperty) == offsetof(Class, delProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, getProperty) == offsetof(Class, getProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, setProperty) == offsetof(Class, setProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, enumerate) == offsetof(Class, enumerate)); -JS_STATIC_ASSERT(offsetof(JSClass, resolve) == offsetof(Class, resolve)); -JS_STATIC_ASSERT(offsetof(JSClass, convert) == offsetof(Class, convert)); -JS_STATIC_ASSERT(offsetof(JSClass, finalize) == offsetof(Class, finalize)); -JS_STATIC_ASSERT(offsetof(JSClass, checkAccess) == offsetof(Class, checkAccess)); -JS_STATIC_ASSERT(offsetof(JSClass, call) == offsetof(Class, call)); -JS_STATIC_ASSERT(offsetof(JSClass, construct) == offsetof(Class, construct)); -JS_STATIC_ASSERT(offsetof(JSClass, hasInstance) == offsetof(Class, hasInstance)); -JS_STATIC_ASSERT(offsetof(JSClass, trace) == offsetof(Class, trace)); -JS_STATIC_ASSERT(sizeof(JSClass) == sizeof(Class)); - -static JS_ALWAYS_INLINE JSClass * -Jsvalify(Class *c) -{ - return (JSClass *)c; -} -static JS_ALWAYS_INLINE const JSClass * -Jsvalify(const Class *c) -{ - return (const JSClass *)c; -} - -static JS_ALWAYS_INLINE Class * -Valueify(JSClass *c) -{ - return (Class *)c; -} -static JS_ALWAYS_INLINE const Class * -Valueify(const JSClass *c) -{ - return (const Class *)c; -} - -/* - * Enumeration describing possible values of the [[Class]] internal property - * value of objects. - */ -enum ESClassValue { - ESClass_Array, ESClass_Number, ESClass_String, ESClass_Boolean, - ESClass_RegExp, ESClass_ArrayBuffer, ESClass_Date -}; - -/* - * Return whether the given object has the given [[Class]] internal property - * value. Beware, this query says nothing about the js::Class of the JSObject - * so the caller must not assume anything about obj's representation (e.g., obj - * may be a proxy). - */ -inline bool -ObjectClassIs(JSObject &obj, ESClassValue classValue, JSContext *cx); - -/* Just a helper that checks v.isObject before calling ObjectClassIs. */ -inline bool -IsObjectWithClass(const Value &v, ESClassValue classValue, JSContext *cx); - -inline bool -IsPoisonedSpecialId(js::SpecialId iden) -{ - if (iden.isObject()) - return IsPoisonedPtr(iden.toObject()); - return false; -} - -template <> struct GCMethods -{ - static SpecialId initial() { return SpecialId(); } - static ThingRootKind kind() { return THING_ROOT_ID; } - static bool poisoned(SpecialId id) { return IsPoisonedSpecialId(id); } -}; - -} /* namespace js */ - -#endif /* jsclass_h */ diff --git a/external/spidermonkey/include/ios/jscpucfg.h b/external/spidermonkey/include/ios/jscpucfg.h index c79bd7ad14..ccacab3482 100644 --- a/external/spidermonkey/include/ios/jscpucfg.h +++ b/external/spidermonkey/include/ios/jscpucfg.h @@ -14,8 +14,6 @@ # if defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_) # define IS_LITTLE_ENDIAN 1 # undef IS_BIG_ENDIAN -# define JS_BYTES_PER_WORD 8 -# define JS_BITS_PER_WORD_LOG2 6 # else /* !(defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)) */ # error "CPU type is unknown" # endif /* !(defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)) */ @@ -28,8 +26,6 @@ # define IS_LITTLE_ENDIAN 1 # undef IS_BIG_ENDIAN -# define JS_BYTES_PER_WORD 4 -# define JS_BITS_PER_WORD_LOG2 5 #elif defined(__APPLE__) # if __LITTLE_ENDIAN__ @@ -57,8 +53,8 @@ /* BSDs */ #elif defined(JS_HAVE_MACHINE_ENDIAN_H) -# include # include +# include # if defined(_BYTE_ORDER) # if _BYTE_ORDER == _LITTLE_ENDIAN diff --git a/external/spidermonkey/include/ios/jsfriendapi.h b/external/spidermonkey/include/ios/jsfriendapi.h index a1c3024fed..811275d332 100644 --- a/external/spidermonkey/include/ios/jsfriendapi.h +++ b/external/spidermonkey/include/ios/jsfriendapi.h @@ -9,11 +9,12 @@ #include "mozilla/MemoryReporting.h" -#include "jsclass.h" -#include "jsprvtd.h" +#include "jsbytecode.h" #include "jspubtd.h" #include "js/CallArgs.h" +#include "js/CallNonGenericMethod.h" +#include "js/Class.h" /* * This macro checks if the stack pointer has exceeded a given limit. If @@ -30,6 +31,12 @@ #define JS_CHECK_STACK_SIZE(limit, lval) JS_CHECK_STACK_SIZE_WITH_TOLERANCE(limit, lval, 0) +class JSAtom; +struct JSErrorFormatString; +class JSLinearString; +struct JSJitInfo; +class JSErrorReport; + namespace JS { template class Heap; @@ -47,11 +54,11 @@ JS_FindCompilationScope(JSContext *cx, JSObject *obj); extern JS_FRIEND_API(JSFunction *) JS_GetObjectFunction(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_SplicePrototype(JSContext *cx, JSObject *obj, JSObject *proto); extern JS_FRIEND_API(JSObject *) -JS_NewObjectWithUniqueType(JSContext *cx, JSClass *clasp, JSObject *proto, JSObject *parent); +JS_NewObjectWithUniqueType(JSContext *cx, const JSClass *clasp, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(uint32_t) JS_ObjectCountDynamicSlots(JS::HandleObject obj); @@ -62,7 +69,7 @@ JS_SetProtoCalled(JSContext *cx); extern JS_FRIEND_API(size_t) JS_GetCustomIteratorCount(JSContext *cx); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_NondeterministicGetWeakMapKeys(JSContext *cx, JSObject *obj, JSObject **ret); /* @@ -71,7 +78,7 @@ JS_NondeterministicGetWeakMapKeys(JSContext *cx, JSObject *obj, JSObject **ret); * Such objects hold no other objects (they have no outgoing reference edges) * and will throw if you touch them (e.g. by reading/writing a property). */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsDeadWrapper(JSObject *obj); /* @@ -112,11 +119,11 @@ JS_GetCompartmentPrincipals(JSCompartment *compartment); extern JS_FRIEND_API(void) JS_SetCompartmentPrincipals(JSCompartment *compartment, JSPrincipals *principals); -/* Safe to call with input obj == NULL. Returns non-NULL iff obj != NULL. */ +/* Safe to call with input obj == nullptr. Returns non-nullptr iff obj != nullptr. */ extern JS_FRIEND_API(JSObject *) JS_ObjectToInnerObject(JSContext *cx, JSObject *obj); -/* Requires obj != NULL. */ +/* Requires obj != nullptr. */ extern JS_FRIEND_API(JSObject *) JS_ObjectToOuterObject(JSContext *cx, JSObject *obj); @@ -126,8 +133,8 @@ JS_CloneObject(JSContext *cx, JSObject *obj, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(JSString *) JS_BasicObjectToString(JSContext *cx, JS::HandleObject obj); -extern JS_FRIEND_API(JSBool) -js_GetterOnlyPropertyStub(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JSBool strict, +extern JS_FRIEND_API(bool) +js_GetterOnlyPropertyStub(JSContext *cx, JS::HandleObject obj, JS::HandleId id, bool strict, JS::MutableHandleValue vp); JS_FRIEND_API(void) @@ -166,18 +173,32 @@ extern JS_FRIEND_API(void) js_DumpChars(const jschar *s, size_t n); #endif +/* + * Copies all own properties from |obj| to |target|. |obj| must be a "native" + * object (that is to say, normal-ish - not an Array or a Proxy). + * + * On entry, |cx| must be in the compartment of |target|. + */ extern JS_FRIEND_API(bool) JS_CopyPropertiesFrom(JSContext *cx, JSObject *target, JSObject *obj); -extern JS_FRIEND_API(JSBool) -JS_WrapPropertyDescriptor(JSContext *cx, js::PropertyDescriptor *desc); +/* + * Single-property version of the above. This function asserts that an |own| + * property of the given name exists on |obj|. + */ +extern JS_FRIEND_API(bool) +JS_CopyPropertyFrom(JSContext *cx, JS::HandleId id, JS::HandleObject target, + JS::HandleObject obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) +JS_WrapPropertyDescriptor(JSContext *cx, JS::MutableHandle desc); + +extern JS_FRIEND_API(bool) JS_WrapAutoIdVector(JSContext *cx, JS::AutoIdVector &props); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_EnumerateState(JSContext *cx, JS::HandleObject obj, JSIterateOp enum_op, - js::MutableHandleValue statep, js::MutableHandleId idp); + JS::MutableHandleValue statep, JS::MutableHandleId idp); struct JSFunctionSpecWithHelp { const char *name; @@ -191,19 +212,49 @@ struct JSFunctionSpecWithHelp { #define JS_FN_HELP(name,call,nargs,flags,usage,help) \ {name, call, nargs, (flags) | JSPROP_ENUMERATE | JSFUN_STUB_GSOPS, usage, help} #define JS_FS_HELP_END \ - {NULL, NULL, 0, 0, NULL, NULL} + {nullptr, nullptr, 0, 0, nullptr, nullptr} extern JS_FRIEND_API(bool) JS_DefineFunctionsWithHelp(JSContext *cx, JSObject *obj, const JSFunctionSpecWithHelp *fs); -typedef bool (* JS_SourceHook)(JSContext *cx, JS::Handle script, - jschar **src, uint32_t *length); - -extern JS_FRIEND_API(void) -JS_SetSourceHook(JSRuntime *rt, JS_SourceHook hook); - namespace js { +/* + * A class of objects that return source code on demand. + * + * When code is compiled with CompileOptions::LAZY_SOURCE, SpiderMonkey + * doesn't retain the source code (and doesn't do lazy bytecode + * generation). If we ever need the source code, say, in response to a call + * to Function.prototype.toSource or Debugger.Source.prototype.text, then + * we call the 'load' member function of the instance of this class that + * has hopefully been registered with the runtime, passing the code's URL, + * and hope that it will be able to find the source. + */ +class SourceHook { + public: + virtual ~SourceHook() { } + + /* + * Set |*src| and |*length| to refer to the source code for |filename|. + * On success, the caller owns the buffer to which |*src| points, and + * should use JS_free to free it. + */ + virtual bool load(JSContext *cx, const char *filename, jschar **src, size_t *length) = 0; +}; + +/* + * Have |rt| use |hook| to retrieve LAZY_SOURCE source code. See the + * comments for SourceHook. The runtime takes ownership of the hook, and + * will delete it when the runtime itself is deleted, or when a new hook is + * set. + */ +extern JS_FRIEND_API(void) +SetSourceHook(JSRuntime *rt, SourceHook *hook); + +/* Remove |rt|'s source hook, and return it. The caller now owns the hook. */ +extern JS_FRIEND_API(SourceHook *) +ForgetSourceHook(JSRuntime *rt); + inline JSRuntime * GetRuntime(const JSContext *cx) { @@ -228,16 +279,21 @@ GetCompartmentZone(JSCompartment *comp); typedef bool (* PreserveWrapperCallback)(JSContext *cx, JSObject *obj); +typedef enum { + CollectNurseryBeforeDump, + IgnoreNurseryObjects +} DumpHeapNurseryBehaviour; + /* * Dump the complete object graph of heap-allocated things. * fp is the file for the dump output. */ extern JS_FRIEND_API(void) -DumpHeapComplete(JSRuntime *rt, FILE *fp); +DumpHeapComplete(JSRuntime *rt, FILE *fp, DumpHeapNurseryBehaviour nurseryBehaviour); -#ifdef OLD_GETTER_SETTER_METHODS -JS_FRIEND_API(JSBool) obj_defineGetter(JSContext *cx, unsigned argc, js::Value *vp); -JS_FRIEND_API(JSBool) obj_defineSetter(JSContext *cx, unsigned argc, js::Value *vp); +#ifdef JS_OLD_GETTER_SETTER_METHODS +JS_FRIEND_API(bool) obj_defineGetter(JSContext *cx, unsigned argc, JS::Value *vp); +JS_FRIEND_API(bool) obj_defineSetter(JSContext *cx, unsigned argc, JS::Value *vp); #endif extern JS_FRIEND_API(bool) @@ -257,7 +313,7 @@ IsAtomsCompartment(JSCompartment *comp); * particularly, always reports when it returns false). */ extern JS_FRIEND_API(bool) -ReportIfUndeclaredVarAssignment(JSContext *cx, HandleString propname); +ReportIfUndeclaredVarAssignment(JSContext *cx, JS::HandleString propname); /* * Returns whether we're in a non-strict property set (in that we're in a @@ -274,7 +330,7 @@ struct WeakMapTracer; * Weak map tracer callback, called once for every binding of every * weak map that was live at the time of the last garbage collection. * - * m will be NULL if the weak map is not contained in a JS Object. + * m will be nullptr if the weak map is not contained in a JS Object. */ typedef void (* WeakMapTraceCallback)(WeakMapTracer *trc, JSObject *m, @@ -330,12 +386,12 @@ GetAnyCompartmentInZone(JS::Zone *zone); namespace shadow { struct TypeObject { - Class *clasp; + const Class *clasp; JSObject *proto; }; struct BaseShape { - js::Class *clasp; + const js::Class *clasp; JSObject *parent; JSObject *_1; JSCompartment *compartment; @@ -353,15 +409,15 @@ public: struct Object { shadow::Shape *shape; shadow::TypeObject *type; - js::Value *slots; - js::Value *_1; + JS::Value *slots; + JS::Value *_1; size_t numFixedSlots() const { return shape->slotInfo >> Shape::FIXED_SLOTS_SHIFT; } - Value *fixedSlots() const { - return (Value *)(uintptr_t(this) + sizeof(shadow::Object)); + JS::Value *fixedSlots() const { + return (JS::Value *)(uintptr_t(this) + sizeof(shadow::Object)); } - js::Value &slotRef(size_t slot) const { + JS::Value &slotRef(size_t slot) const { size_t nfixed = numFixedSlots(); if (slot < nfixed) return fixedSlots()[slot]; @@ -374,7 +430,7 @@ struct Function { uint16_t nargs; uint16_t flags; /* Used only for natives */ - Native native; + JSNative native; const JSJitInfo *jitinfo; void *_1; }; @@ -387,23 +443,17 @@ struct Atom { } /* namespace shadow */ -// These are equal to |&{Function,Object,OuterWindow}ProxyObject::class_|. Use -// them in places where you don't want to #include vm/ProxyObject.h. -extern JS_FRIEND_DATA(js::Class* const) FunctionProxyClassPtr; -extern JS_FRIEND_DATA(js::Class* const) ObjectProxyClassPtr; -extern JS_FRIEND_DATA(js::Class* const) OuterWindowProxyClassPtr; - // This is equal to |&JSObject::class_|. Use it in places where you don't want // to #include jsobj.h. -extern JS_FRIEND_DATA(js::Class* const) ObjectClassPtr; +extern JS_FRIEND_DATA(const js::Class* const) ObjectClassPtr; -inline js::Class * +inline const js::Class * GetObjectClass(JSObject *obj) { return reinterpret_cast(obj)->type->clasp; } -inline JSClass * +inline const JSClass * GetObjectJSClass(JSObject *obj) { return js::Jsvalify(GetObjectClass(obj)); @@ -447,6 +497,16 @@ GetObjectParentMaybeScope(JSObject *obj); JS_FRIEND_API(JSObject *) GetGlobalForObjectCrossCompartment(JSObject *obj); +JS_FRIEND_API(void) +AssertSameCompartment(JSContext *cx, JSObject *obj); + +#ifdef DEBUG +JS_FRIEND_API(void) +AssertSameCompartment(JSObject *objA, JSObject *objB); +#else +inline void AssertSameCompartment(JSObject *objA, JSObject *objB) {} +#endif + // For legacy consumers only. This whole concept is going away soon. JS_FRIEND_API(JSObject *) DefaultObjectForContextOrNull(JSContext *cx); @@ -462,7 +522,7 @@ IsOriginalScriptFunction(JSFunction *fun); /* * Return the outermost enclosing function (script) of the scripted caller. - * This function returns NULL in several cases: + * This function returns nullptr in several cases: * - no script is running on the context * - the caller is in global or eval code * In particular, this function will "stop" its outermost search at eval() and @@ -486,30 +546,18 @@ NewFunctionByIdWithReserved(JSContext *cx, JSNative native, unsigned nargs, unsi JS_FRIEND_API(JSObject *) InitClassWithReserved(JSContext *cx, JSObject *obj, JSObject *parent_proto, - JSClass *clasp, JSNative constructor, unsigned nargs, + const JSClass *clasp, JSNative constructor, unsigned nargs, const JSPropertySpec *ps, const JSFunctionSpec *fs, const JSPropertySpec *static_ps, const JSFunctionSpec *static_fs); -JS_FRIEND_API(const Value &) +JS_FRIEND_API(const JS::Value &) GetFunctionNativeReserved(JSObject *fun, size_t which); JS_FRIEND_API(void) -SetFunctionNativeReserved(JSObject *fun, size_t which, const Value &val); +SetFunctionNativeReserved(JSObject *fun, size_t which, const JS::Value &val); -inline bool -GetObjectProto(JSContext *cx, JS::Handle obj, JS::MutableHandle proto) -{ - js::Class *clasp = GetObjectClass(obj); - if (clasp == js::ObjectProxyClassPtr || - clasp == js::OuterWindowProxyClassPtr || - clasp == js::FunctionProxyClassPtr) - { - return JS_GetPrototype(cx, obj, proto); - } - - proto.set(reinterpret_cast(obj.get())->type->proto); - return true; -} +JS_FRIEND_API(bool) +GetObjectProto(JSContext *cx, JS::Handle obj, JS::MutableHandle proto); inline void * GetObjectPrivate(JSObject *obj) @@ -523,7 +571,7 @@ GetObjectPrivate(JSObject *obj) * Get a slot that is both reserved for object's clasp *and* is fixed (fits * within the maximum capacity for the object's fixed slots). */ -inline const Value & +inline const JS::Value & GetReservedSlot(JSObject *obj, size_t slot) { JS_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); @@ -531,10 +579,10 @@ GetReservedSlot(JSObject *obj, size_t slot) } JS_FRIEND_API(void) -SetReservedSlotWithBarrier(JSObject *obj, size_t slot, const Value &value); +SetReservedSlotWithBarrier(JSObject *obj, size_t slot, const JS::Value &value); inline void -SetReservedSlot(JSObject *obj, size_t slot, const Value &value) +SetReservedSlot(JSObject *obj, size_t slot, const JS::Value &value) { JS_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); shadow::Object *sobj = reinterpret_cast(obj); @@ -553,7 +601,7 @@ SetReservedSlot(JSObject *obj, size_t slot, const Value &value) JS_FRIEND_API(uint32_t) GetObjectSlotSpan(JSObject *obj); -inline const Value & +inline const JS::Value & GetObjectSlot(JSObject *obj, size_t slot) { JS_ASSERT(slot < GetObjectSlotSpan(obj)); @@ -579,26 +627,14 @@ AtomToLinearString(JSAtom *atom) return reinterpret_cast(atom); } -static inline js::PropertyOp -CastAsJSPropertyOp(JSObject *object) -{ - return JS_DATA_TO_FUNC_PTR(js::PropertyOp, object); -} - -static inline js::StrictPropertyOp -CastAsJSStrictPropertyOp(JSObject *object) -{ - return JS_DATA_TO_FUNC_PTR(js::StrictPropertyOp, object); -} +JS_FRIEND_API(bool) +GetPropertyNames(JSContext *cx, JSObject *obj, unsigned flags, JS::AutoIdVector *props); JS_FRIEND_API(bool) -GetPropertyNames(JSContext *cx, JSObject *obj, unsigned flags, js::AutoIdVector *props); +AppendUnique(JSContext *cx, JS::AutoIdVector &base, JS::AutoIdVector &others); JS_FRIEND_API(bool) -AppendUnique(JSContext *cx, AutoIdVector &base, AutoIdVector &others); - -JS_FRIEND_API(bool) -GetGeneric(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id, Value *vp); +GetGeneric(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id, JS::Value *vp); JS_FRIEND_API(bool) StringIsArrayIndex(JSLinearString *str, uint32_t *indexp); @@ -609,6 +645,14 @@ SetPreserveWrapperCallback(JSRuntime *rt, PreserveWrapperCallback callback); JS_FRIEND_API(bool) IsObjectInContextCompartment(JSObject *obj, const JSContext *cx); +/* + * ErrorFromException takes a raw Value so that it's possible to call it during + * GC/CC/whatever, when it may not be possible to get a JSContext to create a + * Rooted. It promises to never ever GC. + */ +JS_FRIEND_API(JSErrorReport*) +ErrorFromException(JS::Value val); + /* * NB: these flag bits are encoded into the bytecode stream in the immediate * operand of JSOP_ITER, so don't change them without advancing vm/Xdr.h's @@ -619,18 +663,18 @@ IsObjectInContextCompartment(JSObject *obj, const JSContext *cx); #define JSITER_KEYVALUE 0x4 /* destructuring for-in wants [key, value] */ #define JSITER_OWNONLY 0x8 /* iterate over obj's own properties only */ #define JSITER_HIDDEN 0x10 /* also enumerate non-enumerable properties */ -#define JSITER_FOR_OF 0x20 /* harmony for-of loop */ -inline uintptr_t -GetNativeStackLimit(const JSRuntime *rt) -{ - return PerThreadDataFriendFields::getMainThread(rt)->nativeStackLimit; -} +JS_FRIEND_API(bool) +RunningWithTrustedPrincipals(JSContext *cx); inline uintptr_t GetNativeStackLimit(JSContext *cx) { - return GetNativeStackLimit(GetRuntime(cx)); + StackKind kind = RunningWithTrustedPrincipals(cx) ? StackForTrustedScript + : StackForUntrustedScript; + PerThreadDataFriendFields *mainThread = + PerThreadDataFriendFields::getMainThread(GetRuntime(cx)); + return mainThread->nativeStackLimit[kind]; } /* @@ -655,6 +699,14 @@ GetNativeStackLimit(JSContext *cx) } \ JS_END_MACRO +#define JS_CHECK_RECURSION_WITH_SP(cx, sp, onerror) \ + JS_BEGIN_MACRO \ + if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ + js_ReportOverRecursed(cx); \ + onerror; \ + } \ + JS_END_MACRO + #define JS_CHECK_CHROME_RECURSION(cx, onerror) \ JS_BEGIN_MACRO \ int stackDummy_; \ @@ -685,94 +737,13 @@ GetPCCountScriptSummary(JSContext *cx, size_t script); JS_FRIEND_API(JSString *) GetPCCountScriptContents(JSContext *cx, size_t script); -/* - * A call stack can be specified to the JS engine such that all JS entry/exits - * to functions push/pop an entry to/from the specified stack. - * - * For more detailed information, see vm/SPSProfiler.h - */ -class ProfileEntry -{ - /* - * All fields are marked volatile to prevent the compiler from re-ordering - * instructions. Namely this sequence: - * - * entry[size] = ...; - * size++; - * - * If the size modification were somehow reordered before the stores, then - * if a sample were taken it would be examining bogus information. - * - * A ProfileEntry represents both a C++ profile entry and a JS one. Both use - * the string as a description, but JS uses the sp as NULL to indicate that - * it is a JS entry. The script_ is then only ever examined for a JS entry, - * and the idx is used by both, but with different meanings. - */ - const char * volatile string; // Descriptive string of this entry - void * volatile sp; // Relevant stack pointer for the entry - JSScript * volatile script_; // if js(), non-null script which is running - int32_t volatile idx; // if js(), idx of pc, otherwise line number - - public: - /* - * All of these methods are marked with the 'volatile' keyword because SPS's - * representation of the stack is stored such that all ProfileEntry - * instances are volatile. These methods would not be available unless they - * were marked as volatile as well - */ - - bool js() volatile { - JS_ASSERT_IF(sp == NULL, script_ != NULL); - return sp == NULL; - } - - uint32_t line() volatile { JS_ASSERT(!js()); return idx; } - JSScript *script() volatile { JS_ASSERT(js()); return script_; } - void *stackAddress() volatile { return sp; } - const char *label() volatile { return string; } - - void setLine(uint32_t aLine) volatile { JS_ASSERT(!js()); idx = aLine; } - void setLabel(const char *aString) volatile { string = aString; } - void setStackAddress(void *aSp) volatile { sp = aSp; } - void setScript(JSScript *aScript) volatile { script_ = aScript; } - - /* we can't know the layout of JSScript, so look in vm/SPSProfiler.cpp */ - JS_FRIEND_API(jsbytecode *) pc() volatile; - JS_FRIEND_API(void) setPC(jsbytecode *pc) volatile; - - static size_t offsetOfString() { return offsetof(ProfileEntry, string); } - static size_t offsetOfStackAddress() { return offsetof(ProfileEntry, sp); } - static size_t offsetOfPCIdx() { return offsetof(ProfileEntry, idx); } - static size_t offsetOfScript() { return offsetof(ProfileEntry, script_); } - - /* - * The index used in the entry can either be a line number or the offset of - * a pc into a script's code. To signify a NULL pc, use a -1 index. This is - * checked against in pc() and setPC() to set/get the right pc. - */ - static const int32_t NullPCIndex = -1; -}; - -JS_FRIEND_API(void) -SetRuntimeProfilingStack(JSRuntime *rt, ProfileEntry *stack, uint32_t *size, - uint32_t max); - -JS_FRIEND_API(void) -EnableRuntimeProfilingStack(JSRuntime *rt, bool enabled); - -JS_FRIEND_API(jsbytecode*) -ProfilingGetPC(JSRuntime *rt, JSScript *script, void *ip); - #ifdef JS_THREADSAFE JS_FRIEND_API(bool) ContextHasOutstandingRequests(const JSContext *cx); #endif -JS_FRIEND_API(bool) -HasUnrootedGlobal(const JSContext *cx); - typedef void -(* ActivityCallback)(void *arg, JSBool active); +(* ActivityCallback)(void *arg, bool active); /* * Sets a callback that is run whenever the runtime goes idle - the @@ -785,22 +756,10 @@ SetActivityCallback(JSRuntime *rt, ActivityCallback cb, void *arg); extern JS_FRIEND_API(const JSStructuredCloneCallbacks *) GetContextStructuredCloneCallbacks(JSContext *cx); -extern JS_FRIEND_API(bool) -CanCallContextDebugHandler(JSContext *cx); - -extern JS_FRIEND_API(JSTrapStatus) -CallContextDebugHandler(JSContext *cx, JSScript *script, jsbytecode *bc, Value *rval); - extern JS_FRIEND_API(bool) IsContextRunningJS(JSContext *cx); -typedef void -(* AnalysisPurgeCallback)(JSRuntime *rt, JS::Handle desc); - -extern JS_FRIEND_API(AnalysisPurgeCallback) -SetAnalysisPurgeCallback(JSRuntime *rt, AnalysisPurgeCallback callback); - -typedef JSBool +typedef bool (* DOMInstanceClassMatchesProto)(JS::HandleObject protoObject, uint32_t protoID, uint32_t depth); struct JSDOMCallbacks { @@ -832,10 +791,10 @@ CastToJSFreeOp(FreeOp *fop) /* * Get an error type name from a JSExnType constant. - * Returns NULL for invalid arguments and JSEXN_INTERNALERR + * Returns nullptr for invalid arguments and JSEXN_INTERNALERR */ extern JS_FRIEND_API(const jschar*) -GetErrorTypeName(JSContext* cx, int16_t exnType); +GetErrorTypeName(JSRuntime* rt, int16_t exnType); #ifdef DEBUG extern JS_FRIEND_API(unsigned) @@ -886,7 +845,7 @@ struct CompartmentsWithPrincipals : public CompartmentFilter { } }; -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) NukeCrossCompartmentWrappers(JSContext* cx, const CompartmentFilter& sourceFilter, const CompartmentFilter& targetFilter, @@ -910,7 +869,7 @@ NukeCrossCompartmentWrappers(JSContext* cx, struct ExpandoAndGeneration { ExpandoAndGeneration() - : expando(UndefinedValue()), + : expando(JS::UndefinedValue()), generation(0) {} @@ -933,10 +892,10 @@ typedef enum DOMProxyShadowsResult { typedef DOMProxyShadowsResult (* DOMProxyShadowsCheck)(JSContext* cx, JS::HandleObject object, JS::HandleId id); JS_FRIEND_API(void) -SetDOMProxyInformation(void *domProxyHandlerFamily, uint32_t domProxyExpandoSlot, +SetDOMProxyInformation(const void *domProxyHandlerFamily, uint32_t domProxyExpandoSlot, DOMProxyShadowsCheck domProxyShadowsCheck); -void *GetDOMProxyHandlerFamily(); +const void *GetDOMProxyHandlerFamily(); uint32_t GetDOMProxyExpandoSlot(); DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); @@ -948,7 +907,7 @@ DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); * Detect whether the internal date value is NaN. (Because failure is * out-of-band for js_DateGet*) */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_DateIsValid(JSObject* obj); extern JS_FRIEND_API(double) @@ -1008,136 +967,6 @@ enum ViewType { } /* namespace ArrayBufferView */ -/* - * A helper for building up an ArrayBuffer object's data - * before creating the ArrayBuffer itself. Will do doubling - * based reallocation, up to an optional maximum growth given. - * - * When all the data has been appended, call getArrayBuffer, - * passing in the JSContext* for which the ArrayBuffer object - * is to be created. This also implicitly resets the builder, - * or it can be reset explicitly at any point by calling reset(). - */ -class ArrayBufferBuilder -{ - void *rawcontents_; - uint8_t *dataptr_; - uint32_t capacity_; - uint32_t length_; - public: - ArrayBufferBuilder() - : rawcontents_(NULL), - dataptr_(NULL), - capacity_(0), - length_(0) - { - } - - ~ArrayBufferBuilder() { - reset(); - } - - void reset() { - if (rawcontents_) - JS_free(NULL, rawcontents_); - rawcontents_ = dataptr_ = NULL; - capacity_ = length_ = 0; - } - - // will truncate if newcap is < length() - bool setCapacity(uint32_t newcap) { - if (!JS_ReallocateArrayBufferContents(NULL, newcap, &rawcontents_, &dataptr_)) - return false; - - capacity_ = newcap; - if (length_ > newcap) - length_ = newcap; - - return true; - } - - // Append datalen bytes from data to the current buffer. If we - // need to grow the buffer, grow by doubling the size up to a - // maximum of maxgrowth (if given). If datalen is greater than - // what the new capacity would end up as, then grow by datalen. - // - // The data parameter must not overlap with anything beyond the - // builder's current valid contents [0..length) - bool append(const uint8_t *newdata, uint32_t datalen, uint32_t maxgrowth = 0) { - if (length_ + datalen > capacity_) { - uint32_t newcap; - // double while under maxgrowth or if not specified - if (!maxgrowth || capacity_ < maxgrowth) - newcap = capacity_ * 2; - else - newcap = capacity_ + maxgrowth; - - // but make sure there's always enough to satisfy our request - if (newcap < length_ + datalen) - newcap = length_ + datalen; - - // did we overflow? - if (newcap < capacity_) - return false; - - if (!setCapacity(newcap)) - return false; - } - - // assert that the region isn't overlapping so we can memcpy; - JS_ASSERT(!areOverlappingRegions(newdata, datalen, dataptr_ + length_, datalen)); - - memcpy(dataptr_ + length_, newdata, datalen); - length_ += datalen; - - return true; - } - - uint8_t *data() { - return dataptr_; - } - - uint32_t length() { - return length_; - } - - uint32_t capacity() { - return capacity_; - } - - JSObject* getArrayBuffer(JSContext *cx) { - // we need to check for length_ == 0, because nothing may have been - // added - if (capacity_ > length_ || length_ == 0) { - if (!setCapacity(length_)) - return NULL; - } - - JSObject* obj = JS_NewArrayBufferWithContents(cx, rawcontents_); - if (!obj) - return NULL; - - rawcontents_ = dataptr_ = NULL; - length_ = capacity_ = 0; - - return obj; - } - -protected: - - static bool areOverlappingRegions(const uint8_t *start1, uint32_t length1, - const uint8_t *start2, uint32_t length2) - { - const uint8_t *end1 = start1 + length1; - const uint8_t *end2 = start2 + length2; - - const uint8_t *max_start = start1 > start2 ? start1 : start2; - const uint8_t *min_end = end1 < end2 ? end1 : end2; - - return max_start < min_end; - } -}; - } /* namespace js */ typedef js::ArrayBufferView::ViewType JSArrayBufferViewType; @@ -1241,7 +1070,7 @@ JS_NewArrayBuffer(JSContext *cx, uint32_t nbytes); * this test or one of the JS_Is*Array tests succeeds, then it is safe to call * the various accessor JSAPI calls defined below. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsTypedArrayObject(JSObject *obj); /* @@ -1251,36 +1080,36 @@ JS_IsTypedArrayObject(JSObject *obj); * is safe to call the various ArrayBufferView accessor JSAPI calls defined * below. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsArrayBufferViewObject(JSObject *obj); /* * Test for specific typed array types (ArrayBufferView subtypes) */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsInt8Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint8Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint8ClampedArray(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsInt16Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint16Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsInt32Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint32Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsFloat32Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsFloat64Array(JSObject *obj); /* - * Unwrap Typed arrays all at once. Return NULL without throwing if the object - * cannot be viewed as the correct typed array, or the typed array object on - * success, filling both outparameters. + * Unwrap Typed arrays all at once. Return nullptr without throwing if the + * object cannot be viewed as the correct typed array, or the typed array + * object on success, filling both outparameters. */ extern JS_FRIEND_API(JSObject *) JS_GetObjectAsInt8Array(JSObject *obj, uint32_t *length, int8_t **data); @@ -1321,7 +1150,7 @@ JS_GetArrayBufferViewType(JSObject *obj); * unwrapping. If this test succeeds, then it is safe to call the various * accessor JSAPI calls defined below. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsArrayBufferObject(JSObject *obj); /* @@ -1382,7 +1211,7 @@ JS_GetTypedArrayByteLength(JSObject *obj); * return false if a security wrapper is encountered that denies the * unwrapping. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsArrayBufferViewObject(JSObject *obj); /* @@ -1435,10 +1264,16 @@ JS_GetArrayBufferViewData(JSObject *obj); extern JS_FRIEND_API(JSObject *) JS_GetArrayBufferViewBuffer(JSObject *obj); +/* + * Set an ArrayBuffer's length to 0 and neuter all of its views. + */ +extern JS_FRIEND_API(void) +JS_NeuterArrayBuffer(JSObject *obj, JSContext *cx); + /* * Check whether obj supports JS_GetDataView* APIs. */ -JS_FRIEND_API(JSBool) +JS_FRIEND_API(bool) JS_IsDataViewObject(JSObject *obj); /* @@ -1457,7 +1292,7 @@ JS_GetDataViewByteOffset(JSObject *obj); * * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is NULL, then DEBUG builds may be + * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be * unable to assert when unwrapping should be disallowed. */ JS_FRIEND_API(uint32_t) @@ -1468,12 +1303,39 @@ JS_GetDataViewByteLength(JSObject *obj); * * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is NULL, then DEBUG builds may be + * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be * unable to assert when unwrapping should be disallowed. */ JS_FRIEND_API(void *) JS_GetDataViewData(JSObject *obj); +namespace js { + +/* + * Add a watchpoint -- in the Object.prototype.watch sense -- to |obj| for the + * property |id|, using the callable object |callable| as the function to be + * called for notifications. + * + * This is an internal function exposed -- temporarily -- only so that DOM + * proxies can be watchable. Don't use it! We'll soon kill off the + * Object.prototype.{,un}watch functions, at which point this will go too. + */ +extern JS_FRIEND_API(bool) +WatchGuts(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); + +/* + * Remove a watchpoint -- in the Object.prototype.watch sense -- from |obj| for + * the property |id|. + * + * This is an internal function exposed -- temporarily -- only so that DOM + * proxies can be watchable. Don't use it! We'll soon kill off the + * Object.prototype.{,un}watch functions, at which point this will go too. + */ +extern JS_FRIEND_API(bool) +UnwatchGuts(JSContext *cx, JS::HandleObject obj, JS::HandleId id); + +} // namespace js + /* * A class, expected to be passed by value, which represents the CallArgs for a * JSJitGetterOp. @@ -1599,7 +1461,7 @@ struct JSJitInfo { }; #define JS_JITINFO_NATIVE_PARALLEL(op) \ - {{NULL},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} + {{nullptr},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} static JS_ALWAYS_INLINE const JSJitInfo * FUNCTION_VALUE_TO_JITINFO(const JS::Value& v) @@ -1632,6 +1494,12 @@ JSID_FROM_BITS(size_t bits) return id; } +namespace js { +namespace detail { +bool IdMatchesAtom(jsid id, JSAtom *atom); +} +} + /* * Must not be used on atoms that are representable as integer jsids. * Prefer NameToId or AtomToId over this function: @@ -1658,18 +1526,18 @@ NON_INTEGER_ATOM_TO_JSID(JSAtom *atom) { JS_ASSERT(((size_t)atom & 0x7) == 0); jsid id = JSID_FROM_BITS((size_t)atom); - JS_ASSERT(id == INTERNED_STRING_TO_JSID(NULL, (JSString*)atom)); + JS_ASSERT(js::detail::IdMatchesAtom(id, atom)); return id; } /* All strings stored in jsids are atomized, but are not necessarily property names. */ -static JS_ALWAYS_INLINE JSBool +static JS_ALWAYS_INLINE bool JSID_IS_ATOM(jsid id) { return JSID_IS_STRING(id); } -static JS_ALWAYS_INLINE JSBool +static JS_ALWAYS_INLINE bool JSID_IS_ATOM(jsid id, JSAtom *atom) { return id == JSID_FROM_BITS((size_t)atom); @@ -1681,21 +1549,21 @@ JSID_TO_ATOM(jsid id) return (JSAtom *)JSID_TO_STRING(id); } -JS_STATIC_ASSERT(sizeof(jsid) == JS_BYTES_PER_WORD); +JS_STATIC_ASSERT(sizeof(jsid) == sizeof(void*)); namespace js { -static JS_ALWAYS_INLINE Value +static JS_ALWAYS_INLINE JS::Value IdToValue(jsid id) { if (JSID_IS_STRING(id)) - return StringValue(JSID_TO_STRING(id)); + return JS::StringValue(JSID_TO_STRING(id)); if (JS_LIKELY(JSID_IS_INT(id))) - return Int32Value(JSID_TO_INT(id)); + return JS::Int32Value(JSID_TO_INT(id)); if (JS_LIKELY(JSID_IS_OBJECT(id))) - return ObjectValue(*JSID_TO_OBJECT(id)); + return JS::ObjectValue(*JSID_TO_OBJECT(id)); JS_ASSERT(JSID_IS_VOID(id)); - return UndefinedValue(); + return JS::UndefinedValue(); } static JS_ALWAYS_INLINE jsval @@ -1710,6 +1578,20 @@ IsReadOnlyDateMethod(JS::IsAcceptableThis test, JS::NativeImpl method); extern JS_FRIEND_API(bool) IsTypedArrayThisCheck(JS::IsAcceptableThis test); +/* + * If the embedder has registered a default JSContext callback, returns the + * result of the callback. Otherwise, asserts that |rt| has exactly one + * JSContext associated with it, and returns that context. + */ +extern JS_FRIEND_API(JSContext *) +DefaultJSContext(JSRuntime *rt); + +typedef JSContext* +(* DefaultJSContextCallback)(JSRuntime *rt); + +JS_FRIEND_API(void) +SetDefaultJSContextCallback(JSRuntime *rt, DefaultJSContextCallback cb); + enum CTypesActivityType { CTYPES_CALL_BEGIN, CTYPES_CALL_END, @@ -1744,7 +1626,7 @@ class JS_FRIEND_API(AutoCTypesActivityCallback) { void DoEndCallback() { if (callback) { callback(cx, endType); - callback = NULL; + callback = nullptr; } } }; @@ -1777,8 +1659,8 @@ JS_FRIEND_API(JSObject *) GetObjectMetadata(JSObject *obj); /* ES5 8.12.8. */ -extern JS_FRIEND_API(JSBool) -DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, MutableHandleValue vp); +extern JS_FRIEND_API(bool) +DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, JS::MutableHandleValue vp); /* * Helper function. To approximate a call to the [[DefineOwnProperty]] internal @@ -1794,16 +1676,16 @@ DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, MutableHandleValu * js::ProxyHandler, or the JSAPI with precisely the right semantics for it. */ extern JS_FRIEND_API(bool) -CheckDefineProperty(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); +CheckDefineProperty(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue value, + JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs); } /* namespace js */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_DefineOwnProperty(JSContext *cx, JSObject *objArg, jsid idArg, - const js::PropertyDescriptor& descriptor, JSBool *bp); + JS::Handle descriptor, bool *bp); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_ReportIsNotFunction(JSContext *cx, const JS::Value& v); #ifdef JSGC_GENERATIONAL diff --git a/external/spidermonkey/include/ios/jslock.h b/external/spidermonkey/include/ios/jslock.h deleted file mode 100644 index 522034ad68..0000000000 --- a/external/spidermonkey/include/ios/jslock.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -#ifndef jslock_h -#define jslock_h - -#ifdef JS_THREADSAFE - -# include "jsapi.h" -# include "pratom.h" -# include "prcvar.h" -# include "prinit.h" -# include "prlock.h" -# include "prthread.h" - -# define JS_ATOMIC_INCREMENT(p) PR_ATOMIC_INCREMENT((int32_t *)(p)) -# define JS_ATOMIC_DECREMENT(p) PR_ATOMIC_DECREMENT((int32_t *)(p)) -# define JS_ATOMIC_ADD(p,v) PR_ATOMIC_ADD((int32_t *)(p), (int32_t)(v)) -# define JS_ATOMIC_SET(p,v) PR_ATOMIC_SET((int32_t *)(p), (int32_t)(v)) - -namespace js { - // Defined in jsgc.cpp. - unsigned GetCPUCount(); -} - -#else /* JS_THREADSAFE */ - -typedef struct PRThread PRThread; -typedef struct PRCondVar PRCondVar; -typedef struct PRLock PRLock; - -# define JS_ATOMIC_INCREMENT(p) (++*(p)) -# define JS_ATOMIC_DECREMENT(p) (--*(p)) -# define JS_ATOMIC_ADD(p,v) (*(p) += (v)) -# define JS_ATOMIC_SET(p,v) (*(p) = (v)) - -#endif /* JS_THREADSAFE */ - -#endif /* jslock_h */ diff --git a/external/spidermonkey/include/ios/jsperf.h b/external/spidermonkey/include/ios/jsperf.h index 468ce8609c..e3cbc23143 100644 --- a/external/spidermonkey/include/ios/jsperf.h +++ b/external/spidermonkey/include/ios/jsperf.h @@ -6,7 +6,10 @@ #ifndef perf_jsperf_h #define perf_jsperf_h -#include "jsapi.h" +#include "jstypes.h" + +#include "js/TypeDecls.h" +#include "js/Utility.h" namespace JS { @@ -118,12 +121,12 @@ extern JS_FRIEND_API(JSObject*) RegisterPerfMeasurement(JSContext *cx, JSObject *global); /* - * Given a jsval which contains an instance of the aforementioned - * wrapper class, extract the C++ object. Returns NULL if the - * jsval is not an instance of the wrapper. + * Given a Value which contains an instance of the aforementioned + * wrapper class, extract the C++ object. Returns nullptr if the + * Value is not an instance of the wrapper. */ extern JS_FRIEND_API(PerfMeasurement*) - ExtractPerfMeasurement(jsval wrapper); + ExtractPerfMeasurement(Value wrapper); } // namespace JS diff --git a/external/spidermonkey/include/ios/jsprf.h b/external/spidermonkey/include/ios/jsprf.h index ce159d8115..b235f0b4fb 100644 --- a/external/spidermonkey/include/ios/jsprf.h +++ b/external/spidermonkey/include/ios/jsprf.h @@ -26,7 +26,6 @@ */ #include -#include #include "jstypes.h" @@ -39,7 +38,7 @@ extern JS_PUBLIC_API(uint32_t) JS_snprintf(char *out, uint32_t outlen, const cha /* ** sprintf into a malloc'd buffer. Return a pointer to the malloc'd -** buffer on success, NULL on failure. Call "JS_smprintf_free" to release +** buffer on success, nullptr on failure. Call "JS_smprintf_free" to release ** the memory returned. */ extern JS_PUBLIC_API(char*) JS_smprintf(const char *fmt, ...); @@ -52,9 +51,9 @@ extern JS_PUBLIC_API(void) JS_smprintf_free(char *mem); /* ** "append" sprintf into a malloc'd buffer. "last" is the last value of ** the malloc'd buffer. sprintf will append data to the end of last, -** growing it as necessary using realloc. If last is NULL, JS_sprintf_append +** growing it as necessary using realloc. If last is nullptr, JS_sprintf_append ** will allocate the initial string. The return value is the new value of -** last for subsequent calls, or NULL if there is a malloc failure. +** last for subsequent calls, or nullptr if there is a malloc failure. */ extern JS_PUBLIC_API(char*) JS_sprintf_append(char *last, const char *fmt, ...); diff --git a/external/spidermonkey/include/ios/jsprototypes.h b/external/spidermonkey/include/ios/jsprototypes.h index f9bacac409..b0fee8c468 100644 --- a/external/spidermonkey/include/ios/jsprototypes.h +++ b/external/spidermonkey/include/ios/jsprototypes.h @@ -9,8 +9,6 @@ #ifndef jsprototypes_h #define jsprototypes_h -#include "jsversion.h" - /* * Enumerator codes in the second column must not change -- they are part of * the JS XDR API. Also note the symbols in the third column are extern "C"; @@ -56,20 +54,7 @@ macro(DataView, 35, js_InitTypedArrayClasses) \ macro(ParallelArray, 36, js_InitParallelArrayClass) \ macro(Intl, 37, js_InitIntlClass) \ - macro(Type, 38, js_InitBinaryDataClasses) \ - macro(Data, 39, js_InitBinaryDataClasses) \ - macro(uint8, 40, js_InitBinaryDataClasses) \ - macro(uint16, 41, js_InitBinaryDataClasses) \ - macro(uint32, 42, js_InitBinaryDataClasses) \ - macro(uint64, 43, js_InitBinaryDataClasses) \ - macro(int8, 44, js_InitBinaryDataClasses) \ - macro(int16, 45, js_InitBinaryDataClasses) \ - macro(int32, 46, js_InitBinaryDataClasses) \ - macro(int64, 47, js_InitBinaryDataClasses) \ - macro(float32, 48, js_InitBinaryDataClasses) \ - macro(float64, 49, js_InitBinaryDataClasses) \ - macro(ArrayType, 50, js_InitBinaryDataClasses) \ - macro(StructType, 51, js_InitBinaryDataClasses) \ - macro(ArrayTypeObject, 52, js_InitBinaryDataClasses) \ + macro(TypedObject, 38, js_InitTypedObjectDummy) \ + macro(GeneratorFunction, 39, js_InitIteratorClasses) \ #endif /* jsprototypes_h */ diff --git a/external/spidermonkey/include/ios/jsproxy.h b/external/spidermonkey/include/ios/jsproxy.h index 56868a05c3..c54e300d73 100644 --- a/external/spidermonkey/include/ios/jsproxy.h +++ b/external/spidermonkey/include/ios/jsproxy.h @@ -7,11 +7,29 @@ #ifndef jsproxy_h #define jsproxy_h -#include "jsapi.h" +#include "mozilla/Maybe.h" + #include "jsfriendapi.h" +#include "js/CallNonGenericMethod.h" +#include "js/Class.h" + namespace js { +using JS::AutoIdVector; +using JS::CallArgs; +using JS::HandleId; +using JS::HandleObject; +using JS::HandleValue; +using JS::IsAcceptableThis; +using JS::MutableHandle; +using JS::MutableHandleObject; +using JS::MutableHandleValue; +using JS::NativeImpl; +using JS::PrivateValue; +using JS::Value; + +class RegExpGuard; class JS_FRIEND_API(Wrapper); /* @@ -49,7 +67,7 @@ class JS_FRIEND_API(Wrapper); */ class JS_FRIEND_API(BaseProxyHandler) { - void *mFamily; + const void *mFamily; bool mHasPrototype; bool mHasPolicy; protected: @@ -58,7 +76,7 @@ class JS_FRIEND_API(BaseProxyHandler) void setHasPolicy(bool aHasPolicy) { mHasPolicy = aHasPolicy; } public: - explicit BaseProxyHandler(void *family); + explicit BaseProxyHandler(const void *family); virtual ~BaseProxyHandler(); bool hasPrototype() { @@ -69,9 +87,12 @@ class JS_FRIEND_API(BaseProxyHandler) return mHasPolicy; } - inline void *family() { + inline const void *family() { return mFamily; } + static size_t offsetOfFamily() { + return offsetof(BaseProxyHandler, mFamily); + } virtual bool isOuterWindow() { return false; @@ -106,12 +127,13 @@ class JS_FRIEND_API(BaseProxyHandler) /* ES5 Harmony fundamental proxy traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject proxy) = 0; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags) = 0; + MutableHandle desc, + unsigned flags) = 0; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, - HandleId id, PropertyDescriptor *desc, + HandleId id, MutableHandle desc, unsigned flags) = 0; virtual bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc) = 0; + MutableHandle desc) = 0; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props) = 0; virtual bool delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) = 0; @@ -144,7 +166,13 @@ class JS_FRIEND_API(BaseProxyHandler) uint32_t index, MutableHandleValue vp, bool *present); virtual bool getPrototypeOf(JSContext *cx, HandleObject proxy, MutableHandleObject protop); - /* See comment for weakmapKeyDelegateOp in jsclass.h. */ + // These two hooks must be overridden, or not overridden, in tandem -- no + // overriding just one! + virtual bool watch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id, + JS::HandleObject callable); + virtual bool unwatch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id); + + /* See comment for weakmapKeyDelegateOp in js/Class.h. */ virtual JSObject *weakmapKeyDelegate(JSObject *proxy); }; @@ -157,17 +185,17 @@ class JS_FRIEND_API(BaseProxyHandler) class JS_PUBLIC_API(DirectProxyHandler) : public BaseProxyHandler { public: - explicit DirectProxyHandler(void *family); + explicit DirectProxyHandler(const void *family); /* ES5 Harmony fundamental proxy traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject proxy) MOZ_OVERRIDE; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, unsigned flags) MOZ_OVERRIDE; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, - HandleId id, PropertyDescriptor *desc, + HandleId id, MutableHandle desc, unsigned flags) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props) MOZ_OVERRIDE; virtual bool delete_(JSContext *cx, HandleObject proxy, HandleId id, @@ -204,8 +232,6 @@ class JS_PUBLIC_API(DirectProxyHandler) : public BaseProxyHandler unsigned indent) MOZ_OVERRIDE; virtual bool regexp_toShared(JSContext *cx, HandleObject proxy, RegExpGuard *g) MOZ_OVERRIDE; - virtual bool defaultValue(JSContext *cx, HandleObject obj, JSType hint, - MutableHandleValue vp) MOZ_OVERRIDE; virtual JSObject *weakmapKeyDelegate(JSObject *proxy); }; @@ -216,14 +242,15 @@ class Proxy /* ES5 Harmony fundamental proxy traps. */ static bool preventExtensions(JSContext *cx, HandleObject proxy); static bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags); + MutableHandle desc, unsigned flags); static bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, unsigned flags, HandleId id, MutableHandleValue vp); static bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags); + MutableHandle desc, unsigned flags); static bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, unsigned flags, HandleId id, MutableHandleValue vp); - static bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, PropertyDescriptor *desc); + static bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, + MutableHandle desc); static bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, HandleValue v); static bool getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props); static bool delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp); @@ -254,32 +281,27 @@ class Proxy static bool defaultValue(JSContext *cx, HandleObject obj, JSType hint, MutableHandleValue vp); static bool getPrototypeOf(JSContext *cx, HandleObject proxy, MutableHandleObject protop); + static bool watch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id, + JS::HandleObject callable); + static bool unwatch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id); + + /* IC entry path for handling __noSuchMethod__ on access. */ + static bool callProp(JSContext *cx, HandleObject proxy, HandleObject reveiver, HandleId id, + MutableHandleValue vp); + static JSObject * const LazyProto; }; -inline bool IsObjectProxyClass(const Class *clasp) -{ - return clasp == js::ObjectProxyClassPtr || clasp == js::OuterWindowProxyClassPtr; -} - -inline bool IsFunctionProxyClass(const Class *clasp) -{ - return clasp == js::FunctionProxyClassPtr; -} +// Use these in places where you don't want to #include vm/ProxyObject.h. +extern JS_FRIEND_DATA(const js::Class* const) CallableProxyClassPtr; +extern JS_FRIEND_DATA(const js::Class* const) UncallableProxyClassPtr; +extern JS_FRIEND_DATA(const js::Class* const) OuterWindowProxyClassPtr; inline bool IsProxyClass(const Class *clasp) { - return IsObjectProxyClass(clasp) || IsFunctionProxyClass(clasp); -} - -inline bool IsObjectProxy(JSObject *obj) -{ - return IsObjectProxyClass(GetObjectClass(obj)); -} - -inline bool IsFunctionProxy(JSObject *obj) -{ - return IsFunctionProxyClass(GetObjectClass(obj)); + return clasp == CallableProxyClassPtr || + clasp == UncallableProxyClassPtr || + clasp == OuterWindowProxyClassPtr; } inline bool IsProxy(JSObject *obj) @@ -342,14 +364,42 @@ SetProxyExtra(JSObject *obj, size_t n, const Value &extra) SetReservedSlot(obj, PROXY_EXTRA_SLOT + n, extra); } -enum ProxyCallable { - ProxyNotCallable = false, - ProxyIsCallable = true +class MOZ_STACK_CLASS ProxyOptions { + public: + ProxyOptions() : callable_(false), + singleton_(false), + forceForegroundFinalization_(false) + {} + + bool callable() const { return callable_; } + ProxyOptions &setCallable(bool flag) { + callable_ = flag; + return *this; + } + + bool singleton() const { return singleton_; } + ProxyOptions &setSingleton(bool flag) { + singleton_ = flag; + return *this; + } + + bool forceForegroundFinalization() const { + return forceForegroundFinalization_; + } + ProxyOptions &setForceForegroundFinalization(bool flag) { + forceForegroundFinalization_ = true; + return *this; + } + + private: + bool callable_; + bool singleton_; + bool forceForegroundFinalization_; }; JS_FRIEND_API(JSObject *) NewProxyObject(JSContext *cx, BaseProxyHandler *handler, HandleValue priv, - JSObject *proto, JSObject *parent, ProxyCallable callable = ProxyNotCallable); + JSObject *proto, JSObject *parent, const ProxyOptions &options = ProxyOptions()); JSObject * RenewProxyObject(JSContext *cx, JSObject *obj, BaseProxyHandler *handler, Value priv); @@ -361,7 +411,7 @@ class JS_FRIEND_API(AutoEnterPolicy) AutoEnterPolicy(JSContext *cx, BaseProxyHandler *handler, HandleObject wrapper, HandleId id, Action act, bool mayThrow) #ifdef DEBUG - : context(NULL) + : context(nullptr) #endif { allow = handler->hasPolicy() ? handler->enter(cx, wrapper, id, act, &rv) @@ -372,8 +422,8 @@ class JS_FRIEND_API(AutoEnterPolicy) // * The policy set rv to false, indicating that we should throw. // * The caller did not instruct us to ignore exceptions. // * The policy did not throw itself. - if (!allow && !rv && mayThrow && !JS_IsExceptionPending(cx)) - reportError(cx, id); + if (!allow && !rv && mayThrow) + reportErrorIfExceptionIsNotPending(cx, id); } virtual ~AutoEnterPolicy() { recordLeave(); } @@ -384,10 +434,10 @@ class JS_FRIEND_API(AutoEnterPolicy) // no-op constructor for subclass AutoEnterPolicy() #ifdef DEBUG - : context(NULL) + : context(nullptr) #endif {}; - void reportError(JSContext *cx, jsid id); + void reportErrorIfExceptionIsNotPending(JSContext *cx, jsid id); bool allow; bool rv; diff --git a/external/spidermonkey/include/ios/jsprvtd.h b/external/spidermonkey/include/ios/jsprvtd.h deleted file mode 100644 index 1fbc086a7c..0000000000 --- a/external/spidermonkey/include/ios/jsprvtd.h +++ /dev/null @@ -1,297 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -#ifndef jsprvtd_h -#define jsprvtd_h -/* - * JS private typename definitions. - * - * This header is included only in other .h files, for convenience and for - * simplicity of type naming. The alternative for structures is to use tags, - * which are named the same as their typedef names (legal in C/C++, and less - * noisy than suffixing the typedef name with "Struct" or "Str"). Instead, - * all .h files that include this file may use the same typedef name, whether - * declaring a pointer to struct type, or defining a member of struct type. - * - * A few fundamental scalar types are defined here too. Neither the scalar - * nor the struct typedefs should change much, therefore the nearly-global - * make dependency induced by this file should not prove painful. - */ - -#include "jsapi.h" -#include "jsutil.h" - -#include "js/HashTable.h" -#include "js/Vector.h" - -/* - * Convenience constants. - */ -#define JS_BITS_PER_UINT32_LOG2 5 -#define JS_BITS_PER_UINT32 32 - -/* The alignment required of objects stored in GC arenas. */ -static const unsigned JS_GCTHING_ALIGN = 8; -static const unsigned JS_GCTHING_ZEROBITS = 3; - -/* Scalar typedefs. */ -typedef uint8_t jsbytecode; -typedef uint8_t jssrcnote; -typedef uintptr_t jsatomid; - -/* Struct typedefs. */ -typedef struct JSGCThing JSGCThing; -typedef struct JSGenerator JSGenerator; -typedef struct JSNativeEnumerator JSNativeEnumerator; -typedef struct JSTryNote JSTryNote; - -/* Friend "Advanced API" typedefs. */ -typedef struct JSAtomState JSAtomState; -typedef struct JSCodeSpec JSCodeSpec; -typedef struct JSPrinter JSPrinter; -typedef struct JSStackHeader JSStackHeader; -typedef struct JSSubString JSSubString; -typedef struct JSSpecializedNative JSSpecializedNative; - -/* String typedefs. */ -class JSDependentString; -class JSExtensibleString; -class JSExternalString; -class JSLinearString; -class JSRope; -class JSAtom; -class JSWrapper; - -namespace js { - -struct ArgumentsData; -struct Class; - -class AutoNameVector; -class RegExpGuard; -class RegExpObject; -class RegExpObjectBuilder; -class RegExpShared; -class RegExpStatics; -class MatchPairs; -class PropertyName; -class LazyScript; - -enum RegExpFlag -{ - IgnoreCaseFlag = 0x01, - GlobalFlag = 0x02, - MultilineFlag = 0x04, - StickyFlag = 0x08, - - NoFlags = 0x00, - AllFlags = 0x0f -}; - -class StringBuffer; - -class FrameRegs; -class StackFrame; -class ScriptFrameIter; - -class Proxy; -class JS_FRIEND_API(AutoEnterPolicy); -class JS_FRIEND_API(BaseProxyHandler); -class JS_FRIEND_API(Wrapper); -class JS_FRIEND_API(CrossCompartmentWrapper); - -class TempAllocPolicy; -class RuntimeAllocPolicy; - -class GlobalObject; - -template -class InlineMap; - -class LifoAlloc; - -class Shape; - -class Breakpoint; -class BreakpointSite; -class Debugger; -class WatchpointMap; - -/* - * Env is the type of what ES5 calls "lexical environments" (runtime - * activations of lexical scopes). This is currently just JSObject, and is - * implemented by Call, Block, With, and DeclEnv objects, among others--but - * environments and objects are really two different concepts. - */ -typedef JSObject Env; - -typedef JSNative Native; -typedef JSParallelNative ParallelNative; -typedef JSThreadSafeNative ThreadSafeNative; -typedef JSPropertyOp PropertyOp; -typedef JSStrictPropertyOp StrictPropertyOp; -typedef JSPropertyDescriptor PropertyDescriptor; - -struct SourceCompressionToken; - -namespace frontend { - -struct BytecodeEmitter; -struct Definition; -class FullParseHandler; -class FunctionBox; -class ObjectBox; -struct Token; -struct TokenPos; -class TokenStream; -class ParseMapPool; -class ParseNode; - -template -class Parser; - -} /* namespace frontend */ - -namespace analyze { - -struct LifetimeVariable; -class LoopAnalysis; -class ScriptAnalysis; -class SlotValue; -class SSAValue; -class SSAUseChain; - -} /* namespace analyze */ - -namespace types { - -class TypeSet; -struct TypeCallsite; -struct TypeObject; -struct TypeCompartment; - -} /* namespace types */ - -typedef JS::Handle HandleShape; -typedef JS::Handle HandleTypeObject; -typedef JS::Handle HandleAtom; -typedef JS::Handle HandlePropertyName; - -typedef JS::MutableHandle MutableHandleShape; -typedef JS::MutableHandle MutableHandleAtom; - -typedef JS::Rooted RootedShape; -typedef JS::Rooted RootedTypeObject; -typedef JS::Rooted RootedAtom; -typedef JS::Rooted RootedPropertyName; - -enum XDRMode { - XDR_ENCODE, - XDR_DECODE -}; - -template -class XDRState; - -class FreeOp; - -struct IdValuePair -{ - jsid id; - Value value; - - IdValuePair() {} - IdValuePair(jsid idArg) - : id(idArg), value(UndefinedValue()) - {} -}; - -} /* namespace js */ - -namespace JSC { - -class ExecutableAllocator; - -} /* namespace JSC */ - -namespace WTF { - -class BumpPointerAllocator; - -} /* namespace WTF */ - -/* "Friend" types used by jscntxt.h and jsdbgapi.h. */ -typedef enum JSTrapStatus { - JSTRAP_ERROR, - JSTRAP_CONTINUE, - JSTRAP_RETURN, - JSTRAP_THROW, - JSTRAP_LIMIT -} JSTrapStatus; - -typedef JSTrapStatus -(* JSTrapHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - jsval closure); - -typedef JSTrapStatus -(* JSInterruptHook)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - void *closure); - -typedef JSTrapStatus -(* JSDebuggerHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - void *closure); - -typedef JSTrapStatus -(* JSThrowHook)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - void *closure); - -typedef JSBool -(* JSWatchPointHandler)(JSContext *cx, JSObject *obj, jsid id, jsval old, - jsval *newp, void *closure); - -/* called just after script creation */ -typedef void -(* JSNewScriptHook)(JSContext *cx, - const char *filename, /* URL of script */ - unsigned lineno, /* first line */ - JSScript *script, - JSFunction *fun, - void *callerdata); - -/* called just before script destruction */ -typedef void -(* JSDestroyScriptHook)(JSFreeOp *fop, - JSScript *script, - void *callerdata); - -typedef void -(* JSSourceHandler)(const char *filename, unsigned lineno, const jschar *str, - size_t length, void **listenerTSData, void *closure); - -/* js::ObjectOps function pointer typedefs. */ - -/* - * A generic type for functions mapping an object to another object, or null - * if an error or exception was thrown on cx. - */ -typedef JSObject * -(* JSObjectOp)(JSContext *cx, JS::Handle obj); - -/* Signature for class initialization ops. */ -typedef JSObject * -(* JSClassInitializerOp)(JSContext *cx, JS::HandleObject obj); - -/* - * Hook that creates an iterator object for a given object. Returns the - * iterator object or null if an error or exception was thrown on cx. - */ -typedef JSObject * -(* JSIteratorOp)(JSContext *cx, JS::HandleObject obj, JSBool keysonly); - - -#endif /* jsprvtd_h */ diff --git a/external/spidermonkey/include/ios/jspubtd.h b/external/spidermonkey/include/ios/jspubtd.h index 96f5dd8297..4aa922eb84 100644 --- a/external/spidermonkey/include/ios/jspubtd.h +++ b/external/spidermonkey/include/ios/jspubtd.h @@ -11,72 +11,35 @@ * JS public API typedefs. */ +#include "mozilla/NullPtr.h" #include "mozilla/PodOperations.h" #include "jsprototypes.h" #include "jstypes.h" +#include "js/TypeDecls.h" + #if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) || defined(DEBUG) # define JSGC_TRACK_EXACT_ROOTS #endif namespace JS { -/* - * Allow headers to reference JS::Value without #including the whole jsapi.h. - * Unfortunately, typedefs (hence jsval) cannot be declared. - */ -class Value; +class AutoIdVector; +class CallArgs; template class Rooted; class JS_PUBLIC_API(AutoGCRooter); +class JS_PUBLIC_API(CompileOptions); +class JS_PUBLIC_API(CompartmentOptions); + struct Zone; } /* namespace JS */ -/* - * In release builds, jsid is defined to be an integral type. This - * prevents many bugs from being caught at compile time. E.g.: - * - * jsid id = ... - * if (id == JS_TRUE) // error - * ... - * - * size_t n = id; // error - * - * To catch more errors, jsid is given a struct type in C++ debug builds. - * Struct assignment and (in C++) operator== allow correct code to be mostly - * oblivious to the change. This feature can be explicitly disabled in debug - * builds by defining JS_NO_JSVAL_JSID_STRUCT_TYPES. - */ -// Needed for cocos2d-js -#define JS_NO_JSVAL_JSID_STRUCT_TYPES -# if defined(DEBUG) && !defined(JS_NO_JSVAL_JSID_STRUCT_TYPES) -# define JS_USE_JSID_STRUCT_TYPES -# endif - -# ifdef JS_USE_JSID_STRUCT_TYPES -struct jsid -{ - size_t asBits; - bool operator==(jsid rhs) const { return asBits == rhs.asBits; } - bool operator!=(jsid rhs) const { return asBits != rhs.asBits; } -}; -# define JSID_BITS(id) (id.asBits) -# else /* defined(JS_USE_JSID_STRUCT_TYPES) */ -typedef ptrdiff_t jsid; -# define JSID_BITS(id) (id) -# endif /* defined(JS_USE_JSID_STRUCT_TYPES) */ - -#ifdef WIN32 -typedef wchar_t jschar; -#else -typedef uint16_t jschar; -#endif - /* * Run-time version enumeration. For compile-time version checking, please use * the JS_HAS_* macros in jsversion.h, or use MOZJS_MAJOR_VERSION, @@ -109,7 +72,7 @@ typedef enum JSType { typedef enum JSProtoKey { #define PROTOKEY_AND_INITIALIZER(name,code,init) JSProto_##name = code, JS_FOR_EACH_PROTOTYPE(PROTOKEY_AND_INITIALIZER) -#undef JS_PROTO +#undef PROTOKEY_AND_INITIALIZER JSProto_LIMIT } JSProtoKey; @@ -175,7 +138,6 @@ typedef enum { typedef struct JSClass JSClass; typedef struct JSCompartment JSCompartment; typedef struct JSConstDoubleSpec JSConstDoubleSpec; -typedef struct JSContext JSContext; typedef struct JSCrossCompartmentCall JSCrossCompartmentCall; typedef struct JSErrorReport JSErrorReport; typedef struct JSExceptionState JSExceptionState; @@ -195,20 +157,32 @@ typedef struct JSStructuredCloneWriter JSStructuredCloneWriter; typedef struct JSTracer JSTracer; class JSFlatString; -class JSFunction; -class JSObject; -class JSScript; class JSStableString; // long story -class JSString; #ifdef JS_THREADSAFE -typedef struct PRCallOnceType JSCallOnceType; +typedef struct PRCallOnceType JSCallOnceType; #else -typedef JSBool JSCallOnceType; +typedef bool JSCallOnceType; #endif -typedef JSBool (*JSInitCallback)(void); +typedef bool (*JSInitCallback)(void); + +/* + * Generic trace operation that calls JS_CallTracer on each traceable thing + * stored in data. + */ +typedef void +(* JSTraceDataOp)(JSTracer *trc, void *data); + +namespace js { +namespace gc { +class StoreBuffer; +} +} namespace JS { + +typedef void (*OffThreadCompileCallback)(void *token, void *callbackData); + namespace shadow { struct Runtime @@ -220,15 +194,36 @@ struct Runtime /* Allow inlining of Nursery::isInside. */ uintptr_t gcNurseryStart_; uintptr_t gcNurseryEnd_; + + private: + js::gc::StoreBuffer *gcStoreBufferPtr_; #endif - Runtime() + public: + Runtime( +#ifdef JSGC_GENERATIONAL + js::gc::StoreBuffer *storeBuffer +#endif + ) : needsBarrier_(false) #ifdef JSGC_GENERATIONAL , gcNurseryStart_(0) , gcNurseryEnd_(0) + , gcStoreBufferPtr_(storeBuffer) #endif {} + + bool needsBarrier() const { + return needsBarrier_; + } + +#ifdef JSGC_GENERATIONAL + js::gc::StoreBuffer *gcStoreBufferPtr() { return gcStoreBufferPtr_; } +#endif + + static JS::shadow::Runtime *asShadowRuntime(JSRuntime *rt) { + return reinterpret_cast(rt); + } }; } /* namespace shadow */ @@ -270,6 +265,19 @@ enum ThingRootKind THING_ROOT_LIMIT }; +/* + * This list enumerates the different types of conceptual stacks we have in + * SpiderMonkey. In reality, they all share the C stack, but we allow different + * stack limits depending on the type of code running. + */ +enum StackKind +{ + StackForSystemCode, // C++, such as the GC, running on behalf of the VM. + StackForTrustedScript, // Script running with trusted principals. + StackForUntrustedScript, // Script running with untrusted principals. + StackKindCount +}; + template struct RootKind; @@ -305,13 +313,13 @@ struct ContextFriendFields public: explicit ContextFriendFields(JSRuntime *rt) - : runtime_(rt), compartment_(NULL), zone_(NULL), autoGCRooters(NULL) + : runtime_(rt), compartment_(nullptr), zone_(nullptr), autoGCRooters(nullptr) { #ifdef JSGC_TRACK_EXACT_ROOTS mozilla::PodArrayZero(thingGCRooters); #endif #if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) - skipGCRooters = NULL; + skipGCRooters = nullptr; #endif } @@ -395,7 +403,7 @@ struct PerThreadDataFriendFields #endif /* Limit pointer for checking native stack consumption. */ - uintptr_t nativeStackLimit; + uintptr_t nativeStackLimit[StackKindCount]; static const size_t RuntimeMainThreadOffset = offsetof(RuntimeDummy, mainThread); diff --git a/external/spidermonkey/include/ios/jstypes.h b/external/spidermonkey/include/ios/jstypes.h index 17f67f70e1..d5b15ccb1d 100644 --- a/external/spidermonkey/include/ios/jstypes.h +++ b/external/spidermonkey/include/ios/jstypes.h @@ -22,9 +22,16 @@ #define jstypes_h #include "mozilla/Attributes.h" -#include "mozilla/Util.h" +#include "mozilla/Types.h" +// jstypes.h is (or should be!) included by every file in SpiderMonkey. +// js-config.h and jsversion.h also should be included by every file. +// So include them here. +// XXX: including them in js/RequiredDefines.h should be a better option, since +// that is by definition the header file that should be included in all +// SpiderMonkey code. However, Gecko doesn't do this! See bug 909576. #include "js-config.h" +#include "jsversion.h" /*********************************************************************** ** MACROS: JS_EXTERN_API @@ -82,10 +89,6 @@ #define JS_NO_FASTCALL #endif -#ifndef JS_INLINE -#define JS_INLINE MOZ_INLINE -#endif - #ifndef JS_ALWAYS_INLINE #define JS_ALWAYS_INLINE MOZ_ALWAYS_INLINE #endif @@ -180,19 +183,6 @@ # error "Implement me" #endif - -/************************************************************************ -** TYPES: JSBool -** DESCRIPTION: -** Use JSBool for variables and parameter types. Use JS_FALSE and JS_TRUE -** for clarity of target type in assignments and actual arguments. Use -** 'if (bool)', 'while (!bool)', '(bool) ? x : y' etc., to test booleans -** just as you would C int-valued conditions. -************************************************************************/ -typedef int JSBool; -#define JS_TRUE (int)1 -#define JS_FALSE (int)0 - /*********************************************************************** ** MACROS: JS_LIKELY ** JS_UNLIKELY @@ -244,7 +234,11 @@ typedef int JSBool; #define JS_BITS_PER_BYTE 8 #define JS_BITS_PER_BYTE_LOG2 3 -#define JS_BITS_PER_WORD (JS_BITS_PER_BYTE * JS_BYTES_PER_WORD) +#if defined(JS_64BIT) +# define JS_BITS_PER_WORD 64 +#else +# define JS_BITS_PER_WORD 32 +#endif /*********************************************************************** ** MACROS: JS_FUNC_TO_DATA_PTR diff --git a/external/spidermonkey/include/ios/jsutil.h b/external/spidermonkey/include/ios/jsutil.h deleted file mode 100644 index 4020822be1..0000000000 --- a/external/spidermonkey/include/ios/jsutil.h +++ /dev/null @@ -1,385 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -/* - * PR assertion checker. - */ - -#ifndef jsutil_h -#define jsutil_h - -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/GuardObjects.h" - -#ifdef USE_ZLIB -#include -#endif - -#include "js/Utility.h" - -/* Forward declarations. */ -struct JSContext; - -static JS_ALWAYS_INLINE void * -js_memcpy(void *dst_, const void *src_, size_t len) -{ - char *dst = (char *) dst_; - const char *src = (const char *) src_; - JS_ASSERT_IF(dst >= src, (size_t) (dst - src) >= len); - JS_ASSERT_IF(src >= dst, (size_t) (src - dst) >= len); - - return memcpy(dst, src, len); -} - -namespace js { - -template -struct AlignmentTestStruct -{ - char c; - T t; -}; - -/* This macro determines the alignment requirements of a type. */ -#define JS_ALIGNMENT_OF(t_) \ - (sizeof(js::AlignmentTestStruct) - sizeof(t_)) - -template -class AlignedPtrAndFlag -{ - uintptr_t bits; - - public: - AlignedPtrAndFlag(T *t, bool aFlag) { - JS_ASSERT((uintptr_t(t) & 1) == 0); - bits = uintptr_t(t) | uintptr_t(aFlag); - } - - T *ptr() const { - return (T *)(bits & ~uintptr_t(1)); - } - - bool flag() const { - return (bits & 1) != 0; - } - - void setPtr(T *t) { - JS_ASSERT((uintptr_t(t) & 1) == 0); - bits = uintptr_t(t) | uintptr_t(flag()); - } - - void setFlag() { - bits |= 1; - } - - void unsetFlag() { - bits &= ~uintptr_t(1); - } - - void set(T *t, bool aFlag) { - JS_ASSERT((uintptr_t(t) & 1) == 0); - bits = uintptr_t(t) | aFlag; - } -}; - -template -static inline void -Reverse(T *beg, T *end) -{ - while (beg != end) { - if (--end == beg) - return; - T tmp = *beg; - *beg = *end; - *end = tmp; - ++beg; - } -} - -template -static inline T * -Find(T *beg, T *end, const T &v) -{ - for (T *p = beg; p != end; ++p) { - if (*p == v) - return p; - } - return end; -} - -template -static inline typename Container::ElementType * -Find(Container &c, const typename Container::ElementType &v) -{ - return Find(c.begin(), c.end(), v); -} - -template -void -ForEach(InputIterT begin, InputIterT end, CallableT f) -{ - for (; begin != end; ++begin) - f(*begin); -} - -template -static inline T -Min(T t1, T t2) -{ - return t1 < t2 ? t1 : t2; -} - -template -static inline T -Max(T t1, T t2) -{ - return t1 > t2 ? t1 : t2; -} - -/* Allows a const variable to be initialized after its declaration. */ -template -static T& -InitConst(const T &t) -{ - return const_cast(t); -} - -template -JS_ALWAYS_INLINE T & -ImplicitCast(U &u) -{ - T &t = u; - return t; -} - -template -class AutoScopedAssign -{ - public: - AutoScopedAssign(T *addr, const T &value - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : addr_(addr), old(*addr_) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - *addr_ = value; - } - - ~AutoScopedAssign() { *addr_ = old; } - - private: - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - T *addr_; - T old; -}; - -template -static inline bool -IsPowerOfTwo(T t) -{ - return t && !(t & (t - 1)); -} - -template -static inline U -ComputeByteAlignment(T bytes, U alignment) -{ - JS_ASSERT(IsPowerOfTwo(alignment)); - return (alignment - (bytes % alignment)) % alignment; -} - -template -static inline T -AlignBytes(T bytes, U alignment) -{ - return bytes + ComputeByteAlignment(bytes, alignment); -} - -JS_ALWAYS_INLINE static size_t -UnsignedPtrDiff(const void *bigger, const void *smaller) -{ - return size_t(bigger) - size_t(smaller); -} - -/*****************************************************************************/ - -/* A bit array is an array of bits represented by an array of words (size_t). */ - -static inline unsigned -NumWordsForBitArrayOfLength(size_t length) -{ - return (length + (JS_BITS_PER_WORD - 1)) / JS_BITS_PER_WORD; -} - -static inline unsigned -BitArrayIndexToWordIndex(size_t length, size_t bitIndex) -{ - unsigned wordIndex = bitIndex / JS_BITS_PER_WORD; - JS_ASSERT(wordIndex < length); - return wordIndex; -} - -static inline size_t -BitArrayIndexToWordMask(size_t i) -{ - return size_t(1) << (i % JS_BITS_PER_WORD); -} - -static inline bool -IsBitArrayElementSet(size_t *array, size_t length, size_t i) -{ - return array[BitArrayIndexToWordIndex(length, i)] & BitArrayIndexToWordMask(i); -} - -static inline bool -IsAnyBitArrayElementSet(size_t *array, size_t length) -{ - unsigned numWords = NumWordsForBitArrayOfLength(length); - for (unsigned i = 0; i < numWords; ++i) { - if (array[i]) - return true; - } - return false; -} - -static inline void -SetBitArrayElement(size_t *array, size_t length, size_t i) -{ - array[BitArrayIndexToWordIndex(length, i)] |= BitArrayIndexToWordMask(i); -} - -static inline void -ClearBitArrayElement(size_t *array, size_t length, size_t i) -{ - array[BitArrayIndexToWordIndex(length, i)] &= ~BitArrayIndexToWordMask(i); -} - -static inline void -ClearAllBitArrayElements(size_t *array, size_t length) -{ - for (unsigned i = 0; i < length; ++i) - array[i] = 0; -} - -#ifdef USE_ZLIB -class Compressor -{ - /* Number of bytes we should hand to zlib each compressMore() call. */ - static const size_t CHUNKSIZE = 2048; - z_stream zs; - const unsigned char *inp; - size_t inplen; - size_t outbytes; - - public: - enum Status { - MOREOUTPUT, - DONE, - CONTINUE, - OOM - }; - - Compressor(const unsigned char *inp, size_t inplen); - ~Compressor(); - bool init(); - void setOutput(unsigned char *out, size_t outlen); - size_t outWritten() const { return outbytes; } - /* Compress some of the input. Return true if it should be called again. */ - Status compressMore(); -}; - -/* - * Decompress a string. The caller must know the length of the output and - * allocate |out| to a string of that length. - */ -bool DecompressString(const unsigned char *inp, size_t inplen, - unsigned char *out, size_t outlen); -#endif - -} /* namespace js */ - -/* Crash diagnostics */ -#ifdef DEBUG -# define JS_CRASH_DIAGNOSTICS 1 -#endif -#ifdef JS_CRASH_DIAGNOSTICS -# define JS_POISON(p, val, size) memset((p), (val), (size)) -#else -# define JS_POISON(p, val, size) ((void) 0) -#endif - -/* Basic stats */ -#ifdef DEBUG -# define JS_BASIC_STATS 1 -#endif -#ifdef JS_BASIC_STATS -# include -typedef struct JSBasicStats { - uint32_t num; - uint32_t max; - double sum; - double sqsum; - uint32_t logscale; /* logarithmic scale: 0 (linear), 2, 10 */ - uint32_t hist[11]; -} JSBasicStats; -# define JS_INIT_STATIC_BASIC_STATS {0,0,0,0,0,{0,0,0,0,0,0,0,0,0,0,0}} -# define JS_BASIC_STATS_INIT(bs) memset((bs), 0, sizeof(JSBasicStats)) -# define JS_BASIC_STATS_ACCUM(bs,val) \ - JS_BasicStatsAccum(bs, val) -# define JS_MeanAndStdDevBS(bs,sigma) \ - JS_MeanAndStdDev((bs)->num, (bs)->sum, (bs)->sqsum, sigma) -extern void -JS_BasicStatsAccum(JSBasicStats *bs, uint32_t val); -extern double -JS_MeanAndStdDev(uint32_t num, double sum, double sqsum, double *sigma); -extern void -JS_DumpBasicStats(JSBasicStats *bs, const char *title, FILE *fp); -extern void -JS_DumpHistogram(JSBasicStats *bs, FILE *fp); -#else -# define JS_BASIC_STATS_ACCUM(bs,val) -#endif - -/* A jsbitmap_t is a long integer that can be used for bitmaps. */ -typedef size_t jsbitmap; -#define JS_TEST_BIT(_map,_bit) ((_map)[(_bit)>>JS_BITS_PER_WORD_LOG2] & \ - ((jsbitmap)1<<((_bit)&(JS_BITS_PER_WORD-1)))) -#define JS_SET_BIT(_map,_bit) ((_map)[(_bit)>>JS_BITS_PER_WORD_LOG2] |= \ - ((jsbitmap)1<<((_bit)&(JS_BITS_PER_WORD-1)))) -#define JS_CLEAR_BIT(_map,_bit) ((_map)[(_bit)>>JS_BITS_PER_WORD_LOG2] &= \ - ~((jsbitmap)1<<((_bit)&(JS_BITS_PER_WORD-1)))) - -/* Wrapper for various macros to stop warnings coming from their expansions. */ -#if defined(__clang__) -# define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \ - JS_BEGIN_MACRO \ - _Pragma("clang diagnostic push") \ - /* If these _Pragmas cause warnings for you, try disabling ccache. */ \ - _Pragma("clang diagnostic ignored \"-Wunused-value\"") \ - { expr; } \ - _Pragma("clang diagnostic pop") \ - JS_END_MACRO -#elif MOZ_IS_GCC - -#if MOZ_GCC_VERSION_AT_LEAST(4, 6, 0) -# define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \ - JS_BEGIN_MACRO \ - _Pragma("GCC diagnostic push") \ - _Pragma("GCC diagnostic ignored \"-Wunused-but-set-variable\"") \ - expr; \ - _Pragma("GCC diagnostic pop") \ - JS_END_MACRO -#endif -#endif - -#if !defined(JS_SILENCE_UNUSED_VALUE_IN_EXPR) -# define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \ - JS_BEGIN_MACRO \ - expr; \ - JS_END_MACRO -#endif - -#endif /* jsutil_h */ diff --git a/external/spidermonkey/include/ios/jsversion.h b/external/spidermonkey/include/ios/jsversion.h index 1780616a32..827a56981d 100644 --- a/external/spidermonkey/include/ios/jsversion.h +++ b/external/spidermonkey/include/ios/jsversion.h @@ -7,19 +7,6 @@ #ifndef jsversion_h #define jsversion_h -/* - * Deprecated JS_VERSION handler. - */ -#ifdef JS_VERSION -# if JS_VERSION == 185 -# warning "JS_VERSION defined but unsupported (legacy)" -# elif JS_VERSION < 185 -# error "Unsupported JS_VERSION" -# else -# error "Unknown JS_VERSION" -# endif -#endif - /* * JS Capability Macros. */ @@ -52,15 +39,15 @@ * Feature for Object.prototype.__{define,lookup}{G,S}etter__ legacy support; * support likely to be made opt-in at some future time. */ -#define OLD_GETTER_SETTER_METHODS 1 +#define JS_OLD_GETTER_SETTER_METHODS 1 /* A kill-switch for bug 586842. Embedders shouldn't touch this! */ -#define USE_NEW_OBJECT_REPRESENTATION 0 +#define JS_USE_NEW_OBJECT_REPRESENTATION 0 -#if USE_NEW_OBJECT_REPRESENTATION -# define NEW_OBJECT_REPRESENTATION_ONLY() ((void)0) +#if JS_USE_NEW_OBJECT_REPRESENTATION +# define JS_NEW_OBJECT_REPRESENTATION_ONLY() ((void)0) #else -# define NEW_OBJECT_REPRESENTATION_ONLY() \ +# define JS_NEW_OBJECT_REPRESENTATION_ONLY() \ MOZ_ASSUME_UNREACHABLE("don't call this! to be used in the new object representation") #endif diff --git a/external/spidermonkey/include/ios/jswrapper.h b/external/spidermonkey/include/ios/jswrapper.h index f78df7db60..938db73ec8 100644 --- a/external/spidermonkey/include/ios/jswrapper.h +++ b/external/spidermonkey/include/ios/jswrapper.h @@ -9,7 +9,6 @@ #include "mozilla/Attributes.h" -#include "jsapi.h" #include "jsproxy.h" namespace js { @@ -38,6 +37,9 @@ class JS_FRIEND_API(Wrapper) : public DirectProxyHandler LAST_USED_FLAG = CROSS_COMPARTMENT }; + virtual bool defaultValue(JSContext *cx, HandleObject obj, JSType hint, + MutableHandleValue vp) MOZ_OVERRIDE; + /* * Wrappers can explicitly specify that they are unsafe to unwrap from a * security perspective (as is the case for SecurityWrappers). If a wrapper @@ -64,6 +66,8 @@ class JS_FRIEND_API(Wrapper) : public DirectProxyHandler virtual ~Wrapper(); + virtual bool finalizeInBackground(Value priv) MOZ_OVERRIDE; + static Wrapper singleton; static Wrapper singletonWithPrototype; }; @@ -76,16 +80,16 @@ class JS_FRIEND_API(CrossCompartmentWrapper) : public Wrapper virtual ~CrossCompartmentWrapper(); - virtual bool finalizeInBackground(Value priv) MOZ_OVERRIDE; - /* ES5 Harmony fundamental wrapper traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject wrapper) MOZ_OVERRIDE; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject wrapper, AutoIdVector &props) MOZ_OVERRIDE; virtual bool delete_(JSContext *cx, HandleObject wrapper, HandleId id, bool *bp) MOZ_OVERRIDE; @@ -149,7 +153,7 @@ class JS_FRIEND_API(SecurityWrapper) : public Base JSContext *cx) MOZ_OVERRIDE; virtual bool regexp_toShared(JSContext *cx, HandleObject proxy, RegExpGuard *g) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; /* * Allow our subclasses to select the superclass behavior they want without @@ -165,18 +169,21 @@ typedef SecurityWrapper CrossCompartmentSecurityWrapper class JS_FRIEND_API(DeadObjectProxy) : public BaseProxyHandler { public: - static int sDeadObjectFamily; + // This variable exists solely to provide a unique address for use as an identifier. + static const char sDeadObjectFamily; explicit DeadObjectProxy(); /* ES5 Harmony fundamental wrapper traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject proxy) MOZ_OVERRIDE; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject wrapper, AutoIdVector &props) MOZ_OVERRIDE; virtual bool delete_(JSContext *cx, HandleObject wrapper, HandleId id, bool *bp) MOZ_OVERRIDE; @@ -213,7 +220,8 @@ TransparentObjectWrapper(JSContext *cx, HandleObject existing, HandleObject obj, // Proxy family for wrappers. Public so that IsWrapper() can be fully inlined by // jsfriendapi users. -extern JS_FRIEND_DATA(int) sWrapperFamily; +// This variable exists solely to provide a unique address for use as an identifier. +extern JS_FRIEND_DATA(const char) sWrapperFamily; inline bool IsWrapper(JSObject *obj) @@ -226,7 +234,7 @@ IsWrapper(JSObject *obj) // previously wrapped. Otherwise, this returns the first object for // which JSObject::isWrapper returns false. JS_FRIEND_API(JSObject *) -UncheckedUnwrap(JSObject *obj, bool stopAtOuter = true, unsigned *flagsp = NULL); +UncheckedUnwrap(JSObject *obj, bool stopAtOuter = true, unsigned *flagsp = nullptr); // Given a JSObject, returns that object stripped of wrappers. At each stage, // the security wrapper has the opportunity to veto the unwrap. Since checked @@ -247,7 +255,8 @@ bool IsDeadProxyObject(JSObject *obj); JSObject * -NewDeadProxyObject(JSContext *cx, JSObject *parent); +NewDeadProxyObject(JSContext *cx, JSObject *parent, + const ProxyOptions &options = ProxyOptions()); void NukeCrossCompartmentWrapper(JSContext *cx, JSObject *wrapper); diff --git a/external/spidermonkey/include/ios/mozilla/Alignment.h b/external/spidermonkey/include/ios/mozilla/Alignment.h new file mode 100644 index 0000000000..29599d0ef1 --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/Alignment.h @@ -0,0 +1,137 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=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/. */ + +/* Functionality related to memory alignment. */ + +#ifndef mozilla_Alignment_h +#define mozilla_Alignment_h + +#include +#include + +namespace mozilla { + +/* + * This class, and the corresponding macro MOZ_ALIGNOF, figures out how many + * bytes of alignment a given type needs. + */ +template +class AlignmentFinder +{ + struct Aligner + { + char c; + T t; + }; + + public: + static const size_t alignment = sizeof(Aligner) - sizeof(T); +}; + +#define MOZ_ALIGNOF(T) mozilla::AlignmentFinder::alignment + +/* + * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types. + * + * For instance, + * + * MOZ_ALIGNED_DECL(char arr[2], 8); + * + * will declare a two-character array |arr| aligned to 8 bytes. + */ + +#if defined(__GNUC__) +# define MOZ_ALIGNED_DECL(_type, _align) \ + _type __attribute__((aligned(_align))) +#elif defined(_MSC_VER) +# define MOZ_ALIGNED_DECL(_type, _align) \ + __declspec(align(_align)) _type +#else +# warning "We don't know how to align variables on this compiler." +# define MOZ_ALIGNED_DECL(_type, _align) _type +#endif + +/* + * AlignedElem is a structure whose alignment is guaranteed to be at least N + * bytes. + * + * We support 1, 2, 4, 8, and 16-bit alignment. + */ +template +struct AlignedElem; + +/* + * We have to specialize this template because GCC doesn't like __attribute__((aligned(foo))) where + * foo is a template parameter. + */ + +template<> +struct AlignedElem<1> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 1); +}; + +template<> +struct AlignedElem<2> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 2); +}; + +template<> +struct AlignedElem<4> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 4); +}; + +template<> +struct AlignedElem<8> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 8); +}; + +template<> +struct AlignedElem<16> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 16); +}; + +/* + * This utility pales in comparison to Boost's aligned_storage. The utility + * simply assumes that uint64_t is enough alignment for anyone. This may need + * to be extended one day... + * + * As an important side effect, pulling the storage into this template is + * enough obfuscation to confuse gcc's strict-aliasing analysis into not giving + * false negatives when we cast from the char buffer to whatever type we've + * constructed using the bytes. + */ +template +struct AlignedStorage +{ + union U { + char bytes[Nbytes]; + uint64_t _; + } u; + + const void* addr() const { return u.bytes; } + void* addr() { return u.bytes; } +}; + +template +struct AlignedStorage2 +{ + union U { + char bytes[sizeof(T)]; + uint64_t _; + } u; + + const T* addr() const { return reinterpret_cast(u.bytes); } + T* addr() { return static_cast(static_cast(u.bytes)); } +}; + +} /* namespace mozilla */ + +#endif /* mozilla_Alignment_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Assertions.h b/external/spidermonkey/include/ios/mozilla/Assertions.h index 00b7037802..f902199051 100644 --- a/external/spidermonkey/include/ios/mozilla/Assertions.h +++ b/external/spidermonkey/include/ios/mozilla/Assertions.h @@ -180,7 +180,7 @@ __declspec(noreturn) __inline void MOZ_NoReturn() {} # ifdef __cplusplus # define MOZ_REALLY_CRASH() \ do { \ - __debugbreak(); \ + ::__debugbreak(); \ *((volatile int*) NULL) = 123; \ ::TerminateProcess(::GetCurrentProcess(), 3); \ ::MOZ_NoReturn(); \ diff --git a/external/spidermonkey/include/ios/mozilla/Atomics.h b/external/spidermonkey/include/ios/mozilla/Atomics.h index f876683c3e..31e6a7daec 100644 --- a/external/spidermonkey/include/ios/mozilla/Atomics.h +++ b/external/spidermonkey/include/ios/mozilla/Atomics.h @@ -17,6 +17,8 @@ #define mozilla_Atomics_h #include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" +#include "mozilla/Compiler.h" #include "mozilla/TypeTraits.h" #include @@ -26,34 +28,16 @@ * does not have . So be sure to check for support * along with C++0x support. */ -#if defined(__clang__) +#if defined(__clang__) || defined(__GNUC__) /* - * clang doesn't like libstdc++'s version of before GCC 4.7, - * due to the loose typing of the __sync_* family of functions done by - * GCC. We do not have a particularly good way to detect this sort of - * case at this point, so just assume that if we're on a Linux system, - * we can't use the system's . - * - * OpenBSD uses an old libstdc++ 4.2.1 and thus doesnt have . + * Clang doesn't like from libstdc++ before 4.7 due to the + * loose typing of the atomic builtins. GCC 4.5 and 4.6 lacks inline + * definitions for unspecialized std::atomic and causes linking errors. + * Therefore, we require at least 4.7.0 for using libstdc++. */ -# if !defined(__linux__) && !defined(__OpenBSD__) && \ - (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) && \ - __has_include() +# if MOZ_USING_LIBSTDCXX && MOZ_LIBSTDCXX_VERSION_AT_LEAST(4, 7, 0) # define MOZ_HAVE_CXX11_ATOMICS -# endif -/* - * Android uses a different C++ standard library that does not provide - * support for . - * - * GCC 4.5.x and 4.6.x's unspecialized std::atomic template doesn't include - * inline definitions for the functions declared therein. This oversight - * leads to linking errors when using atomic enums. We therefore require - * GCC 4.7 or higher. - */ -#elif defined(__GNUC__) && !defined(__ANDROID__) -# include "mozilla/Compiler.h" -# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) && \ - MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) +# elif MOZ_USING_LIBCXX # define MOZ_HAVE_CXX11_ATOMICS # endif #elif defined(_MSC_VER) && _MSC_VER >= 1700 @@ -845,8 +829,8 @@ class AtomicBase typename Intrinsics::ValueType mValue; public: - AtomicBase() : mValue() {} - AtomicBase(T aInit) { Intrinsics::store(mValue, aInit); } + MOZ_CONSTEXPR AtomicBase() : mValue() {} + MOZ_CONSTEXPR AtomicBase(T aInit) : mValue(aInit) {} operator T() const { return Intrinsics::load(mValue); } @@ -889,8 +873,8 @@ class AtomicBaseIncDec : public AtomicBase typedef typename detail::AtomicBase Base; public: - AtomicBaseIncDec() : Base() {} - AtomicBaseIncDec(T aInit) : Base(aInit) {} + MOZ_CONSTEXPR AtomicBaseIncDec() : Base() {} + MOZ_CONSTEXPR AtomicBaseIncDec(T aInit) : Base(aInit) {} using Base::operator=; @@ -943,8 +927,8 @@ class Atomic::value>::Type> typedef typename detail::AtomicBaseIncDec Base; public: - Atomic() : Base() {} - Atomic(T aInit) : Base(aInit) {} + MOZ_CONSTEXPR Atomic() : Base() {} + MOZ_CONSTEXPR Atomic(T aInit) : Base(aInit) {} using Base::operator=; @@ -972,8 +956,8 @@ class Atomic : public detail::AtomicBaseIncDec typedef typename detail::AtomicBaseIncDec Base; public: - Atomic() : Base() {} - Atomic(T* aInit) : Base(aInit) {} + MOZ_CONSTEXPR Atomic() : Base() {} + MOZ_CONSTEXPR Atomic(T* aInit) : Base(aInit) {} using Base::operator=; @@ -1000,8 +984,8 @@ class Atomic::value>::Type> typedef typename detail::AtomicBase Base; public: - Atomic() : Base() {} - Atomic(T aInit) : Base(aInit) {} + MOZ_CONSTEXPR Atomic() : Base() {} + MOZ_CONSTEXPR Atomic(T aInit) : Base(aInit) {} using Base::operator=; diff --git a/external/spidermonkey/include/ios/mozilla/Attributes.h b/external/spidermonkey/include/ios/mozilla/Attributes.h index 6ea9776fbf..0786cb2fe5 100644 --- a/external/spidermonkey/include/ios/mozilla/Attributes.h +++ b/external/spidermonkey/include/ios/mozilla/Attributes.h @@ -11,26 +11,10 @@ #include "mozilla/Compiler.h" -/* - * MOZ_INLINE is a macro which expands to tell the compiler that the method - * decorated with it should be inlined. This macro is usable from C and C++ - * code, even though C89 does not support the |inline| keyword. The compiler - * may ignore this directive if it chooses. - */ -#if defined(__cplusplus) -# define MOZ_INLINE inline -#elif defined(_MSC_VER) -# define MOZ_INLINE __inline -#elif defined(__GNUC__) -# define MOZ_INLINE __inline__ -#else -# define MOZ_INLINE inline -#endif - /* * MOZ_ALWAYS_INLINE is a macro which expands to tell the compiler that the * method decorated with it must be inlined, even if the compiler thinks - * otherwise. This is only a (much) stronger version of the MOZ_INLINE hint: + * otherwise. This is only a (much) stronger version of the inline hint: * compilers are not guaranteed to respect it (although they're much more likely * to do so). * @@ -40,15 +24,17 @@ #if defined(_MSC_VER) # define MOZ_ALWAYS_INLINE_EVEN_DEBUG __forceinline #elif defined(__GNUC__) -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __attribute__((always_inline)) MOZ_INLINE +# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __attribute__((always_inline)) inline #else -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_INLINE +# define MOZ_ALWAYS_INLINE_EVEN_DEBUG inline #endif -#if defined(DEBUG) -# define MOZ_ALWAYS_INLINE MOZ_INLINE -#else +#if !defined(DEBUG) # define MOZ_ALWAYS_INLINE MOZ_ALWAYS_INLINE_EVEN_DEBUG +#elif defined(_MSC_VER) && !defined(__cplusplus) +# define MOZ_ALWAYS_INLINE __inline +#else +# define MOZ_ALWAYS_INLINE inline #endif /* @@ -170,12 +156,31 @@ * Furthermore, it will prevent the compiler from inlining the function because * inlining currently breaks the blacklisting mechanism of AddressSanitizer. */ -#if defined(MOZ_ASAN) -# define MOZ_ASAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_address_safety_analysis)) -# else -# define MOZ_ASAN_BLACKLIST +#if defined(__has_feature) +# if __has_feature(address_sanitizer) +# define MOZ_ASAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_address)) +# else +# define MOZ_ASAN_BLACKLIST /* nothing */ +# endif +#else +# define MOZ_ASAN_BLACKLIST /* nothing */ #endif +/* + * MOZ_TSAN_BLACKLIST is a macro to tell ThreadSanitizer (a compile-time + * instrumentation shipped with Clang) to not instrument the annotated function. + * Furthermore, it will prevent the compiler from inlining the function because + * inlining currently breaks the blacklisting mechanism of ThreadSanitizer. + */ +#if defined(__has_feature) +# if __has_feature(thread_sanitizer) +# define MOZ_TSAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_thread)) +# else +# define MOZ_TSAN_BLACKLIST /* nothing */ +# endif +#else +# define MOZ_TSAN_BLACKLIST /* nothing */ +#endif #ifdef __cplusplus diff --git a/external/spidermonkey/include/ios/mozilla/Char16.h b/external/spidermonkey/include/ios/mozilla/Char16.h index e4b184f950..fb182dfde2 100644 --- a/external/spidermonkey/include/ios/mozilla/Char16.h +++ b/external/spidermonkey/include/ios/mozilla/Char16.h @@ -9,16 +9,11 @@ #ifndef mozilla_Char16_h #define mozilla_Char16_h -#include "mozilla/Assertions.h" - /* * C11 and C++11 introduce a char16_t type and support for UTF-16 string and * character literals. C++11's char16_t is a distinct builtin type. C11's * char16_t is a typedef for uint_least16_t. Technically, char16_t is a 16-bit * code unit of a Unicode code point, not a "character". - * - * For now, Char16.h only supports C++ because we don't want mix different C - * and C++ definitions of char16_t in the same code base. */ #ifdef _MSC_VER @@ -26,20 +21,52 @@ * C++11 says char16_t is a distinct builtin type, but Windows's yvals.h * typedefs char16_t as an unsigned short. We would like to alias char16_t * to Windows's 16-bit wchar_t so we can declare UTF-16 literals as constant - * expressions (and pass char16_t pointers to Windows APIs). We #define our - * char16_t as a macro to override yval.h's typedef of the same name. + * expressions (and pass char16_t pointers to Windows APIs). We #define + * _CHAR16T here in order to prevent yvals.h from overriding our char16_t + * typedefs, which we set to wchar_t for C++ code and to unsigned short for + * C code. + * + * In addition, #defining _CHAR16T will prevent yvals.h from defining a + * char32_t type, so we have to undo that damage here and provide our own, + * which is identical to the yvals.h type. */ # define MOZ_UTF16_HELPER(s) L##s -# include -# define char16_t wchar_t +# define _CHAR16T +# ifdef __cplusplus + typedef wchar_t char16_t; +# else + typedef unsigned short char16_t; +# endif + typedef unsigned int char32_t; #elif defined(__cplusplus) && \ (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) /* C++11 has a builtin char16_t type. */ # define MOZ_UTF16_HELPER(s) u##s + /** + * This macro is used to distinguish when char16_t would be a distinct + * typedef from wchar_t. + */ +# define MOZ_CHAR16_IS_NOT_WCHAR +#elif !defined(__cplusplus) +# if defined(WIN32) +# include + typedef wchar_t char16_t; +# else + /** + * We can't use the stdint.h uint16_t type here because including + * stdint.h will break building some of our C libraries, such as + * sqlite. + */ + typedef unsigned short char16_t; +# endif #else # error "Char16.h requires C++11 (or something like it) for UTF-16 support." #endif +/* This is a temporary hack until bug 927728 is fixed. */ +#define __PRUNICHAR__ +typedef char16_t PRUnichar; + /* * Macro arguments used in concatenation or stringification won't be expanded. * Therefore, in order for |MOZ_UTF16(FOO)| to work as expected (which is to @@ -50,8 +77,12 @@ */ #define MOZ_UTF16(s) MOZ_UTF16_HELPER(s) +#if defined(__cplusplus) && \ + (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) static_assert(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); +static_assert(char16_t(-1) > char16_t(0), "Is char16_t type unsigned?"); static_assert(sizeof(MOZ_UTF16('A')) == 2, "Is char literal 16 bits?"); static_assert(sizeof(MOZ_UTF16("")[0]) == 2, "Is string char 16 bits?"); +#endif #endif /* mozilla_Char16_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Compiler.h b/external/spidermonkey/include/ios/mozilla/Compiler.h index d1ef1e79aa..fd5c98c98d 100644 --- a/external/spidermonkey/include/ios/mozilla/Compiler.h +++ b/external/spidermonkey/include/ios/mozilla/Compiler.h @@ -29,4 +29,77 @@ #endif +/* + * The situation with standard libraries is a lot worse than with compilers, + * particularly as clang and gcc could end up using one of three or so standard + * libraries, and they may not be up-to-snuff with newer C++11 versions. To + * detect the library, we're going to include cstddef (which is a small header + * which will be transitively included by everybody else at some point) to grab + * the version macros and deduce macros from there. + */ +#ifdef __cplusplus +# include +# ifdef _STLPORT_MAJOR +# define MOZ_USING_STLPORT 1 +# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) \ + (_STLPORT_VERSION >= ((major) << 8 | (minor) << 4 | (patch))) +# elif defined(_LIBCPP_VERSION) + /* + * libc++, unfortunately, doesn't appear to have useful versioning macros. + * Hopefully, the recommendations of N3694 with respect to standard libraries + * will get applied instead and we won't need to worry about version numbers + * here. + */ +# define MOZ_USING_LIBCXX 1 +# elif defined(__GLIBCXX__) +# define MOZ_USING_LIBSTDCXX 1 + /* + * libstdc++ is also annoying and doesn't give us useful versioning macros + * for the library. If we're using gcc, then assume that libstdc++ matches + * the compiler version. If we're using clang, we're going to have to fake + * major/minor combinations by looking for newly-defined config macros. + */ +# if MOZ_IS_GCC +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + MOZ_GCC_VERSION_AT_LEAST(major, minor, patch) +# elif defined(_GLIBCXX_THROW_OR_ABORT) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 8)) +# elif defined(_GLIBCXX_NOEXCEPT) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 7)) +# elif defined(_GLIBCXX_USE_DEPRECATED) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 6)) +# elif defined(_GLIBCXX_PSEUDO_VISIBILITY) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 5)) +# elif defined(_GLIBCXX_BEGIN_EXTERN_C) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 4)) +# elif defined(_GLIBCXX_VISIBILITY_ATTR) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 3)) +# elif defined(_GLIBCXX_VISIBILITY) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 2)) +# else +# error "Your version of libstdc++ is unknown to us and is likely too old." +# endif +# endif + + // Flesh out the defines for everyone else +# ifndef MOZ_USING_STLPORT +# define MOZ_USING_STLPORT 0 +# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) 0 +# endif +# ifndef MOZ_USING_LIBCXX +# define MOZ_USING_LIBCXX 0 +# endif +# ifndef MOZ_USING_LIBSTDCXX +# define MOZ_USING_LIBSTDCXX 0 +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) 0 +# endif +#endif /* __cplusplus */ + #endif /* mozilla_Compiler_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Compression.h b/external/spidermonkey/include/ios/mozilla/Compression.h new file mode 100644 index 0000000000..da77fa895f --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/Compression.h @@ -0,0 +1,116 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* 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/. */ + +/* Various simple compression/decompression functions. */ + +#ifndef mozilla_Compression_h_ +#define mozilla_Compression_h_ + +#include "mozilla/Types.h" +#include "mozilla/Assertions.h" + +namespace mozilla { +namespace Compression { + +/** + * LZ4 is a very fast byte-wise compression algorithm. + * + * Compared to Google's Snappy it is faster to compress and decompress and + * generally produces output of about the same size. + * + * Compared to zlib it compresses at about 10x the speed, decompresses at about + * 4x the speed and produces output of about 1.5x the size. + * + */ + +class LZ4 +{ + +public: + + /** + * Compresses 'inputSize' bytes from 'source' into 'dest'. + * Destination buffer must be already allocated, + * and must be sized to handle worst cases situations (input data not compressible) + * Worst case size evaluation is provided by function LZ4_compressBound() + * + * @param inputSize is the input size. Max supported value is ~1.9GB + * @param return the number of bytes written in buffer dest + */ + static MFBT_API size_t compress(const char* source, size_t inputSize, char* dest); + + /** + * Compress 'inputSize' bytes from 'source' into an output buffer + * 'dest' of maximum size 'maxOutputSize'. If it cannot achieve it, + * compression will stop, and result of the function will be zero, + * 'dest' will still be written to, but since the number of input + * bytes consumed is not returned the result is not usable. + * + * This function never writes outside of provided output buffer. + * + * @param inputSize is the input size. Max supported value is ~1.9GB + * @param maxOutputSize is the size of the destination buffer (which must be already allocated) + * @return the number of bytes written in buffer 'dest' + or 0 if the compression fails + */ + static MFBT_API size_t compressLimitedOutput(const char* source, size_t inputSize, char* dest, + size_t maxOutputSize); + + /** + * If the source stream is malformed, the function will stop decoding + * and return a negative result, indicating the byte position of the + * faulty instruction + * + * This function never writes outside of provided buffers, and never + * modifies input buffer. + * + * note : destination buffer must be already allocated. + * its size must be a minimum of 'outputSize' bytes. + * @param outputSize is the output size, therefore the original size + * @return the number of bytes read in the source buffer + */ + static MFBT_API bool decompress(const char* source, char* dest, size_t outputSize); + + /** + * If the source stream is malformed, the function will stop decoding + * and return false. + * + * This function never writes beyond dest + maxOutputSize, and is + * therefore protected against malicious data packets. + * + * note : Destination buffer must be already allocated. + * This version is slightly slower than the decompress + * without the maxOutputSize + * + * @param inputSize is the length of the input compressed data + * @param maxOutputSize is the size of the destination buffer (which must be already allocated) + * @param outputSize the actual number of bytes decoded in the destination buffer (necessarily <= maxOutputSize) + + */ + static MFBT_API bool decompress(const char* source, size_t inputSize, char* dest, + size_t maxOutputSize, size_t *outputSize); + + /* + Provides the maximum size that LZ4 may output in a "worst case" + scenario (input data not compressible) primarily useful for memory + allocation of output buffer. + note : this function is limited by "int" range (2^31-1) + + @param inputSize is the input size. Max supported value is ~1.9GB + @return maximum output size in a "worst case" scenario + */ + static MFBT_API size_t maxCompressedSize(size_t inputSize) + { + size_t max = ((inputSize) + ((inputSize)/255) + 16); + MOZ_ASSERT(max > inputSize); + return max; + } + +}; + +} /* namespace Compression */ +} /* namespace mozilla */ + +#endif /* mozilla_Compression_h_ */ diff --git a/external/spidermonkey/include/ios/mozilla/Endian.h b/external/spidermonkey/include/ios/mozilla/Endian.h index dc6d11d3ba..cb6bd27c05 100644 --- a/external/spidermonkey/include/ios/mozilla/Endian.h +++ b/external/spidermonkey/include/ios/mozilla/Endian.h @@ -238,9 +238,9 @@ class EndianUtils { DebugOnly byteDestPtr = static_cast(dest); DebugOnly byteSrcPtr = static_cast(src); - MOZ_ASSERT((byteDestPtr < byteSrcPtr && + MOZ_ASSERT((byteDestPtr <= byteSrcPtr && byteDestPtr + count <= byteSrcPtr) || - (byteSrcPtr < byteDestPtr && + (byteSrcPtr <= byteDestPtr && byteSrcPtr + count <= byteDestPtr)); } diff --git a/external/spidermonkey/include/ios/mozilla/FloatingPoint.h b/external/spidermonkey/include/ios/mozilla/FloatingPoint.h index d80f6a7234..eff26b4bb8 100644 --- a/external/spidermonkey/include/ios/mozilla/FloatingPoint.h +++ b/external/spidermonkey/include/ios/mozilla/FloatingPoint.h @@ -12,6 +12,7 @@ #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Casting.h" +#include "mozilla/Types.h" #include @@ -58,6 +59,30 @@ static_assert((DoubleSignBit | DoubleExponentBits | DoubleSignificandBits) == ~uint64_t(0), "all bits accounted for"); +/* + * Ditto for |float| that must be a 32-bit double format number type, compatible + * with the IEEE-754 standard. + */ +static_assert(sizeof(float) == sizeof(uint32_t), "float must be 32bits"); + +const unsigned FloatExponentBias = 127; +const unsigned FloatExponentShift = 23; + +const uint32_t FloatSignBit = 0x80000000UL; +const uint32_t FloatExponentBits = 0x7F800000UL; +const uint32_t FloatSignificandBits = 0x007FFFFFUL; + +static_assert((FloatSignBit & FloatExponentBits) == 0, + "sign bit doesn't overlap exponent bits"); +static_assert((FloatSignBit & FloatSignificandBits) == 0, + "sign bit doesn't overlap significand bits"); +static_assert((FloatExponentBits & FloatSignificandBits) == 0, + "exponent bits don't overlap significand bits"); + +static_assert((FloatSignBit | FloatExponentBits | FloatSignificandBits) == + ~uint32_t(0), + "all bits accounted for"); + /** Determines whether a double is NaN. */ static MOZ_ALWAYS_INLINE bool IsNaN(double d) @@ -115,7 +140,12 @@ IsNegativeZero(double d) return bits == DoubleSignBit; } -/** Returns the exponent portion of the double. */ +/** + * Returns the exponent portion of the double. + * + * Zero is not special-cased, so ExponentComponent(0.0) is + * -int_fast16_t(DoubleExponentBias). + */ static MOZ_ALWAYS_INLINE int_fast16_t ExponentComponent(double d) { @@ -190,7 +220,13 @@ DoubleIsInt32(double d, int32_t* i) static MOZ_ALWAYS_INLINE double UnspecifiedNaN() { - return SpecificNaN(0, 0xfffffffffffffULL); + /* + * If we can use any quiet NaN, we might as well use the all-ones NaN, + * since it's cheap to materialize on common platforms (such as x64, where + * this value can be represented in a 32-bit signed immediate field, allowing + * it to be stored to memory in a single instruction). + */ + return SpecificNaN(1, 0xfffffffffffffULL); } /** @@ -206,6 +242,46 @@ DoublesAreIdentical(double d1, double d2) return BitwiseCast(d1) == BitwiseCast(d2); } +/** Determines whether a float is NaN. */ +static MOZ_ALWAYS_INLINE bool +IsFloatNaN(float f) +{ + /* + * A float is NaN if all exponent bits are 1 and the significand contains at + * least one non-zero bit. + */ + uint32_t bits = BitwiseCast(f); + return (bits & FloatExponentBits) == FloatExponentBits && + (bits & FloatSignificandBits) != 0; +} + +/** Constructs a NaN value with the specified sign bit and significand bits. */ +static MOZ_ALWAYS_INLINE float +SpecificFloatNaN(int signbit, uint32_t significand) +{ + MOZ_ASSERT(signbit == 0 || signbit == 1); + MOZ_ASSERT((significand & ~FloatSignificandBits) == 0); + MOZ_ASSERT(significand & FloatSignificandBits); + + float f = BitwiseCast((signbit ? FloatSignBit : 0) | + FloatExponentBits | + significand); + MOZ_ASSERT(IsFloatNaN(f)); + return f; +} + +/** + * Returns true if the given value can be losslessly represented as an IEEE-754 + * single format number, false otherwise. All NaN values are considered + * representable (notwithstanding that the exact bit pattern of a double format + * NaN value can't be exactly represented in single format). + * + * This function isn't inlined to avoid buggy optimizations by MSVC. + */ +MOZ_WARN_UNUSED_RESULT +extern MFBT_API bool +IsFloat32Representable(double x); + } /* namespace mozilla */ #endif /* mozilla_FloatingPoint_h */ diff --git a/external/spidermonkey/include/ios/mozilla/HashFunctions.h b/external/spidermonkey/include/ios/mozilla/HashFunctions.h index 6d0d24e7b1..b228955ce5 100644 --- a/external/spidermonkey/include/ios/mozilla/HashFunctions.h +++ b/external/spidermonkey/include/ios/mozilla/HashFunctions.h @@ -48,6 +48,7 @@ #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/Char16.h" #include "mozilla/Types.h" #include @@ -326,6 +327,22 @@ HashString(const uint16_t* str, size_t length) return detail::HashKnownLength(str, length); } +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +MOZ_WARN_UNUSED_RESULT +inline uint32_t +HashString(const char16_t* str) +{ + return detail::HashUntilZero(str); +} + +MOZ_WARN_UNUSED_RESULT +inline uint32_t +HashString(const char16_t* str, size_t length) +{ + return detail::HashKnownLength(str, length); +} +#endif + /* * On Windows, wchar_t (PRUnichar) is not the same as uint16_t, even though it's * the same width! diff --git a/external/spidermonkey/include/ios/mozilla/IntegerPrintfMacros.h b/external/spidermonkey/include/ios/mozilla/IntegerPrintfMacros.h new file mode 100644 index 0000000000..1ae60d618e --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/IntegerPrintfMacros.h @@ -0,0 +1,40 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* 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/. */ + +/* Implements the C99 interface, minus the SCN* format macros. */ + +#ifndef mozilla_IntegerPrintfMacros_h_ +#define mozilla_IntegerPrintfMacros_h_ + +/* + * MSVC++ doesn't include , even in versions shipping , so + * we have to reimplement it there. Note: #includes . + * + * Note that this header DOES NOT implement 's scanf macros. MSVC's + * scanf doesn't have sufficient format specifier support to implement them + * (specifically, to implement scanning into an 8-bit location). + * + * http://stackoverflow.com/questions/3036396/scanfd-char-char-as-int-format-string + * + * Moreover, scanf is a footgun: if the input number exceeds the bounds of the + * target type, behavior is undefined (in the compiler sense: that is, this code + * could overwrite your hard drive with zeroes): + * + * uint8_t u; + * sscanf("256", "%" SCNu8, &u); // BAD + * + * This header will sometimes provide SCN* macros, by dint of being implemented + * using . But for these reasons, *never* use them! + */ + +#if defined(MOZ_CUSTOM_INTTYPES_H) +# include MOZ_CUSTOM_INTTYPES_H +#elif defined(_MSC_VER) +# include "mozilla/MSIntTypes.h" +#else +# include +#endif + +#endif /* mozilla_IntegerPrintfMacros_h_ */ diff --git a/external/spidermonkey/include/ios/mozilla/LinkedList.h b/external/spidermonkey/include/ios/mozilla/LinkedList.h index c29760b3e7..f35e7d56ab 100644 --- a/external/spidermonkey/include/ios/mozilla/LinkedList.h +++ b/external/spidermonkey/include/ios/mozilla/LinkedList.h @@ -58,6 +58,7 @@ #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/Move.h" #include "mozilla/NullPtr.h" #ifdef __cplusplus @@ -116,6 +117,36 @@ class LinkedListElement isSentinel(false) { } + LinkedListElement(LinkedListElement&& other) + : isSentinel(other.isSentinel) + { + if (!other.isInList()) { + next = this; + prev = this; + return; + } + + MOZ_ASSERT(other.next->prev == &other); + MOZ_ASSERT(other.prev->next == &other); + + /* + * Initialize |this| with |other|'s prev/next pointers, and adjust those + * element to point to this one. + */ + next = other.next; + prev = other.prev; + + next->prev = this; + prev->next = this; + + /* + * Adjust |other| so it doesn't think it's in a list. This makes it + * safely destructable. + */ + other.next = &other; + other.prev = &other; + } + ~LinkedListElement() { if (!isSentinel && isInList()) remove(); @@ -148,8 +179,8 @@ class LinkedListElement * linked list when you call setNext(); otherwise, this method will assert. */ void setNext(T* elem) { - MOZ_ASSERT(isInList()); - setNextUnsafe(elem); + MOZ_ASSERT(isInList()); + setNextUnsafe(elem); } /* @@ -252,8 +283,8 @@ class LinkedListElement } private: - LinkedListElement& operator=(const LinkedList& other) MOZ_DELETE; - LinkedListElement(const LinkedList& other) MOZ_DELETE; + LinkedListElement& operator=(const LinkedListElement& other) MOZ_DELETE; + LinkedListElement(const LinkedListElement& other) MOZ_DELETE; }; template @@ -265,6 +296,10 @@ class LinkedList public: LinkedList() : sentinel(LinkedListElement::NODE_KIND_SENTINEL) { } + LinkedList(LinkedList&& other) + : sentinel(mozilla::Move(other.sentinel)) + { } + ~LinkedList() { MOZ_ASSERT(isEmpty()); } @@ -361,7 +396,7 @@ class LinkedList for (slow = sentinel.next, fast1 = sentinel.next->next, fast2 = sentinel.next->next->next; - slow != sentinel && fast1 != sentinel && fast2 != sentinel; + slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; slow = slow->next, fast1 = fast2->next, fast2 = fast1->next) { MOZ_ASSERT(slow != fast1); @@ -372,7 +407,7 @@ class LinkedList for (slow = sentinel.prev, fast1 = sentinel.prev->prev, fast2 = sentinel.prev->prev->prev; - slow != sentinel && fast1 != sentinel && fast2 != sentinel; + slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; slow = slow->prev, fast1 = fast2->prev, fast2 = fast1->prev) { MOZ_ASSERT(slow != fast1); @@ -384,14 +419,14 @@ class LinkedList * isSentinel == true. */ for (const LinkedListElement* elem = sentinel.next; - elem != sentinel; + elem != &sentinel; elem = elem->next) { MOZ_ASSERT(!elem->isSentinel); } /* Check that the next/prev pointers match up. */ - const LinkedListElement* prev = sentinel; + const LinkedListElement* prev = &sentinel; const LinkedListElement* cur = sentinel.next; do { MOZ_ASSERT(cur->prev == prev); @@ -399,7 +434,7 @@ class LinkedList prev = cur; cur = cur->next; - } while (cur != sentinel); + } while (cur != &sentinel); #endif /* ifdef DEBUG */ } diff --git a/external/spidermonkey/include/ios/mozilla/MSIntTypes.h b/external/spidermonkey/include/ios/mozilla/MSIntTypes.h new file mode 100644 index 0000000000..3dfba55f58 --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/MSIntTypes.h @@ -0,0 +1,198 @@ +// ISO C9x compliant inttypes.h for Microsoft Visual Studio +// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 +// +// Copyright (c) 2006 Alexander Chemeris +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// 3. The name of the author may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef _MSC_VER // [ +#error "Use this header only with Microsoft Visual C++ compilers!" +#endif // _MSC_VER ] + +#ifndef _MSC_INTTYPES_H_ // [ +#define _MSC_INTTYPES_H_ + +#if _MSC_VER > 1000 +#pragma once +#endif + +#include + +// 7.8 Format conversion of integer types + +typedef struct { + intmax_t quot; + intmax_t rem; +} imaxdiv_t; + +// 7.8.1 Macros for format specifiers + +#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 + +// The fprintf macros for signed integers are: +#define PRId8 "d" +#define PRIi8 "i" +#define PRIdLEAST8 "d" +#define PRIiLEAST8 "i" +#define PRIdFAST8 "d" +#define PRIiFAST8 "i" + +#define PRId16 "hd" +#define PRIi16 "hi" +#define PRIdLEAST16 "hd" +#define PRIiLEAST16 "hi" +#define PRIdFAST16 "hd" +#define PRIiFAST16 "hi" + +#define PRId32 "I32d" +#define PRIi32 "I32i" +#define PRIdLEAST32 "I32d" +#define PRIiLEAST32 "I32i" +#define PRIdFAST32 "I32d" +#define PRIiFAST32 "I32i" + +#define PRId64 "I64d" +#define PRIi64 "I64i" +#define PRIdLEAST64 "I64d" +#define PRIiLEAST64 "I64i" +#define PRIdFAST64 "I64d" +#define PRIiFAST64 "I64i" + +#define PRIdMAX "I64d" +#define PRIiMAX "I64i" + +#define PRIdPTR "Id" +#define PRIiPTR "Ii" + +// The fprintf macros for unsigned integers are: +#define PRIo8 "o" +#define PRIu8 "u" +#define PRIx8 "x" +#define PRIX8 "X" +#define PRIoLEAST8 "o" +#define PRIuLEAST8 "u" +#define PRIxLEAST8 "x" +#define PRIXLEAST8 "X" +#define PRIoFAST8 "o" +#define PRIuFAST8 "u" +#define PRIxFAST8 "x" +#define PRIXFAST8 "X" + +#define PRIo16 "ho" +#define PRIu16 "hu" +#define PRIx16 "hx" +#define PRIX16 "hX" +#define PRIoLEAST16 "ho" +#define PRIuLEAST16 "hu" +#define PRIxLEAST16 "hx" +#define PRIXLEAST16 "hX" +#define PRIoFAST16 "ho" +#define PRIuFAST16 "hu" +#define PRIxFAST16 "hx" +#define PRIXFAST16 "hX" + +#define PRIo32 "I32o" +#define PRIu32 "I32u" +#define PRIx32 "I32x" +#define PRIX32 "I32X" +#define PRIoLEAST32 "I32o" +#define PRIuLEAST32 "I32u" +#define PRIxLEAST32 "I32x" +#define PRIXLEAST32 "I32X" +#define PRIoFAST32 "I32o" +#define PRIuFAST32 "I32u" +#define PRIxFAST32 "I32x" +#define PRIXFAST32 "I32X" + +#define PRIo64 "I64o" +#define PRIu64 "I64u" +#define PRIx64 "I64x" +#define PRIX64 "I64X" +#define PRIoLEAST64 "I64o" +#define PRIuLEAST64 "I64u" +#define PRIxLEAST64 "I64x" +#define PRIXLEAST64 "I64X" +#define PRIoFAST64 "I64o" +#define PRIuFAST64 "I64u" +#define PRIxFAST64 "I64x" +#define PRIXFAST64 "I64X" + +#define PRIoMAX "I64o" +#define PRIuMAX "I64u" +#define PRIxMAX "I64x" +#define PRIXMAX "I64X" + +#define PRIoPTR "Io" +#define PRIuPTR "Iu" +#define PRIxPTR "Ix" +#define PRIXPTR "IX" + +// DO NOT SUPPORT THE scanf MACROS! See the comment at the top of +// IntegerPrintfMacros.h. + +#endif // __STDC_FORMAT_MACROS ] + +// 7.8.2 Functions for greatest-width integer types + +// 7.8.2.1 The imaxabs function +#define imaxabs _abs64 + +// 7.8.2.2 The imaxdiv function + +// This is modified version of div() function from Microsoft's div.c found +// in %MSVC.NET%\crt\src\div.c +#ifdef STATIC_IMAXDIV // [ +static +#else // STATIC_IMAXDIV ][ +_inline +#endif // STATIC_IMAXDIV ] +imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) +{ + imaxdiv_t result; + + result.quot = numer / denom; + result.rem = numer % denom; + + if (numer < 0 && result.rem > 0) { + // did division wrong; must fix up + ++result.quot; + result.rem -= denom; + } + + return result; +} + +// 7.8.2.3 The strtoimax and strtoumax functions +#define strtoimax _strtoi64 +#define strtoumax _strtoui64 + +// 7.8.2.4 The wcstoimax and wcstoumax functions +#define wcstoimax _wcstoi64 +#define wcstoumax _wcstoui64 + + +#endif // _MSC_INTTYPES_H_ ] diff --git a/external/spidermonkey/include/ios/mozilla/MathAlgorithms.h b/external/spidermonkey/include/ios/mozilla/MathAlgorithms.h index 6d58691e06..941ac81271 100644 --- a/external/spidermonkey/include/ios/mozilla/MathAlgorithms.h +++ b/external/spidermonkey/include/ios/mozilla/MathAlgorithms.h @@ -186,6 +186,16 @@ namespace detail { return uint_fast8_t(index); } + inline uint_fast8_t + CountPopulation32(uint32_t u) + { + uint32_t sum2 = (u & 0x55555555) + ((u & 0xaaaaaaaa) >> 1); + uint32_t sum4 = (sum2 & 0x33333333) + ((sum2 & 0xcccccccc) >> 2); + uint32_t sum8 = (sum4 & 0x0f0f0f0f) + ((sum4 & 0xf0f0f0f0) >> 4); + uint32_t sum16 = (sum8 & 0x00ff00ff) + ((sum8 & 0xff00ff00) >> 8); + return sum16; + } + inline uint_fast8_t CountLeadingZeroes64(uint64_t u) { @@ -242,6 +252,12 @@ namespace detail { return __builtin_ctz(u); } + inline uint_fast8_t + CountPopulation32(uint32_t u) + { + return __builtin_popcount(u); + } + inline uint_fast8_t CountLeadingZeroes64(uint64_t u) { @@ -258,6 +274,7 @@ namespace detail { # error "Implement these!" inline uint_fast8_t CountLeadingZeroes32(uint32_t u) MOZ_DELETE; inline uint_fast8_t CountTrailingZeroes32(uint32_t u) MOZ_DELETE; + inline uint_fast8_t CountPopulation32(uint32_t u) MOZ_DELETE; inline uint_fast8_t CountLeadingZeroes64(uint64_t u) MOZ_DELETE; inline uint_fast8_t CountTrailingZeroes64(uint64_t u) MOZ_DELETE; #endif @@ -300,6 +317,15 @@ CountTrailingZeroes32(uint32_t u) return detail::CountTrailingZeroes32(u); } +/** + * Compute the number of one bits in the number |u|, + */ +inline uint_fast8_t +CountPopulation32(uint32_t u) +{ + return detail::CountPopulation32(u); +} + /** Analogous to CountLeadingZeroes32, but for 64-bit numbers. */ inline uint_fast8_t CountLeadingZeroes64(uint64_t u) diff --git a/external/spidermonkey/include/ios/mozilla/Maybe.h b/external/spidermonkey/include/ios/mozilla/Maybe.h new file mode 100644 index 0000000000..25683a28ab --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/Maybe.h @@ -0,0 +1,163 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=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/. */ + +/* A class for lazily constructing an object without sticking it on the heap. */ + +#ifndef mozilla_Maybe_h +#define mozilla_Maybe_h + +#include "mozilla/Alignment.h" +#include "mozilla/Assertions.h" + +// For placement new +#include + +namespace mozilla { + +/* + * Small utility for lazily constructing objects without using dynamic storage. + * When a Maybe is constructed, it is |empty()|, i.e., no value of T has + * been constructed and no T destructor will be called when the Maybe is + * destroyed. Upon calling |construct|, a T object will be constructed with the + * given arguments and that object will be destroyed when the owning Maybe + * is destroyed. + * + * N.B. GCC seems to miss some optimizations with Maybe and may generate extra + * branches/loads/stores. Use with caution on hot paths. + */ +template +class Maybe +{ + AlignedStorage2 storage; + bool constructed; + + T& asT() { return *storage.addr(); } + + public: + Maybe() { constructed = false; } + ~Maybe() { if (constructed) asT().~T(); } + + bool empty() const { return !constructed; } + + void construct() { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(); + constructed = true; + } + + template + void construct(const T1& t1) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); + constructed = true; + } + + T* addr() { + MOZ_ASSERT(constructed); + return &asT(); + } + + T& ref() { + MOZ_ASSERT(constructed); + return asT(); + } + + const T& ref() const { + MOZ_ASSERT(constructed); + return const_cast(this)->asT(); + } + + void destroy() { + ref().~T(); + constructed = false; + } + + void destroyIfConstructed() { + if (!empty()) + destroy(); + } + + private: + Maybe(const Maybe& other) MOZ_DELETE; + const Maybe& operator=(const Maybe& other) MOZ_DELETE; +}; + +} // namespace mozilla + +#endif /* mozilla_Maybe_h */ diff --git a/external/spidermonkey/include/ios/mozilla/Move.h b/external/spidermonkey/include/ios/mozilla/Move.h index 97178daaa6..a18da32ad8 100644 --- a/external/spidermonkey/include/ios/mozilla/Move.h +++ b/external/spidermonkey/include/ios/mozilla/Move.h @@ -9,11 +9,21 @@ #ifndef mozilla_Move_h #define mozilla_Move_h +#include "mozilla/TypeTraits.h" + namespace mozilla { /* * "Move" References * + * [Once upon a time, C++11 rvalue references were not implemented by all the + * compilers we cared about, so we invented mozilla::Move() (now called + * OldMove()), which does something similar. We're in the process of + * transitioning away from this to pure stl (bug 896100). Until that bug is + * completed, this header will provide both mozilla::OldMove() and + * mozilla::Move().] + * + * * Some types can be copied much more efficiently if we know the original's * value need not be preserved --- that is, if we are doing a "move", not a * "copy". For example, if we have: @@ -48,18 +58,28 @@ namespace mozilla { * efficiently than it can be copied, and provide an implementation of that * move operation. * - * The Move(T&) function takes a reference to a T, and returns a MoveRef - * referring to the same value; that's 1). A MoveRef is simply a reference + * The OldMove(T&) function takes a reference to a T, and returns a MoveRef + * referring to the same value; that's (1). A MoveRef is simply a reference * to a T, annotated to say that a copy constructor applied to it may move that * T, instead of copying it. Finally, a constructor that accepts an MoveRef - * should perform a more efficient move, instead of a copy, providing 2). + * should perform a more efficient move, instead of a copy, providing (2). * - * So, where we might define a copy constructor for a class C like this: + * The Move(T&) function takes a reference to a T and returns a T&&. It acts + * just like std::move(), which is not available on all our platforms. + * + * In new code, you should use Move(T&) and T&& instead of OldMove(T&) and + * MoveRef, where possible. + * + * Where we might define a copy constructor for a class C like this: * * C(const C& rhs) { ... copy rhs to this ... } * * we would declare a move constructor like this: * + * C(C&& rhs) { .. move rhs to this ... } + * + * or, in the deprecated OldMove style: + * * C(MoveRef rhs) { ... move rhs to this ... } * * And where we might perform a copy like this: @@ -68,7 +88,11 @@ namespace mozilla { * * we would perform a move like this: * - * C c2(Move(c1)) + * C c2(Move(c1)); + * + * or, in the deprecated OldMove style: + * + * C c2(OldMove(c1)); * * Note that MoveRef implicitly converts to T&, so you can pass a MoveRef * to an ordinary copy constructor for a type that doesn't support a special @@ -82,7 +106,7 @@ namespace mozilla { * which runs this's destructor, and then applies the move constructor to * *this's memory. A typical definition: * - * C& operator=(MoveRef rhs) { + * C& operator=(C&& rhs) { // or |MoveRef rhs| * this->~C(); * new(this) C(rhs); * return *this; @@ -90,14 +114,14 @@ namespace mozilla { * * With that in place, one can write move assignments like this: * - * c2 = Move(c1); + * c2 = Move(c1); // or OldMove() * * This destroys c1, moves c1's value to c2, and leaves c1 in an undefined but * destructible state. * - * This header file defines MoveRef and Move in the mozilla namespace. It's up - * to individual containers to annotate moves as such, by calling Move; and it's - * up to individual types to define move constructors. + * This header file defines MoveRef, Move, and OldMove in the mozilla namespace. + * It's up to individual containers to annotate moves as such, by calling Move + * or OldMove; and it's up to individual types to define move constructors. * * One hint: if you're writing a move constructor where the type has members * that should be moved themselves, it's much nicer to write this: @@ -125,14 +149,14 @@ class MoveRef template inline MoveRef -Move(T& t) +OldMove(T& t) { return MoveRef(t); } template inline MoveRef -Move(const T& t) +OldMove(const T& t) { // With some versions of gcc, for a class C, there's an (incorrect) ambiguity // between the C(const C&) constructor and the default C(C&&) C++11 move @@ -151,14 +175,45 @@ Move(const T& t) return MoveRef(const_cast(t)); } +/** + * Identical to std::Move(); this is necessary until our stlport supports + * std::move(). + */ +template +inline typename RemoveReference::Type&& +Move(T&& a) +{ + return static_cast::Type&&>(a); +} + +/** + * These two overloads are identidal to std::Forward(); they are necessary until + * our stlport supports std::forward(). + */ +template +inline T&& +Forward(typename RemoveReference::Type& a) +{ + return static_cast(a); +} + +template +inline T&& +Forward(typename RemoveReference::Type&& t) +{ + static_assert(!IsLvalueReference::value, + "misuse of Forward detected! try the other overload"); + return static_cast(t); +} + /** Swap |t| and |u| using move-construction if possible. */ template inline void Swap(T& t, T& u) { - T tmp(Move(t)); - t = Move(u); - u = Move(tmp); + T tmp(OldMove(t)); + t = OldMove(u); + u = OldMove(tmp); } } // namespace mozilla diff --git a/external/spidermonkey/include/ios/mozilla/NullPtr.h b/external/spidermonkey/include/ios/mozilla/NullPtr.h index 14c0f07df2..35faadc4c3 100644 --- a/external/spidermonkey/include/ios/mozilla/NullPtr.h +++ b/external/spidermonkey/include/ios/mozilla/NullPtr.h @@ -12,8 +12,6 @@ #ifndef mozilla_NullPtr_h #define mozilla_NullPtr_h -#include "mozilla/Compiler.h" - #if defined(__clang__) # ifndef __has_extension # define __has_extension __has_feature @@ -23,6 +21,7 @@ # endif #elif defined(__GNUC__) # if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L +# include "mozilla/Compiler.h" # if MOZ_GCC_VERSION_AT_LEAST(4, 6, 0) # define MOZ_HAVE_CXX11_NULLPTR # endif diff --git a/external/spidermonkey/include/ios/mozilla/NumericLimits.h b/external/spidermonkey/include/ios/mozilla/NumericLimits.h new file mode 100644 index 0000000000..d2ee29813e --- /dev/null +++ b/external/spidermonkey/include/ios/mozilla/NumericLimits.h @@ -0,0 +1,40 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=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/. */ + +/* Compatibility with std::numeric_limits. */ + +#ifndef mozilla_NumericLimits_h +#define mozilla_NumericLimits_h + +#include "mozilla/Char16.h" + +#include +#include + +namespace mozilla { + +/** + * The NumericLimits class provides a compatibility layer with std::numeric_limits + * for char16_t, otherwise it is exactly the same as std::numeric_limits. + * Code which does not need std::numeric_limits should avoid using + * NumericLimits. + */ +template +class NumericLimits : public std::numeric_limits +{ +}; + +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> +class NumericLimits : public std::numeric_limits +{ + // char16_t and uint16_t numeric limits should be exactly the same. +}; +#endif + +} // namespace mozilla + +#endif /* mozilla_NumericLimits_h */ diff --git a/external/spidermonkey/include/ios/mozilla/PodOperations.h b/external/spidermonkey/include/ios/mozilla/PodOperations.h index bec89fa928..668197cdc1 100644 --- a/external/spidermonkey/include/ios/mozilla/PodOperations.h +++ b/external/spidermonkey/include/ios/mozilla/PodOperations.h @@ -24,7 +24,7 @@ namespace mozilla { /** Set the contents of |t| to 0. */ template -static void +static MOZ_ALWAYS_INLINE void PodZero(T* t) { memset(t, 0, sizeof(T)); @@ -32,7 +32,7 @@ PodZero(T* t) /** Set the contents of |nelem| elements starting at |t| to 0. */ template -static void +static MOZ_ALWAYS_INLINE void PodZero(T* t, size_t nelem) { /* @@ -58,7 +58,7 @@ static void PodZero(T (&t)[N], size_t nelem) MOZ_DELETE; /** Set the contents of the array |t| to zero. */ template -static void +static MOZ_ALWAYS_INLINE void PodArrayZero(T (&t)[N]) { memset(t, 0, N * sizeof(T)); @@ -69,7 +69,7 @@ PodArrayZero(T (&t)[N]) * overlap. */ template -static void +static MOZ_ALWAYS_INLINE void PodAssign(T* dst, const T* src) { MOZ_ASSERT(dst != src); @@ -83,7 +83,7 @@ PodAssign(T* dst, const T* src) * overlap! */ template -MOZ_ALWAYS_INLINE static void +static MOZ_ALWAYS_INLINE void PodCopy(T* dst, const T* src, size_t nelem) { MOZ_ASSERT(dst != src); @@ -103,7 +103,7 @@ PodCopy(T* dst, const T* src, size_t nelem) } template -MOZ_ALWAYS_INLINE static void +static MOZ_ALWAYS_INLINE void PodCopy(volatile T* dst, const volatile T* src, size_t nelem) { MOZ_ASSERT(dst != src); @@ -127,7 +127,7 @@ PodCopy(volatile T* dst, const volatile T* src, size_t nelem) * The arrays must not overlap! */ template -static void +static MOZ_ALWAYS_INLINE void PodArrayCopy(T (&dst)[N], const T (&src)[N]) { PodCopy(dst, src, N); @@ -138,7 +138,7 @@ PodArrayCopy(T (&dst)[N], const T (&src)[N]) * |len| elements at |two|. */ template -MOZ_ALWAYS_INLINE static bool +static MOZ_ALWAYS_INLINE bool PodEqual(const T* one, const T* two, size_t len) { if (len < 128) { diff --git a/external/spidermonkey/include/ios/mozilla/RefPtr.h b/external/spidermonkey/include/ios/mozilla/RefPtr.h index 3c275afdc7..72c7904554 100644 --- a/external/spidermonkey/include/ios/mozilla/RefPtr.h +++ b/external/spidermonkey/include/ios/mozilla/RefPtr.h @@ -68,18 +68,18 @@ class RefCounted public: // Compatibility with nsRefPtr. - void AddRef() { + void AddRef() const { MOZ_ASSERT(refCnt >= 0); ++refCnt; } - void Release() { + void Release() const { MOZ_ASSERT(refCnt > 0); if (0 == --refCnt) { #ifdef DEBUG refCnt = detail::DEAD; #endif - delete static_cast(this); + delete static_cast(this); } } @@ -93,7 +93,7 @@ class RefCounted } private: - typename Conditional, int>::Type refCnt; + mutable typename Conditional, int>::Type refCnt; }; } diff --git a/external/spidermonkey/include/ios/mozilla/TypeTraits.h b/external/spidermonkey/include/ios/mozilla/TypeTraits.h index 53c0b5c2f6..1ccd0c85d1 100644 --- a/external/spidermonkey/include/ios/mozilla/TypeTraits.h +++ b/external/spidermonkey/include/ios/mozilla/TypeTraits.h @@ -63,6 +63,9 @@ template<> struct IsIntegralHelper : TrueType {}; template<> struct IsIntegralHelper : TrueType {}; template<> struct IsIntegralHelper : TrueType {}; template<> struct IsIntegralHelper : TrueType {}; +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> struct IsIntegralHelper : TrueType {}; +#endif } /* namespace detail */ @@ -218,6 +221,9 @@ template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> struct IsPod : TrueType {}; +#endif template struct IsPod : TrueType {}; namespace detail { @@ -418,6 +424,16 @@ struct IsConvertible : IntegralConstant::value> {}; +/** + * Is IsLvalueReference is true if its template param is T& and is false if + * its type is T or T&&. + */ +template +struct IsLvalueReference : FalseType {}; + +template +struct IsLvalueReference : TrueType {}; + /* 20.9.7 Transformations between types [meta.trans] */ /* 20.9.7.1 Const-volatile modifications [meta.trans.cv] */ @@ -478,6 +494,32 @@ struct RemoveCV /* 20.9.7.2 Reference modifications [meta.trans.ref] */ +/** + * Converts reference types to the underlying types. + * + * mozilla::RemoveReference::Type is T; + * mozilla::RemoveReference::Type is T; + * mozilla::RemoveReference::Type is T; + */ + +template +struct RemoveReference +{ + typedef T Type; +}; + +template +struct RemoveReference +{ + typedef T Type; +}; + +template +struct RemoveReference +{ + typedef T Type; +}; + /* 20.9.7.3 Sign modifications [meta.trans.sign] */ template diff --git a/external/spidermonkey/include/ios/mozilla/TypedEnum.h b/external/spidermonkey/include/ios/mozilla/TypedEnum.h index 6f595cb4c5..9c7590deff 100644 --- a/external/spidermonkey/include/ios/mozilla/TypedEnum.h +++ b/external/spidermonkey/include/ios/mozilla/TypedEnum.h @@ -28,7 +28,7 @@ # endif #elif defined(__GNUC__) # if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L -# if MOZ_GCC_VERSION_AT_LEAST(4, 5, 1) +# if MOZ_GCC_VERSION_AT_LEAST(4, 6, 3) # define MOZ_HAVE_CXX11_ENUM_TYPE # define MOZ_HAVE_CXX11_STRONG_ENUMS # endif @@ -72,7 +72,7 @@ * strongly-typed enumeration feature of C++11 ("enum class"). If supported * by the compiler, an enum defined using these macros will not be implicitly * converted to any other type, and its enumerators will be scoped using the - * enumeration name. Place MOZ_BEGIN_ENUM_CLASS(EnumName, type) in place of + * enumeration name. Place MOZ_BEGIN_ENUM_CLASS(EnumName [, type]) in place of * "enum EnumName {", and MOZ_END_ENUM_CLASS(EnumName) in place of the closing * "};". For example, * @@ -87,10 +87,9 @@ * fail. In other compilers, Enum itself will actually be defined as a class, * and some implicit conversions will fail while others will succeed. * - * The type argument specifies the underlying type for the enum where - * supported, as with MOZ_ENUM_TYPE(). For simplicity, it is currently - * mandatory. As with MOZ_ENUM_TYPE(), it will do nothing on compilers that do - * not support it. + * The optional type argument specifies the underlying type for the enum where + * supported, as with MOZ_ENUM_TYPE(). As with MOZ_ENUM_TYPE(), it will do + * nothing on compilers that do not support it. * * MOZ_{BEGIN,END}_ENUM_CLASS doesn't work for defining enum classes nested * inside classes. To define an enum class nested inside another class, use @@ -114,7 +113,12 @@ * All compilers that support strong enums also support an explicit * underlying type, so no extra check is needed. */ -# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ + + /* Single-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER1(Name) \ + enum class Name { + /* Two-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER2(Name, type) \ enum class Name : type { # define MOZ_END_NESTED_ENUM_CLASS(Name) \ }; @@ -154,8 +158,17 @@ * { * return Enum::A; * } - */\ -# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ + */ + + /* Single-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER1(Name) \ + class Name \ + { \ + public: \ + enum Enum \ + { + /* Two-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER2(Name, type) \ class Name \ { \ public: \ @@ -226,7 +239,36 @@ inline int& operator<<=(int&, const Name::Enum&) MOZ_DELETE; \ inline int& operator>>=(int&, const Name::Enum&) MOZ_DELETE; #endif -# define MOZ_BEGIN_ENUM_CLASS(Name, type) MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) + + /* + * Count the number of arguments passed to MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS, + * very carefully tiptoeing around an MSVC bug where it improperly expands + * __VA_ARGS__ as a single token in argument lists. See these URLs for + * details: + * + * http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement + * http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/#comment-644 + */ +# define MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL2(_1, _2, count, ...) \ + count +# define MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL(args) \ + MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL2 args +# define MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS(...) \ + MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL((__VA_ARGS__, 2, 1, 0)) + /* Pick the right helper macro to invoke. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER2(count) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER##count +# define MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER1(count) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER2(count) +# define MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER(count) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER1(count) + /* The actual macro. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_GLUE(x, y) x y +# define MOZ_BEGIN_NESTED_ENUM_CLASS(...) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_GLUE(MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER(MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS(__VA_ARGS__)), \ + (__VA_ARGS__)) + +# define MOZ_BEGIN_ENUM_CLASS(...) MOZ_BEGIN_NESTED_ENUM_CLASS(__VA_ARGS__) # define MOZ_END_ENUM_CLASS(Name) \ MOZ_END_NESTED_ENUM_CLASS(Name) \ MOZ_FINISH_NESTED_ENUM_CLASS(Name) diff --git a/external/spidermonkey/include/ios/mozilla/Util.h b/external/spidermonkey/include/ios/mozilla/Util.h index 4f1c634a59..b4cf2e425b 100644 --- a/external/spidermonkey/include/ios/mozilla/Util.h +++ b/external/spidermonkey/include/ios/mozilla/Util.h @@ -18,267 +18,10 @@ #ifdef __cplusplus +#include "mozilla/Alignment.h" + namespace mozilla { -/* - * This class, and the corresponding macro MOZ_ALIGNOF, figure out how many - * bytes of alignment a given type needs. - */ -template -class AlignmentFinder -{ - struct Aligner - { - char c; - T t; - }; - - public: - static const size_t alignment = sizeof(Aligner) - sizeof(T); -}; - -#define MOZ_ALIGNOF(T) mozilla::AlignmentFinder::alignment - -/* - * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types. - * - * For instance, - * - * MOZ_ALIGNED_DECL(char arr[2], 8); - * - * will declare a two-character array |arr| aligned to 8 bytes. - */ - -#if defined(__GNUC__) -# define MOZ_ALIGNED_DECL(_type, _align) \ - _type __attribute__((aligned(_align))) -#elif defined(_MSC_VER) -# define MOZ_ALIGNED_DECL(_type, _align) \ - __declspec(align(_align)) _type -#else -# warning "We don't know how to align variables on this compiler." -# define MOZ_ALIGNED_DECL(_type, _align) _type -#endif - -/* - * AlignedElem is a structure whose alignment is guaranteed to be at least N - * bytes. - * - * We support 1, 2, 4, 8, and 16-bit alignment. - */ -template -struct AlignedElem; - -/* - * We have to specialize this template because GCC doesn't like __attribute__((aligned(foo))) where - * foo is a template parameter. - */ - -template<> -struct AlignedElem<1> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 1); -}; - -template<> -struct AlignedElem<2> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 2); -}; - -template<> -struct AlignedElem<4> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 4); -}; - -template<> -struct AlignedElem<8> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 8); -}; - -template<> -struct AlignedElem<16> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 16); -}; - -/* - * This utility pales in comparison to Boost's aligned_storage. The utility - * simply assumes that uint64_t is enough alignment for anyone. This may need - * to be extended one day... - * - * As an important side effect, pulling the storage into this template is - * enough obfuscation to confuse gcc's strict-aliasing analysis into not giving - * false negatives when we cast from the char buffer to whatever type we've - * constructed using the bytes. - */ -template -struct AlignedStorage -{ - union U { - char bytes[nbytes]; - uint64_t _; - } u; - - const void* addr() const { return u.bytes; } - void* addr() { return u.bytes; } -}; - -template -struct AlignedStorage2 -{ - union U { - char bytes[sizeof(T)]; - uint64_t _; - } u; - - const T* addr() const { return reinterpret_cast(u.bytes); } - T* addr() { return static_cast(static_cast(u.bytes)); } -}; - -/* - * Small utility for lazily constructing objects without using dynamic storage. - * When a Maybe is constructed, it is |empty()|, i.e., no value of T has - * been constructed and no T destructor will be called when the Maybe is - * destroyed. Upon calling |construct|, a T object will be constructed with the - * given arguments and that object will be destroyed when the owning Maybe - * is destroyed. - * - * N.B. GCC seems to miss some optimizations with Maybe and may generate extra - * branches/loads/stores. Use with caution on hot paths. - */ -template -class Maybe -{ - AlignedStorage2 storage; - bool constructed; - - T& asT() { return *storage.addr(); } - - public: - Maybe() { constructed = false; } - ~Maybe() { if (constructed) asT().~T(); } - - bool empty() const { return !constructed; } - - void construct() { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(); - constructed = true; - } - - template - void construct(const T1& t1) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7, const T8& t8) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7, const T8& t8, const T9& t9) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); - constructed = true; - } - - T* addr() { - MOZ_ASSERT(constructed); - return &asT(); - } - - T& ref() { - MOZ_ASSERT(constructed); - return asT(); - } - - const T& ref() const { - MOZ_ASSERT(constructed); - return const_cast(this)->asT(); - } - - void destroy() { - ref().~T(); - constructed = false; - } - - void destroyIfConstructed() { - if (!empty()) - destroy(); - } - - private: - Maybe(const Maybe& other) MOZ_DELETE; - const Maybe& operator=(const Maybe& other) MOZ_DELETE; -}; - /* * Safely subtract two pointers when it is known that end >= begin. This avoids * the common compiler bug that if (size_t(end) - size_t(begin)) has the MSB diff --git a/external/spidermonkey/include/ios/mozilla/Vector.h b/external/spidermonkey/include/ios/mozilla/Vector.h index 8759df8c06..54e266eeb7 100644 --- a/external/spidermonkey/include/ios/mozilla/Vector.h +++ b/external/spidermonkey/include/ios/mozilla/Vector.h @@ -9,6 +9,7 @@ #ifndef mozilla_Vector_h #define mozilla_Vector_h +#include "mozilla/Alignment.h" #include "mozilla/AllocPolicy.h" #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" @@ -19,7 +20,7 @@ #include "mozilla/ReentrancyGuard.h" #include "mozilla/TemplateLib.h" #include "mozilla/TypeTraits.h" -#include "mozilla/Util.h" +#include "mozilla/Util.h" // for PointerRangeSize #include // for placement new @@ -85,7 +86,7 @@ struct VectorImpl template static inline void moveConstruct(T* dst, const U* srcbeg, const U* srcend) { for (const U* p = srcbeg; p < srcend; ++p, ++dst) - new(dst) T(Move(*p)); + new(dst) T(OldMove(*p)); } /* @@ -114,7 +115,7 @@ struct VectorImpl T* dst = newbuf; T* src = v.beginNoCheck(); for (; src < v.endNoCheck(); ++dst, ++src) - new(dst) T(Move(*src)); + new(dst) T(OldMove(*src)); VectorImpl::destroy(v.beginNoCheck(), v.endNoCheck()); v.free_(v.mBegin); v.mBegin = newbuf; @@ -547,8 +548,8 @@ class VectorBase : private AllocPolicy void swap(ThisVector& other); private: - VectorBase(const ThisVector&) MOZ_DELETE; - void operator=(const ThisVector&) MOZ_DELETE; + VectorBase(const VectorBase&) MOZ_DELETE; + void operator=(const VectorBase&) MOZ_DELETE; }; /* This does the re-entrancy check plus several other sanity checks. */ @@ -565,14 +566,15 @@ template MOZ_ALWAYS_INLINE VectorBase::VectorBase(AP ap) : AP(ap), - mBegin(static_cast(storage.addr())), mLength(0), mCapacity(sInlineCapacity) #ifdef DEBUG , mReserved(sInlineCapacity), entered(false) #endif -{} +{ + mBegin = static_cast(storage.addr()); +} /* Move constructor. */ template diff --git a/external/spidermonkey/include/ios/mozilla/WeakPtr.h b/external/spidermonkey/include/ios/mozilla/WeakPtr.h index c714ebf565..0165e3a017 100644 --- a/external/spidermonkey/include/ios/mozilla/WeakPtr.h +++ b/external/spidermonkey/include/ios/mozilla/WeakPtr.h @@ -14,9 +14,6 @@ * the WeakPtrs to it and allows the WeakReference to live beyond the lifetime * of 'Foo'. * - * AtomicSupportsWeakPtr can be used for a variant with an atomically updated - * reference counter. - * * The overhead of WeakPtr is that accesses to 'Foo' becomes an additional * dereference, and an additional heap allocated pointer sized object shared * between all of the WeakPtrs. @@ -63,7 +60,6 @@ #define mozilla_WeakPtr_h #include "mozilla/Assertions.h" -#include "mozilla/Atomics.h" #include "mozilla/NullPtr.h" #include "mozilla/RefPtr.h" #include "mozilla/TypeTraits.h" @@ -76,8 +72,8 @@ template class SupportsWeakPtrBase; namespace detail { // This can live beyond the lifetime of the class derived from SupportsWeakPtrBase. -template -class WeakReference : public RefCounted, Atomicity> +template +class WeakReference : public ::mozilla::RefCounted > { public: explicit WeakReference(T* p) : ptr(p) {} @@ -86,8 +82,8 @@ class WeakReference : public RefCounted, Atomicity> } private: - friend class WeakPtrBase; - friend class SupportsWeakPtrBase; + friend class WeakPtrBase >; + friend class SupportsWeakPtrBase >; void detach() { ptr = nullptr; } @@ -121,30 +117,10 @@ class SupportsWeakPtrBase }; template -class SupportsWeakPtr - : public SupportsWeakPtrBase > +class SupportsWeakPtr : public SupportsWeakPtrBase > { }; -template -class AtomicSupportsWeakPtr - : public SupportsWeakPtrBase > -{ -}; - -namespace detail { - -template -struct WeakReferenceCount -{ - static const RefCountAtomicity atomicity = - IsBaseOf, T>::value - ? AtomicRefCount - : NonAtomicRefCount; -}; - -} - template class WeakPtrBase { @@ -177,9 +153,9 @@ class WeakPtrBase }; template -class WeakPtr : public WeakPtrBase::atomicity> > +class WeakPtr : public WeakPtrBase > { - typedef WeakPtrBase::atomicity> > Base; + typedef WeakPtrBase > Base; public: WeakPtr(const WeakPtr& o) : Base(o) {} WeakPtr(const Base& o) : Base(o) {} diff --git a/external/spidermonkey/include/mac/js-config.h b/external/spidermonkey/include/mac/js-config.h index ae4f2abf71..771ede7669 100644 --- a/external/spidermonkey/include/mac/js-config.h +++ b/external/spidermonkey/include/mac/js-config.h @@ -5,8 +5,8 @@ * 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/. */ -#ifndef js_config_h___ -#define js_config_h___ +#ifndef js_config_h +#define js_config_h /* Definitions set at build time that affect SpiderMonkey's public API. This header file is generated by the SpiderMonkey configure script, @@ -20,7 +20,7 @@ /* Define to 1 if SpiderMonkey should support the ability to perform entirely too much GC. */ -#define JS_GC_ZEAL 1 +/* #undef JS_GC_ZEAL */ /* Define to 1 if the header is present and useable. See jscpucfg.h. */ @@ -34,12 +34,8 @@ useable. See jscpucfg.h. */ /* #undef JS_HAVE_SYS_ISA_DEFS_H */ -/* The configure script defines these if it doesn't #define - JS_HAVE_STDINT_H. */ -#define JS_BYTES_PER_WORD 8 - /* MOZILLA JSAPI version number components */ -#define MOZJS_MAJOR_VERSION 25 +#define MOZJS_MAJOR_VERSION 27 #define MOZJS_MINOR_VERSION 0 -#endif /* js_config_h___ */ +#endif /* js_config_h */ diff --git a/external/spidermonkey/include/mac/js.msg b/external/spidermonkey/include/mac/js.msg index 3f665d8d54..da7361d5df 100644 --- a/external/spidermonkey/include/mac/js.msg +++ b/external/spidermonkey/include/mac/js.msg @@ -221,8 +221,8 @@ MSG_DEF(JSMSG_CANT_DECODE_PRINCIPALS, 167, 0, JSEXN_INTERNALERR, "can't decode J MSG_DEF(JSMSG_CANT_SEAL_OBJECT, 168, 1, JSEXN_ERR, "can't seal {0} objects") MSG_DEF(JSMSG_TOO_MANY_CATCH_VARS, 169, 0, JSEXN_SYNTAXERR, "too many catch variables") MSG_DEF(JSMSG_NEGATIVE_REPETITION_COUNT, 170, 0, JSEXN_RANGEERR, "repeat count must be non-negative") -MSG_DEF(JSMSG_UNUSED171, 171, 0, JSEXN_NONE, "") -MSG_DEF(JSMSG_UNUSED172, 172, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_INVALID_FOR_OF_INIT, 171, 0, JSEXN_SYNTAXERR, "for-of loop variable declaration may not have an initializer") +MSG_DEF(JSMSG_INVALID_MAP_ITERABLE, 172, 0, JSEXN_TYPEERR, "iterable for map should have array-like objects") MSG_DEF(JSMSG_UNUSED173, 173, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED174, 174, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_NESTING_GENERATOR, 175, 0, JSEXN_TYPEERR, "already executing generator") @@ -233,8 +233,8 @@ MSG_DEF(JSMSG_UNUSED179, 179, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED180, 180, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED181, 181, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_BAD_GENERATOR_SEND, 182, 1, JSEXN_TYPEERR, "attempt to send {0} to newborn generator") -MSG_DEF(JSMSG_UNUSED183, 183, 0, JSEXN_NONE, "") -MSG_DEF(JSMSG_UNUSED184, 184, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_SC_NOT_TRANSFERABLE, 183, 0, JSEXN_TYPEERR, "invalid transferable array for structured clone") +MSG_DEF(JSMSG_SC_DUP_TRANSFERABLE, 184, 0, JSEXN_TYPEERR, "duplicate transferable for structured clone") MSG_DEF(JSMSG_CANT_REPORT_AS_NON_EXTENSIBLE, 185, 0, JSEXN_TYPEERR, "proxy can't report an extensible object as non-extensible") MSG_DEF(JSMSG_UNUSED186, 186, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED187, 187, 0, JSEXN_NONE, "") @@ -260,7 +260,7 @@ MSG_DEF(JSMSG_USER_DEFINED_ERROR, 206, 0, JSEXN_ERR, "JS_ReportError was cal MSG_DEF(JSMSG_WRONG_CONSTRUCTOR, 207, 1, JSEXN_TYPEERR, "wrong constructor called for {0}") MSG_DEF(JSMSG_BAD_GENERATOR_RETURN, 208, 1, JSEXN_TYPEERR, "generator function {0} returns a value") MSG_DEF(JSMSG_BAD_ANON_GENERATOR_RETURN, 209, 0, JSEXN_TYPEERR, "anonymous generator function returns a value") -MSG_DEF(JSMSG_NAME_AFTER_FOR_PAREN, 210, 0, JSEXN_SYNTAXERR, "missing name after for (") +MSG_DEF(JSMSG_UNUSED210, 210, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_IN_AFTER_FOR_NAME, 211, 0, JSEXN_SYNTAXERR, "missing 'in' or 'of' after for") MSG_DEF(JSMSG_BAD_TRAP_RETURN_VALUE, 212, 2, JSEXN_TYPEERR,"trap {1} for {0} returned a primitive value") MSG_DEF(JSMSG_UNUSED213, 213, 0, JSEXN_NONE, "") @@ -269,7 +269,7 @@ MSG_DEF(JSMSG_BAD_GENERATOR_SYNTAX, 215, 1, JSEXN_SYNTAXERR, "{0} expression m MSG_DEF(JSMSG_ARRAY_COMP_LEFTSIDE, 216, 0, JSEXN_SYNTAXERR, "invalid array comprehension left-hand side") MSG_DEF(JSMSG_UNUSED217, 217, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_EMPTY_ARRAY_REDUCE, 218, 0, JSEXN_TYPEERR, "reduce of empty array with no initial value") -MSG_DEF(JSMSG_UNUSED219, 219, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_BAD_SYMBOL, 219, 1, JSEXN_TYPEERR, "{0} is not a well-known @@-symbol") MSG_DEF(JSMSG_BAD_DELETE_OPERAND, 220, 0, JSEXN_REFERENCEERR, "invalid delete operand") MSG_DEF(JSMSG_BAD_INCOP_OPERAND, 221, 0, JSEXN_REFERENCEERR, "invalid increment/decrement operand") MSG_DEF(JSMSG_UNEXPECTED_TYPE, 222, 2, JSEXN_TYPEERR, "{0} is {1}") @@ -353,7 +353,7 @@ MSG_DEF(JSMSG_REST_WITH_DEFAULT, 299, 0, JSEXN_SYNTAXERR, "rest parameter m MSG_DEF(JSMSG_NONDEFAULT_FORMAL_AFTER_DEFAULT, 300, 0, JSEXN_SYNTAXERR, "parameter(s) with default followed by parameter without default") MSG_DEF(JSMSG_YIELD_IN_DEFAULT, 301, 0, JSEXN_SYNTAXERR, "yield in default expression") MSG_DEF(JSMSG_INTRINSIC_NOT_DEFINED, 302, 1, JSEXN_REFERENCEERR, "no intrinsic function {0}") -MSG_DEF(JSMSG_ALREADY_HAS_SOURCEMAP, 303, 1, JSEXN_ERR, "{0} is being assigned a source map, yet already has one") +MSG_DEF(JSMSG_ALREADY_HAS_PRAGMA, 303, 2, JSEXN_ERR, "{0} is being assigned a {1}, but already has one") MSG_DEF(JSMSG_PAR_ARRAY_BAD_ARG, 304, 1, JSEXN_RANGEERR, "invalid ParallelArray{0} argument") MSG_DEF(JSMSG_PAR_ARRAY_BAD_PARTITION, 305, 0, JSEXN_ERR, "argument must be divisible by outermost dimension") MSG_DEF(JSMSG_PAR_ARRAY_REDUCE_EMPTY, 306, 0, JSEXN_ERR, "cannot reduce ParallelArray object whose outermost dimension is empty") @@ -375,7 +375,7 @@ MSG_DEF(JSMSG_MUST_REPORT_UNDEFINED, 321, 0, JSEXN_TYPEERR, "proxy must report MSG_DEF(JSMSG_CANT_SET_NW_NC, 322, 0, JSEXN_TYPEERR, "proxy can't successfully set a non-writable, non-configurable property") MSG_DEF(JSMSG_CANT_SET_WO_SETTER, 323, 0, JSEXN_TYPEERR, "proxy can't succesfully set an accessor property without a setter") MSG_DEF(JSMSG_DEBUG_BAD_REFERENT, 324, 2, JSEXN_TYPEERR, "{0} does not refer to {1}") -MSG_DEF(JSMSG_DEBUG_WRAPPER_IN_WAY, 325, 2, JSEXN_TYPEERR, "{0} is a wrapper around {1}, but a direct reference is required") +MSG_DEF(JSMSG_DEBUG_WRAPPER_IN_WAY, 325, 3, JSEXN_TYPEERR, "{0} is {1}{2}a global object, but a direct reference is required") MSG_DEF(JSMSG_UNWRAP_DENIED, 326, 0, JSEXN_ERR, "permission denied to unwrap object") MSG_DEF(JSMSG_INTL_OBJECT_NOT_INITED, 327, 3, JSEXN_TYPEERR, "Intl.{0}.prototype.{1} called on value that's not an object initialized as a {2}") MSG_DEF(JSMSG_INVALID_LOCALES_ELEMENT,328, 0, JSEXN_TYPEERR, "invalid element in locales argument") @@ -400,12 +400,23 @@ MSG_DEF(JSMSG_YIELD_IN_ARROW, 346, 0, JSEXN_SYNTAXERR, "arrow function m MSG_DEF(JSMSG_WRONG_VALUE, 347, 2, JSEXN_ERR, "expected {0} but found {1}") MSG_DEF(JSMSG_PAR_ARRAY_SCATTER_BAD_TARGET, 348, 1, JSEXN_ERR, "target for index {0} is not an integer") MSG_DEF(JSMSG_SELFHOSTED_UNBOUND_NAME,349, 0, JSEXN_TYPEERR, "self-hosted code may not contain unbound name lookups") -MSG_DEF(JSMSG_DEPRECATED_SOURCE_MAP, 350, 0, JSEXN_SYNTAXERR, "Using //@ to indicate source map URL pragmas is deprecated. Use //# instead") +MSG_DEF(JSMSG_DEPRECATED_PRAGMA, 350, 1, JSEXN_SYNTAXERR, "Using //@ to indicate {0} pragmas is deprecated. Use //# instead") MSG_DEF(JSMSG_BAD_DESTRUCT_ASSIGN, 351, 1, JSEXN_SYNTAXERR, "can't assign to {0} using destructuring assignment") -MSG_DEF(JSMSG_BINARYDATA_ARRAYTYPE_BAD_ARGS, 352, 0, JSEXN_ERR, "Invalid arguments") -MSG_DEF(JSMSG_BINARYDATA_BINARYARRAY_BAD_INDEX, 353, 0, JSEXN_RANGEERR, "invalid or out-of-range index") -MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_ARGS, 354, 0, JSEXN_RANGEERR, "invalid field descriptor") -MSG_DEF(JSMSG_BINARYDATA_NOT_BINARYSTRUCT, 355, 1, JSEXN_TYPEERR, "{0} is not a BinaryStruct") -MSG_DEF(JSMSG_BINARYDATA_SUBARRAY_INTEGER_ARG, 356, 1, JSEXN_ERR, "argument {0} must be an integer") -MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_EMPTY_DESCRIPTOR, 357, 0, JSEXN_ERR, "field descriptor cannot be empty") -MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_FIELD, 358, 1, JSEXN_ERR, "field {0} is not a valid BinaryData Type descriptor") +MSG_DEF(JSMSG_TYPEDOBJECT_ARRAYTYPE_BAD_ARGS, 352, 0, JSEXN_ERR, "Invalid arguments") +MSG_DEF(JSMSG_TYPEDOBJECT_BINARYARRAY_BAD_INDEX, 353, 0, JSEXN_RANGEERR, "invalid or out-of-range index") +MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_BAD_ARGS, 354, 0, JSEXN_RANGEERR, "invalid field descriptor") +MSG_DEF(JSMSG_TYPEDOBJECT_NOT_BINARYSTRUCT, 355, 1, JSEXN_TYPEERR, "{0} is not a BinaryStruct") +MSG_DEF(JSMSG_TYPEDOBJECT_SUBARRAY_INTEGER_ARG, 356, 1, JSEXN_ERR, "argument {0} must be an integer") +MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_EMPTY_DESCRIPTOR, 357, 0, JSEXN_ERR, "field descriptor cannot be empty") +MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_BAD_FIELD, 358, 1, JSEXN_ERR, "field {0} is not a valid BinaryData Type descriptor") +MSG_DEF(JSMSG_GENERATOR_FINISHED, 359, 0, JSEXN_TYPEERR, "generator has already finished") +MSG_DEF(JSMSG_TYPEDOBJECT_TOO_BIG, 360, 0, JSEXN_ERR, "Type is too large to allocate") +MSG_DEF(JSMSG_TYPEDOBJECT_NOT_TYPE_OBJECT, 361, 0, JSEXN_ERR, "Expected a type object") +MSG_DEF(JSMSG_TOO_MANY_CON_SPREADARGS, 362, 0, JSEXN_RANGEERR, "too many constructor arguments") +MSG_DEF(JSMSG_TOO_MANY_FUN_SPREADARGS, 363, 0, JSEXN_RANGEERR, "too many function arguments") +MSG_DEF(JSMSG_DEBUG_NOT_DEBUGGEE, 364, 2, JSEXN_ERR, "{0} is not a debuggee {1}") +MSG_DEF(JSMSG_TYPEDOBJECT_NOT_TYPED_OBJECT, 365, 0, JSEXN_ERR, "Expected a typed object") +MSG_DEF(JSMSG_TYPEDOBJECT_NO_SUCH_PROP, 366, 1, JSEXN_TYPEERR, "No such property: {0}") +MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_BAD_ARGS, 367, 2, JSEXN_TYPEERR, "argument {0} invalid: expected {1}") +MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_UNATTACHED, 368, 0, JSEXN_TYPEERR, "handle unattached") +MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_BAD_TYPE, 369, 0, JSEXN_TYPEERR, "handle moved to destination of incorrect type") diff --git a/external/spidermonkey/include/mac/js/Anchor.h b/external/spidermonkey/include/mac/js/Anchor.h index 0d458e6fb6..c2324fb2e9 100644 --- a/external/spidermonkey/include/mac/js/Anchor.h +++ b/external/spidermonkey/include/mac/js/Anchor.h @@ -11,12 +11,7 @@ #include "mozilla/Attributes.h" -class JSFunction; -class JSObject; -class JSScript; -class JSString; - -namespace JS { class Value; } +#include "js/TypeDecls.h" namespace JS { diff --git a/external/spidermonkey/include/mac/js/CallArgs.h b/external/spidermonkey/include/mac/js/CallArgs.h index 8027ffc71a..5c7a201101 100644 --- a/external/spidermonkey/include/mac/js/CallArgs.h +++ b/external/spidermonkey/include/mac/js/CallArgs.h @@ -38,22 +38,19 @@ #include "js/RootingAPI.h" #include "js/Value.h" -struct JSContext; -class JSObject; - /* Typedef for native functions called by the JS VM. */ -typedef JSBool +typedef bool (* JSNative)(JSContext *cx, unsigned argc, JS::Value *vp); /* Typedef for native functions that may be called in parallel. */ -typedef js::ParallelResult +typedef bool (* JSParallelNative)(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); /* * Typedef for native functions that may be called either in parallel or * sequential execution. */ -typedef JSBool +typedef bool (* JSThreadSafeNative)(js::ThreadSafeContext *cx, unsigned argc, JS::Value *vp); /* @@ -61,11 +58,11 @@ typedef JSBool * a JSNative or a JSParallelNative. */ template -inline JSBool +inline bool JSNativeThreadSafeWrapper(JSContext *cx, unsigned argc, JS::Value *vp); template -inline js::ParallelResult +inline bool JSParallelNativeThreadSafeWrapper(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); /* @@ -89,7 +86,7 @@ extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; * return value for a function call. The principal way to create a * CallReceiver is using JS::CallReceiverFromVp: * - * static JSBool + * static bool * FunctionReturningThis(JSContext *cx, unsigned argc, JS::Value *vp) * { * JS::CallReceiver rec = JS::CallReceiverFromVp(vp); @@ -282,7 +279,7 @@ CallReceiverFromVp(Value *vp) * the function call's arguments. The principal way to create a CallArgs is * like so, using JS::CallArgsFromVp: * - * static JSBool + * static bool * FunctionReturningArgcTimesArg0(JSContext *cx, unsigned argc, JS::Value *vp) * { * JS::CallArgs args = JS::CallArgsFromVp(argc, vp); diff --git a/external/spidermonkey/include/mac/js/CallNonGenericMethod.h b/external/spidermonkey/include/mac/js/CallNonGenericMethod.h new file mode 100644 index 0000000000..05097f0294 --- /dev/null +++ b/external/spidermonkey/include/mac/js/CallNonGenericMethod.h @@ -0,0 +1,117 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_CallNonGenericMethod_h +#define js_CallNonGenericMethod_h + +#include "jstypes.h" + +#include "js/CallArgs.h" + +namespace JS { + +// Returns true if |v| is considered an acceptable this-value. +typedef bool (*IsAcceptableThis)(Handle v); + +// Implements the guts of a method; guaranteed to be provided an acceptable +// this-value, as determined by a corresponding IsAcceptableThis method. +typedef bool (*NativeImpl)(JSContext *cx, CallArgs args); + +namespace detail { + +// DON'T CALL THIS DIRECTLY. It's for use only by CallNonGenericMethod! +extern JS_PUBLIC_API(bool) +CallMethodIfWrapped(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args); + +} // namespace detail + +// Methods usually act upon |this| objects only from a single global object and +// compartment. Sometimes, however, a method must act upon |this| values from +// multiple global objects or compartments. In such cases the |this| value a +// method might see will be wrapped, such that various access to the object -- +// to its class, its private data, its reserved slots, and so on -- will not +// work properly without entering that object's compartment. This method +// implements a solution to this problem. +// +// To implement a method that accepts |this| values from multiple compartments, +// define two functions. The first function matches the IsAcceptableThis type +// and indicates whether the provided value is an acceptable |this| for the +// method; it must be a pure function only of its argument. +// +// static const JSClass AnswerClass = { ... }; +// +// static bool +// IsAnswerObject(const Value &v) +// { +// if (!v.isObject()) +// return false; +// return JS_GetClass(&v.toObject()) == &AnswerClass; +// } +// +// The second function implements the NativeImpl signature and defines the +// behavior of the method when it is provided an acceptable |this| value. +// Aside from some typing niceties -- see the CallArgs interface for details -- +// its interface is the same as that of JSNative. +// +// static bool +// answer_getAnswer_impl(JSContext *cx, JS::CallArgs args) +// { +// args.rval().setInt32(42); +// return true; +// } +// +// The implementation function is guaranteed to be called *only* with a |this| +// value which is considered acceptable. +// +// Now to implement the actual method, write a JSNative that calls the method +// declared below, passing the appropriate template and runtime arguments. +// +// static bool +// answer_getAnswer(JSContext *cx, unsigned argc, JS::Value *vp) +// { +// JS::CallArgs args = JS::CallArgsFromVp(argc, vp); +// return JS::CallNonGenericMethod(cx, args); +// } +// +// Note that, because they are used as template arguments, the predicate +// and implementation functions must have external linkage. (This is +// unfortunate, but GCC wasn't inlining things as one would hope when we +// passed them as function arguments.) +// +// JS::CallNonGenericMethod will test whether |args.thisv()| is acceptable. If +// it is, it will call the provided implementation function, which will return +// a value and indicate success. If it is not, it will attempt to unwrap +// |this| and call the implementation function on the unwrapped |this|. If +// that succeeds, all well and good. If it doesn't succeed, a TypeError will +// be thrown. +// +// Note: JS::CallNonGenericMethod will only work correctly if it's called in +// tail position in a JSNative. Do not call it from any other place. +// +template +JS_ALWAYS_INLINE bool +CallNonGenericMethod(JSContext *cx, CallArgs args) +{ + HandleValue thisv = args.thisv(); + if (Test(thisv)) + return Impl(cx, args); + + return detail::CallMethodIfWrapped(cx, Test, Impl, args); +} + +JS_ALWAYS_INLINE bool +CallNonGenericMethod(JSContext *cx, IsAcceptableThis Test, NativeImpl Impl, CallArgs args) +{ + HandleValue thisv = args.thisv(); + if (Test(thisv)) + return Impl(cx, args); + + return detail::CallMethodIfWrapped(cx, Test, Impl, args); +} + +} // namespace JS + +#endif /* js_CallNonGenericMethod_h */ diff --git a/external/spidermonkey/include/mac/js/CharacterEncoding.h b/external/spidermonkey/include/mac/js/CharacterEncoding.h index e88e08e1be..7918b83484 100644 --- a/external/spidermonkey/include/mac/js/CharacterEncoding.h +++ b/external/spidermonkey/include/mac/js/CharacterEncoding.h @@ -7,11 +7,15 @@ #ifndef js_CharacterEncoding_h #define js_CharacterEncoding_h +#include "mozilla/NullPtr.h" #include "mozilla/Range.h" +#include "js/TypeDecls.h" #include "js/Utility.h" -#include "jspubtd.h" +namespace js { +struct ThreadSafeContext; +} namespace JS { @@ -41,7 +45,7 @@ class Latin1CharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: - Latin1CharsZ() : Base(NULL, 0) {} + Latin1CharsZ() : Base(nullptr, 0) {} Latin1CharsZ(char *aBytes, size_t aLength) : Base(reinterpret_cast(aBytes), aLength) @@ -80,7 +84,7 @@ class UTF8CharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: - UTF8CharsZ() : Base(NULL, 0) {} + UTF8CharsZ() : Base(nullptr, 0) {} UTF8CharsZ(char *aBytes, size_t aLength) : Base(reinterpret_cast(aBytes), aLength) @@ -138,7 +142,7 @@ class TwoByteCharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: - TwoByteCharsZ() : Base(NULL, 0) {} + TwoByteCharsZ() : Base(nullptr, 0) {} TwoByteCharsZ(jschar *chars, size_t length) : Base(chars, length) @@ -154,7 +158,7 @@ class TwoByteCharsZ : public mozilla::RangedPtr * output. The returned string is zero terminated. The returned string or the * returned string's |start()| must be freed with JS_free or js_free, * respectively. If allocation fails, an OOM error will be set and the method - * will return a NULL chars (which can be tested for with the ! operator). + * will return a nullptr chars (which can be tested for with the ! operator). * This method cannot trigger GC. */ extern Latin1CharsZ diff --git a/external/spidermonkey/include/mac/js/Class.h b/external/spidermonkey/include/mac/js/Class.h new file mode 100644 index 0000000000..4058688e99 --- /dev/null +++ b/external/spidermonkey/include/mac/js/Class.h @@ -0,0 +1,699 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +/* JSClass definition and its component types, plus related interfaces. */ + +#ifndef js_Class_h +#define js_Class_h + +#include "mozilla/NullPtr.h" + +#include "jstypes.h" + +#include "js/CallArgs.h" +#include "js/Id.h" +#include "js/TypeDecls.h" + +/* + * A JSClass acts as a vtable for JS objects that allows JSAPI clients to + * control various aspects of the behavior of an object like property lookup. + * js::Class is an engine-private extension that allows more control over + * object behavior and, e.g., allows custom slow layout. + */ + +class JSFreeOp; + +namespace js { + +class Class; +class FreeOp; +class PropertyId; +class PropertyName; +class Shape; +class SpecialId; + +// This is equal to JSFunction::class_. Use it in places where you don't want +// to #include jsfun.h. +extern JS_FRIEND_DATA(const js::Class* const) FunctionClassPtr; + +static JS_ALWAYS_INLINE jsid +SPECIALID_TO_JSID(const SpecialId &sid); + +/* + * We partition the ways to refer to a property into three: by an index + * (uint32_t); by a string whose characters do not represent an index + * (PropertyName, see vm/String.h); and by various special values. + * + * Special values are encoded using SpecialId, which is layout-compatible but + * non-interconvertible with jsid. A SpecialId is used for JSID_VOID, which + * does not occur in JS scripts but may be used to indicate the absence of a + * valid identifier. In the future, a SpecialId may also be an object used by + * Harmony-proposed private names. + */ +class SpecialId +{ + uintptr_t bits_; + + /* Needs access to raw bits. */ + friend JS_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid); + friend class PropertyId; + + static const uintptr_t TYPE_VOID = JSID_TYPE_VOID; + static const uintptr_t TYPE_OBJECT = JSID_TYPE_OBJECT; + static const uintptr_t TYPE_MASK = JSID_TYPE_MASK; + + SpecialId(uintptr_t bits) : bits_(bits) { } + + public: + SpecialId() : bits_(TYPE_VOID) { } + + /* Object-valued */ + + SpecialId(JSObject &obj) + : bits_(uintptr_t(&obj) | TYPE_OBJECT) + { + JS_ASSERT(&obj != nullptr); + JS_ASSERT((uintptr_t(&obj) & TYPE_MASK) == 0); + } + + bool isObject() const { + return (bits_ & TYPE_MASK) == TYPE_OBJECT && bits_ != TYPE_OBJECT; + } + + JSObject *toObject() const { + JS_ASSERT(isObject()); + return reinterpret_cast(bits_ & ~TYPE_MASK); + } + + /* Empty */ + + static SpecialId empty() { + SpecialId sid(TYPE_OBJECT); + JS_ASSERT(sid.isEmpty()); + return sid; + } + + bool isEmpty() const { + return bits_ == TYPE_OBJECT; + } + + /* Void */ + + static SpecialId voidId() { + SpecialId sid(TYPE_VOID); + JS_ASSERT(sid.isVoid()); + return sid; + } + + bool isVoid() const { + return bits_ == TYPE_VOID; + } +}; + +static JS_ALWAYS_INLINE jsid +SPECIALID_TO_JSID(const SpecialId &sid) +{ + jsid id; + JSID_BITS(id) = sid.bits_; + JS_ASSERT_IF(sid.isObject(), JSID_IS_OBJECT(id) && JSID_TO_OBJECT(id) == sid.toObject()); + JS_ASSERT_IF(sid.isVoid(), JSID_IS_VOID(id)); + JS_ASSERT_IF(sid.isEmpty(), JSID_IS_EMPTY(id)); + return id; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_SPECIAL(jsid id) +{ + return JSID_IS_OBJECT(id) || JSID_IS_EMPTY(id) || JSID_IS_VOID(id); +} + +static JS_ALWAYS_INLINE SpecialId +JSID_TO_SPECIALID(jsid id) +{ + JS_ASSERT(JSID_IS_SPECIAL(id)); + if (JSID_IS_OBJECT(id)) + return SpecialId(*JSID_TO_OBJECT(id)); + if (JSID_IS_EMPTY(id)) + return SpecialId::empty(); + JS_ASSERT(JSID_IS_VOID(id)); + return SpecialId::voidId(); +} + +typedef JS::Handle HandleSpecialId; + +} // namespace js + +// JSClass operation signatures. + +// Add or get a property named by id in obj. Note the jsid id type -- id may +// be a string (Unicode property identifier) or an int (element index). The +// *vp out parameter, on success, is the new property value after the action. +typedef bool +(* JSPropertyOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + JS::MutableHandle vp); + +// Set a property named by id in obj, treating the assignment as strict +// mode code if strict is true. Note the jsid id type -- id may be a string +// (Unicode property identifier) or an int (element index). The *vp out +// parameter, on success, is the new property value after the +// set. +typedef bool +(* JSStrictPropertyOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + bool strict, JS::MutableHandle vp); + +// Delete a property named by id in obj. +// +// If an error occurred, return false as per normal JSAPI error practice. +// +// If no error occurred, but the deletion attempt wasn't allowed (perhaps +// because the property was non-configurable), set *succeeded to false and +// return true. This will cause |delete obj[id]| to evaluate to false in +// non-strict mode code, and to throw a TypeError in strict mode code. +// +// If no error occurred and the deletion wasn't disallowed (this is *not* the +// same as saying that a deletion actually occurred -- deleting a non-existent +// property, or an inherited property, is allowed -- it's just pointless), +// set *succeeded to true and return true. +typedef bool +(* JSDeletePropertyOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + bool *succeeded); + +// This function type is used for callbacks that enumerate the properties of +// a JSObject. The behavior depends on the value of enum_op: +// +// JSENUMERATE_INIT +// A new, opaque iterator state should be allocated and stored in *statep. +// (You can use PRIVATE_TO_JSVAL() to tag the pointer to be stored). +// +// The number of properties that will be enumerated should be returned as +// an integer jsval in *idp, if idp is non-null, and provided the number of +// enumerable properties is known. If idp is non-null and the number of +// enumerable properties can't be computed in advance, *idp should be set +// to JSVAL_ZERO. +// +// JSENUMERATE_INIT_ALL +// Used identically to JSENUMERATE_INIT, but exposes all properties of the +// object regardless of enumerability. +// +// JSENUMERATE_NEXT +// A previously allocated opaque iterator state is passed in via statep. +// Return the next jsid in the iteration using *idp. The opaque iterator +// state pointed at by statep is destroyed and *statep is set to JSVAL_NULL +// if there are no properties left to enumerate. +// +// JSENUMERATE_DESTROY +// Destroy the opaque iterator state previously allocated in *statep by a +// call to this function when enum_op was JSENUMERATE_INIT or +// JSENUMERATE_INIT_ALL. +// +// The return value is used to indicate success, with a value of false +// indicating failure. +typedef bool +(* JSNewEnumerateOp)(JSContext *cx, JS::Handle obj, JSIterateOp enum_op, + JS::MutableHandle statep, JS::MutableHandle idp); + +// The old-style JSClass.enumerate op should define all lazy properties not +// yet reflected in obj. +typedef bool +(* JSEnumerateOp)(JSContext *cx, JS::Handle obj); + +// Resolve a lazy property named by id in obj by defining it directly in obj. +// Lazy properties are those reflected from some peer native property space +// (e.g., the DOM attributes for a given node reflected as obj) on demand. +// +// JS looks for a property in an object, and if not found, tries to resolve +// the given id. If resolve succeeds, the engine looks again in case resolve +// defined obj[id]. If no such property exists directly in obj, the process +// is repeated with obj's prototype, etc. +// +// NB: JSNewResolveOp provides a cheaper way to resolve lazy properties. +typedef bool +(* JSResolveOp)(JSContext *cx, JS::Handle obj, JS::Handle id); + +// Like JSResolveOp, but flags provide contextual information as follows: +// +// JSRESOLVE_ASSIGNING obj[id] is on the left-hand side of an assignment +// +// The *objp out parameter, on success, should be null to indicate that id +// was not resolved; and non-null, referring to obj or one of its prototypes, +// if id was resolved. The hook may assume *objp is null on entry. +// +// This hook instead of JSResolveOp is called via the JSClass.resolve member +// if JSCLASS_NEW_RESOLVE is set in JSClass.flags. +typedef bool +(* JSNewResolveOp)(JSContext *cx, JS::Handle obj, JS::Handle id, unsigned flags, + JS::MutableHandle objp); + +// Convert obj to the given type, returning true with the resulting value in +// *vp on success, and returning false on error or exception. +typedef bool +(* JSConvertOp)(JSContext *cx, JS::Handle obj, JSType type, + JS::MutableHandle vp); + +// Finalize obj, which the garbage collector has determined to be unreachable +// from other live objects or from GC roots. Obviously, finalizers must never +// store a reference to obj. +typedef void +(* JSFinalizeOp)(JSFreeOp *fop, JSObject *obj); + +// Finalizes external strings created by JS_NewExternalString. +struct JSStringFinalizer { + void (*finalize)(const JSStringFinalizer *fin, jschar *chars); +}; + +// JSClass.checkAccess type: check whether obj[id] may be accessed per mode, +// returning false on error/exception, true on success with obj[id]'s last-got +// value in *vp, and its attributes in *attrsp. As for JSPropertyOp above, id +// is either a string or an int jsval. +typedef bool +(* JSCheckAccessOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + JSAccessMode mode, JS::MutableHandle vp); + +// Return whether the first principal subsumes the second. The exact meaning of +// 'subsumes' is left up to the browser. Subsumption is checked inside the JS +// engine when determining, e.g., which stack frames to display in a backtrace. +typedef bool +(* JSSubsumesOp)(JSPrincipals *first, JSPrincipals *second); + +// Check whether v is an instance of obj. Return false on error or exception, +// true on success with true in *bp if v is an instance of obj, false in +// *bp otherwise. +typedef bool +(* JSHasInstanceOp)(JSContext *cx, JS::Handle obj, JS::MutableHandle vp, + bool *bp); + +// Function type for trace operation of the class called to enumerate all +// traceable things reachable from obj's private data structure. For each such +// thing, a trace implementation must call one of the JS_Call*Tracer variants +// on the thing. +// +// JSTraceOp implementation can assume that no other threads mutates object +// state. It must not change state of the object or corresponding native +// structures. The only exception for this rule is the case when the embedding +// needs a tight integration with GC. In that case the embedding can check if +// the traversal is a part of the marking phase through calling +// JS_IsGCMarkingTracer and apply a special code like emptying caches or +// marking its native structures. +typedef void +(* JSTraceOp)(JSTracer *trc, JSObject *obj); + +// A generic type for functions mapping an object to another object, or null +// if an error or exception was thrown on cx. +typedef JSObject * +(* JSObjectOp)(JSContext *cx, JS::Handle obj); + +// Hook that creates an iterator object for a given object. Returns the +// iterator object or null if an error or exception was thrown on cx. +typedef JSObject * +(* JSIteratorOp)(JSContext *cx, JS::HandleObject obj, bool keysonly); + +typedef JSObject * +(* JSWeakmapKeyDelegateOp)(JSObject *obj); + +/* js::Class operation signatures. */ + +namespace js { + +typedef bool +(* LookupGenericOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* LookupPropOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* LookupElementOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* LookupSpecialOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* DefineGenericOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue value, + JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs); +typedef bool +(* DefinePropOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + JS::HandleValue value, JSPropertyOp getter, JSStrictPropertyOp setter, + unsigned attrs); +typedef bool +(* DefineElementOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, JS::HandleValue value, + JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs); +typedef bool +(* DefineSpecialOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, + JS::HandleValue value, JSPropertyOp getter, JSStrictPropertyOp setter, + unsigned attrs); +typedef bool +(* GenericIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, JS::HandleId id, + JS::MutableHandleValue vp); +typedef bool +(* PropertyIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, + JS::Handle name, JS::MutableHandleValue vp); +typedef bool +(* ElementIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, uint32_t index, + JS::MutableHandleValue vp); +typedef bool +(* ElementIfPresentOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, + uint32_t index, JS::MutableHandleValue vp, bool* present); +typedef bool +(* SpecialIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, + HandleSpecialId sid, JS::MutableHandleValue vp); +typedef bool +(* StrictGenericIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* StrictPropertyIdOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* StrictElementIdOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* StrictSpecialIdOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* GenericAttributesOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, unsigned *attrsp); +typedef bool +(* PropertyAttributesOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + unsigned *attrsp); +typedef bool +(* DeletePropertyOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + bool *succeeded); +typedef bool +(* DeleteElementOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, bool *succeeded); +typedef bool +(* DeleteSpecialOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, bool *succeeded); + +typedef bool +(* WatchOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); + +typedef bool +(* UnwatchOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id); + +typedef JSObject * +(* ObjectOp)(JSContext *cx, JS::HandleObject obj); +typedef void +(* FinalizeOp)(FreeOp *fop, JSObject *obj); + +#define JS_CLASS_MEMBERS \ + const char *name; \ + uint32_t flags; \ + \ + /* Mandatory function pointer members. */ \ + JSPropertyOp addProperty; \ + JSDeletePropertyOp delProperty; \ + JSPropertyOp getProperty; \ + JSStrictPropertyOp setProperty; \ + JSEnumerateOp enumerate; \ + JSResolveOp resolve; \ + JSConvertOp convert; \ + \ + /* Optional members (may be null). */ \ + FinalizeOp finalize; \ + JSCheckAccessOp checkAccess; \ + JSNative call; \ + JSHasInstanceOp hasInstance; \ + JSNative construct; \ + JSTraceOp trace + +/* + * The helper struct to measure the size of JS_CLASS_MEMBERS to know how much + * we have to pad js::Class to match the size of JSClass. + */ +struct ClassSizeMeasurement +{ + JS_CLASS_MEMBERS; +}; + +struct ClassExtension +{ + JSObjectOp outerObject; + JSObjectOp innerObject; + JSIteratorOp iteratorObject; + + /* + * isWrappedNative is true only if the class is an XPCWrappedNative. + * WeakMaps use this to override the wrapper disposal optimization. + */ + bool isWrappedNative; + + /* + * If an object is used as a key in a weakmap, it may be desirable for the + * garbage collector to keep that object around longer than it otherwise + * would. A common case is when the key is a wrapper around an object in + * another compartment, and we want to avoid collecting the wrapper (and + * removing the weakmap entry) as long as the wrapped object is alive. In + * that case, the wrapped object is returned by the wrapper's + * weakmapKeyDelegateOp hook. As long as the wrapper is used as a weakmap + * key, it will not be collected (and remain in the weakmap) until the + * wrapped object is collected. + */ + JSWeakmapKeyDelegateOp weakmapKeyDelegateOp; +}; + +#define JS_NULL_CLASS_EXT {nullptr,nullptr,nullptr,false,nullptr} + +struct ObjectOps +{ + LookupGenericOp lookupGeneric; + LookupPropOp lookupProperty; + LookupElementOp lookupElement; + LookupSpecialOp lookupSpecial; + DefineGenericOp defineGeneric; + DefinePropOp defineProperty; + DefineElementOp defineElement; + DefineSpecialOp defineSpecial; + GenericIdOp getGeneric; + PropertyIdOp getProperty; + ElementIdOp getElement; + ElementIfPresentOp getElementIfPresent; /* can be null */ + SpecialIdOp getSpecial; + StrictGenericIdOp setGeneric; + StrictPropertyIdOp setProperty; + StrictElementIdOp setElement; + StrictSpecialIdOp setSpecial; + GenericAttributesOp getGenericAttributes; + GenericAttributesOp setGenericAttributes; + DeletePropertyOp deleteProperty; + DeleteElementOp deleteElement; + DeleteSpecialOp deleteSpecial; + WatchOp watch; + UnwatchOp unwatch; + + JSNewEnumerateOp enumerate; + ObjectOp thisObject; +}; + +#define JS_NULL_OBJECT_OPS \ + {nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr, \ + nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr, \ + nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr} + +} // namespace js + +// Classes, objects, and properties. + +typedef void (*JSClassInternal)(); + +struct JSClass { + const char *name; + uint32_t flags; + + // Mandatory function pointer members. + JSPropertyOp addProperty; + JSDeletePropertyOp delProperty; + JSPropertyOp getProperty; + JSStrictPropertyOp setProperty; + JSEnumerateOp enumerate; + JSResolveOp resolve; + JSConvertOp convert; + + // Optional members (may be null). + JSFinalizeOp finalize; + JSCheckAccessOp checkAccess; + JSNative call; + JSHasInstanceOp hasInstance; + JSNative construct; + JSTraceOp trace; + + void *reserved[42]; +}; + +#define JSCLASS_HAS_PRIVATE (1<<0) // objects have private slot +#define JSCLASS_NEW_ENUMERATE (1<<1) // has JSNewEnumerateOp hook +#define JSCLASS_NEW_RESOLVE (1<<2) // has JSNewResolveOp hook +#define JSCLASS_PRIVATE_IS_NSISUPPORTS (1<<3) // private is (nsISupports *) +#define JSCLASS_IS_DOMJSCLASS (1<<4) // objects are DOM +#define JSCLASS_IMPLEMENTS_BARRIERS (1<<5) // Correctly implements GC read + // and write barriers +#define JSCLASS_EMULATES_UNDEFINED (1<<6) // objects of this class act + // like the value undefined, + // in some contexts +#define JSCLASS_USERBIT1 (1<<7) // Reserved for embeddings. + +// To reserve slots fetched and stored via JS_Get/SetReservedSlot, bitwise-or +// JSCLASS_HAS_RESERVED_SLOTS(n) into the initializer for JSClass.flags, where +// n is a constant in [1, 255]. Reserved slots are indexed from 0 to n-1. +#define JSCLASS_RESERVED_SLOTS_SHIFT 8 // room for 8 flags below */ +#define JSCLASS_RESERVED_SLOTS_WIDTH 8 // and 16 above this field */ +#define JSCLASS_RESERVED_SLOTS_MASK JS_BITMASK(JSCLASS_RESERVED_SLOTS_WIDTH) +#define JSCLASS_HAS_RESERVED_SLOTS(n) (((n) & JSCLASS_RESERVED_SLOTS_MASK) \ + << JSCLASS_RESERVED_SLOTS_SHIFT) +#define JSCLASS_RESERVED_SLOTS(clasp) (((clasp)->flags \ + >> JSCLASS_RESERVED_SLOTS_SHIFT) \ + & JSCLASS_RESERVED_SLOTS_MASK) + +#define JSCLASS_HIGH_FLAGS_SHIFT (JSCLASS_RESERVED_SLOTS_SHIFT + \ + JSCLASS_RESERVED_SLOTS_WIDTH) + +#define JSCLASS_IS_ANONYMOUS (1<<(JSCLASS_HIGH_FLAGS_SHIFT+0)) +#define JSCLASS_IS_GLOBAL (1<<(JSCLASS_HIGH_FLAGS_SHIFT+1)) +#define JSCLASS_INTERNAL_FLAG2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+2)) +#define JSCLASS_INTERNAL_FLAG3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+3)) + +// Indicate whether the proto or ctor should be frozen. +#define JSCLASS_FREEZE_PROTO (1<<(JSCLASS_HIGH_FLAGS_SHIFT+4)) +#define JSCLASS_FREEZE_CTOR (1<<(JSCLASS_HIGH_FLAGS_SHIFT+5)) + +// Reserved for embeddings. +#define JSCLASS_USERBIT2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+6)) +#define JSCLASS_USERBIT3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+7)) + +#define JSCLASS_BACKGROUND_FINALIZE (1<<(JSCLASS_HIGH_FLAGS_SHIFT+8)) + +// Bits 26 through 31 are reserved for the CACHED_PROTO_KEY mechanism, see +// below. + +// ECMA-262 requires that most constructors used internally create objects +// with "the original Foo.prototype value" as their [[Prototype]] (__proto__) +// member initial value. The "original ... value" verbiage is there because +// in ECMA-262, global properties naming class objects are read/write and +// deleteable, for the most part. +// +// Implementing this efficiently requires that global objects have classes +// with the following flags. Failure to use JSCLASS_GLOBAL_FLAGS was +// previously allowed, but is now an ES5 violation and thus unsupported. +// +#define JSCLASS_GLOBAL_SLOT_COUNT (3 + JSProto_LIMIT * 3 + 28) +#define JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(n) \ + (JSCLASS_IS_GLOBAL | JSCLASS_HAS_RESERVED_SLOTS(JSCLASS_GLOBAL_SLOT_COUNT + (n))) +#define JSCLASS_GLOBAL_FLAGS \ + JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(0) +#define JSCLASS_HAS_GLOBAL_FLAG_AND_SLOTS(clasp) \ + (((clasp)->flags & JSCLASS_IS_GLOBAL) \ + && JSCLASS_RESERVED_SLOTS(clasp) >= JSCLASS_GLOBAL_SLOT_COUNT) + +// Fast access to the original value of each standard class's prototype. +#define JSCLASS_CACHED_PROTO_SHIFT (JSCLASS_HIGH_FLAGS_SHIFT + 10) +#define JSCLASS_CACHED_PROTO_WIDTH 6 +#define JSCLASS_CACHED_PROTO_MASK JS_BITMASK(JSCLASS_CACHED_PROTO_WIDTH) +#define JSCLASS_HAS_CACHED_PROTO(key) (uint32_t(key) << JSCLASS_CACHED_PROTO_SHIFT) +#define JSCLASS_CACHED_PROTO_KEY(clasp) ((JSProtoKey) \ + (((clasp)->flags \ + >> JSCLASS_CACHED_PROTO_SHIFT) \ + & JSCLASS_CACHED_PROTO_MASK)) + +// Initializer for unused members of statically initialized JSClass structs. +#define JSCLASS_NO_INTERNAL_MEMBERS {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} +#define JSCLASS_NO_OPTIONAL_MEMBERS 0,0,0,0,0,JSCLASS_NO_INTERNAL_MEMBERS + +namespace js { + +struct Class +{ + JS_CLASS_MEMBERS; + ClassExtension ext; + ObjectOps ops; + uint8_t pad[sizeof(JSClass) - sizeof(ClassSizeMeasurement) - + sizeof(ClassExtension) - sizeof(ObjectOps)]; + + /* Class is not native and its map is not a scope. */ + static const uint32_t NON_NATIVE = JSCLASS_INTERNAL_FLAG2; + + bool isNative() const { + return !(flags & NON_NATIVE); + } + + bool hasPrivate() const { + return !!(flags & JSCLASS_HAS_PRIVATE); + } + + bool emulatesUndefined() const { + return flags & JSCLASS_EMULATES_UNDEFINED; + } + + bool isCallable() const { + return this == js::FunctionClassPtr || call; + } + + static size_t offsetOfFlags() { return offsetof(Class, flags); } +}; + +JS_STATIC_ASSERT(offsetof(JSClass, name) == offsetof(Class, name)); +JS_STATIC_ASSERT(offsetof(JSClass, flags) == offsetof(Class, flags)); +JS_STATIC_ASSERT(offsetof(JSClass, addProperty) == offsetof(Class, addProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, delProperty) == offsetof(Class, delProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, getProperty) == offsetof(Class, getProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, setProperty) == offsetof(Class, setProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, enumerate) == offsetof(Class, enumerate)); +JS_STATIC_ASSERT(offsetof(JSClass, resolve) == offsetof(Class, resolve)); +JS_STATIC_ASSERT(offsetof(JSClass, convert) == offsetof(Class, convert)); +JS_STATIC_ASSERT(offsetof(JSClass, finalize) == offsetof(Class, finalize)); +JS_STATIC_ASSERT(offsetof(JSClass, checkAccess) == offsetof(Class, checkAccess)); +JS_STATIC_ASSERT(offsetof(JSClass, call) == offsetof(Class, call)); +JS_STATIC_ASSERT(offsetof(JSClass, construct) == offsetof(Class, construct)); +JS_STATIC_ASSERT(offsetof(JSClass, hasInstance) == offsetof(Class, hasInstance)); +JS_STATIC_ASSERT(offsetof(JSClass, trace) == offsetof(Class, trace)); +JS_STATIC_ASSERT(sizeof(JSClass) == sizeof(Class)); + +static JS_ALWAYS_INLINE const JSClass * +Jsvalify(const Class *c) +{ + return (const JSClass *)c; +} + +static JS_ALWAYS_INLINE const Class * +Valueify(const JSClass *c) +{ + return (const Class *)c; +} + +/* + * Enumeration describing possible values of the [[Class]] internal property + * value of objects. + */ +enum ESClassValue { + ESClass_Array, ESClass_Number, ESClass_String, ESClass_Boolean, + ESClass_RegExp, ESClass_ArrayBuffer, ESClass_Date +}; + +/* + * Return whether the given object has the given [[Class]] internal property + * value. Beware, this query says nothing about the js::Class of the JSObject + * so the caller must not assume anything about obj's representation (e.g., obj + * may be a proxy). + */ +inline bool +ObjectClassIs(JSObject &obj, ESClassValue classValue, JSContext *cx); + +/* Just a helper that checks v.isObject before calling ObjectClassIs. */ +inline bool +IsObjectWithClass(const JS::Value &v, ESClassValue classValue, JSContext *cx); + +inline bool +IsPoisonedSpecialId(js::SpecialId iden) +{ + if (iden.isObject()) + return JS::IsPoisonedPtr(iden.toObject()); + return false; +} + +template <> struct GCMethods +{ + static SpecialId initial() { return SpecialId(); } + static ThingRootKind kind() { return THING_ROOT_ID; } + static bool poisoned(SpecialId id) { return IsPoisonedSpecialId(id); } +}; + +} /* namespace js */ + +#endif /* js_Class_h */ diff --git a/external/spidermonkey/include/mac/js/GCAPI.h b/external/spidermonkey/include/mac/js/GCAPI.h index a9bef77c09..9cdf56bcce 100644 --- a/external/spidermonkey/include/mac/js/GCAPI.h +++ b/external/spidermonkey/include/mac/js/GCAPI.h @@ -7,7 +7,11 @@ #ifndef js_GCAPI_h #define js_GCAPI_h +#include "mozilla/NullPtr.h" + #include "js/HeapAPI.h" +#include "js/RootingAPI.h" +#include "js/Value.h" namespace JS { @@ -15,13 +19,12 @@ namespace JS { /* Reasons internal to the JS engine */ \ D(API) \ D(MAYBEGC) \ - D(LAST_CONTEXT) \ + D(DESTROY_RUNTIME) \ D(DESTROY_CONTEXT) \ D(LAST_DITCH) \ D(TOO_MUCH_MALLOC) \ D(ALLOC_TRIGGER) \ D(DEBUG_GC) \ - D(DEBUG_MODE_GC) \ D(TRANSPLANT) \ D(RESET) \ D(OUT_OF_NURSERY) \ @@ -206,12 +209,25 @@ PokeGC(JSRuntime *rt); extern JS_FRIEND_API(bool) WasIncrementalGC(JSRuntime *rt); -class ObjectPtr +extern JS_FRIEND_API(size_t) +GetGCNumber(); + +class AutoAssertNoGC { +#ifdef DEBUG + size_t gcNumber; + + public: + AutoAssertNoGC(); + ~AutoAssertNoGC(); +#endif +}; + +class JS_PUBLIC_API(ObjectPtr) { Heap value; public: - ObjectPtr() : value(NULL) {} + ObjectPtr() : value(nullptr) {} ObjectPtr(JSObject *obj) : value(obj) {} @@ -221,7 +237,7 @@ class ObjectPtr void finalize(JSRuntime *rt) { if (IsIncrementalBarrierNeeded(rt)) IncrementalObjectBarrier(value); - value = NULL; + value = nullptr; } void init(JSObject *obj) { value = obj; } @@ -232,9 +248,7 @@ class ObjectPtr IncrementalObjectBarrier(value); } - bool isAboutToBeFinalized() { - return JS_IsAboutToBeFinalized(&value); - } + bool isAboutToBeFinalized(); ObjectPtr &operator=(JSObject *obj) { IncrementalObjectBarrier(value); @@ -242,9 +256,7 @@ class ObjectPtr return *this; } - void trace(JSTracer *trc, const char *name) { - JS_CallHeapObjectTracer(trc, &value, name); - } + void trace(JSTracer *trc, const char *name); JSObject &operator*() const { return *value; } JSObject *operator->() const { return value; } @@ -255,7 +267,7 @@ class ObjectPtr * Unsets the gray bit for anything reachable from |thing|. |kind| should not be * JSTRACE_SHAPE. |thing| should be non-null. */ -extern JS_FRIEND_API(void) +extern JS_FRIEND_API(bool) UnmarkGrayGCThingRecursively(void *thing, JSGCTraceKind kind); /* @@ -276,7 +288,7 @@ ExposeGCThingToActiveJS(void *thing, JSGCTraceKind kind) * All live objects in the nursery are moved to tenured at the beginning of * each GC slice, so the gray marker never sees nursery things. */ - if (uintptr_t(thing) >= rt->gcNurseryStart_ && uintptr_t(thing) < rt->gcNurseryEnd_) + if (js::gc::IsInsideNursery(rt, thing)) return; #endif if (IsIncrementalBarrierNeededOnGCThing(rt, thing, kind)) @@ -292,6 +304,37 @@ ExposeValueToActiveJS(const Value &v) ExposeGCThingToActiveJS(v.toGCThing(), v.gcKind()); } +static JS_ALWAYS_INLINE void +ExposeObjectToActiveJS(JSObject *obj) +{ + ExposeGCThingToActiveJS(obj, JSTRACE_OBJECT); +} + +/* + * If a GC is currently marking, mark the object black. + */ +static JS_ALWAYS_INLINE void +MarkGCThingAsLive(JSRuntime *rt_, void *thing, JSGCTraceKind kind) +{ + shadow::Runtime *rt = shadow::Runtime::asShadowRuntime(rt_); +#ifdef JSGC_GENERATIONAL + /* + * Any object in the nursery will not be freed during any GC running at that time. + */ + if (js::gc::IsInsideNursery(rt, thing)) + return; +#endif + if (IsIncrementalBarrierNeededOnGCThing(rt, thing, kind)) + IncrementalReferenceBarrier(thing, kind); +} + +static JS_ALWAYS_INLINE void +MarkStringAsLive(Zone *zone, JSString *string) +{ + JSRuntime *rt = JS::shadow::Zone::asShadowZone(zone)->runtimeFromMainThread(); + MarkGCThingAsLive(rt, string, JSTRACE_STRING); +} + } /* namespace JS */ #endif /* js_GCAPI_h */ diff --git a/external/spidermonkey/include/mac/js/HashTable.h b/external/spidermonkey/include/mac/js/HashTable.h index aa05b71472..a6b4361dea 100644 --- a/external/spidermonkey/include/mac/js/HashTable.h +++ b/external/spidermonkey/include/mac/js/HashTable.h @@ -7,17 +7,18 @@ #ifndef js_HashTable_h #define js_HashTable_h +#include "mozilla/Alignment.h" #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Casting.h" #include "mozilla/DebugOnly.h" #include "mozilla/MemoryReporting.h" #include "mozilla/Move.h" +#include "mozilla/NullPtr.h" #include "mozilla/PodOperations.h" #include "mozilla/ReentrancyGuard.h" #include "mozilla/TemplateLib.h" #include "mozilla/TypeTraits.h" -#include "mozilla/Util.h" #include "js/Utility.h" @@ -60,7 +61,7 @@ class HashMap { typedef Key KeyType; static const Key &getKey(TableEntry &e) { return e.key; } - static void setKey(TableEntry &e, Key &k) { const_cast(e.key) = k; } + static void setKey(TableEntry &e, Key &k) { HashPolicy::rekey(const_cast(e.key), k); } }; typedef detail::HashTable Impl; @@ -138,18 +139,18 @@ class HashMap template bool add(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.add(p, mozilla::Move(e)); + return impl.add(p, mozilla::OldMove(e)); } bool add(AddPtr &p, const Key &k) { Entry e(k, Value()); - return impl.add(p, mozilla::Move(e)); + return impl.add(p, mozilla::OldMove(e)); } template bool relookupOrAdd(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.relookupOrAdd(p, k, mozilla::Move(e)); + return impl.relookupOrAdd(p, k, mozilla::OldMove(e)); } // |all()| returns a Range containing |count()| elements. E.g.: @@ -213,7 +214,7 @@ class HashMap /************************************************** Shorthand operations */ bool has(const Lookup &l) const { - return impl.lookup(l) != NULL; + return impl.lookup(l) != nullptr; } // Overwrite existing value with v. Return false on oom. @@ -231,7 +232,7 @@ class HashMap template bool putNew(const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.putNew(k, mozilla::Move(e)); + return impl.putNew(k, mozilla::OldMove(e)); } // Add (k,defaultValue) if |k| is not found. Return a false-y Ptr on oom. @@ -249,17 +250,22 @@ class HashMap remove(p); } + // Infallibly rekey one entry, if necessary. + // Requires template parameters Key and HashPolicy::Lookup to be the same type. + void rekeyIfMoved(const Key &old_key, const Key &new_key) { + if (old_key != new_key) + rekeyAs(old_key, new_key, new_key); + } + // Infallibly rekey one entry, if present. - void rekey(const Lookup &old_key, const Key &new_key) { - if (old_key != new_key) { - if (Ptr p = lookup(old_key)) - impl.rekey(p, new_key, new_key); - } + void rekeyAs(const Lookup &old_lookup, const Lookup &new_lookup, const Key &new_key) { + if (Ptr p = lookup(old_lookup)) + impl.rekeyAndMaybeRehash(p, new_lookup, new_key); } // HashMap is movable - HashMap(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} - void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } + HashMap(mozilla::MoveRef rhs) : impl(mozilla::OldMove(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::OldMove(rhs->impl); } private: // HashMap is not copyable or assignable @@ -295,7 +301,7 @@ class HashSet { typedef T KeyType; static const KeyType &getKey(const T &t) { return t; } - static void setKey(T &t, KeyType &k) { t = k; } + static void setKey(T &t, KeyType &k) { HashPolicy::rekey(t, k); } }; typedef detail::HashTable Impl; @@ -323,6 +329,10 @@ class HashSet typedef typename Impl::Ptr Ptr; Ptr lookup(const Lookup &l) const { return impl.lookup(l); } + // Like lookup, but does not assert if two threads call lookup at the same + // time. Only use this method when none of the threads will modify the map. + Ptr readonlyThreadsafeLookup(const Lookup &l) const { return impl.readonlyThreadsafeLookup(l); } + // Assuming |p.found()|, remove |*p|. void remove(Ptr p) { impl.remove(p); } @@ -425,7 +435,7 @@ class HashSet /************************************************** Shorthand operations */ bool has(const Lookup &l) const { - return impl.lookup(l) != NULL; + return impl.lookup(l) != nullptr; } // Overwrite existing value with v. Return false on oom. @@ -449,16 +459,21 @@ class HashSet } // Infallibly rekey one entry, if present. - void rekey(const Lookup &old_key, const T &new_key) { - if (old_key != new_key) { - if (Ptr p = lookup(old_key)) - impl.rekey(p, new_key, new_key); - } + // Requires template parameters T and HashPolicy::Lookup to be the same type. + void rekeyIfMoved(const Lookup &old_value, const T &new_value) { + if (old_value != new_value) + rekeyAs(old_value, new_value, new_value); + } + + // Infallibly rekey one entry, if present. + void rekeyAs(const Lookup &old_lookup, const Lookup &new_lookup, const T &new_value) { + if (Ptr p = lookup(old_lookup)) + impl.rekeyAndMaybeRehash(p, new_lookup, new_value); } // HashSet is movable - HashSet(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} - void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } + HashSet(mozilla::MoveRef rhs) : impl(mozilla::OldMove(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::OldMove(rhs->impl); } private: // HashSet is not copyable or assignable @@ -505,7 +520,7 @@ struct PointerHasher JS_ASSERT(!JS::IsPoisonedPtr(l)); size_t word = reinterpret_cast(l) >> zeroBits; JS_STATIC_ASSERT(sizeof(HashNumber) == 4); -#if JS_BYTES_PER_WORD == 4 +#if JS_BITS_PER_WORD == 32 return HashNumber(word); #else JS_STATIC_ASSERT(sizeof word == 8); @@ -517,6 +532,9 @@ struct PointerHasher JS_ASSERT(!JS::IsPoisonedPtr(l)); return k == l; } + static void rekey(Key &k, const Key& newKey) { + k = newKey; + } }; // Default hash policy: just use the 'lookup' value. This of course only @@ -535,6 +553,9 @@ struct DefaultHasher // Use builtin or overloaded operator==. return k == l; } + static void rekey(Key &k, const Key& newKey) { + k = newKey; + } }; // Specialize hashing policy for pointer types. It assumes that the type is @@ -558,6 +579,19 @@ struct DefaultHasher } }; +template <> +struct DefaultHasher +{ + typedef float Lookup; + static HashNumber hash(float f) { + JS_STATIC_ASSERT(sizeof(HashNumber) == 4); + return HashNumber(mozilla::BitwiseCast(f)); + } + static bool match(float lhs, float rhs) { + return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); + } +}; + /*****************************************************************************/ // Both HashMap and HashSet are implemented by a single HashTable that is even @@ -579,7 +613,7 @@ class HashMapEntry HashMapEntry(const KeyInput &k, const ValueInput &v) : key(k), value(v) {} HashMapEntry(mozilla::MoveRef rhs) - : key(mozilla::Move(rhs->key)), value(mozilla::Move(rhs->value)) { } + : key(mozilla::OldMove(rhs->key)), value(mozilla::OldMove(rhs->value)) { } typedef Key KeyType; typedef Value ValueType; @@ -750,7 +784,7 @@ class HashTable : private AllocPolicy mozilla::DebugOnly validEntry; public: - Range() : cur(NULL), end(NULL), validEntry(false) {} + Range() : cur(nullptr), end(nullptr), validEntry(false) {} bool empty() const { return cur == end; @@ -808,7 +842,7 @@ class HashTable : private AllocPolicy // a new key at the new Lookup position. |front()| is invalid after // this operation until the next call to |popFront()|. void rekeyFront(const Lookup &l, const Key &k) { - table.rekey(*this->cur, l, k); + table.rekeyWithoutRehash(*this->cur, l, k); rekeyed = true; this->validEntry = false; } @@ -834,13 +868,13 @@ class HashTable : private AllocPolicy : AllocPolicy(*rhs) { mozilla::PodAssign(this, &*rhs); - rhs->table = NULL; + rhs->table = nullptr; } void operator=(mozilla::MoveRef rhs) { if (table) destroyTable(*this, table, capacity()); mozilla::PodAssign(this, &*rhs); - rhs->table = NULL; + rhs->table = nullptr; } private: @@ -941,7 +975,7 @@ class HashTable : private AllocPolicy entryCount(0), gen(0), removedCount(0), - table(NULL), + table(nullptr), entered(false), mutationCount(0) {} @@ -1067,7 +1101,7 @@ class HashTable : private AllocPolicy DoubleHash dh = hash2(keyHash); // Save the first removed entry pointer so we can recycle later. - Entry *firstRemoved = NULL; + Entry *firstRemoved = nullptr; while(true) { if (JS_UNLIKELY(entry->isRemoved())) { @@ -1163,7 +1197,7 @@ class HashTable : private AllocPolicy for (Entry *src = oldTable, *end = src + oldCap; src < end; ++src) { if (src->isLive()) { HashNumber hn = src->getKeyHash(); - findFreeEntry(hn).setLive(hn, mozilla::Move(src->get())); + findFreeEntry(hn).setLive(hn, mozilla::OldMove(src->get())); src->destroy(); } } @@ -1307,7 +1341,7 @@ class HashTable : private AllocPolicy return; destroyTable(*this, table, capacity()); - table = NULL; + table = nullptr; gen++; entryCount = 0; removedCount = 0; @@ -1456,15 +1490,21 @@ class HashTable : private AllocPolicy checkUnderloaded(); } - void rekey(Ptr p, const Lookup &l, const Key &k) + void rekeyWithoutRehash(Ptr p, const Lookup &l, const Key &k) { JS_ASSERT(table); mozilla::ReentrancyGuard g(*this); JS_ASSERT(p.found()); - typename HashTableEntry::NonConstT t(mozilla::Move(*p)); + typename HashTableEntry::NonConstT t(mozilla::OldMove(*p)); HashPolicy::setKey(t, const_cast(k)); remove(*p.entry_); - putNewInfallible(l, mozilla::Move(t)); + putNewInfallible(l, mozilla::OldMove(t)); + } + + void rekeyAndMaybeRehash(Ptr p, const Lookup &l, const Key &k) + { + rekeyWithoutRehash(p, l, k); + checkOverRemoved(); } #undef METER diff --git a/external/spidermonkey/include/mac/js/HeapAPI.h b/external/spidermonkey/include/mac/js/HeapAPI.h index 4d739304bc..438c23c05f 100644 --- a/external/spidermonkey/include/mac/js/HeapAPI.h +++ b/external/spidermonkey/include/mac/js/HeapAPI.h @@ -7,12 +7,23 @@ #ifndef js_HeapAPI_h #define js_HeapAPI_h +#include + #include "jspubtd.h" #include "js/Utility.h" /* These values are private to the JS engine. */ namespace js { + +// Whether the current thread is permitted access to any part of the specified +// runtime or zone. +JS_FRIEND_API(bool) +CurrentThreadCanAccessRuntime(JSRuntime *rt); + +JS_FRIEND_API(bool) +CurrentThreadCanAccessZone(JS::Zone *zone); + namespace gc { const size_t ArenaShift = 12; @@ -57,9 +68,43 @@ struct ArenaHeader struct Zone { + protected: + JSRuntime *const runtime_; + JSTracer *const barrierTracer_; // A pointer to the JSRuntime's |gcMarker|. + + public: bool needsBarrier_; - Zone() : needsBarrier_(false) {} + Zone(JSRuntime *runtime, JSTracer *barrierTracerArg) + : runtime_(runtime), + barrierTracer_(barrierTracerArg), + needsBarrier_(false) + {} + + bool needsBarrier() const { + return needsBarrier_; + } + + JSTracer *barrierTracer() { + JS_ASSERT(needsBarrier_); + JS_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); + return barrierTracer_; + } + + JSRuntime *runtimeFromMainThread() const { + JS_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); + return runtime_; + } + + // Note: Unrestricted access to the zone's runtime from an arbitrary + // thread can easily lead to races. Use this method very carefully. + JSRuntime *runtimeFromAnyThread() const { + return runtime_; + } + + static JS::shadow::Zone *asShadowZone(JS::Zone *zone) { + return reinterpret_cast(zone); + } }; } /* namespace shadow */ @@ -94,8 +139,9 @@ GetGCThingMarkWordAndMask(const void *thing, uint32_t color, size_t bit = (addr & js::gc::ChunkMask) / js::gc::CellSize + color; JS_ASSERT(bit < js::gc::ChunkMarkBitmapBits); uintptr_t *bitmap = GetGCThingMarkBitmap(thing); - *maskp = uintptr_t(1) << (bit % JS_BITS_PER_WORD); - *wordp = &bitmap[bit / JS_BITS_PER_WORD]; + const uintptr_t nbits = sizeof(*bitmap) * CHAR_BIT; + *maskp = uintptr_t(1) << (bit % nbits); + *wordp = &bitmap[bit / nbits]; } static JS_ALWAYS_INLINE JS::shadow::ArenaHeader * @@ -106,6 +152,16 @@ GetGCThingArena(void *thing) return reinterpret_cast(addr); } +JS_ALWAYS_INLINE bool +IsInsideNursery(const JS::shadow::Runtime *runtime, const void *p) +{ +#ifdef JSGC_GENERATIONAL + return uintptr_t(p) >= runtime->gcNurseryStart_ && uintptr_t(p) < runtime->gcNurseryEnd_; +#else + return false; +#endif +} + } /* namespace gc */ } /* namespace js */ @@ -128,6 +184,16 @@ GetObjectZone(JSObject *obj) static JS_ALWAYS_INLINE bool GCThingIsMarkedGray(void *thing) { +#ifdef JSGC_GENERATIONAL + /* + * GC things residing in the nursery cannot be gray: they have no mark bits. + * All live objects in the nursery are moved to tenured at the beginning of + * each GC slice, so the gray marker never sees nursery things. + */ + JS::shadow::Runtime *rt = js::gc::GetGCThingRuntime(thing); + if (js::gc::IsInsideNursery(rt, thing)) + return false; +#endif uintptr_t *word, mask; js::gc::GetGCThingMarkWordAndMask(thing, js::gc::GRAY, &word, &mask); return *word & mask; diff --git a/external/spidermonkey/include/mac/js/Id.h b/external/spidermonkey/include/mac/js/Id.h new file mode 100644 index 0000000000..447deb62e6 --- /dev/null +++ b/external/spidermonkey/include/mac/js/Id.h @@ -0,0 +1,192 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_Id_h +#define js_Id_h + +// A jsid is an identifier for a property or method of an object which is +// either a 31-bit signed integer, interned string or object. +// +// Also, there is an additional jsid value, JSID_VOID, which does not occur in +// JS scripts but may be used to indicate the absence of a valid jsid. A void +// jsid is not a valid id and only arises as an exceptional API return value, +// such as in JS_NextProperty. Embeddings must not pass JSID_VOID into JSAPI +// entry points expecting a jsid and do not need to handle JSID_VOID in hooks +// receiving a jsid except when explicitly noted in the API contract. +// +// A jsid is not implicitly convertible to or from a jsval; JS_ValueToId or +// JS_IdToValue must be used instead. + +#include "mozilla/NullPtr.h" + +#include "jstypes.h" + +#include "js/RootingAPI.h" +#include "js/TypeDecls.h" +#include "js/Utility.h" + +#ifdef JS_USE_JSID_STRUCT_TYPES +struct jsid +{ + size_t asBits; + bool operator==(jsid rhs) const { return asBits == rhs.asBits; } + bool operator!=(jsid rhs) const { return asBits != rhs.asBits; } +}; +# define JSID_BITS(id) (id.asBits) +#else +# define JSID_BITS(id) (id) +#endif + +#define JSID_TYPE_STRING 0x0 +#define JSID_TYPE_INT 0x1 +#define JSID_TYPE_VOID 0x2 +#define JSID_TYPE_OBJECT 0x4 +#define JSID_TYPE_MASK 0x7 + +// Avoid using canonical 'id' for jsid parameters since this is a magic word in +// Objective-C++ which, apparently, wants to be able to #include jsapi.h. +#define id iden + +static JS_ALWAYS_INLINE bool +JSID_IS_STRING(jsid id) +{ + return (JSID_BITS(id) & JSID_TYPE_MASK) == 0; +} + +static JS_ALWAYS_INLINE JSString * +JSID_TO_STRING(jsid id) +{ + JS_ASSERT(JSID_IS_STRING(id)); + return (JSString *)JSID_BITS(id); +} + +static JS_ALWAYS_INLINE bool +JSID_IS_ZERO(jsid id) +{ + return JSID_BITS(id) == 0; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_INT(jsid id) +{ + return !!(JSID_BITS(id) & JSID_TYPE_INT); +} + +static JS_ALWAYS_INLINE int32_t +JSID_TO_INT(jsid id) +{ + JS_ASSERT(JSID_IS_INT(id)); + return ((uint32_t)JSID_BITS(id)) >> 1; +} + +#define JSID_INT_MIN 0 +#define JSID_INT_MAX INT32_MAX + +static JS_ALWAYS_INLINE bool +INT_FITS_IN_JSID(int32_t i) +{ + return i >= 0; +} + +static JS_ALWAYS_INLINE jsid +INT_TO_JSID(int32_t i) +{ + jsid id; + JS_ASSERT(INT_FITS_IN_JSID(i)); + JSID_BITS(id) = ((i << 1) | JSID_TYPE_INT); + return id; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_OBJECT(jsid id) +{ + return (JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_OBJECT && + (size_t)JSID_BITS(id) != JSID_TYPE_OBJECT; +} + +static JS_ALWAYS_INLINE JSObject * +JSID_TO_OBJECT(jsid id) +{ + JS_ASSERT(JSID_IS_OBJECT(id)); + return (JSObject *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); +} + +static JS_ALWAYS_INLINE jsid +OBJECT_TO_JSID(JSObject *obj) +{ + jsid id; + JS_ASSERT(obj != nullptr); + JS_ASSERT(((size_t)obj & JSID_TYPE_MASK) == 0); + JSID_BITS(id) = ((size_t)obj | JSID_TYPE_OBJECT); + return id; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_GCTHING(jsid id) +{ + return JSID_IS_STRING(id) || JSID_IS_OBJECT(id); +} + +static JS_ALWAYS_INLINE void * +JSID_TO_GCTHING(jsid id) +{ + return (void *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); +} + +static JS_ALWAYS_INLINE bool +JSID_IS_VOID(const jsid id) +{ + JS_ASSERT_IF(((size_t)JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_VOID, + JSID_BITS(id) == JSID_TYPE_VOID); + return ((size_t)JSID_BITS(id) == JSID_TYPE_VOID); +} + +static JS_ALWAYS_INLINE bool +JSID_IS_EMPTY(const jsid id) +{ + return ((size_t)JSID_BITS(id) == JSID_TYPE_OBJECT); +} + +#undef id + +#ifdef JS_USE_JSID_STRUCT_TYPES +extern JS_PUBLIC_DATA(const jsid) JSID_VOID; +extern JS_PUBLIC_DATA(const jsid) JSID_EMPTY; +#else +# define JSID_VOID ((jsid)JSID_TYPE_VOID) +# define JSID_EMPTY ((jsid)JSID_TYPE_OBJECT) +#endif + +extern JS_PUBLIC_DATA(const JS::Handle) JSID_VOIDHANDLE; +extern JS_PUBLIC_DATA(const JS::Handle) JSID_EMPTYHANDLE; + +namespace js { + +inline bool +IsPoisonedId(jsid iden) +{ + if (JSID_IS_STRING(iden)) + return JS::IsPoisonedPtr(JSID_TO_STRING(iden)); + if (JSID_IS_OBJECT(iden)) + return JS::IsPoisonedPtr(JSID_TO_OBJECT(iden)); + return false; +} + +template <> struct GCMethods +{ + static jsid initial() { return JSID_VOID; } + static ThingRootKind kind() { return THING_ROOT_ID; } + static bool poisoned(jsid id) { return IsPoisonedId(id); } + static bool needsPostBarrier(jsid id) { return false; } +#ifdef JSGC_GENERATIONAL + static void postBarrier(jsid *idp) {} + static void relocate(jsid *idp) {} +#endif +}; + +} + +#endif /* js_Id_h */ diff --git a/external/spidermonkey/include/mac/js/MemoryMetrics.h b/external/spidermonkey/include/mac/js/MemoryMetrics.h index ed61e1c427..2336e35624 100644 --- a/external/spidermonkey/include/mac/js/MemoryMetrics.h +++ b/external/spidermonkey/include/mac/js/MemoryMetrics.h @@ -7,20 +7,54 @@ #ifndef js_MemoryMetrics_h #define js_MemoryMetrics_h -// These declarations are not within jsapi.h because they are highly likely to -// change in the future. Depend on them at your own risk. +// These declarations are highly likely to change in the future. Depend on them +// at your own risk. #include "mozilla/MemoryReporting.h" +#include "mozilla/NullPtr.h" +#include "mozilla/PodOperations.h" #include #include "jsalloc.h" #include "jspubtd.h" +#include "js/HashTable.h" #include "js/Utility.h" #include "js/Vector.h" -class nsISupports; // This is needed for ObjectPrivateVisitor. +class nsISupports; // Needed for ObjectPrivateVisitor. + +namespace JS { + +struct TabSizes +{ + enum Kind { + Objects, + Strings, + Private, + Other + }; + + TabSizes() { mozilla::PodZero(this); } + + void add(Kind kind, size_t n) { + switch (kind) { + case Objects: objects += n; break; + case Strings: strings += n; break; + case Private: private_ += n; break; + case Other: other += n; break; + default: MOZ_CRASH("bad TabSizes kind"); + } + } + + size_t objects; + size_t strings; + size_t private_; + size_t other; +}; + +} // namespace JS namespace js { @@ -30,9 +64,86 @@ namespace js { // MemoryReportingSundriesThreshold() bytes. // // We need to define this value here, rather than in the code which actually -// generates the memory reports, because HugeStringInfo uses this value. +// generates the memory reports, because NotableStringInfo uses this value. JS_FRIEND_API(size_t) MemoryReportingSundriesThreshold(); +// This hash policy avoids flattening ropes (which perturbs the site being +// measured and requires a JSContext) at the expense of doing a FULL ROPE COPY +// on every hash and match! Beware. +struct InefficientNonFlatteningStringHashPolicy +{ + typedef JSString *Lookup; + static HashNumber hash(const Lookup &l); + static bool match(const JSString *const &k, const Lookup &l); +}; + +// This file features many classes with numerous size_t fields, and each such +// class has one or more methods that need to operate on all of these fields. +// Writing these individually is error-prone -- it's easy to add a new field +// without updating all the required methods. So we define a single macro list +// in each class to name the fields (and notable characteristics of them), and +// then use the following macros to transform those lists into the required +// methods. +// +// In some classes, one or more of the macro arguments aren't used. We use '_' +// for those. +// +#define DECL_SIZE(kind, gc, mSize) size_t mSize; +#define ZERO_SIZE(kind, gc, mSize) mSize(0), +#define COPY_OTHER_SIZE(kind, gc, mSize) mSize(other.mSize), +#define ADD_OTHER_SIZE(kind, gc, mSize) mSize += other.mSize; +#define ADD_SIZE_TO_N_IF_LIVE_GC_THING(kind, gc, mSize) n += (js::gc == js::IsLiveGCThing) ? mSize : 0; +#define ADD_TO_TAB_SIZES(kind, gc, mSize) sizes->add(JS::TabSizes::kind, mSize); + +// Used to annotate which size_t fields measure live GC things and which don't. +enum { + NotLiveGCThing = false, + IsLiveGCThing = true +}; + +struct ZoneStatsPod +{ +#define FOR_EACH_SIZE(macro) \ + macro(Other, NotLiveGCThing, gcHeapArenaAdmin) \ + macro(Other, NotLiveGCThing, unusedGCThings) \ + macro(Other, IsLiveGCThing, lazyScriptsGCHeap) \ + macro(Other, NotLiveGCThing, lazyScriptsMallocHeap) \ + macro(Other, IsLiveGCThing, ionCodesGCHeap) \ + macro(Other, IsLiveGCThing, typeObjectsGCHeap) \ + macro(Other, NotLiveGCThing, typeObjectsMallocHeap) \ + macro(Other, NotLiveGCThing, typePool) \ + macro(Strings, IsLiveGCThing, stringsShortGCHeap) \ + macro(Strings, IsLiveGCThing, stringsNormalGCHeap) \ + macro(Strings, NotLiveGCThing, stringsNormalMallocHeap) + + ZoneStatsPod() + : FOR_EACH_SIZE(ZERO_SIZE) + extra() + {} + + void add(const ZoneStatsPod &other) { + FOR_EACH_SIZE(ADD_OTHER_SIZE) + // Do nothing with |extra|. + } + + size_t sizeOfLiveGCThings() const { + size_t n = 0; + FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) + // Do nothing with |extra|. + return n; + } + + void addToTabSizes(JS::TabSizes *sizes) const { + FOR_EACH_SIZE(ADD_TO_TAB_SIZES) + // Do nothing with |extra|. + } + + FOR_EACH_SIZE(DECL_SIZE) + void *extra; // This field can be used by embedders. + +#undef FOR_EACH_SIZE +}; + } // namespace js namespace JS { @@ -40,352 +151,320 @@ namespace JS { // Data for tracking memory usage of things hanging off objects. struct ObjectsExtraSizes { - size_t slots; - size_t elementsNonAsmJS; - size_t elementsAsmJSHeap; - size_t elementsAsmJSNonHeap; - size_t argumentsData; - size_t regExpStatics; - size_t propertyIteratorData; - size_t ctypesData; - size_t private_; // The '_' suffix is required because |private| is a keyword. - // Note that this field is measured separately from the others. +#define FOR_EACH_SIZE(macro) \ + macro(Objects, NotLiveGCThing, mallocHeapSlots) \ + macro(Objects, NotLiveGCThing, mallocHeapElementsNonAsmJS) \ + macro(Objects, NotLiveGCThing, mallocHeapElementsAsmJS) \ + macro(Objects, NotLiveGCThing, nonHeapElementsAsmJS) \ + macro(Objects, NotLiveGCThing, nonHeapCodeAsmJS) \ + macro(Objects, NotLiveGCThing, mallocHeapAsmJSModuleData) \ + macro(Objects, NotLiveGCThing, mallocHeapArgumentsData) \ + macro(Objects, NotLiveGCThing, mallocHeapRegExpStatics) \ + macro(Objects, NotLiveGCThing, mallocHeapPropertyIteratorData) \ + macro(Objects, NotLiveGCThing, mallocHeapCtypesData) - ObjectsExtraSizes() { memset(this, 0, sizeof(ObjectsExtraSizes)); } + ObjectsExtraSizes() + : FOR_EACH_SIZE(ZERO_SIZE) + dummy() + {} - void add(ObjectsExtraSizes &sizes) { - this->slots += sizes.slots; - this->elementsNonAsmJS += sizes.elementsNonAsmJS; - this->elementsAsmJSHeap += sizes.elementsAsmJSHeap; - this->elementsAsmJSNonHeap += sizes.elementsAsmJSNonHeap; - this->argumentsData += sizes.argumentsData; - this->regExpStatics += sizes.regExpStatics; - this->propertyIteratorData += sizes.propertyIteratorData; - this->ctypesData += sizes.ctypesData; - this->private_ += sizes.private_; + void add(const ObjectsExtraSizes &other) { + FOR_EACH_SIZE(ADD_OTHER_SIZE) } -}; -// Data for tracking analysis/inference memory usage. -struct TypeInferenceSizes -{ - size_t typeScripts; - size_t typeResults; - size_t analysisPool; - size_t pendingArrays; - size_t allocationSiteTables; - size_t arrayTypeTables; - size_t objectTypeTables; - - TypeInferenceSizes() { memset(this, 0, sizeof(TypeInferenceSizes)); } - - void add(TypeInferenceSizes &sizes) { - this->typeScripts += sizes.typeScripts; - this->typeResults += sizes.typeResults; - this->analysisPool += sizes.analysisPool; - this->pendingArrays += sizes.pendingArrays; - this->allocationSiteTables += sizes.allocationSiteTables; - this->arrayTypeTables += sizes.arrayTypeTables; - this->objectTypeTables += sizes.objectTypeTables; + size_t sizeOfLiveGCThings() const { + size_t n = 0; + FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) + return n; } + + void addToTabSizes(TabSizes *sizes) const { + FOR_EACH_SIZE(ADD_TO_TAB_SIZES) + } + + FOR_EACH_SIZE(DECL_SIZE) + int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) + +#undef FOR_EACH_SIZE }; // Data for tracking JIT-code memory usage. struct CodeSizes { - size_t ion; - size_t asmJS; - size_t baseline; - size_t regexp; - size_t other; - size_t unused; +#define FOR_EACH_SIZE(macro) \ + macro(_, _, ion) \ + macro(_, _, baseline) \ + macro(_, _, regexp) \ + macro(_, _, other) \ + macro(_, _, unused) - CodeSizes() { memset(this, 0, sizeof(CodeSizes)); } + CodeSizes() + : FOR_EACH_SIZE(ZERO_SIZE) + dummy() + {} + + FOR_EACH_SIZE(DECL_SIZE) + int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) + +#undef FOR_EACH_SIZE }; -// Holds data about a huge string (one which uses more HugeStringInfo::MinSize -// bytes of memory), so we can report it individually. -struct HugeStringInfo +// This class holds information about the memory taken up by identical copies of +// a particular string. Multiple JSStrings may have their sizes aggregated +// together into one StringInfo object. +struct StringInfo { - HugeStringInfo() : length(0), size(0) { memset(&buffer, 0, sizeof(buffer)); } + StringInfo() + : length(0), numCopies(0), shortGCHeap(0), normalGCHeap(0), normalMallocHeap(0) + {} + + StringInfo(size_t len, size_t shorts, size_t normals, size_t chars) + : length(len), + numCopies(1), + shortGCHeap(shorts), + normalGCHeap(normals), + normalMallocHeap(chars) + {} + + void add(size_t shorts, size_t normals, size_t chars) { + shortGCHeap += shorts; + normalGCHeap += normals; + normalMallocHeap += chars; + numCopies++; + } + + void add(const StringInfo& info) { + MOZ_ASSERT(length == info.length); + + shortGCHeap += info.shortGCHeap; + normalGCHeap += info.normalGCHeap; + normalMallocHeap += info.normalMallocHeap; + numCopies += info.numCopies; + } + + size_t totalSizeOf() const { + return shortGCHeap + normalGCHeap + normalMallocHeap; + } + + size_t totalGCHeapSizeOf() const { + return shortGCHeap + normalGCHeap; + } + + // The string's length, excluding the null-terminator. + size_t length; + + // How many copies of the string have we seen? + size_t numCopies; + + // These are all totals across all copies of the string we've seen. + size_t shortGCHeap; + size_t normalGCHeap; + size_t normalMallocHeap; +}; + +// Holds data about a notable string (one which uses more than +// NotableStringInfo::notableSize() bytes of memory), so we can report it +// individually. +// +// Essentially the only difference between this class and StringInfo is that +// NotableStringInfo holds a copy of the string's chars. +struct NotableStringInfo : public StringInfo +{ + NotableStringInfo(); + NotableStringInfo(JSString *str, const StringInfo &info); + NotableStringInfo(mozilla::MoveRef info); + NotableStringInfo &operator=(mozilla::MoveRef info); + + ~NotableStringInfo() { + js_free(buffer); + } // A string needs to take up this many bytes of storage before we consider - // it to be "huge". - static size_t MinSize() { + // it to be "notable". + static size_t notableSize() { return js::MemoryReportingSundriesThreshold(); } - // A string's size in memory is not necessarily equal to twice its length - // because the allocator and the JS engine both may round up. - size_t length; - size_t size; + char *buffer; - // We record the first 32 chars of the escaped string here. (We escape the - // string so we can use a char[] instead of a jschar[] here. - char buffer[32]; + private: + NotableStringInfo(const NotableStringInfo& info) MOZ_DELETE; }; -// These measurements relate directly to the JSRuntime, and not to +// These measurements relate directly to the JSRuntime, and not to zones and // compartments within it. struct RuntimeSizes { - RuntimeSizes() { memset(this, 0, sizeof(RuntimeSizes)); } +#define FOR_EACH_SIZE(macro) \ + macro(_, _, object) \ + macro(_, _, atomsTable) \ + macro(_, _, contexts) \ + macro(_, _, dtoa) \ + macro(_, _, temporary) \ + macro(_, _, regexpData) \ + macro(_, _, interpreterStack) \ + macro(_, _, gcMarker) \ + macro(_, _, mathCache) \ + macro(_, _, scriptData) \ + macro(_, _, scriptSources) - size_t object; - size_t atomsTable; - size_t contexts; - size_t dtoa; - size_t temporary; - size_t regexpData; - size_t interpreterStack; - size_t gcMarker; - size_t mathCache; - size_t scriptData; - size_t scriptSources; - - CodeSizes code; -}; - -struct ZoneStats -{ - ZoneStats() - : extra(NULL), - gcHeapArenaAdmin(0), - gcHeapUnusedGcThings(0), - gcHeapStringsNormal(0), - gcHeapStringsShort(0), - gcHeapLazyScripts(0), - gcHeapTypeObjects(0), - gcHeapIonCodes(0), - stringCharsNonHuge(0), - lazyScripts(0), - typeObjects(0), - typePool(0), - hugeStrings() + RuntimeSizes() + : FOR_EACH_SIZE(ZERO_SIZE) + code() {} - ZoneStats(const ZoneStats &other) - : extra(other.extra), - gcHeapArenaAdmin(other.gcHeapArenaAdmin), - gcHeapUnusedGcThings(other.gcHeapUnusedGcThings), - gcHeapStringsNormal(other.gcHeapStringsNormal), - gcHeapStringsShort(other.gcHeapStringsShort), - gcHeapLazyScripts(other.gcHeapLazyScripts), - gcHeapTypeObjects(other.gcHeapTypeObjects), - gcHeapIonCodes(other.gcHeapIonCodes), - stringCharsNonHuge(other.stringCharsNonHuge), - lazyScripts(other.lazyScripts), - typeObjects(other.typeObjects), - typePool(other.typePool), - hugeStrings() - { - hugeStrings.appendAll(other.hugeStrings); + FOR_EACH_SIZE(DECL_SIZE) + CodeSizes code; + +#undef FOR_EACH_SIZE +}; + +struct ZoneStats : js::ZoneStatsPod +{ + ZoneStats() { + strings.init(); } - // Add other's numbers to this object's numbers. - void add(ZoneStats &other) { - #define ADD(x) this->x += other.x + ZoneStats(mozilla::MoveRef other) + : ZoneStatsPod(other), + strings(mozilla::OldMove(other->strings)), + notableStrings(mozilla::OldMove(other->notableStrings)) + {} - ADD(gcHeapArenaAdmin); - ADD(gcHeapUnusedGcThings); + // Add other's numbers to this object's numbers. Both objects' + // notableStrings vectors must be empty at this point, because we can't + // merge them. (A NotableStringInfo contains only a prefix of the string, + // so we can't tell whether two NotableStringInfo objects correspond to the + // same string.) + void add(const ZoneStats &other) { + ZoneStatsPod::add(other); - ADD(gcHeapStringsNormal); - ADD(gcHeapStringsShort); - ADD(gcHeapLazyScripts); - ADD(gcHeapTypeObjects); - ADD(gcHeapIonCodes); + MOZ_ASSERT(notableStrings.empty()); + MOZ_ASSERT(other.notableStrings.empty()); - ADD(stringCharsNonHuge); - ADD(lazyScripts); - ADD(typeObjects); - ADD(typePool); - - #undef ADD - - hugeStrings.appendAll(other.hugeStrings); + for (StringsHashMap::Range r = other.strings.all(); !r.empty(); r.popFront()) { + StringsHashMap::AddPtr p = strings.lookupForAdd(r.front().key); + if (p) { + // We've seen this string before; add its size to our tally. + p->value.add(r.front().value); + } else { + // We haven't seen this string before; add it to the hashtable. + strings.add(p, r.front().key, r.front().value); + } + } } - // This field can be used by embedders. - void *extra; + size_t sizeOfLiveGCThings() const { + size_t n = ZoneStatsPod::sizeOfLiveGCThings(); + for (size_t i = 0; i < notableStrings.length(); i++) { + const JS::NotableStringInfo& info = notableStrings[i]; + n += info.totalGCHeapSizeOf(); + } + return n; + } - size_t gcHeapArenaAdmin; - size_t gcHeapUnusedGcThings; + typedef js::HashMap StringsHashMap; - size_t gcHeapStringsNormal; - size_t gcHeapStringsShort; - - size_t gcHeapLazyScripts; - size_t gcHeapTypeObjects; - size_t gcHeapIonCodes; - - size_t stringCharsNonHuge; - size_t lazyScripts; - size_t typeObjects; - size_t typePool; - - js::Vector hugeStrings; - - // The size of all the live things in the GC heap that don't belong to any - // compartment. - size_t GCHeapThingsSize(); + StringsHashMap strings; + js::Vector notableStrings; }; struct CompartmentStats { +#define FOR_EACH_SIZE(macro) \ + macro(Objects, IsLiveGCThing, objectsGCHeapOrdinary) \ + macro(Objects, IsLiveGCThing, objectsGCHeapFunction) \ + macro(Objects, IsLiveGCThing, objectsGCHeapDenseArray) \ + macro(Objects, IsLiveGCThing, objectsGCHeapSlowArray) \ + macro(Objects, IsLiveGCThing, objectsGCHeapCrossCompartmentWrapper) \ + macro(Private, NotLiveGCThing, objectsPrivate) \ + macro(Other, IsLiveGCThing, shapesGCHeapTreeGlobalParented) \ + macro(Other, IsLiveGCThing, shapesGCHeapTreeNonGlobalParented) \ + macro(Other, IsLiveGCThing, shapesGCHeapDict) \ + macro(Other, IsLiveGCThing, shapesGCHeapBase) \ + macro(Other, NotLiveGCThing, shapesMallocHeapTreeTables) \ + macro(Other, NotLiveGCThing, shapesMallocHeapDictTables) \ + macro(Other, NotLiveGCThing, shapesMallocHeapTreeShapeKids) \ + macro(Other, NotLiveGCThing, shapesMallocHeapCompartmentTables) \ + macro(Other, IsLiveGCThing, scriptsGCHeap) \ + macro(Other, NotLiveGCThing, scriptsMallocHeapData) \ + macro(Other, NotLiveGCThing, baselineData) \ + macro(Other, NotLiveGCThing, baselineStubsFallback) \ + macro(Other, NotLiveGCThing, baselineStubsOptimized) \ + macro(Other, NotLiveGCThing, ionData) \ + macro(Other, NotLiveGCThing, typeInferenceTypeScripts) \ + macro(Other, NotLiveGCThing, typeInferencePendingArrays) \ + macro(Other, NotLiveGCThing, typeInferenceAllocationSiteTables) \ + macro(Other, NotLiveGCThing, typeInferenceArrayTypeTables) \ + macro(Other, NotLiveGCThing, typeInferenceObjectTypeTables) \ + macro(Other, NotLiveGCThing, compartmentObject) \ + macro(Other, NotLiveGCThing, crossCompartmentWrappersTable) \ + macro(Other, NotLiveGCThing, regexpCompartment) \ + macro(Other, NotLiveGCThing, debuggeesSet) + CompartmentStats() - : extra(NULL), - gcHeapObjectsOrdinary(0), - gcHeapObjectsFunction(0), - gcHeapObjectsDenseArray(0), - gcHeapObjectsSlowArray(0), - gcHeapObjectsCrossCompartmentWrapper(0), - gcHeapShapesTreeGlobalParented(0), - gcHeapShapesTreeNonGlobalParented(0), - gcHeapShapesDict(0), - gcHeapShapesBase(0), - gcHeapScripts(0), + : FOR_EACH_SIZE(ZERO_SIZE) objectsExtra(), - shapesExtraTreeTables(0), - shapesExtraDictTables(0), - shapesExtraTreeShapeKids(0), - shapesCompartmentTables(0), - scriptData(0), - baselineData(0), - baselineStubsFallback(0), - baselineStubsOptimized(0), - ionData(0), - compartmentObject(0), - crossCompartmentWrappersTable(0), - regexpCompartment(0), - debuggeesSet(0), - typeInference() + extra() {} CompartmentStats(const CompartmentStats &other) - : extra(other.extra), - gcHeapObjectsOrdinary(other.gcHeapObjectsOrdinary), - gcHeapObjectsFunction(other.gcHeapObjectsFunction), - gcHeapObjectsDenseArray(other.gcHeapObjectsDenseArray), - gcHeapObjectsSlowArray(other.gcHeapObjectsSlowArray), - gcHeapObjectsCrossCompartmentWrapper(other.gcHeapObjectsCrossCompartmentWrapper), - gcHeapShapesTreeGlobalParented(other.gcHeapShapesTreeGlobalParented), - gcHeapShapesTreeNonGlobalParented(other.gcHeapShapesTreeNonGlobalParented), - gcHeapShapesDict(other.gcHeapShapesDict), - gcHeapShapesBase(other.gcHeapShapesBase), - gcHeapScripts(other.gcHeapScripts), + : FOR_EACH_SIZE(COPY_OTHER_SIZE) objectsExtra(other.objectsExtra), - shapesExtraTreeTables(other.shapesExtraTreeTables), - shapesExtraDictTables(other.shapesExtraDictTables), - shapesExtraTreeShapeKids(other.shapesExtraTreeShapeKids), - shapesCompartmentTables(other.shapesCompartmentTables), - scriptData(other.scriptData), - baselineData(other.baselineData), - baselineStubsFallback(other.baselineStubsFallback), - baselineStubsOptimized(other.baselineStubsOptimized), - ionData(other.ionData), - compartmentObject(other.compartmentObject), - crossCompartmentWrappersTable(other.crossCompartmentWrappersTable), - regexpCompartment(other.regexpCompartment), - debuggeesSet(other.debuggeesSet), - typeInference(other.typeInference) - { + extra(other.extra) + {} + + void add(const CompartmentStats &other) { + FOR_EACH_SIZE(ADD_OTHER_SIZE) + objectsExtra.add(other.objectsExtra); + // Do nothing with |extra|. } - // This field can be used by embedders. - void *extra; - - // If you add a new number, remember to update the constructors, add(), and - // maybe gcHeapThingsSize()! - size_t gcHeapObjectsOrdinary; - size_t gcHeapObjectsFunction; - size_t gcHeapObjectsDenseArray; - size_t gcHeapObjectsSlowArray; - size_t gcHeapObjectsCrossCompartmentWrapper; - size_t gcHeapShapesTreeGlobalParented; - size_t gcHeapShapesTreeNonGlobalParented; - size_t gcHeapShapesDict; - size_t gcHeapShapesBase; - size_t gcHeapScripts; - ObjectsExtraSizes objectsExtra; - - size_t shapesExtraTreeTables; - size_t shapesExtraDictTables; - size_t shapesExtraTreeShapeKids; - size_t shapesCompartmentTables; - size_t scriptData; - size_t baselineData; - size_t baselineStubsFallback; - size_t baselineStubsOptimized; - size_t ionData; - size_t compartmentObject; - size_t crossCompartmentWrappersTable; - size_t regexpCompartment; - size_t debuggeesSet; - - TypeInferenceSizes typeInference; - - // Add cStats's numbers to this object's numbers. - void add(CompartmentStats &cStats) { - #define ADD(x) this->x += cStats.x - - ADD(gcHeapObjectsOrdinary); - ADD(gcHeapObjectsFunction); - ADD(gcHeapObjectsDenseArray); - ADD(gcHeapObjectsSlowArray); - ADD(gcHeapObjectsCrossCompartmentWrapper); - ADD(gcHeapShapesTreeGlobalParented); - ADD(gcHeapShapesTreeNonGlobalParented); - ADD(gcHeapShapesDict); - ADD(gcHeapShapesBase); - ADD(gcHeapScripts); - objectsExtra.add(cStats.objectsExtra); - - ADD(shapesExtraTreeTables); - ADD(shapesExtraDictTables); - ADD(shapesExtraTreeShapeKids); - ADD(shapesCompartmentTables); - ADD(scriptData); - ADD(baselineData); - ADD(baselineStubsFallback); - ADD(baselineStubsOptimized); - ADD(ionData); - ADD(compartmentObject); - ADD(crossCompartmentWrappersTable); - ADD(regexpCompartment); - ADD(debuggeesSet); - - #undef ADD - - typeInference.add(cStats.typeInference); + size_t sizeOfLiveGCThings() const { + size_t n = 0; + FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) + n += objectsExtra.sizeOfLiveGCThings(); + // Do nothing with |extra|. + return n; } - // The size of all the live things in the GC heap. - size_t GCHeapThingsSize(); + void addToTabSizes(TabSizes *sizes) const { + FOR_EACH_SIZE(ADD_TO_TAB_SIZES); + objectsExtra.addToTabSizes(sizes); + // Do nothing with |extra|. + } + + FOR_EACH_SIZE(DECL_SIZE) + ObjectsExtraSizes objectsExtra; + void *extra; // This field can be used by embedders. + +#undef FOR_EACH_SIZE }; struct RuntimeStats { +#define FOR_EACH_SIZE(macro) \ + macro(_, _, gcHeapChunkTotal) \ + macro(_, _, gcHeapDecommittedArenas) \ + macro(_, _, gcHeapUnusedChunks) \ + macro(_, _, gcHeapUnusedArenas) \ + macro(_, _, gcHeapChunkAdmin) \ + macro(_, _, gcHeapGCThings) \ + RuntimeStats(mozilla::MallocSizeOf mallocSizeOf) - : runtime(), - gcHeapChunkTotal(0), - gcHeapDecommittedArenas(0), - gcHeapUnusedChunks(0), - gcHeapUnusedArenas(0), - gcHeapUnusedGcThings(0), - gcHeapChunkAdmin(0), - gcHeapGcThings(0), + : FOR_EACH_SIZE(ZERO_SIZE) + runtime(), cTotals(), zTotals(), compartmentStatsVector(), zoneStatsVector(), - currZoneStats(NULL), + currZoneStats(nullptr), mallocSizeOf_(mallocSizeOf) {} - RuntimeSizes runtime; - - // If you add a new number, remember to update the constructor! - // Here's a useful breakdown of the GC heap. // // - rtStats.gcHeapChunkTotal @@ -394,28 +473,24 @@ struct RuntimeStats // - unused bytes // - rtStats.gcHeapUnusedChunks (empty chunks) // - rtStats.gcHeapUnusedArenas (empty arenas within non-empty chunks) - // - rtStats.total.gcHeapUnusedGcThings (empty GC thing slots within non-empty arenas) + // - rtStats.zTotals.unusedGCThings (empty GC thing slots within non-empty arenas) // - used bytes // - rtStats.gcHeapChunkAdmin - // - rtStats.total.gcHeapArenaAdmin - // - rtStats.gcHeapGcThings (in-use GC things) + // - rtStats.zTotals.gcHeapArenaAdmin + // - rtStats.gcHeapGCThings (in-use GC things) + // == rtStats.zTotals.sizeOfLiveGCThings() + rtStats.cTotals.sizeOfLiveGCThings() // // It's possible that some arenas in empty chunks may be decommitted, but // we don't count those under rtStats.gcHeapDecommittedArenas because (a) // it's rare, and (b) this means that rtStats.gcHeapUnusedChunks is a // multiple of the chunk size, which is good. - size_t gcHeapChunkTotal; - size_t gcHeapDecommittedArenas; - size_t gcHeapUnusedChunks; - size_t gcHeapUnusedArenas; - size_t gcHeapUnusedGcThings; - size_t gcHeapChunkAdmin; - size_t gcHeapGcThings; + FOR_EACH_SIZE(DECL_SIZE) - // The sum of all compartment's measurements. - CompartmentStats cTotals; - ZoneStats zTotals; + RuntimeSizes runtime; + + CompartmentStats cTotals; // The sum of this runtime's compartments' measurements. + ZoneStats zTotals; // The sum of this runtime's zones' measurements. js::Vector compartmentStatsVector; js::Vector zoneStatsVector; @@ -426,6 +501,8 @@ struct RuntimeStats virtual void initExtraCompartmentStats(JSCompartment *c, CompartmentStats *cstats) = 0; virtual void initExtraZoneStats(JS::Zone *zone, ZoneStats *zstats) = 0; + +#undef FOR_EACH_SIZE }; class ObjectPrivateVisitor @@ -437,7 +514,7 @@ class ObjectPrivateVisitor // A callback that gets a JSObject's nsISupports pointer, if it has one. // Note: this function does *not* addref |iface|. - typedef JSBool(*GetISupportsFun)(JSObject *obj, nsISupports **iface); + typedef bool(*GetISupportsFun)(JSObject *obj, nsISupports **iface); GetISupportsFun getISupports_; ObjectPrivateVisitor(GetISupportsFun getISupports) @@ -457,6 +534,17 @@ UserCompartmentCount(JSRuntime *rt); extern JS_PUBLIC_API(size_t) PeakSizeOfTemporary(const JSRuntime *rt); +extern JS_PUBLIC_API(bool) +AddSizeOfTab(JSRuntime *rt, JSObject *obj, mozilla::MallocSizeOf mallocSizeOf, + ObjectPrivateVisitor *opv, TabSizes *sizes); + } // namespace JS +#undef DECL_SIZE +#undef ZERO_SIZE +#undef COPY_OTHER_SIZE +#undef ADD_OTHER_SIZE +#undef ADD_SIZE_TO_N_IF_LIVE_GC_THING +#undef ADD_TO_TAB_SIZES + #endif /* js_MemoryMetrics_h */ diff --git a/external/spidermonkey/include/mac/jsdbgapi.h b/external/spidermonkey/include/mac/js/OldDebugAPI.h similarity index 77% rename from external/spidermonkey/include/mac/jsdbgapi.h rename to external/spidermonkey/include/mac/js/OldDebugAPI.h index 0ce7101337..5e5bdf38d7 100644 --- a/external/spidermonkey/include/mac/jsdbgapi.h +++ b/external/spidermonkey/include/mac/js/OldDebugAPI.h @@ -4,13 +4,24 @@ * 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/. */ -#ifndef jsdbgapi_h -#define jsdbgapi_h +#ifndef js_OldDebugAPI_h +#define js_OldDebugAPI_h + /* * JS debugger API. */ -#include "jsprvtd.h" +#include "mozilla/NullPtr.h" + +#include "jsbytecode.h" + +#include "js/CallArgs.h" +#include "js/TypeDecls.h" + +class JSAtom; +class JSFreeOp; + +namespace js { class StackFrame; } namespace JS { @@ -34,21 +45,68 @@ extern JS_PUBLIC_API(void) FreeStackDescription(JSContext *cx, StackDescription *desc); extern JS_PUBLIC_API(char *) -FormatStackDump(JSContext *cx, char *buf, - JSBool showArgs, JSBool showLocals, - JSBool showThisProps); +FormatStackDump(JSContext *cx, char *buf, bool showArgs, bool showLocals, bool showThisProps); } # ifdef DEBUG -JS_FRIEND_API(void) js_DumpValue(const js::Value &val); +JS_FRIEND_API(void) js_DumpValue(const JS::Value &val); JS_FRIEND_API(void) js_DumpId(jsid id); -JS_FRIEND_API(void) js_DumpStackFrame(JSContext *cx, js::StackFrame *start = NULL); +JS_FRIEND_API(void) js_DumpStackFrame(JSContext *cx, js::StackFrame *start = nullptr); # endif JS_FRIEND_API(void) js_DumpBacktrace(JSContext *cx); +typedef enum JSTrapStatus { + JSTRAP_ERROR, + JSTRAP_CONTINUE, + JSTRAP_RETURN, + JSTRAP_THROW, + JSTRAP_LIMIT +} JSTrapStatus; + +typedef JSTrapStatus +(* JSTrapHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + JS::Value closure); + +typedef JSTrapStatus +(* JSInterruptHook)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + void *closure); + +typedef JSTrapStatus +(* JSDebuggerHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + void *closure); + +typedef JSTrapStatus +(* JSThrowHook)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + void *closure); + +typedef bool +(* JSWatchPointHandler)(JSContext *cx, JSObject *obj, jsid id, JS::Value old, + JS::Value *newp, void *closure); + +/* called just after script creation */ +typedef void +(* JSNewScriptHook)(JSContext *cx, + const char *filename, /* URL of script */ + unsigned lineno, /* first line */ + JSScript *script, + JSFunction *fun, + void *callerdata); + +/* called just before script destruction */ +typedef void +(* JSDestroyScriptHook)(JSFreeOp *fop, + JSScript *script, + void *callerdata); + +typedef void +(* JSSourceHandler)(const char *filename, unsigned lineno, const jschar *str, + size_t length, void **listenerTSData, void *closure); + + + extern JS_PUBLIC_API(JSCompartment *) JS_EnterCompartmentOfScript(JSContext *cx, JSScript *target); @@ -60,7 +118,7 @@ JS_DecompileScript(JSContext *cx, JSScript *script, const char *name, unsigned i * be able to support compartment-wide debugging. */ extern JS_PUBLIC_API(void) -JS_SetRuntimeDebugMode(JSRuntime *rt, JSBool debug); +JS_SetRuntimeDebugMode(JSRuntime *rt, bool debug); /* * Debug mode is a compartment-wide mode that enables a debugger to attach @@ -73,42 +131,42 @@ JS_SetRuntimeDebugMode(JSRuntime *rt, JSBool debug); */ /* Get current state of debugging mode. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_GetDebugMode(JSContext *cx); /* * Turn on/off debugging mode for all compartments. This returns false if any code * from any of the runtime's compartments is running or on the stack. */ -JS_FRIEND_API(JSBool) -JS_SetDebugModeForAllCompartments(JSContext *cx, JSBool debug); +JS_FRIEND_API(bool) +JS_SetDebugModeForAllCompartments(JSContext *cx, bool debug); /* * Turn on/off debugging mode for a single compartment. This should only be * used when no code from this compartment is running or on the stack in any * thread. */ -JS_FRIEND_API(JSBool) -JS_SetDebugModeForCompartment(JSContext *cx, JSCompartment *comp, JSBool debug); +JS_FRIEND_API(bool) +JS_SetDebugModeForCompartment(JSContext *cx, JSCompartment *comp, bool debug); /* * Turn on/off debugging mode for a context's compartment. */ -JS_FRIEND_API(JSBool) -JS_SetDebugMode(JSContext *cx, JSBool debug); +JS_FRIEND_API(bool) +JS_SetDebugMode(JSContext *cx, bool debug); /* Turn on single step mode. */ -extern JS_PUBLIC_API(JSBool) -JS_SetSingleStepMode(JSContext *cx, JSScript *script, JSBool singleStep); +extern JS_PUBLIC_API(bool) +JS_SetSingleStepMode(JSContext *cx, JSScript *script, bool singleStep); /* The closure argument will be marked. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetTrap(JSContext *cx, JSScript *script, jsbytecode *pc, - JSTrapHandler handler, jsval closure); + JSTrapHandler handler, JS::Value closure); extern JS_PUBLIC_API(void) JS_ClearTrap(JSContext *cx, JSScript *script, jsbytecode *pc, - JSTrapHandler *handlerp, jsval *closurep); + JSTrapHandler *handlerp, JS::Value *closurep); extern JS_PUBLIC_API(void) JS_ClearScriptTraps(JSRuntime *rt, JSScript *script); @@ -116,28 +174,25 @@ JS_ClearScriptTraps(JSRuntime *rt, JSScript *script); extern JS_PUBLIC_API(void) JS_ClearAllTrapsForCompartment(JSContext *cx); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetInterrupt(JSRuntime *rt, JSInterruptHook handler, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_ClearInterrupt(JSRuntime *rt, JSInterruptHook *handlerp, void **closurep); /************************************************************************/ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetWatchPoint(JSContext *cx, JSObject *obj, jsid id, JSWatchPointHandler handler, JSObject *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_ClearWatchPoint(JSContext *cx, JSObject *obj, jsid id, JSWatchPointHandler *handlerp, JSObject **closurep); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_ClearWatchPointsForObject(JSContext *cx, JSObject *obj); -extern JS_PUBLIC_API(JSBool) -JS_ClearAllWatchPoints(JSContext *cx); - /************************************************************************/ // Raw JSScript* because this needs to be callable from a signal handler. @@ -150,7 +205,7 @@ JS_LineNumberToPC(JSContext *cx, JSScript *script, unsigned lineno); extern JS_PUBLIC_API(jsbytecode *) JS_EndPC(JSContext *cx, JSScript *script); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_GetLinePCs(JSContext *cx, JSScript *script, unsigned startLine, unsigned maxLines, unsigned* count, unsigned** lines, jsbytecode*** pcs); @@ -158,7 +213,7 @@ JS_GetLinePCs(JSContext *cx, JSScript *script, extern JS_PUBLIC_API(unsigned) JS_GetFunctionArgumentCount(JSContext *cx, JSFunction *fun); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_FunctionHasLocalNames(JSContext *cx, JSFunction *fun); /* @@ -230,9 +285,8 @@ JS_GetScriptIsSelfHosted(JSScript *script); /************************************************************************/ /* - * Hook setters for script creation and destruction, see jsprvtd.h for the - * typedefs. These macros provide binary compatibility and newer, shorter - * synonyms. + * Hook setters for script creation and destruction. These macros provide + * binary compatibility and newer, shorter synonyms. */ #define JS_SetNewScriptHook JS_SetNewScriptHookProc #define JS_SetDestroyScriptHook JS_SetDestroyScriptHookProc @@ -247,11 +301,11 @@ JS_SetDestroyScriptHook(JSRuntime *rt, JSDestroyScriptHook hook, /************************************************************************/ typedef struct JSPropertyDesc { - jsval id; /* primary id, atomized string, or int */ - jsval value; /* property value */ + JS::Value id; /* primary id, atomized string, or int */ + JS::Value value; /* property value */ uint8_t flags; /* flags, see below */ uint8_t spare; /* unused */ - jsval alias; /* alias id if JSPD_ALIAS flag */ + JS::Value alias; /* alias id if JSPD_ALIAS flag */ } JSPropertyDesc; #define JSPD_ENUMERATE 0x01 /* visible to for/in loop */ @@ -260,7 +314,7 @@ typedef struct JSPropertyDesc { #define JSPD_ALIAS 0x08 /* property has an alias id */ #define JSPD_EXCEPTION 0x40 /* exception occurred fetching the property, */ /* value is exception */ -#define JSPD_ERROR 0x80 /* native getter returned JS_FALSE without */ +#define JSPD_ERROR 0x80 /* native getter returned false without */ /* throwing an exception */ typedef struct JSPropertyDescArray { @@ -270,7 +324,7 @@ typedef struct JSPropertyDescArray { typedef struct JSScopeProperty JSScopeProperty; -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_GetPropertyDescArray(JSContext *cx, JSObject *obj, JSPropertyDescArray *pda); extern JS_PUBLIC_API(void) @@ -358,8 +412,8 @@ class JS_PUBLIC_API(JSBrokenFrameIterator) * or function call: just before execution begins and just after it finishes. * In both cases the 'current' frame is that of the executing code. * - * The 'before' param is JS_TRUE for the hook invocation before the execution - * and JS_FALSE for the invocation after the code has run. + * The 'before' param is true for the hook invocation before the execution + * and false for the invocation after the code has run. * * The 'ok' param is significant only on the post execution invocation to * signify whether or not the code completed 'normally'. @@ -373,14 +427,14 @@ class JS_PUBLIC_API(JSBrokenFrameIterator) * in 'closure' to cause the 'after' invocation to be called with the same * 'closure' value as the 'before'. * - * Returning NULL in the 'before' hook will cause the 'after' hook *not* to + * Returning nullptr in the 'before' hook will cause the 'after' hook *not* to * be called. */ typedef void * (* JSInterpreterHook)(JSContext *cx, JSAbstractFramePtr frame, bool isConstructing, - JSBool before, JSBool *ok, void *closure); + bool before, bool *ok, void *closure); -typedef JSBool +typedef bool (* JSDebugErrorHook)(JSContext *cx, const char *message, JSErrorReport *report, void *closure); @@ -407,22 +461,22 @@ typedef struct JSDebugHooks { /************************************************************************/ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetDebuggerHandler(JSRuntime *rt, JSDebuggerHandler hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetSourceHandler(JSRuntime *rt, JSSourceHandler handler, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetExecuteHook(JSRuntime *rt, JSInterpreterHook hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetCallHook(JSRuntime *rt, JSInterpreterHook hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetThrowHook(JSRuntime *rt, JSThrowHook hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetDebugErrorHook(JSRuntime *rt, JSDebugErrorHook hook, void *closure); /************************************************************************/ @@ -433,11 +487,11 @@ JS_GetGlobalDebugHooks(JSRuntime *rt); /** * Add various profiling-related functions as properties of the given object. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_DefineProfilingFunctions(JSContext *cx, JSObject *obj); /* Defined in vm/Debugger.cpp. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_DefineDebuggerObject(JSContext *cx, JSObject *obj); extern JS_PUBLIC_API(void) @@ -452,8 +506,13 @@ JS_DumpPCCounts(JSContext *cx, JSScript *script); extern JS_PUBLIC_API(void) JS_DumpCompartmentPCCounts(JSContext *cx); +namespace js { +extern JS_FRIEND_API(bool) +CanCallContextDebugHandler(JSContext *cx); +} + /* Call the context debug handler on the topmost scripted frame. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_CallContextDebugHandler(JSContext *cx); -#endif /* jsdbgapi_h */ +#endif /* js_OldDebugAPI_h */ diff --git a/external/spidermonkey/include/mac/js/ProfilingStack.h b/external/spidermonkey/include/mac/js/ProfilingStack.h new file mode 100644 index 0000000000..c67f98952c --- /dev/null +++ b/external/spidermonkey/include/mac/js/ProfilingStack.h @@ -0,0 +1,95 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_ProfilingStack_h +#define js_ProfilingStack_h + +#include "mozilla/NullPtr.h" + +#include "jsbytecode.h" +#include "jstypes.h" + +#include "js/Utility.h" + +struct JSRuntime; + +namespace js { + +// A call stack can be specified to the JS engine such that all JS entry/exits +// to functions push/pop an entry to/from the specified stack. +// +// For more detailed information, see vm/SPSProfiler.h. +// +class ProfileEntry +{ + // All fields are marked volatile to prevent the compiler from re-ordering + // instructions. Namely this sequence: + // + // entry[size] = ...; + // size++; + // + // If the size modification were somehow reordered before the stores, then + // if a sample were taken it would be examining bogus information. + // + // A ProfileEntry represents both a C++ profile entry and a JS one. Both use + // the string as a description, but JS uses the sp as nullptr to indicate + // that it is a JS entry. The script_ is then only ever examined for a JS + // entry, and the idx is used by both, but with different meanings. + // + const char * volatile string; // Descriptive string of this entry + void * volatile sp; // Relevant stack pointer for the entry + JSScript * volatile script_; // if js(), non-null script which is running + int32_t volatile idx; // if js(), idx of pc, otherwise line number + + public: + // All of these methods are marked with the 'volatile' keyword because SPS's + // representation of the stack is stored such that all ProfileEntry + // instances are volatile. These methods would not be available unless they + // were marked as volatile as well. + + bool js() volatile { + JS_ASSERT_IF(sp == nullptr, script_ != nullptr); + return sp == nullptr; + } + + uint32_t line() volatile { JS_ASSERT(!js()); return idx; } + JSScript *script() volatile { JS_ASSERT(js()); return script_; } + void *stackAddress() volatile { return sp; } + const char *label() volatile { return string; } + + void setLine(uint32_t aLine) volatile { JS_ASSERT(!js()); idx = aLine; } + void setLabel(const char *aString) volatile { string = aString; } + void setStackAddress(void *aSp) volatile { sp = aSp; } + void setScript(JSScript *aScript) volatile { script_ = aScript; } + + // We can't know the layout of JSScript, so look in vm/SPSProfiler.cpp. + JS_FRIEND_API(jsbytecode *) pc() volatile; + JS_FRIEND_API(void) setPC(jsbytecode *pc) volatile; + + static size_t offsetOfString() { return offsetof(ProfileEntry, string); } + static size_t offsetOfStackAddress() { return offsetof(ProfileEntry, sp); } + static size_t offsetOfPCIdx() { return offsetof(ProfileEntry, idx); } + static size_t offsetOfScript() { return offsetof(ProfileEntry, script_); } + + // The index used in the entry can either be a line number or the offset of + // a pc into a script's code. To signify a nullptr pc, use a -1 index. This + // is checked against in pc() and setPC() to set/get the right pc. + static const int32_t NullPCIndex = -1; +}; + +JS_FRIEND_API(void) +SetRuntimeProfilingStack(JSRuntime *rt, ProfileEntry *stack, uint32_t *size, + uint32_t max); + +JS_FRIEND_API(void) +EnableRuntimeProfilingStack(JSRuntime *rt, bool enabled); + +JS_FRIEND_API(jsbytecode*) +ProfilingGetPC(JSRuntime *rt, JSScript *script, void *ip); + +} // namespace js + +#endif /* js_ProfilingStack_h */ diff --git a/external/spidermonkey/include/mac/js/PropertyKey.h b/external/spidermonkey/include/mac/js/PropertyKey.h index c949db13a5..1f90653b40 100644 --- a/external/spidermonkey/include/mac/js/PropertyKey.h +++ b/external/spidermonkey/include/mac/js/PropertyKey.h @@ -9,12 +9,9 @@ #ifndef js_PropertyKey_h #define js_PropertyKey_h -#include "mozilla/Attributes.h" - +#include "js/TypeDecls.h" #include "js/Value.h" -struct JSContext; - namespace JS { class PropertyKey; diff --git a/external/spidermonkey/include/mac/js/RequiredDefines.h b/external/spidermonkey/include/mac/js/RequiredDefines.h index 6af9ca871b..3c8f429132 100644 --- a/external/spidermonkey/include/mac/js/RequiredDefines.h +++ b/external/spidermonkey/include/mac/js/RequiredDefines.h @@ -15,9 +15,17 @@ /* * The c99 defining the limit macros (UINT32_MAX for example), says: - * C++ implementations should define these macros only when __STDC_LIMIT_MACROS - * is defined before is included. + * + * C++ implementations should define these macros only when + * __STDC_LIMIT_MACROS is defined before is included. + * + * The same also occurs with __STDC_CONSTANT_MACROS for the constant macros + * (INT8_C for example) used to specify a literal constant of the proper type, + * and with __STDC_FORMAT_MACROS for the format macros (PRId32 for example) used + * with the fprintf function family. */ #define __STDC_LIMIT_MACROS +#define __STDC_CONSTANT_MACROS +#define __STDC_FORMAT_MACROS #endif /* js_RequiredDefines_h */ diff --git a/external/spidermonkey/include/mac/js/RootingAPI.h b/external/spidermonkey/include/mac/js/RootingAPI.h index c4a5925ae7..82863f020a 100644 --- a/external/spidermonkey/include/mac/js/RootingAPI.h +++ b/external/spidermonkey/include/mac/js/RootingAPI.h @@ -8,12 +8,14 @@ #define js_RootingAPI_h #include "mozilla/GuardObjects.h" +#include "mozilla/NullPtr.h" #include "mozilla/TypeTraits.h" -#include "js/Utility.h" - #include "jspubtd.h" +#include "js/TypeDecls.h" +#include "js/Utility.h" + /* * Moving GC Stack Rooting * @@ -97,7 +99,6 @@ namespace js { -class Module; class ScriptSourceObject; template @@ -116,13 +117,13 @@ template class HeapBase {}; /* - * js::NullPtr acts like a NULL pointer in contexts that require a Handle. + * js::NullPtr acts like a nullptr pointer in contexts that require a Handle. * * Handle provides an implicit constructor for js::NullPtr so that, given: * foo(Handle h); * callers can simply write: * foo(js::NullPtr()); - * which avoids creating a Rooted just to pass NULL. + * which avoids creating a Rooted just to pass nullptr. * * This is the SpiderMonkey internal variant. js::NullPtr should be used in * preference to JS::NullPtr to avoid the GOT access required for JS_PUBLIC_API @@ -143,9 +144,6 @@ namespace JS { template class Rooted; -template class Handle; -template class MutableHandle; - /* This is exposing internal state of the GC for inlining purposes. */ JS_FRIEND_API(bool) isGCEnabled(); @@ -155,13 +153,13 @@ CheckStackRoots(JSContext *cx); #endif /* - * JS::NullPtr acts like a NULL pointer in contexts that require a Handle. + * JS::NullPtr acts like a nullptr pointer in contexts that require a Handle. * * Handle provides an implicit constructor for JS::NullPtr so that, given: * foo(Handle h); * callers can simply write: * foo(JS::NullPtr()); - * which avoids creating a Rooted just to pass NULL. + * which avoids creating a Rooted just to pass nullptr. */ struct JS_PUBLIC_API(NullPtr) { @@ -377,7 +375,7 @@ class TenuredHeap : public js::HeapBase template class MOZ_NONHEAP_CLASS Handle : public js::HandleBase { - friend class MutableHandle; + friend class JS::MutableHandle; public: /* Creates a handle from a handle of a type convertible to T. */ @@ -390,14 +388,14 @@ class MOZ_NONHEAP_CLASS Handle : public js::HandleBase ptr = reinterpret_cast(handle.address()); } - /* Create a handle for a NULL pointer. */ + /* Create a handle for a nullptr pointer. */ Handle(js::NullPtr) { static_assert(mozilla::IsPointer::value, "js::NullPtr overload not valid for non-pointer types"); ptr = reinterpret_cast(&js::NullPtr::constNullValue); } - /* Create a handle for a NULL pointer. */ + /* Create a handle for a nullptr pointer. */ Handle(JS::NullPtr) { static_assert(mozilla::IsPointer::value, "JS::NullPtr overload not valid for non-pointer types"); @@ -457,24 +455,18 @@ class MOZ_NONHEAP_CLASS Handle : public js::HandleBase bool operator!=(const T &other) const { return *ptr != other; } bool operator==(const T &other) const { return *ptr == other; } + /* Change this handle to point to the same rooted location RHS does. */ + void repoint(const Handle &rhs) { ptr = rhs.address(); } + private: Handle() {} const T *ptr; - template - void operator=(S v) MOZ_DELETE; + template void operator=(S) MOZ_DELETE; + void operator=(Handle) MOZ_DELETE; }; -typedef Handle HandleObject; -typedef Handle HandleModule; -typedef Handle HandleScriptSource; -typedef Handle HandleFunction; -typedef Handle HandleScript; -typedef Handle HandleString; -typedef Handle HandleId; -typedef Handle HandleValue; - /* * Similar to a handle, but the underlying storage can be changed. This is * useful for outparams. @@ -488,6 +480,10 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase { public: inline MutableHandle(Rooted *root); + MutableHandle(int) MOZ_DELETE; +#ifdef MOZ_HAVE_CXX11_NULLPTR + MutableHandle(decltype(nullptr)) MOZ_DELETE; +#endif void set(T v) { JS_ASSERT(!js::GCMethods::poisoned(v)); @@ -526,13 +522,6 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase void operator=(MutableHandle other) MOZ_DELETE; }; -typedef MutableHandle MutableHandleObject; -typedef MutableHandle MutableHandleFunction; -typedef MutableHandle MutableHandleScript; -typedef MutableHandle MutableHandleString; -typedef MutableHandle MutableHandleId; -typedef MutableHandle MutableHandleValue; - #ifdef JSGC_GENERATIONAL JS_PUBLIC_API(void) HeapCellPostBarrier(js::gc::Cell **cellp); JS_PUBLIC_API(void) HeapCellRelocate(js::gc::Cell **cellp); @@ -614,7 +603,7 @@ struct RootKind template struct GCMethods { - static T *initial() { return NULL; } + static T *initial() { return nullptr; } static ThingRootKind kind() { return RootKind::rootKind(); } static bool poisoned(T *v) { return JS::IsPoisonedPtr(v); } static bool needsPostBarrier(T *v) { return v; } @@ -628,12 +617,11 @@ struct GCMethods #endif }; -// XXX: Needed for cocos2d JS Bindings -//#if defined(DEBUG) +#if defined(DEBUG) /* This helper allows us to assert that Rooted is scoped within a request. */ extern JS_PUBLIC_API(bool) IsInRequest(JSContext *cx); -//#endif +#endif } /* namespace js */ @@ -730,12 +718,15 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase init(js::PerThreadDataFriendFields::getMainThread(rt)); } - ~Rooted() { + // Note that we need to let the compiler generate the default destructor in + // non-exact-rooting builds because of a bug in the instrumented PGO builds + // using MSVC, see bug 915735 for more details. #ifdef JSGC_TRACK_EXACT_ROOTS + ~Rooted() { JS_ASSERT(*stack == reinterpret_cast*>(this)); *stack = prev; -#endif } +#endif #ifdef JSGC_TRACK_EXACT_ROOTS Rooted *previous() { return prev; } @@ -803,8 +794,6 @@ class Rooted; #endif typedef Rooted RootedObject; -typedef Rooted RootedModule; -typedef Rooted RootedScriptSource; typedef Rooted RootedFunction; typedef Rooted RootedScript; typedef Rooted RootedString; @@ -857,6 +846,10 @@ class SkipRoot void init(js::ContextFriendFields *cx, const T *ptr, size_t count) {} public: + ~SkipRoot() { + // An empty destructor is needed to avoid warnings from clang about + // unused local variables of this type. + } #endif /* DEBUG && JSGC_ROOT_ANALYSIS */ @@ -1063,7 +1056,7 @@ inline void MaybeCheckStackRoots(JSContext *cx) class CompilerRootNode { protected: - CompilerRootNode(js::gc::Cell *ptr) : next(NULL), ptr_(ptr) {} + CompilerRootNode(js::gc::Cell *ptr) : next(nullptr), ptr_(ptr) {} public: void **address() { return (void **)&ptr_; } diff --git a/external/spidermonkey/include/mac/js/StructuredClone.h b/external/spidermonkey/include/mac/js/StructuredClone.h new file mode 100644 index 0000000000..d32bdd8dd6 --- /dev/null +++ b/external/spidermonkey/include/mac/js/StructuredClone.h @@ -0,0 +1,163 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_StructuredClone_h +#define js_StructuredClone_h + +#include "mozilla/NullPtr.h" + +#include + +#include "jstypes.h" + +#include "js/RootingAPI.h" +#include "js/TypeDecls.h" +#include "js/Value.h" + +struct JSRuntime; +struct JSStructuredCloneReader; +struct JSStructuredCloneWriter; + +// API for the HTML5 internal structured cloning algorithm. + +// Read structured data from the reader r. This hook is used to read a value +// previously serialized by a call to the WriteStructuredCloneOp hook. +// +// tag and data are the pair of uint32_t values from the header. The callback +// may use the JS_Read* APIs to read any other relevant parts of the object +// from the reader r. closure is any value passed to the JS_ReadStructuredClone +// function. Return the new object on success, nullptr on error/exception. +typedef JSObject *(*ReadStructuredCloneOp)(JSContext *cx, JSStructuredCloneReader *r, + uint32_t tag, uint32_t data, void *closure); + +// Structured data serialization hook. The engine can write primitive values, +// Objects, Arrays, Dates, RegExps, TypedArrays, and ArrayBuffers. Any other +// type of object requires application support. This callback must first use +// the JS_WriteUint32Pair API to write an object header, passing a value +// greater than JS_SCTAG_USER to the tag parameter. Then it can use the +// JS_Write* APIs to write any other relevant parts of the value v to the +// writer w. closure is any value passed to the JS_WriteStructuredCLone function. +// +// Return true on success, false on error/exception. +typedef bool (*WriteStructuredCloneOp)(JSContext *cx, JSStructuredCloneWriter *w, + JS::Handle obj, void *closure); + +// This is called when JS_WriteStructuredClone is given an invalid transferable. +// To follow HTML5, the application must throw a DATA_CLONE_ERR DOMException +// with error set to one of the JS_SCERR_* values. +typedef void (*StructuredCloneErrorOp)(JSContext *cx, uint32_t errorid); + +// The maximum supported structured-clone serialization format version. Note +// that this does not need to be bumped for Transferable-only changes, since +// they are never saved to persistent storage. +#define JS_STRUCTURED_CLONE_VERSION 2 + +struct JSStructuredCloneCallbacks { + ReadStructuredCloneOp read; + WriteStructuredCloneOp write; + StructuredCloneErrorOp reportError; +}; + +// Note: if the *data contains transferable objects, it can be read only once. +JS_PUBLIC_API(bool) +JS_ReadStructuredClone(JSContext *cx, uint64_t *data, size_t nbytes, uint32_t version, + JS::MutableHandleValue vp, + const JSStructuredCloneCallbacks *optionalCallbacks, void *closure); + +// Note: On success, the caller is responsible for calling +// JS_ClearStructuredClone(*datap, nbytesp). +JS_PUBLIC_API(bool) +JS_WriteStructuredClone(JSContext *cx, JS::HandleValue v, uint64_t **datap, size_t *nbytesp, + const JSStructuredCloneCallbacks *optionalCallbacks, + void *closure, JS::HandleValue transferable); + +JS_PUBLIC_API(bool) +JS_ClearStructuredClone(const uint64_t *data, size_t nbytes); + +JS_PUBLIC_API(bool) +JS_StructuredCloneHasTransferables(const uint64_t *data, size_t nbytes, bool *hasTransferable); + +JS_PUBLIC_API(bool) +JS_StructuredClone(JSContext *cx, JS::HandleValue v, JS::MutableHandleValue vp, + const JSStructuredCloneCallbacks *optionalCallbacks, void *closure); + +// RAII sugar for JS_WriteStructuredClone. +class JS_PUBLIC_API(JSAutoStructuredCloneBuffer) { + uint64_t *data_; + size_t nbytes_; + uint32_t version_; + + public: + JSAutoStructuredCloneBuffer() + : data_(nullptr), nbytes_(0), version_(JS_STRUCTURED_CLONE_VERSION) {} + + ~JSAutoStructuredCloneBuffer() { clear(); } + + uint64_t *data() const { return data_; } + size_t nbytes() const { return nbytes_; } + + void clear(); + + // Copy some memory. It will be automatically freed by the destructor. + bool copy(const uint64_t *data, size_t nbytes, uint32_t version=JS_STRUCTURED_CLONE_VERSION); + + // Adopt some memory. It will be automatically freed by the destructor. + // data must have been allocated by the JS engine (e.g., extracted via + // JSAutoStructuredCloneBuffer::steal). + void adopt(uint64_t *data, size_t nbytes, uint32_t version=JS_STRUCTURED_CLONE_VERSION); + + // Remove the buffer so that it will not be automatically freed. + // After this, the caller is responsible for feeding the memory back to + // JSAutoStructuredCloneBuffer::adopt. + void steal(uint64_t **datap, size_t *nbytesp, uint32_t *versionp=nullptr); + + bool read(JSContext *cx, JS::MutableHandleValue vp, + const JSStructuredCloneCallbacks *optionalCallbacks=nullptr, void *closure=nullptr); + + bool write(JSContext *cx, JS::HandleValue v, + const JSStructuredCloneCallbacks *optionalCallbacks=nullptr, void *closure=nullptr); + + bool write(JSContext *cx, JS::HandleValue v, JS::HandleValue transferable, + const JSStructuredCloneCallbacks *optionalCallbacks=nullptr, void *closure=nullptr); + + // Swap ownership with another JSAutoStructuredCloneBuffer. + void swap(JSAutoStructuredCloneBuffer &other); + + private: + // Copy and assignment are not supported. + JSAutoStructuredCloneBuffer(const JSAutoStructuredCloneBuffer &other); + JSAutoStructuredCloneBuffer &operator=(const JSAutoStructuredCloneBuffer &other); +}; + +// The range of tag values the application may use for its own custom object types. +#define JS_SCTAG_USER_MIN ((uint32_t) 0xFFFF8000) +#define JS_SCTAG_USER_MAX ((uint32_t) 0xFFFFFFFF) + +#define JS_SCERR_RECURSION 0 +#define JS_SCERR_TRANSFERABLE 1 + +JS_PUBLIC_API(void) +JS_SetStructuredCloneCallbacks(JSRuntime *rt, const JSStructuredCloneCallbacks *callbacks); + +JS_PUBLIC_API(bool) +JS_ReadUint32Pair(JSStructuredCloneReader *r, uint32_t *p1, uint32_t *p2); + +JS_PUBLIC_API(bool) +JS_ReadBytes(JSStructuredCloneReader *r, void *p, size_t len); + +JS_PUBLIC_API(bool) +JS_ReadTypedArray(JSStructuredCloneReader *r, JS::Value *vp); + +JS_PUBLIC_API(bool) +JS_WriteUint32Pair(JSStructuredCloneWriter *w, uint32_t tag, uint32_t data); + +JS_PUBLIC_API(bool) +JS_WriteBytes(JSStructuredCloneWriter *w, const void *p, size_t len); + +JS_PUBLIC_API(bool) +JS_WriteTypedArray(JSStructuredCloneWriter *w, JS::Value v); + +#endif /* js_StructuredClone_h */ diff --git a/external/spidermonkey/include/mac/js/Tracer.h b/external/spidermonkey/include/mac/js/Tracer.h new file mode 100644 index 0000000000..89994612f6 --- /dev/null +++ b/external/spidermonkey/include/mac/js/Tracer.h @@ -0,0 +1,193 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_Tracer_h +#define js_Tracer_h + +#include "mozilla/NullPtr.h" + +#include "jspubtd.h" + +struct JSTracer; + +namespace JS { +template class Heap; +template class TenuredHeap; +} + +// Tracer callback, called for each traceable thing directly referenced by a +// particular object or runtime structure. It is the callback responsibility +// to ensure the traversal of the full object graph via calling eventually +// JS_TraceChildren on the passed thing. In this case the callback must be +// prepared to deal with cycles in the traversal graph. +// +// kind argument is one of JSTRACE_OBJECT, JSTRACE_STRING or a tag denoting +// internal implementation-specific traversal kind. In the latter case the only +// operations on thing that the callback can do is to call JS_TraceChildren or +// JS_GetTraceThingInfo. +// +// If eagerlyTraceWeakMaps is true, when we trace a WeakMap visit all +// of its mappings. This should be used in cases where the tracer +// wants to use the existing liveness of entries. +typedef void +(* JSTraceCallback)(JSTracer *trc, void **thingp, JSGCTraceKind kind); + +// Callback that JSTraceOp implementation can provide to return a string +// describing the reference traced with JS_CallTracer. +typedef void +(* JSTraceNamePrinter)(JSTracer *trc, char *buf, size_t bufsize); + +enum WeakMapTraceKind { + DoNotTraceWeakMaps = 0, + TraceWeakMapValues = 1, + TraceWeakMapKeysValues = 2 +}; + +struct JSTracer { + JSRuntime *runtime; + JSTraceCallback callback; + JSTraceNamePrinter debugPrinter; + const void *debugPrintArg; + size_t debugPrintIndex; + WeakMapTraceKind eagerlyTraceWeakMaps; +#ifdef JS_GC_ZEAL + void *realLocation; +#endif +}; + +// Set debugging information about a reference to a traceable thing to prepare +// for the following call to JS_CallTracer. +// +// When printer is null, arg must be const char * or char * C string naming +// the reference and index must be either (size_t)-1 indicating that the name +// alone describes the reference or it must be an index into some array vector +// that stores the reference. +// +// When printer callback is not null, the arg and index arguments are +// available to the callback as debugPrintArg and debugPrintIndex fields +// of JSTracer. +// +// The storage for name or callback's arguments needs to live only until +// the following call to JS_CallTracer returns. +// +# define JS_SET_TRACING_DETAILS(trc, printer, arg, index) \ + JS_BEGIN_MACRO \ + (trc)->debugPrinter = (printer); \ + (trc)->debugPrintArg = (arg); \ + (trc)->debugPrintIndex = (index); \ + JS_END_MACRO + +// Sets the real location for a marked reference, when passing the address +// directly is not feasable. +// +// FIXME: This is currently overcomplicated by our need to nest calls for Values +// stored as keys in hash tables, but will get simplified once we can rekey +// in-place. +// +#ifdef JS_GC_ZEAL +# define JS_SET_TRACING_LOCATION(trc, location) \ + JS_BEGIN_MACRO \ + if (!(trc)->realLocation || !(location)) \ + (trc)->realLocation = (location); \ + JS_END_MACRO +# define JS_UNSET_TRACING_LOCATION(trc) \ + JS_BEGIN_MACRO \ + (trc)->realLocation = nullptr; \ + JS_END_MACRO +#else +# define JS_SET_TRACING_LOCATION(trc, location) \ + JS_BEGIN_MACRO \ + JS_END_MACRO +# define JS_UNSET_TRACING_LOCATION(trc) \ + JS_BEGIN_MACRO \ + JS_END_MACRO +#endif + +// Convenience macro to describe the argument of JS_CallTracer using C string +// and index. +# define JS_SET_TRACING_INDEX(trc, name, index) \ + JS_SET_TRACING_DETAILS(trc, nullptr, name, index) + +// Convenience macro to describe the argument of JS_CallTracer using C string. +# define JS_SET_TRACING_NAME(trc, name) \ + JS_SET_TRACING_DETAILS(trc, nullptr, name, (size_t)-1) + +// The JS_Call*Tracer family of functions traces the given GC thing reference. +// This performs the tracing action configured on the given JSTracer: +// typically calling the JSTracer::callback or marking the thing as live. +// +// The argument to JS_Call*Tracer is an in-out param: when the function +// returns, the garbage collector might have moved the GC thing. In this case, +// the reference passed to JS_Call*Tracer will be updated to the object's new +// location. Callers of this method are responsible for updating any state +// that is dependent on the object's address. For example, if the object's +// address is used as a key in a hashtable, then the object must be removed +// and re-inserted with the correct hash. +// +extern JS_PUBLIC_API(void) +JS_CallValueTracer(JSTracer *trc, JS::Value *valuep, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallIdTracer(JSTracer *trc, jsid *idp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallObjectTracer(JSTracer *trc, JSObject **objp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallStringTracer(JSTracer *trc, JSString **strp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallScriptTracer(JSTracer *trc, JSScript **scriptp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapValueTracer(JSTracer *trc, JS::Heap *valuep, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapIdTracer(JSTracer *trc, JS::Heap *idp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapObjectTracer(JSTracer *trc, JS::Heap *objp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapStringTracer(JSTracer *trc, JS::Heap *strp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapScriptTracer(JSTracer *trc, JS::Heap *scriptp, const char *name); + +template +inline void +JS_CallHashSetObjectTracer(JSTracer *trc, HashSetEnum &e, JSObject *const &key, const char *name) +{ + JSObject *updated = key; + JS_SET_TRACING_LOCATION(trc, reinterpret_cast(&const_cast(key))); + JS_CallObjectTracer(trc, &updated, name); + if (updated != key) + e.rekeyFront(key, updated); +} + +// Trace an object that is known to always be tenured. No post barriers are +// required in this case. +extern JS_PUBLIC_API(void) +JS_CallTenuredObjectTracer(JSTracer *trc, JS::TenuredHeap *objp, const char *name); + +// API for JSTraceCallback implementations. +extern JS_PUBLIC_API(void) +JS_TracerInit(JSTracer *trc, JSRuntime *rt, JSTraceCallback callback); + +extern JS_PUBLIC_API(void) +JS_TraceChildren(JSTracer *trc, void *thing, JSGCTraceKind kind); + +extern JS_PUBLIC_API(void) +JS_TraceRuntime(JSTracer *trc); + +extern JS_PUBLIC_API(void) +JS_GetTraceThingInfo(char *buf, size_t bufsize, JSTracer *trc, + void *thing, JSGCTraceKind kind, bool includeDetails); + +extern JS_PUBLIC_API(const char *) +JS_GetTraceEdgeName(JSTracer *trc, char *buffer, int bufferSize); + +#endif /* js_Tracer_h */ diff --git a/external/spidermonkey/include/mac/js/TypeDecls.h b/external/spidermonkey/include/mac/js/TypeDecls.h new file mode 100644 index 0000000000..ec944d374c --- /dev/null +++ b/external/spidermonkey/include/mac/js/TypeDecls.h @@ -0,0 +1,81 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +// This file contains public type declarations that are used *frequently*. If +// it doesn't occur at least 10 times in Gecko, it probably shouldn't be in +// here. +// +// It includes only: +// - forward declarations of structs and classes; +// - typedefs; +// - enums (maybe). +// It does *not* contain any struct or class definitions. + +#ifndef js_TypeDecls_h +#define js_TypeDecls_h + +#include +#include + +struct JSContext; +class JSFunction; +class JSObject; +class JSScript; +class JSString; + +// In release builds, jsid is defined to be an integral type. This +// prevents many bugs from being caught at compile time. E.g.: +// +// jsid id = ... +// if (id) // error +// ... +// +// size_t n = id; // error +// +// To catch more errors, jsid is given a struct type in C++ debug builds. +// Struct assignment and (in C++) operator== allow correct code to be mostly +// oblivious to the change. This feature can be explicitly disabled in debug +// builds by defining JS_NO_JSVAL_JSID_STRUCT_TYPES. +// + +// Needed for cocos2d-js +#define JS_NO_JSVAL_JSID_STRUCT_TYPES + +#if defined(DEBUG) && !defined(JS_NO_JSVAL_JSID_STRUCT_TYPES) +# define JS_USE_JSID_STRUCT_TYPES +#endif + +#ifdef JS_USE_JSID_STRUCT_TYPES +struct jsid; +#else +typedef ptrdiff_t jsid; +#endif + +typedef char16_t jschar; + +namespace JS { + +class Value; +template class Handle; +template class MutableHandle; + +typedef Handle HandleFunction; +typedef Handle HandleId; +typedef Handle HandleObject; +typedef Handle HandleScript; +typedef Handle HandleString; +typedef Handle HandleValue; + +typedef MutableHandle MutableHandleFunction; +typedef MutableHandle MutableHandleId; +typedef MutableHandle MutableHandleObject; +typedef MutableHandle MutableHandleScript; +typedef MutableHandle MutableHandleString; +typedef MutableHandle MutableHandleValue; + +} // namespace JS + +#endif /* js_TypeDecls_h */ diff --git a/external/spidermonkey/include/mac/js/Utility.h b/external/spidermonkey/include/mac/js/Utility.h index 9d391e5c8a..cdaf19ba5f 100644 --- a/external/spidermonkey/include/mac/js/Utility.h +++ b/external/spidermonkey/include/mac/js/Utility.h @@ -11,6 +11,7 @@ #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" #include "mozilla/Move.h" +#include "mozilla/NullPtr.h" #include "mozilla/Scoped.h" #include "mozilla/TemplateLib.h" @@ -18,8 +19,8 @@ #include #ifdef JS_OOM_DO_BACKTRACES -#include #include +#include #endif #include "jstypes.h" @@ -44,16 +45,6 @@ namespace js {} #define JS_ALWAYS_TRUE(expr) MOZ_ALWAYS_TRUE(expr) #define JS_ALWAYS_FALSE(expr) MOZ_ALWAYS_FALSE(expr) -#ifdef DEBUG -# ifdef JS_THREADSAFE -# define JS_THREADSAFE_ASSERT(expr) JS_ASSERT(expr) -# else -# define JS_THREADSAFE_ASSERT(expr) ((void) 0) -# endif -#else -# define JS_THREADSAFE_ASSERT(expr) ((void) 0) -#endif - #if defined(DEBUG) # define JS_DIAGNOSTICS_ASSERT(expr) MOZ_ASSERT(expr) #elif defined(JS_CRASH_DIAGNOSTICS) @@ -96,7 +87,7 @@ static JS_ALWAYS_INLINE void PrintBacktrace() { void* OOM_trace[JS_OOM_BACKTRACE_SIZE]; - char** OOM_traceSymbols = NULL; + char** OOM_traceSymbols = nullptr; int32_t OOM_traceSize = 0; int32_t OOM_traceIdx = 0; OOM_traceSize = backtrace(OOM_trace, JS_OOM_BACKTRACE_SIZE); @@ -126,7 +117,7 @@ PrintBacktrace() { \ if (++OOM_counter > OOM_maxAllocations) { \ JS_OOM_EMIT_BACKTRACE();\ - return NULL; \ + return nullptr; \ } \ } while (0) @@ -136,7 +127,7 @@ PrintBacktrace() if (++OOM_counter > OOM_maxAllocations) { \ JS_OOM_EMIT_BACKTRACE();\ js_ReportOutOfMemory(cx);\ - return NULL; \ + return nullptr; \ } \ } while (0) @@ -145,31 +136,31 @@ PrintBacktrace() # define JS_OOM_POSSIBLY_FAIL_REPORT(cx) do {} while(0) # endif /* DEBUG */ -static JS_INLINE void* js_malloc(size_t bytes) +static inline void* js_malloc(size_t bytes) { JS_OOM_POSSIBLY_FAIL(); return malloc(bytes); } -static JS_INLINE void* js_calloc(size_t bytes) +static inline void* js_calloc(size_t bytes) { JS_OOM_POSSIBLY_FAIL(); return calloc(bytes, 1); } -static JS_INLINE void* js_calloc(size_t nmemb, size_t size) +static inline void* js_calloc(size_t nmemb, size_t size) { JS_OOM_POSSIBLY_FAIL(); return calloc(nmemb, size); } -static JS_INLINE void* js_realloc(void* p, size_t bytes) +static inline void* js_realloc(void* p, size_t bytes) { JS_OOM_POSSIBLY_FAIL(); return realloc(p, bytes); } -static JS_INLINE void js_free(void* p) +static inline void js_free(void* p) { free(p); } @@ -241,7 +232,7 @@ static JS_INLINE void js_free(void* p) #define JS_NEW_BODY(allocator, t, parms) \ void *memory = allocator(sizeof(t)); \ - return memory ? new(memory) t parms : NULL; + return memory ? new(memory) t parms : nullptr; /* * Given a class which should provide 'new' methods, add @@ -360,7 +351,7 @@ static JS_ALWAYS_INLINE T * js_pod_malloc(size_t numElems) { if (numElems & mozilla::tl::MulOverflowMask::value) - return NULL; + return nullptr; return (T *)js_malloc(numElems * sizeof(T)); } @@ -369,7 +360,7 @@ static JS_ALWAYS_INLINE T * js_pod_calloc(size_t numElems) { if (numElems & mozilla::tl::MulOverflowMask::value) - return NULL; + return nullptr; return (T *)js_calloc(numElems * sizeof(T)); } @@ -379,7 +370,7 @@ template struct ScopedFreePtrTraits { typedef T* type; - static T* empty() { return NULL; } + static T* empty() { return nullptr; } static void release(T* ptr) { js_free(ptr); } }; SCOPED_TEMPLATE(ScopedJSFreePtr, ScopedFreePtrTraits) diff --git a/external/spidermonkey/include/mac/js/Value.h b/external/spidermonkey/include/mac/js/Value.h index 9b2c5dd6f9..7a772bcfba 100644 --- a/external/spidermonkey/include/mac/js/Value.h +++ b/external/spidermonkey/include/mac/js/Value.h @@ -15,6 +15,8 @@ #include /* for std::numeric_limits */ +#include "jstypes.h" + #include "js/Anchor.h" #include "js/RootingAPI.h" #include "js/Utility.h" @@ -248,7 +250,7 @@ typedef union jsval_layout union { int32_t i32; uint32_t u32; - JSBool boo; + uint32_t boo; // Don't use |bool| -- it must be four bytes. JSString *str; JSObject *obj; void *ptr; @@ -295,7 +297,7 @@ typedef union jsval_layout union { int32_t i32; uint32_t u32; - JSBool boo; + uint32_t boo; // Don't use |bool| -- it must be four bytes. JSString *str; JSObject *obj; void *ptr; @@ -333,6 +335,49 @@ typedef union jsval_layout JS_STATIC_ASSERT(sizeof(jsval_layout) == 8); +/* + * For codesize purposes on some platforms, it's important that the + * compiler know that JS::Values constructed from constant values can be + * folded to constant bit patterns at compile time, rather than + * constructed at runtime. Doing this requires a fair amount of C++11 + * features, which are not supported on all of our compilers. Set up + * some defines and helper macros in an attempt to confine the ugliness + * here, rather than scattering it all about the file. The important + * features are: + * + * - constexpr; + * - defaulted functions; + * - C99-style designated initializers. + */ +#if defined(__clang__) +# if __has_feature(cxx_constexpr) && __has_feature(cxx_defaulted_functions) +# define JS_VALUE_IS_CONSTEXPR +# endif +#elif defined(__GNUC__) +/* + * We need 4.5 for defaulted functions, 4.6 for constexpr, 4.7 because 4.6 + * doesn't understand |(X) { .field = ... }| syntax, and 4.7.3 because + * versions prior to that have bugs in the C++ front-end that cause crashes. + */ +# if MOZ_GCC_VERSION_AT_LEAST(4, 7, 3) +# define JS_VALUE_IS_CONSTEXPR +# endif +#endif + +#if defined(JS_VALUE_IS_CONSTEXPR) +# define JS_RETURN_LAYOUT_FROM_BITS(BITS) \ + return (jsval_layout) { .asBits = (BITS) } +# define JS_VALUE_CONSTEXPR MOZ_CONSTEXPR +# define JS_VALUE_CONSTEXPR_VAR MOZ_CONSTEXPR_VAR +#else +# define JS_RETURN_LAYOUT_FROM_BITS(BITS) \ + jsval_layout l; \ + l.asBits = (BITS); \ + return l; +# define JS_VALUE_CONSTEXPR +# define JS_VALUE_CONSTEXPR_VAR const +#endif + #if JS_BITS_PER_WORD == 32 /* @@ -341,15 +386,13 @@ JS_STATIC_ASSERT(sizeof(jsval_layout) == 8); * Thus, all comparisons should explicitly cast operands to uint32_t. */ -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout BUILD_JSVAL(JSValueTag tag, uint32_t payload) { - jsval_layout l; - l.asBits = (((uint64_t)(uint32_t)tag) << 32) | payload; - return l; + JS_RETURN_LAYOUT_FROM_BITS((((uint64_t)(uint32_t)tag) << 32) | payload); } -static inline JSBool +static inline bool JSVAL_IS_DOUBLE_IMPL(jsval_layout l) { return (uint32_t)l.s.tag <= (uint32_t)JSVAL_TAG_CLEAR; @@ -364,7 +407,7 @@ DOUBLE_TO_JSVAL_IMPL(double d) return l; } -static inline JSBool +static inline bool JSVAL_IS_INT32_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_INT32; @@ -376,16 +419,20 @@ JSVAL_TO_INT32_IMPL(jsval_layout l) return l.s.payload.i32; } -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout INT32_TO_JSVAL_IMPL(int32_t i) { +#if defined(JS_VALUE_IS_CONSTEXPR) + return BUILD_JSVAL(JSVAL_TAG_INT32, i); +#else jsval_layout l; l.s.tag = JSVAL_TAG_INT32; l.s.payload.i32 = i; return l; +#endif } -static inline JSBool +static inline bool JSVAL_IS_NUMBER_IMPL(jsval_layout l) { JSValueTag tag = l.s.tag; @@ -393,13 +440,13 @@ JSVAL_IS_NUMBER_IMPL(jsval_layout l) return (uint32_t)tag <= (uint32_t)JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET; } -static inline JSBool +static inline bool JSVAL_IS_UNDEFINED_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_UNDEFINED; } -static inline JSBool +static inline bool JSVAL_IS_STRING_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_STRING; @@ -421,47 +468,46 @@ JSVAL_TO_STRING_IMPL(jsval_layout l) return l.s.payload.str; } -static inline JSBool +static inline bool JSVAL_IS_BOOLEAN_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_BOOLEAN; } -static inline JSBool +static inline bool JSVAL_TO_BOOLEAN_IMPL(jsval_layout l) { return l.s.payload.boo; } static inline jsval_layout -BOOLEAN_TO_JSVAL_IMPL(JSBool b) +BOOLEAN_TO_JSVAL_IMPL(bool b) { jsval_layout l; - MOZ_ASSERT(b == JS_TRUE || b == JS_FALSE); l.s.tag = JSVAL_TAG_BOOLEAN; l.s.payload.boo = b; return l; } -static inline JSBool +static inline bool JSVAL_IS_MAGIC_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_MAGIC; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_OBJECT; } -static inline JSBool +static inline bool JSVAL_IS_PRIMITIVE_IMPL(jsval_layout l) { return (uint32_t)l.s.tag < (uint32_t)JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_OR_NULL_IMPL(jsval_layout l) { MOZ_ASSERT((uint32_t)l.s.tag <= (uint32_t)JSVAL_TAG_OBJECT); @@ -484,7 +530,7 @@ OBJECT_TO_JSVAL_IMPL(JSObject *obj) return l; } -static inline JSBool +static inline bool JSVAL_IS_NULL_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_NULL; @@ -507,7 +553,7 @@ JSVAL_TO_PRIVATE_PTR_IMPL(jsval_layout l) return l.s.payload.ptr; } -static inline JSBool +static inline bool JSVAL_IS_GCTHING_IMPL(jsval_layout l) { /* gcc sometimes generates signed < without explicit casts. */ @@ -520,7 +566,7 @@ JSVAL_TO_GCTHING_IMPL(jsval_layout l) return l.s.payload.ptr; } -static inline JSBool +static inline bool JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_STRING || l.s.tag == JSVAL_TAG_OBJECT; @@ -529,19 +575,19 @@ JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) static inline uint32_t JSVAL_TRACE_KIND_IMPL(jsval_layout l) { - return (uint32_t)(JSBool)JSVAL_IS_STRING_IMPL(l); + return (uint32_t)(bool)JSVAL_IS_STRING_IMPL(l); } -static inline JSBool +static inline bool JSVAL_IS_SPECIFIC_INT32_IMPL(jsval_layout l, int32_t i32) { return l.s.tag == JSVAL_TAG_INT32 && l.s.payload.i32 == i32; } -static inline JSBool -JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, JSBool b) +static inline bool +JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, bool b) { - return (l.s.tag == JSVAL_TAG_BOOLEAN) && (l.s.payload.boo == b); + return (l.s.tag == JSVAL_TAG_BOOLEAN) && (l.s.payload.boo == uint32_t(b)); } static inline jsval_layout @@ -553,7 +599,7 @@ MAGIC_TO_JSVAL_IMPL(JSWhyMagic why) return l; } -static inline JSBool +static inline bool JSVAL_SAME_TYPE_IMPL(jsval_layout lhs, jsval_layout rhs) { JSValueTag ltag = lhs.s.tag, rtag = rhs.s.tag; @@ -570,15 +616,13 @@ JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(jsval_layout l) #elif JS_BITS_PER_WORD == 64 -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout BUILD_JSVAL(JSValueTag tag, uint64_t payload) { - jsval_layout l; - l.asBits = (((uint64_t)(uint32_t)tag) << JSVAL_TAG_SHIFT) | payload; - return l; + JS_RETURN_LAYOUT_FROM_BITS((((uint64_t)(uint32_t)tag) << JSVAL_TAG_SHIFT) | payload); } -static inline JSBool +static inline bool JSVAL_IS_DOUBLE_IMPL(jsval_layout l) { return l.asBits <= JSVAL_SHIFTED_TAG_MAX_DOUBLE; @@ -593,7 +637,7 @@ DOUBLE_TO_JSVAL_IMPL(double d) return l; } -static inline JSBool +static inline bool JSVAL_IS_INT32_IMPL(jsval_layout l) { return (uint32_t)(l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_INT32; @@ -605,27 +649,25 @@ JSVAL_TO_INT32_IMPL(jsval_layout l) return (int32_t)l.asBits; } -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout INT32_TO_JSVAL_IMPL(int32_t i32) { - jsval_layout l; - l.asBits = ((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32; - return l; + JS_RETURN_LAYOUT_FROM_BITS(((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32); } -static inline JSBool +static inline bool JSVAL_IS_NUMBER_IMPL(jsval_layout l) { return l.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET; } -static inline JSBool +static inline bool JSVAL_IS_UNDEFINED_IMPL(jsval_layout l) { return l.asBits == JSVAL_SHIFTED_TAG_UNDEFINED; } -static inline JSBool +static inline bool JSVAL_IS_STRING_IMPL(jsval_layout l) { return (uint32_t)(l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_STRING; @@ -648,47 +690,46 @@ JSVAL_TO_STRING_IMPL(jsval_layout l) return (JSString *)(l.asBits & JSVAL_PAYLOAD_MASK); } -static inline JSBool +static inline bool JSVAL_IS_BOOLEAN_IMPL(jsval_layout l) { return (uint32_t)(l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_BOOLEAN; } -static inline JSBool +static inline bool JSVAL_TO_BOOLEAN_IMPL(jsval_layout l) { - return (JSBool)l.asBits; + return (bool)(l.asBits & JSVAL_PAYLOAD_MASK); } static inline jsval_layout -BOOLEAN_TO_JSVAL_IMPL(JSBool b) +BOOLEAN_TO_JSVAL_IMPL(bool b) { jsval_layout l; - MOZ_ASSERT(b == JS_TRUE || b == JS_FALSE); l.asBits = ((uint64_t)(uint32_t)b) | JSVAL_SHIFTED_TAG_BOOLEAN; return l; } -static inline JSBool +static inline bool JSVAL_IS_MAGIC_IMPL(jsval_layout l) { return (l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_MAGIC; } -static inline JSBool +static inline bool JSVAL_IS_PRIMITIVE_IMPL(jsval_layout l) { return l.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_IMPL(jsval_layout l) { MOZ_ASSERT((l.asBits >> JSVAL_TAG_SHIFT) <= JSVAL_SHIFTED_TAG_OBJECT); return l.asBits >= JSVAL_SHIFTED_TAG_OBJECT; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_OR_NULL_IMPL(jsval_layout l) { MOZ_ASSERT((l.asBits >> JSVAL_TAG_SHIFT) <= JSVAL_TAG_OBJECT); @@ -714,13 +755,13 @@ OBJECT_TO_JSVAL_IMPL(JSObject *obj) return l; } -static inline JSBool +static inline bool JSVAL_IS_NULL_IMPL(jsval_layout l) { return l.asBits == JSVAL_SHIFTED_TAG_NULL; } -static inline JSBool +static inline bool JSVAL_IS_GCTHING_IMPL(jsval_layout l) { return l.asBits >= JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET; @@ -734,7 +775,7 @@ JSVAL_TO_GCTHING_IMPL(jsval_layout l) return (void *)ptrBits; } -static inline JSBool +static inline bool JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) { return JSVAL_IS_GCTHING_IMPL(l) && !JSVAL_IS_NULL_IMPL(l); @@ -743,7 +784,7 @@ JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) static inline uint32_t JSVAL_TRACE_KIND_IMPL(jsval_layout l) { - return (uint32_t)(JSBool)!(JSVAL_IS_OBJECT_IMPL(l)); + return (uint32_t)(bool)!(JSVAL_IS_OBJECT_IMPL(l)); } static inline jsval_layout @@ -764,14 +805,14 @@ JSVAL_TO_PRIVATE_PTR_IMPL(jsval_layout l) return (void *)(l.asBits << 1); } -static inline JSBool +static inline bool JSVAL_IS_SPECIFIC_INT32_IMPL(jsval_layout l, int32_t i32) { return l.asBits == (((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32); } -static inline JSBool -JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, JSBool b) +static inline bool +JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, bool b) { return l.asBits == (((uint64_t)(uint32_t)b) | JSVAL_SHIFTED_TAG_BOOLEAN); } @@ -784,7 +825,7 @@ MAGIC_TO_JSVAL_IMPL(JSWhyMagic why) return l; } -static inline JSBool +static inline bool JSVAL_SAME_TYPE_IMPL(jsval_layout lhs, jsval_layout rhs) { uint64_t lbits = lhs.asBits, rbits = rhs.asBits; @@ -803,10 +844,12 @@ JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(jsval_layout l) #endif /* JS_BITS_PER_WORD */ static inline jsval_layout JSVAL_TO_IMPL(JS::Value v); -static inline JS::Value IMPL_TO_JSVAL(jsval_layout l); +static inline JS_VALUE_CONSTEXPR JS::Value IMPL_TO_JSVAL(jsval_layout l); namespace JS { +static inline JS_VALUE_CONSTEXPR JS::Value UndefinedValue(); + /** * Returns a generic quiet NaN value, with all payload bits set to zero. * @@ -816,7 +859,7 @@ namespace JS { static MOZ_ALWAYS_INLINE double GenericNaN() { - return mozilla::SpecificNaN(0, 0x8000000000000ULL); + return mozilla::SpecificNaN(0, 0x8000000000000ULL); } static inline double @@ -869,6 +912,10 @@ class Value * N.B. the default constructor leaves Value unitialized. Adding a default * constructor prevents Value from being stored in a union. */ +#if defined(JS_VALUE_IS_CONSTEXPR) + Value() = default; + Value(const Value& v) = default; +#endif /*** Mutators ***/ @@ -893,6 +940,10 @@ class Value data = DOUBLE_TO_JSVAL_IMPL(d); } + void setNaN() { + setDouble(GenericNaN()); + } + double &getDoubleRef() { MOZ_ASSERT(isDouble()); return data.asDouble; @@ -1173,16 +1224,20 @@ class Value jsval_layout data; private: +#if defined(JS_VALUE_IS_CONSTEXPR) + JS_VALUE_CONSTEXPR Value(jsval_layout layout) : data(layout) {} +#endif + void staticAssertions() { JS_STATIC_ASSERT(sizeof(JSValueType) == 1); JS_STATIC_ASSERT(sizeof(JSValueTag) == 4); - JS_STATIC_ASSERT(sizeof(JSBool) == 4); JS_STATIC_ASSERT(sizeof(JSWhyMagic) <= 4); JS_STATIC_ASSERT(sizeof(Value) == 8); } friend jsval_layout (::JSVAL_TO_IMPL)(Value); - friend Value (::IMPL_TO_JSVAL)(jsval_layout l); + friend Value JS_VALUE_CONSTEXPR (::IMPL_TO_JSVAL)(jsval_layout l); + friend Value JS_VALUE_CONSTEXPR (JS::UndefinedValue)(); }; inline bool @@ -1205,12 +1260,16 @@ NullValue() return v; } -static inline Value +static inline JS_VALUE_CONSTEXPR Value UndefinedValue() { - Value v; +#if defined(JS_VALUE_IS_CONSTEXPR) + return Value(BUILD_JSVAL(JSVAL_TAG_UNDEFINED, 0)); +#else + JS::Value v; v.setUndefined(); return v; +#endif } static inline Value @@ -1229,6 +1288,22 @@ DoubleValue(double dbl) return v; } +static inline Value +DoubleNaNValue() +{ + Value v; + v.setNaN(); + return v; +} + +static inline Value +Float32Value(float f) +{ + Value v; + v.setDouble(f); + return v; +} + static inline Value StringValue(JSString *str) { @@ -1499,6 +1574,7 @@ class UnbarrieredMutableValueOperations : public ValueOperations void setUndefined() { value()->setUndefined(); } void setInt32(int32_t i) { value()->setInt32(i); } void setDouble(double d) { value()->setDouble(d); } + void setNaN() { setDouble(JS::GenericNaN()); } void setBoolean(bool b) { value()->setBoolean(b); } void setMagic(JSWhyMagic why) { value()->setMagic(why); } bool setNumber(uint32_t ui) { return value()->setNumber(ui); } @@ -1620,12 +1696,16 @@ JSVAL_TO_IMPL(JS::Value v) return v.data; } -inline JS::Value +inline JS_VALUE_CONSTEXPR JS::Value IMPL_TO_JSVAL(jsval_layout l) { +#if defined(JS_VALUE_IS_CONSTEXPR) + return JS::Value(l); +#else JS::Value v; v.data = l; return v; +#endif } namespace JS { @@ -1678,19 +1758,19 @@ static_assert(sizeof(jsval_layout) == sizeof(JS::Value), /************************************************************************/ -static inline JSBool +static inline bool JSVAL_IS_NULL(jsval v) { return JSVAL_IS_NULL_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_VOID(jsval v) { return JSVAL_IS_UNDEFINED_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_INT(jsval v) { return JSVAL_IS_INT32_IMPL(JSVAL_TO_IMPL(v)); @@ -1703,13 +1783,13 @@ JSVAL_TO_INT(jsval v) return JSVAL_TO_INT32_IMPL(JSVAL_TO_IMPL(v)); } -static inline jsval +static inline JS_VALUE_CONSTEXPR jsval INT_TO_JSVAL(int32_t i) { return IMPL_TO_JSVAL(INT32_TO_JSVAL_IMPL(i)); } -static inline JSBool +static inline bool JSVAL_IS_DOUBLE(jsval v) { return JSVAL_IS_DOUBLE_IMPL(JSVAL_TO_IMPL(v)); @@ -1724,7 +1804,7 @@ JSVAL_TO_DOUBLE(jsval v) return l.asDouble; } -static inline jsval +static inline JS_VALUE_CONSTEXPR jsval DOUBLE_TO_JSVAL(double d) { /* @@ -1733,29 +1813,35 @@ DOUBLE_TO_JSVAL(double d) * return IMPL_TO_JSVAL(DOUBLE_TO_JSVAL_IMPL(d)); * because GCC from XCode 3.1.4 miscompiles the above code. */ +#if defined(JS_VALUE_IS_CONSTEXPR) + return IMPL_TO_JSVAL(MOZ_UNLIKELY(d != d) + ? (jsval_layout) { .asBits = 0x7FF8000000000000LL } + : (jsval_layout) { .asDouble = d }); +#else jsval_layout l; if (MOZ_UNLIKELY(d != d)) l.asBits = 0x7FF8000000000000LL; else l.asDouble = d; return IMPL_TO_JSVAL(l); +#endif } -static inline jsval +static inline JS_VALUE_CONSTEXPR jsval UINT_TO_JSVAL(uint32_t i) { - if (i <= JSVAL_INT_MAX) - return INT_TO_JSVAL((int32_t)i); - return DOUBLE_TO_JSVAL((double)i); + return (i <= JSVAL_INT_MAX + ? INT_TO_JSVAL((int32_t)i) + : DOUBLE_TO_JSVAL((double)i)); } -static inline JSBool +static inline bool JSVAL_IS_NUMBER(jsval v) { return JSVAL_IS_NUMBER_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_STRING(jsval v) { return JSVAL_IS_STRING_IMPL(JSVAL_TO_IMPL(v)); @@ -1789,13 +1875,13 @@ OBJECT_TO_JSVAL(JSObject *obj) return IMPL_TO_JSVAL(BUILD_JSVAL(JSVAL_TAG_NULL, 0)); } -static inline JSBool +static inline bool JSVAL_IS_BOOLEAN(jsval v) { return JSVAL_IS_BOOLEAN_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_TO_BOOLEAN(jsval v) { MOZ_ASSERT(JSVAL_IS_BOOLEAN(v)); @@ -1803,18 +1889,18 @@ JSVAL_TO_BOOLEAN(jsval v) } static inline jsval -BOOLEAN_TO_JSVAL(JSBool b) +BOOLEAN_TO_JSVAL(bool b) { return IMPL_TO_JSVAL(BOOLEAN_TO_JSVAL_IMPL(b)); } -static inline JSBool +static inline bool JSVAL_IS_PRIMITIVE(jsval v) { return JSVAL_IS_PRIMITIVE_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_GCTHING(jsval v) { return JSVAL_IS_GCTHING_IMPL(JSVAL_TO_IMPL(v)); @@ -1842,4 +1928,25 @@ JSVAL_TO_PRIVATE(jsval v) return JSVAL_TO_PRIVATE_PTR_IMPL(JSVAL_TO_IMPL(v)); } +// JS constants. For efficiency, prefer predicates (e.g. v.isNull()) and +// constructing values from scratch (e.g. Int32Value(0)). These constants are +// stored in memory and initialized at startup, so testing against them and +// using them requires memory loads and will be correspondingly slow. +extern JS_PUBLIC_DATA(const jsval) JSVAL_NULL; +extern JS_PUBLIC_DATA(const jsval) JSVAL_ZERO; +extern JS_PUBLIC_DATA(const jsval) JSVAL_ONE; +extern JS_PUBLIC_DATA(const jsval) JSVAL_FALSE; +extern JS_PUBLIC_DATA(const jsval) JSVAL_TRUE; +extern JS_PUBLIC_DATA(const jsval) JSVAL_VOID; + +namespace JS { + +extern JS_PUBLIC_DATA(const Handle) NullHandleValue; +extern JS_PUBLIC_DATA(const Handle) UndefinedHandleValue; + +} + +#undef JS_VALUE_IS_CONSTEXPR +#undef JS_RETURN_LAYOUT_FROM_BITS + #endif /* js_Value_h */ diff --git a/external/spidermonkey/include/mac/jsalloc.h b/external/spidermonkey/include/mac/jsalloc.h index 3abc4966d1..03b6b569e1 100644 --- a/external/spidermonkey/include/mac/jsalloc.h +++ b/external/spidermonkey/include/mac/jsalloc.h @@ -9,12 +9,9 @@ #ifndef jsalloc_h #define jsalloc_h -#include "mozilla/AllocPolicy.h" - +#include "js/TypeDecls.h" #include "js/Utility.h" -struct JSContext; - namespace js { class ContextFriendFields; @@ -56,14 +53,14 @@ class TempAllocPolicy void *malloc_(size_t bytes) { void *p = js_malloc(bytes); if (JS_UNLIKELY(!p)) - p = onOutOfMemory(NULL, bytes); + p = onOutOfMemory(nullptr, bytes); return p; } void *calloc_(size_t bytes) { void *p = js_calloc(bytes); if (JS_UNLIKELY(!p)) - p = onOutOfMemory(NULL, bytes); + p = onOutOfMemory(nullptr, bytes); return p; } diff --git a/external/spidermonkey/include/mac/jsapi.h.REMOVED.git-id b/external/spidermonkey/include/mac/jsapi.h.REMOVED.git-id index 27b6bbed78..f73a8c745e 100644 --- a/external/spidermonkey/include/mac/jsapi.h.REMOVED.git-id +++ b/external/spidermonkey/include/mac/jsapi.h.REMOVED.git-id @@ -1 +1 @@ -e14ea931f699b1808c06886e55e977c9819f3774 \ No newline at end of file +38fc2004d49d7c513aff0f7f43d79524ec667c2c \ No newline at end of file diff --git a/external/spidermonkey/include/mac/jsbytecode.h b/external/spidermonkey/include/mac/jsbytecode.h new file mode 100644 index 0000000000..8e4f4cf90b --- /dev/null +++ b/external/spidermonkey/include/mac/jsbytecode.h @@ -0,0 +1,14 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef jsbytecode_h +#define jsbytecode_h + +#include + +typedef uint8_t jsbytecode; + +#endif /* jsbytecode_h */ diff --git a/external/spidermonkey/include/mac/jsclass.h b/external/spidermonkey/include/mac/jsclass.h deleted file mode 100644 index def641715d..0000000000 --- a/external/spidermonkey/include/mac/jsclass.h +++ /dev/null @@ -1,405 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -#ifndef jsclass_h -#define jsclass_h -/* - * A JSClass acts as a vtable for JS objects that allows JSAPI clients to - * control various aspects of the behavior of an object like property lookup. - * js::Class is an engine-private extension that allows more control over - * object behavior and, e.g., allows custom slow layout. - */ - -#include "jsapi.h" -#include "jsprvtd.h" - -namespace js { - -class PropertyName; -class SpecialId; -class PropertyId; - -// This is equal to JSFunction::class_. Use it in places where you don't want -// to #include jsfun.h. -extern JS_FRIEND_DATA(js::Class* const) FunctionClassPtr; - -static JS_ALWAYS_INLINE jsid -SPECIALID_TO_JSID(const SpecialId &sid); - -/* - * We partition the ways to refer to a property into three: by an index - * (uint32_t); by a string whose characters do not represent an index - * (PropertyName, see vm/String.h); and by various special values. - * - * Special values are encoded using SpecialId, which is layout-compatible but - * non-interconvertible with jsid. A SpecialId is used for JSID_VOID, which - * does not occur in JS scripts but may be used to indicate the absence of a - * valid identifier. In the future, a SpecialId may also be an object used by - * Harmony-proposed private names. - */ -class SpecialId -{ - uintptr_t bits_; - - /* Needs access to raw bits. */ - friend JS_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid); - friend class PropertyId; - - static const uintptr_t TYPE_VOID = JSID_TYPE_VOID; - static const uintptr_t TYPE_OBJECT = JSID_TYPE_OBJECT; - static const uintptr_t TYPE_MASK = JSID_TYPE_MASK; - - SpecialId(uintptr_t bits) : bits_(bits) { } - - public: - SpecialId() : bits_(TYPE_VOID) { } - - /* Object-valued */ - - SpecialId(JSObject &obj) - : bits_(uintptr_t(&obj) | TYPE_OBJECT) - { - JS_ASSERT(&obj != NULL); - JS_ASSERT((uintptr_t(&obj) & TYPE_MASK) == 0); - } - - bool isObject() const { - return (bits_ & TYPE_MASK) == TYPE_OBJECT && bits_ != TYPE_OBJECT; - } - - JSObject *toObject() const { - JS_ASSERT(isObject()); - return reinterpret_cast(bits_ & ~TYPE_MASK); - } - - /* Empty */ - - static SpecialId empty() { - SpecialId sid(TYPE_OBJECT); - JS_ASSERT(sid.isEmpty()); - return sid; - } - - bool isEmpty() const { - return bits_ == TYPE_OBJECT; - } - - /* Void */ - - static SpecialId voidId() { - SpecialId sid(TYPE_VOID); - JS_ASSERT(sid.isVoid()); - return sid; - } - - bool isVoid() const { - return bits_ == TYPE_VOID; - } -}; - -static JS_ALWAYS_INLINE jsid -SPECIALID_TO_JSID(const SpecialId &sid) -{ - jsid id; - JSID_BITS(id) = sid.bits_; - JS_ASSERT_IF(sid.isObject(), JSID_IS_OBJECT(id) && JSID_TO_OBJECT(id) == sid.toObject()); - JS_ASSERT_IF(sid.isVoid(), JSID_IS_VOID(id)); - JS_ASSERT_IF(sid.isEmpty(), JSID_IS_EMPTY(id)); - return id; -} - -static JS_ALWAYS_INLINE bool -JSID_IS_SPECIAL(jsid id) -{ - return JSID_IS_OBJECT(id) || JSID_IS_EMPTY(id) || JSID_IS_VOID(id); -} - -static JS_ALWAYS_INLINE SpecialId -JSID_TO_SPECIALID(jsid id) -{ - JS_ASSERT(JSID_IS_SPECIAL(id)); - if (JSID_IS_OBJECT(id)) - return SpecialId(*JSID_TO_OBJECT(id)); - if (JSID_IS_EMPTY(id)) - return SpecialId::empty(); - JS_ASSERT(JSID_IS_VOID(id)); - return SpecialId::voidId(); -} - -typedef JS::Handle HandleSpecialId; - -/* js::Class operation signatures. */ - -typedef JSBool -(* LookupGenericOp)(JSContext *cx, HandleObject obj, HandleId id, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* LookupPropOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* LookupElementOp)(JSContext *cx, HandleObject obj, uint32_t index, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* LookupSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* DefineGenericOp)(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* DefinePropOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* DefineElementOp)(JSContext *cx, HandleObject obj, uint32_t index, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* DefineSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* GenericIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandleId id, MutableHandleValue vp); -typedef JSBool -(* PropertyIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandlePropertyName name, MutableHandleValue vp); -typedef JSBool -(* ElementIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, uint32_t index, MutableHandleValue vp); -typedef JSBool -(* ElementIfPresentOp)(JSContext *cx, HandleObject obj, HandleObject receiver, uint32_t index, MutableHandleValue vp, bool* present); -typedef JSBool -(* SpecialIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandleSpecialId sid, MutableHandleValue vp); -typedef JSBool -(* StrictGenericIdOp)(JSContext *cx, HandleObject obj, HandleId id, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* StrictPropertyIdOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* StrictElementIdOp)(JSContext *cx, HandleObject obj, uint32_t index, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* StrictSpecialIdOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* GenericAttributesOp)(JSContext *cx, HandleObject obj, HandleId id, unsigned *attrsp); -typedef JSBool -(* PropertyAttributesOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, unsigned *attrsp); -typedef JSBool -(* ElementAttributesOp)(JSContext *cx, HandleObject obj, uint32_t index, unsigned *attrsp); -typedef JSBool -(* SpecialAttributesOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, unsigned *attrsp); -typedef JSBool -(* DeletePropertyOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, JSBool *succeeded); -typedef JSBool -(* DeleteElementOp)(JSContext *cx, HandleObject obj, uint32_t index, JSBool *succeeded); -typedef JSBool -(* DeleteSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, JSBool *succeeded); - - -typedef JSObject * -(* ObjectOp)(JSContext *cx, HandleObject obj); -typedef void -(* FinalizeOp)(FreeOp *fop, JSObject *obj); - -#define JS_CLASS_MEMBERS \ - const char *name; \ - uint32_t flags; \ - \ - /* Mandatory function pointer members. */ \ - JSPropertyOp addProperty; \ - JSDeletePropertyOp delProperty; \ - JSPropertyOp getProperty; \ - JSStrictPropertyOp setProperty; \ - JSEnumerateOp enumerate; \ - JSResolveOp resolve; \ - JSConvertOp convert; \ - \ - /* Optional members (may be null). */ \ - FinalizeOp finalize; \ - JSCheckAccessOp checkAccess; \ - JSNative call; \ - JSHasInstanceOp hasInstance; \ - JSNative construct; \ - JSTraceOp trace - -/* - * The helper struct to measure the size of JS_CLASS_MEMBERS to know how much - * we have to pad js::Class to match the size of JSClass. - */ -struct ClassSizeMeasurement -{ - JS_CLASS_MEMBERS; -}; - -struct ClassExtension -{ - JSObjectOp outerObject; - JSObjectOp innerObject; - JSIteratorOp iteratorObject; - - /* - * isWrappedNative is true only if the class is an XPCWrappedNative. - * WeakMaps use this to override the wrapper disposal optimization. - */ - bool isWrappedNative; - - /* - * If an object is used as a key in a weakmap, it may be desirable for the - * garbage collector to keep that object around longer than it otherwise - * would. A common case is when the key is a wrapper around an object in - * another compartment, and we want to avoid collecting the wrapper (and - * removing the weakmap entry) as long as the wrapped object is alive. In - * that case, the wrapped object is returned by the wrapper's - * weakmapKeyDelegateOp hook. As long as the wrapper is used as a weakmap - * key, it will not be collected (and remain in the weakmap) until the - * wrapped object is collected. - */ - JSWeakmapKeyDelegateOp weakmapKeyDelegateOp; -}; - -#define JS_NULL_CLASS_EXT {NULL,NULL,NULL,false,NULL} - -struct ObjectOps -{ - LookupGenericOp lookupGeneric; - LookupPropOp lookupProperty; - LookupElementOp lookupElement; - LookupSpecialOp lookupSpecial; - DefineGenericOp defineGeneric; - DefinePropOp defineProperty; - DefineElementOp defineElement; - DefineSpecialOp defineSpecial; - GenericIdOp getGeneric; - PropertyIdOp getProperty; - ElementIdOp getElement; - ElementIfPresentOp getElementIfPresent; /* can be null */ - SpecialIdOp getSpecial; - StrictGenericIdOp setGeneric; - StrictPropertyIdOp setProperty; - StrictElementIdOp setElement; - StrictSpecialIdOp setSpecial; - GenericAttributesOp getGenericAttributes; - PropertyAttributesOp getPropertyAttributes; - ElementAttributesOp getElementAttributes; - SpecialAttributesOp getSpecialAttributes; - GenericAttributesOp setGenericAttributes; - PropertyAttributesOp setPropertyAttributes; - ElementAttributesOp setElementAttributes; - SpecialAttributesOp setSpecialAttributes; - DeletePropertyOp deleteProperty; - DeleteElementOp deleteElement; - DeleteSpecialOp deleteSpecial; - - JSNewEnumerateOp enumerate; - ObjectOp thisObject; -}; - -#define JS_NULL_OBJECT_OPS \ - {NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, \ - NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, \ - NULL,NULL,NULL} - -struct Class -{ - JS_CLASS_MEMBERS; - ClassExtension ext; - ObjectOps ops; - uint8_t pad[sizeof(JSClass) - sizeof(ClassSizeMeasurement) - - sizeof(ClassExtension) - sizeof(ObjectOps)]; - - /* Class is not native and its map is not a scope. */ - static const uint32_t NON_NATIVE = JSCLASS_INTERNAL_FLAG2; - - bool isNative() const { - return !(flags & NON_NATIVE); - } - - bool hasPrivate() const { - return !!(flags & JSCLASS_HAS_PRIVATE); - } - - bool emulatesUndefined() const { - return flags & JSCLASS_EMULATES_UNDEFINED; - } - - bool isCallable() const { - return this == js::FunctionClassPtr || call; - } - - static size_t offsetOfFlags() { return offsetof(Class, flags); } -}; - -JS_STATIC_ASSERT(offsetof(JSClass, name) == offsetof(Class, name)); -JS_STATIC_ASSERT(offsetof(JSClass, flags) == offsetof(Class, flags)); -JS_STATIC_ASSERT(offsetof(JSClass, addProperty) == offsetof(Class, addProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, delProperty) == offsetof(Class, delProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, getProperty) == offsetof(Class, getProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, setProperty) == offsetof(Class, setProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, enumerate) == offsetof(Class, enumerate)); -JS_STATIC_ASSERT(offsetof(JSClass, resolve) == offsetof(Class, resolve)); -JS_STATIC_ASSERT(offsetof(JSClass, convert) == offsetof(Class, convert)); -JS_STATIC_ASSERT(offsetof(JSClass, finalize) == offsetof(Class, finalize)); -JS_STATIC_ASSERT(offsetof(JSClass, checkAccess) == offsetof(Class, checkAccess)); -JS_STATIC_ASSERT(offsetof(JSClass, call) == offsetof(Class, call)); -JS_STATIC_ASSERT(offsetof(JSClass, construct) == offsetof(Class, construct)); -JS_STATIC_ASSERT(offsetof(JSClass, hasInstance) == offsetof(Class, hasInstance)); -JS_STATIC_ASSERT(offsetof(JSClass, trace) == offsetof(Class, trace)); -JS_STATIC_ASSERT(sizeof(JSClass) == sizeof(Class)); - -static JS_ALWAYS_INLINE JSClass * -Jsvalify(Class *c) -{ - return (JSClass *)c; -} -static JS_ALWAYS_INLINE const JSClass * -Jsvalify(const Class *c) -{ - return (const JSClass *)c; -} - -static JS_ALWAYS_INLINE Class * -Valueify(JSClass *c) -{ - return (Class *)c; -} -static JS_ALWAYS_INLINE const Class * -Valueify(const JSClass *c) -{ - return (const Class *)c; -} - -/* - * Enumeration describing possible values of the [[Class]] internal property - * value of objects. - */ -enum ESClassValue { - ESClass_Array, ESClass_Number, ESClass_String, ESClass_Boolean, - ESClass_RegExp, ESClass_ArrayBuffer, ESClass_Date -}; - -/* - * Return whether the given object has the given [[Class]] internal property - * value. Beware, this query says nothing about the js::Class of the JSObject - * so the caller must not assume anything about obj's representation (e.g., obj - * may be a proxy). - */ -inline bool -ObjectClassIs(JSObject &obj, ESClassValue classValue, JSContext *cx); - -/* Just a helper that checks v.isObject before calling ObjectClassIs. */ -inline bool -IsObjectWithClass(const Value &v, ESClassValue classValue, JSContext *cx); - -inline bool -IsPoisonedSpecialId(js::SpecialId iden) -{ - if (iden.isObject()) - return IsPoisonedPtr(iden.toObject()); - return false; -} - -template <> struct GCMethods -{ - static SpecialId initial() { return SpecialId(); } - static ThingRootKind kind() { return THING_ROOT_ID; } - static bool poisoned(SpecialId id) { return IsPoisonedSpecialId(id); } -}; - -} /* namespace js */ - -#endif /* jsclass_h */ diff --git a/external/spidermonkey/include/mac/jscpucfg.h b/external/spidermonkey/include/mac/jscpucfg.h index c79bd7ad14..ccacab3482 100644 --- a/external/spidermonkey/include/mac/jscpucfg.h +++ b/external/spidermonkey/include/mac/jscpucfg.h @@ -14,8 +14,6 @@ # if defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_) # define IS_LITTLE_ENDIAN 1 # undef IS_BIG_ENDIAN -# define JS_BYTES_PER_WORD 8 -# define JS_BITS_PER_WORD_LOG2 6 # else /* !(defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)) */ # error "CPU type is unknown" # endif /* !(defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)) */ @@ -28,8 +26,6 @@ # define IS_LITTLE_ENDIAN 1 # undef IS_BIG_ENDIAN -# define JS_BYTES_PER_WORD 4 -# define JS_BITS_PER_WORD_LOG2 5 #elif defined(__APPLE__) # if __LITTLE_ENDIAN__ @@ -57,8 +53,8 @@ /* BSDs */ #elif defined(JS_HAVE_MACHINE_ENDIAN_H) -# include # include +# include # if defined(_BYTE_ORDER) # if _BYTE_ORDER == _LITTLE_ENDIAN diff --git a/external/spidermonkey/include/mac/jsfriendapi.h b/external/spidermonkey/include/mac/jsfriendapi.h index a1c3024fed..811275d332 100644 --- a/external/spidermonkey/include/mac/jsfriendapi.h +++ b/external/spidermonkey/include/mac/jsfriendapi.h @@ -9,11 +9,12 @@ #include "mozilla/MemoryReporting.h" -#include "jsclass.h" -#include "jsprvtd.h" +#include "jsbytecode.h" #include "jspubtd.h" #include "js/CallArgs.h" +#include "js/CallNonGenericMethod.h" +#include "js/Class.h" /* * This macro checks if the stack pointer has exceeded a given limit. If @@ -30,6 +31,12 @@ #define JS_CHECK_STACK_SIZE(limit, lval) JS_CHECK_STACK_SIZE_WITH_TOLERANCE(limit, lval, 0) +class JSAtom; +struct JSErrorFormatString; +class JSLinearString; +struct JSJitInfo; +class JSErrorReport; + namespace JS { template class Heap; @@ -47,11 +54,11 @@ JS_FindCompilationScope(JSContext *cx, JSObject *obj); extern JS_FRIEND_API(JSFunction *) JS_GetObjectFunction(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_SplicePrototype(JSContext *cx, JSObject *obj, JSObject *proto); extern JS_FRIEND_API(JSObject *) -JS_NewObjectWithUniqueType(JSContext *cx, JSClass *clasp, JSObject *proto, JSObject *parent); +JS_NewObjectWithUniqueType(JSContext *cx, const JSClass *clasp, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(uint32_t) JS_ObjectCountDynamicSlots(JS::HandleObject obj); @@ -62,7 +69,7 @@ JS_SetProtoCalled(JSContext *cx); extern JS_FRIEND_API(size_t) JS_GetCustomIteratorCount(JSContext *cx); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_NondeterministicGetWeakMapKeys(JSContext *cx, JSObject *obj, JSObject **ret); /* @@ -71,7 +78,7 @@ JS_NondeterministicGetWeakMapKeys(JSContext *cx, JSObject *obj, JSObject **ret); * Such objects hold no other objects (they have no outgoing reference edges) * and will throw if you touch them (e.g. by reading/writing a property). */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsDeadWrapper(JSObject *obj); /* @@ -112,11 +119,11 @@ JS_GetCompartmentPrincipals(JSCompartment *compartment); extern JS_FRIEND_API(void) JS_SetCompartmentPrincipals(JSCompartment *compartment, JSPrincipals *principals); -/* Safe to call with input obj == NULL. Returns non-NULL iff obj != NULL. */ +/* Safe to call with input obj == nullptr. Returns non-nullptr iff obj != nullptr. */ extern JS_FRIEND_API(JSObject *) JS_ObjectToInnerObject(JSContext *cx, JSObject *obj); -/* Requires obj != NULL. */ +/* Requires obj != nullptr. */ extern JS_FRIEND_API(JSObject *) JS_ObjectToOuterObject(JSContext *cx, JSObject *obj); @@ -126,8 +133,8 @@ JS_CloneObject(JSContext *cx, JSObject *obj, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(JSString *) JS_BasicObjectToString(JSContext *cx, JS::HandleObject obj); -extern JS_FRIEND_API(JSBool) -js_GetterOnlyPropertyStub(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JSBool strict, +extern JS_FRIEND_API(bool) +js_GetterOnlyPropertyStub(JSContext *cx, JS::HandleObject obj, JS::HandleId id, bool strict, JS::MutableHandleValue vp); JS_FRIEND_API(void) @@ -166,18 +173,32 @@ extern JS_FRIEND_API(void) js_DumpChars(const jschar *s, size_t n); #endif +/* + * Copies all own properties from |obj| to |target|. |obj| must be a "native" + * object (that is to say, normal-ish - not an Array or a Proxy). + * + * On entry, |cx| must be in the compartment of |target|. + */ extern JS_FRIEND_API(bool) JS_CopyPropertiesFrom(JSContext *cx, JSObject *target, JSObject *obj); -extern JS_FRIEND_API(JSBool) -JS_WrapPropertyDescriptor(JSContext *cx, js::PropertyDescriptor *desc); +/* + * Single-property version of the above. This function asserts that an |own| + * property of the given name exists on |obj|. + */ +extern JS_FRIEND_API(bool) +JS_CopyPropertyFrom(JSContext *cx, JS::HandleId id, JS::HandleObject target, + JS::HandleObject obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) +JS_WrapPropertyDescriptor(JSContext *cx, JS::MutableHandle desc); + +extern JS_FRIEND_API(bool) JS_WrapAutoIdVector(JSContext *cx, JS::AutoIdVector &props); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_EnumerateState(JSContext *cx, JS::HandleObject obj, JSIterateOp enum_op, - js::MutableHandleValue statep, js::MutableHandleId idp); + JS::MutableHandleValue statep, JS::MutableHandleId idp); struct JSFunctionSpecWithHelp { const char *name; @@ -191,19 +212,49 @@ struct JSFunctionSpecWithHelp { #define JS_FN_HELP(name,call,nargs,flags,usage,help) \ {name, call, nargs, (flags) | JSPROP_ENUMERATE | JSFUN_STUB_GSOPS, usage, help} #define JS_FS_HELP_END \ - {NULL, NULL, 0, 0, NULL, NULL} + {nullptr, nullptr, 0, 0, nullptr, nullptr} extern JS_FRIEND_API(bool) JS_DefineFunctionsWithHelp(JSContext *cx, JSObject *obj, const JSFunctionSpecWithHelp *fs); -typedef bool (* JS_SourceHook)(JSContext *cx, JS::Handle script, - jschar **src, uint32_t *length); - -extern JS_FRIEND_API(void) -JS_SetSourceHook(JSRuntime *rt, JS_SourceHook hook); - namespace js { +/* + * A class of objects that return source code on demand. + * + * When code is compiled with CompileOptions::LAZY_SOURCE, SpiderMonkey + * doesn't retain the source code (and doesn't do lazy bytecode + * generation). If we ever need the source code, say, in response to a call + * to Function.prototype.toSource or Debugger.Source.prototype.text, then + * we call the 'load' member function of the instance of this class that + * has hopefully been registered with the runtime, passing the code's URL, + * and hope that it will be able to find the source. + */ +class SourceHook { + public: + virtual ~SourceHook() { } + + /* + * Set |*src| and |*length| to refer to the source code for |filename|. + * On success, the caller owns the buffer to which |*src| points, and + * should use JS_free to free it. + */ + virtual bool load(JSContext *cx, const char *filename, jschar **src, size_t *length) = 0; +}; + +/* + * Have |rt| use |hook| to retrieve LAZY_SOURCE source code. See the + * comments for SourceHook. The runtime takes ownership of the hook, and + * will delete it when the runtime itself is deleted, or when a new hook is + * set. + */ +extern JS_FRIEND_API(void) +SetSourceHook(JSRuntime *rt, SourceHook *hook); + +/* Remove |rt|'s source hook, and return it. The caller now owns the hook. */ +extern JS_FRIEND_API(SourceHook *) +ForgetSourceHook(JSRuntime *rt); + inline JSRuntime * GetRuntime(const JSContext *cx) { @@ -228,16 +279,21 @@ GetCompartmentZone(JSCompartment *comp); typedef bool (* PreserveWrapperCallback)(JSContext *cx, JSObject *obj); +typedef enum { + CollectNurseryBeforeDump, + IgnoreNurseryObjects +} DumpHeapNurseryBehaviour; + /* * Dump the complete object graph of heap-allocated things. * fp is the file for the dump output. */ extern JS_FRIEND_API(void) -DumpHeapComplete(JSRuntime *rt, FILE *fp); +DumpHeapComplete(JSRuntime *rt, FILE *fp, DumpHeapNurseryBehaviour nurseryBehaviour); -#ifdef OLD_GETTER_SETTER_METHODS -JS_FRIEND_API(JSBool) obj_defineGetter(JSContext *cx, unsigned argc, js::Value *vp); -JS_FRIEND_API(JSBool) obj_defineSetter(JSContext *cx, unsigned argc, js::Value *vp); +#ifdef JS_OLD_GETTER_SETTER_METHODS +JS_FRIEND_API(bool) obj_defineGetter(JSContext *cx, unsigned argc, JS::Value *vp); +JS_FRIEND_API(bool) obj_defineSetter(JSContext *cx, unsigned argc, JS::Value *vp); #endif extern JS_FRIEND_API(bool) @@ -257,7 +313,7 @@ IsAtomsCompartment(JSCompartment *comp); * particularly, always reports when it returns false). */ extern JS_FRIEND_API(bool) -ReportIfUndeclaredVarAssignment(JSContext *cx, HandleString propname); +ReportIfUndeclaredVarAssignment(JSContext *cx, JS::HandleString propname); /* * Returns whether we're in a non-strict property set (in that we're in a @@ -274,7 +330,7 @@ struct WeakMapTracer; * Weak map tracer callback, called once for every binding of every * weak map that was live at the time of the last garbage collection. * - * m will be NULL if the weak map is not contained in a JS Object. + * m will be nullptr if the weak map is not contained in a JS Object. */ typedef void (* WeakMapTraceCallback)(WeakMapTracer *trc, JSObject *m, @@ -330,12 +386,12 @@ GetAnyCompartmentInZone(JS::Zone *zone); namespace shadow { struct TypeObject { - Class *clasp; + const Class *clasp; JSObject *proto; }; struct BaseShape { - js::Class *clasp; + const js::Class *clasp; JSObject *parent; JSObject *_1; JSCompartment *compartment; @@ -353,15 +409,15 @@ public: struct Object { shadow::Shape *shape; shadow::TypeObject *type; - js::Value *slots; - js::Value *_1; + JS::Value *slots; + JS::Value *_1; size_t numFixedSlots() const { return shape->slotInfo >> Shape::FIXED_SLOTS_SHIFT; } - Value *fixedSlots() const { - return (Value *)(uintptr_t(this) + sizeof(shadow::Object)); + JS::Value *fixedSlots() const { + return (JS::Value *)(uintptr_t(this) + sizeof(shadow::Object)); } - js::Value &slotRef(size_t slot) const { + JS::Value &slotRef(size_t slot) const { size_t nfixed = numFixedSlots(); if (slot < nfixed) return fixedSlots()[slot]; @@ -374,7 +430,7 @@ struct Function { uint16_t nargs; uint16_t flags; /* Used only for natives */ - Native native; + JSNative native; const JSJitInfo *jitinfo; void *_1; }; @@ -387,23 +443,17 @@ struct Atom { } /* namespace shadow */ -// These are equal to |&{Function,Object,OuterWindow}ProxyObject::class_|. Use -// them in places where you don't want to #include vm/ProxyObject.h. -extern JS_FRIEND_DATA(js::Class* const) FunctionProxyClassPtr; -extern JS_FRIEND_DATA(js::Class* const) ObjectProxyClassPtr; -extern JS_FRIEND_DATA(js::Class* const) OuterWindowProxyClassPtr; - // This is equal to |&JSObject::class_|. Use it in places where you don't want // to #include jsobj.h. -extern JS_FRIEND_DATA(js::Class* const) ObjectClassPtr; +extern JS_FRIEND_DATA(const js::Class* const) ObjectClassPtr; -inline js::Class * +inline const js::Class * GetObjectClass(JSObject *obj) { return reinterpret_cast(obj)->type->clasp; } -inline JSClass * +inline const JSClass * GetObjectJSClass(JSObject *obj) { return js::Jsvalify(GetObjectClass(obj)); @@ -447,6 +497,16 @@ GetObjectParentMaybeScope(JSObject *obj); JS_FRIEND_API(JSObject *) GetGlobalForObjectCrossCompartment(JSObject *obj); +JS_FRIEND_API(void) +AssertSameCompartment(JSContext *cx, JSObject *obj); + +#ifdef DEBUG +JS_FRIEND_API(void) +AssertSameCompartment(JSObject *objA, JSObject *objB); +#else +inline void AssertSameCompartment(JSObject *objA, JSObject *objB) {} +#endif + // For legacy consumers only. This whole concept is going away soon. JS_FRIEND_API(JSObject *) DefaultObjectForContextOrNull(JSContext *cx); @@ -462,7 +522,7 @@ IsOriginalScriptFunction(JSFunction *fun); /* * Return the outermost enclosing function (script) of the scripted caller. - * This function returns NULL in several cases: + * This function returns nullptr in several cases: * - no script is running on the context * - the caller is in global or eval code * In particular, this function will "stop" its outermost search at eval() and @@ -486,30 +546,18 @@ NewFunctionByIdWithReserved(JSContext *cx, JSNative native, unsigned nargs, unsi JS_FRIEND_API(JSObject *) InitClassWithReserved(JSContext *cx, JSObject *obj, JSObject *parent_proto, - JSClass *clasp, JSNative constructor, unsigned nargs, + const JSClass *clasp, JSNative constructor, unsigned nargs, const JSPropertySpec *ps, const JSFunctionSpec *fs, const JSPropertySpec *static_ps, const JSFunctionSpec *static_fs); -JS_FRIEND_API(const Value &) +JS_FRIEND_API(const JS::Value &) GetFunctionNativeReserved(JSObject *fun, size_t which); JS_FRIEND_API(void) -SetFunctionNativeReserved(JSObject *fun, size_t which, const Value &val); +SetFunctionNativeReserved(JSObject *fun, size_t which, const JS::Value &val); -inline bool -GetObjectProto(JSContext *cx, JS::Handle obj, JS::MutableHandle proto) -{ - js::Class *clasp = GetObjectClass(obj); - if (clasp == js::ObjectProxyClassPtr || - clasp == js::OuterWindowProxyClassPtr || - clasp == js::FunctionProxyClassPtr) - { - return JS_GetPrototype(cx, obj, proto); - } - - proto.set(reinterpret_cast(obj.get())->type->proto); - return true; -} +JS_FRIEND_API(bool) +GetObjectProto(JSContext *cx, JS::Handle obj, JS::MutableHandle proto); inline void * GetObjectPrivate(JSObject *obj) @@ -523,7 +571,7 @@ GetObjectPrivate(JSObject *obj) * Get a slot that is both reserved for object's clasp *and* is fixed (fits * within the maximum capacity for the object's fixed slots). */ -inline const Value & +inline const JS::Value & GetReservedSlot(JSObject *obj, size_t slot) { JS_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); @@ -531,10 +579,10 @@ GetReservedSlot(JSObject *obj, size_t slot) } JS_FRIEND_API(void) -SetReservedSlotWithBarrier(JSObject *obj, size_t slot, const Value &value); +SetReservedSlotWithBarrier(JSObject *obj, size_t slot, const JS::Value &value); inline void -SetReservedSlot(JSObject *obj, size_t slot, const Value &value) +SetReservedSlot(JSObject *obj, size_t slot, const JS::Value &value) { JS_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); shadow::Object *sobj = reinterpret_cast(obj); @@ -553,7 +601,7 @@ SetReservedSlot(JSObject *obj, size_t slot, const Value &value) JS_FRIEND_API(uint32_t) GetObjectSlotSpan(JSObject *obj); -inline const Value & +inline const JS::Value & GetObjectSlot(JSObject *obj, size_t slot) { JS_ASSERT(slot < GetObjectSlotSpan(obj)); @@ -579,26 +627,14 @@ AtomToLinearString(JSAtom *atom) return reinterpret_cast(atom); } -static inline js::PropertyOp -CastAsJSPropertyOp(JSObject *object) -{ - return JS_DATA_TO_FUNC_PTR(js::PropertyOp, object); -} - -static inline js::StrictPropertyOp -CastAsJSStrictPropertyOp(JSObject *object) -{ - return JS_DATA_TO_FUNC_PTR(js::StrictPropertyOp, object); -} +JS_FRIEND_API(bool) +GetPropertyNames(JSContext *cx, JSObject *obj, unsigned flags, JS::AutoIdVector *props); JS_FRIEND_API(bool) -GetPropertyNames(JSContext *cx, JSObject *obj, unsigned flags, js::AutoIdVector *props); +AppendUnique(JSContext *cx, JS::AutoIdVector &base, JS::AutoIdVector &others); JS_FRIEND_API(bool) -AppendUnique(JSContext *cx, AutoIdVector &base, AutoIdVector &others); - -JS_FRIEND_API(bool) -GetGeneric(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id, Value *vp); +GetGeneric(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id, JS::Value *vp); JS_FRIEND_API(bool) StringIsArrayIndex(JSLinearString *str, uint32_t *indexp); @@ -609,6 +645,14 @@ SetPreserveWrapperCallback(JSRuntime *rt, PreserveWrapperCallback callback); JS_FRIEND_API(bool) IsObjectInContextCompartment(JSObject *obj, const JSContext *cx); +/* + * ErrorFromException takes a raw Value so that it's possible to call it during + * GC/CC/whatever, when it may not be possible to get a JSContext to create a + * Rooted. It promises to never ever GC. + */ +JS_FRIEND_API(JSErrorReport*) +ErrorFromException(JS::Value val); + /* * NB: these flag bits are encoded into the bytecode stream in the immediate * operand of JSOP_ITER, so don't change them without advancing vm/Xdr.h's @@ -619,18 +663,18 @@ IsObjectInContextCompartment(JSObject *obj, const JSContext *cx); #define JSITER_KEYVALUE 0x4 /* destructuring for-in wants [key, value] */ #define JSITER_OWNONLY 0x8 /* iterate over obj's own properties only */ #define JSITER_HIDDEN 0x10 /* also enumerate non-enumerable properties */ -#define JSITER_FOR_OF 0x20 /* harmony for-of loop */ -inline uintptr_t -GetNativeStackLimit(const JSRuntime *rt) -{ - return PerThreadDataFriendFields::getMainThread(rt)->nativeStackLimit; -} +JS_FRIEND_API(bool) +RunningWithTrustedPrincipals(JSContext *cx); inline uintptr_t GetNativeStackLimit(JSContext *cx) { - return GetNativeStackLimit(GetRuntime(cx)); + StackKind kind = RunningWithTrustedPrincipals(cx) ? StackForTrustedScript + : StackForUntrustedScript; + PerThreadDataFriendFields *mainThread = + PerThreadDataFriendFields::getMainThread(GetRuntime(cx)); + return mainThread->nativeStackLimit[kind]; } /* @@ -655,6 +699,14 @@ GetNativeStackLimit(JSContext *cx) } \ JS_END_MACRO +#define JS_CHECK_RECURSION_WITH_SP(cx, sp, onerror) \ + JS_BEGIN_MACRO \ + if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ + js_ReportOverRecursed(cx); \ + onerror; \ + } \ + JS_END_MACRO + #define JS_CHECK_CHROME_RECURSION(cx, onerror) \ JS_BEGIN_MACRO \ int stackDummy_; \ @@ -685,94 +737,13 @@ GetPCCountScriptSummary(JSContext *cx, size_t script); JS_FRIEND_API(JSString *) GetPCCountScriptContents(JSContext *cx, size_t script); -/* - * A call stack can be specified to the JS engine such that all JS entry/exits - * to functions push/pop an entry to/from the specified stack. - * - * For more detailed information, see vm/SPSProfiler.h - */ -class ProfileEntry -{ - /* - * All fields are marked volatile to prevent the compiler from re-ordering - * instructions. Namely this sequence: - * - * entry[size] = ...; - * size++; - * - * If the size modification were somehow reordered before the stores, then - * if a sample were taken it would be examining bogus information. - * - * A ProfileEntry represents both a C++ profile entry and a JS one. Both use - * the string as a description, but JS uses the sp as NULL to indicate that - * it is a JS entry. The script_ is then only ever examined for a JS entry, - * and the idx is used by both, but with different meanings. - */ - const char * volatile string; // Descriptive string of this entry - void * volatile sp; // Relevant stack pointer for the entry - JSScript * volatile script_; // if js(), non-null script which is running - int32_t volatile idx; // if js(), idx of pc, otherwise line number - - public: - /* - * All of these methods are marked with the 'volatile' keyword because SPS's - * representation of the stack is stored such that all ProfileEntry - * instances are volatile. These methods would not be available unless they - * were marked as volatile as well - */ - - bool js() volatile { - JS_ASSERT_IF(sp == NULL, script_ != NULL); - return sp == NULL; - } - - uint32_t line() volatile { JS_ASSERT(!js()); return idx; } - JSScript *script() volatile { JS_ASSERT(js()); return script_; } - void *stackAddress() volatile { return sp; } - const char *label() volatile { return string; } - - void setLine(uint32_t aLine) volatile { JS_ASSERT(!js()); idx = aLine; } - void setLabel(const char *aString) volatile { string = aString; } - void setStackAddress(void *aSp) volatile { sp = aSp; } - void setScript(JSScript *aScript) volatile { script_ = aScript; } - - /* we can't know the layout of JSScript, so look in vm/SPSProfiler.cpp */ - JS_FRIEND_API(jsbytecode *) pc() volatile; - JS_FRIEND_API(void) setPC(jsbytecode *pc) volatile; - - static size_t offsetOfString() { return offsetof(ProfileEntry, string); } - static size_t offsetOfStackAddress() { return offsetof(ProfileEntry, sp); } - static size_t offsetOfPCIdx() { return offsetof(ProfileEntry, idx); } - static size_t offsetOfScript() { return offsetof(ProfileEntry, script_); } - - /* - * The index used in the entry can either be a line number or the offset of - * a pc into a script's code. To signify a NULL pc, use a -1 index. This is - * checked against in pc() and setPC() to set/get the right pc. - */ - static const int32_t NullPCIndex = -1; -}; - -JS_FRIEND_API(void) -SetRuntimeProfilingStack(JSRuntime *rt, ProfileEntry *stack, uint32_t *size, - uint32_t max); - -JS_FRIEND_API(void) -EnableRuntimeProfilingStack(JSRuntime *rt, bool enabled); - -JS_FRIEND_API(jsbytecode*) -ProfilingGetPC(JSRuntime *rt, JSScript *script, void *ip); - #ifdef JS_THREADSAFE JS_FRIEND_API(bool) ContextHasOutstandingRequests(const JSContext *cx); #endif -JS_FRIEND_API(bool) -HasUnrootedGlobal(const JSContext *cx); - typedef void -(* ActivityCallback)(void *arg, JSBool active); +(* ActivityCallback)(void *arg, bool active); /* * Sets a callback that is run whenever the runtime goes idle - the @@ -785,22 +756,10 @@ SetActivityCallback(JSRuntime *rt, ActivityCallback cb, void *arg); extern JS_FRIEND_API(const JSStructuredCloneCallbacks *) GetContextStructuredCloneCallbacks(JSContext *cx); -extern JS_FRIEND_API(bool) -CanCallContextDebugHandler(JSContext *cx); - -extern JS_FRIEND_API(JSTrapStatus) -CallContextDebugHandler(JSContext *cx, JSScript *script, jsbytecode *bc, Value *rval); - extern JS_FRIEND_API(bool) IsContextRunningJS(JSContext *cx); -typedef void -(* AnalysisPurgeCallback)(JSRuntime *rt, JS::Handle desc); - -extern JS_FRIEND_API(AnalysisPurgeCallback) -SetAnalysisPurgeCallback(JSRuntime *rt, AnalysisPurgeCallback callback); - -typedef JSBool +typedef bool (* DOMInstanceClassMatchesProto)(JS::HandleObject protoObject, uint32_t protoID, uint32_t depth); struct JSDOMCallbacks { @@ -832,10 +791,10 @@ CastToJSFreeOp(FreeOp *fop) /* * Get an error type name from a JSExnType constant. - * Returns NULL for invalid arguments and JSEXN_INTERNALERR + * Returns nullptr for invalid arguments and JSEXN_INTERNALERR */ extern JS_FRIEND_API(const jschar*) -GetErrorTypeName(JSContext* cx, int16_t exnType); +GetErrorTypeName(JSRuntime* rt, int16_t exnType); #ifdef DEBUG extern JS_FRIEND_API(unsigned) @@ -886,7 +845,7 @@ struct CompartmentsWithPrincipals : public CompartmentFilter { } }; -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) NukeCrossCompartmentWrappers(JSContext* cx, const CompartmentFilter& sourceFilter, const CompartmentFilter& targetFilter, @@ -910,7 +869,7 @@ NukeCrossCompartmentWrappers(JSContext* cx, struct ExpandoAndGeneration { ExpandoAndGeneration() - : expando(UndefinedValue()), + : expando(JS::UndefinedValue()), generation(0) {} @@ -933,10 +892,10 @@ typedef enum DOMProxyShadowsResult { typedef DOMProxyShadowsResult (* DOMProxyShadowsCheck)(JSContext* cx, JS::HandleObject object, JS::HandleId id); JS_FRIEND_API(void) -SetDOMProxyInformation(void *domProxyHandlerFamily, uint32_t domProxyExpandoSlot, +SetDOMProxyInformation(const void *domProxyHandlerFamily, uint32_t domProxyExpandoSlot, DOMProxyShadowsCheck domProxyShadowsCheck); -void *GetDOMProxyHandlerFamily(); +const void *GetDOMProxyHandlerFamily(); uint32_t GetDOMProxyExpandoSlot(); DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); @@ -948,7 +907,7 @@ DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); * Detect whether the internal date value is NaN. (Because failure is * out-of-band for js_DateGet*) */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_DateIsValid(JSObject* obj); extern JS_FRIEND_API(double) @@ -1008,136 +967,6 @@ enum ViewType { } /* namespace ArrayBufferView */ -/* - * A helper for building up an ArrayBuffer object's data - * before creating the ArrayBuffer itself. Will do doubling - * based reallocation, up to an optional maximum growth given. - * - * When all the data has been appended, call getArrayBuffer, - * passing in the JSContext* for which the ArrayBuffer object - * is to be created. This also implicitly resets the builder, - * or it can be reset explicitly at any point by calling reset(). - */ -class ArrayBufferBuilder -{ - void *rawcontents_; - uint8_t *dataptr_; - uint32_t capacity_; - uint32_t length_; - public: - ArrayBufferBuilder() - : rawcontents_(NULL), - dataptr_(NULL), - capacity_(0), - length_(0) - { - } - - ~ArrayBufferBuilder() { - reset(); - } - - void reset() { - if (rawcontents_) - JS_free(NULL, rawcontents_); - rawcontents_ = dataptr_ = NULL; - capacity_ = length_ = 0; - } - - // will truncate if newcap is < length() - bool setCapacity(uint32_t newcap) { - if (!JS_ReallocateArrayBufferContents(NULL, newcap, &rawcontents_, &dataptr_)) - return false; - - capacity_ = newcap; - if (length_ > newcap) - length_ = newcap; - - return true; - } - - // Append datalen bytes from data to the current buffer. If we - // need to grow the buffer, grow by doubling the size up to a - // maximum of maxgrowth (if given). If datalen is greater than - // what the new capacity would end up as, then grow by datalen. - // - // The data parameter must not overlap with anything beyond the - // builder's current valid contents [0..length) - bool append(const uint8_t *newdata, uint32_t datalen, uint32_t maxgrowth = 0) { - if (length_ + datalen > capacity_) { - uint32_t newcap; - // double while under maxgrowth or if not specified - if (!maxgrowth || capacity_ < maxgrowth) - newcap = capacity_ * 2; - else - newcap = capacity_ + maxgrowth; - - // but make sure there's always enough to satisfy our request - if (newcap < length_ + datalen) - newcap = length_ + datalen; - - // did we overflow? - if (newcap < capacity_) - return false; - - if (!setCapacity(newcap)) - return false; - } - - // assert that the region isn't overlapping so we can memcpy; - JS_ASSERT(!areOverlappingRegions(newdata, datalen, dataptr_ + length_, datalen)); - - memcpy(dataptr_ + length_, newdata, datalen); - length_ += datalen; - - return true; - } - - uint8_t *data() { - return dataptr_; - } - - uint32_t length() { - return length_; - } - - uint32_t capacity() { - return capacity_; - } - - JSObject* getArrayBuffer(JSContext *cx) { - // we need to check for length_ == 0, because nothing may have been - // added - if (capacity_ > length_ || length_ == 0) { - if (!setCapacity(length_)) - return NULL; - } - - JSObject* obj = JS_NewArrayBufferWithContents(cx, rawcontents_); - if (!obj) - return NULL; - - rawcontents_ = dataptr_ = NULL; - length_ = capacity_ = 0; - - return obj; - } - -protected: - - static bool areOverlappingRegions(const uint8_t *start1, uint32_t length1, - const uint8_t *start2, uint32_t length2) - { - const uint8_t *end1 = start1 + length1; - const uint8_t *end2 = start2 + length2; - - const uint8_t *max_start = start1 > start2 ? start1 : start2; - const uint8_t *min_end = end1 < end2 ? end1 : end2; - - return max_start < min_end; - } -}; - } /* namespace js */ typedef js::ArrayBufferView::ViewType JSArrayBufferViewType; @@ -1241,7 +1070,7 @@ JS_NewArrayBuffer(JSContext *cx, uint32_t nbytes); * this test or one of the JS_Is*Array tests succeeds, then it is safe to call * the various accessor JSAPI calls defined below. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsTypedArrayObject(JSObject *obj); /* @@ -1251,36 +1080,36 @@ JS_IsTypedArrayObject(JSObject *obj); * is safe to call the various ArrayBufferView accessor JSAPI calls defined * below. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsArrayBufferViewObject(JSObject *obj); /* * Test for specific typed array types (ArrayBufferView subtypes) */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsInt8Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint8Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint8ClampedArray(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsInt16Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint16Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsInt32Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint32Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsFloat32Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsFloat64Array(JSObject *obj); /* - * Unwrap Typed arrays all at once. Return NULL without throwing if the object - * cannot be viewed as the correct typed array, or the typed array object on - * success, filling both outparameters. + * Unwrap Typed arrays all at once. Return nullptr without throwing if the + * object cannot be viewed as the correct typed array, or the typed array + * object on success, filling both outparameters. */ extern JS_FRIEND_API(JSObject *) JS_GetObjectAsInt8Array(JSObject *obj, uint32_t *length, int8_t **data); @@ -1321,7 +1150,7 @@ JS_GetArrayBufferViewType(JSObject *obj); * unwrapping. If this test succeeds, then it is safe to call the various * accessor JSAPI calls defined below. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsArrayBufferObject(JSObject *obj); /* @@ -1382,7 +1211,7 @@ JS_GetTypedArrayByteLength(JSObject *obj); * return false if a security wrapper is encountered that denies the * unwrapping. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsArrayBufferViewObject(JSObject *obj); /* @@ -1435,10 +1264,16 @@ JS_GetArrayBufferViewData(JSObject *obj); extern JS_FRIEND_API(JSObject *) JS_GetArrayBufferViewBuffer(JSObject *obj); +/* + * Set an ArrayBuffer's length to 0 and neuter all of its views. + */ +extern JS_FRIEND_API(void) +JS_NeuterArrayBuffer(JSObject *obj, JSContext *cx); + /* * Check whether obj supports JS_GetDataView* APIs. */ -JS_FRIEND_API(JSBool) +JS_FRIEND_API(bool) JS_IsDataViewObject(JSObject *obj); /* @@ -1457,7 +1292,7 @@ JS_GetDataViewByteOffset(JSObject *obj); * * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is NULL, then DEBUG builds may be + * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be * unable to assert when unwrapping should be disallowed. */ JS_FRIEND_API(uint32_t) @@ -1468,12 +1303,39 @@ JS_GetDataViewByteLength(JSObject *obj); * * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is NULL, then DEBUG builds may be + * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be * unable to assert when unwrapping should be disallowed. */ JS_FRIEND_API(void *) JS_GetDataViewData(JSObject *obj); +namespace js { + +/* + * Add a watchpoint -- in the Object.prototype.watch sense -- to |obj| for the + * property |id|, using the callable object |callable| as the function to be + * called for notifications. + * + * This is an internal function exposed -- temporarily -- only so that DOM + * proxies can be watchable. Don't use it! We'll soon kill off the + * Object.prototype.{,un}watch functions, at which point this will go too. + */ +extern JS_FRIEND_API(bool) +WatchGuts(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); + +/* + * Remove a watchpoint -- in the Object.prototype.watch sense -- from |obj| for + * the property |id|. + * + * This is an internal function exposed -- temporarily -- only so that DOM + * proxies can be watchable. Don't use it! We'll soon kill off the + * Object.prototype.{,un}watch functions, at which point this will go too. + */ +extern JS_FRIEND_API(bool) +UnwatchGuts(JSContext *cx, JS::HandleObject obj, JS::HandleId id); + +} // namespace js + /* * A class, expected to be passed by value, which represents the CallArgs for a * JSJitGetterOp. @@ -1599,7 +1461,7 @@ struct JSJitInfo { }; #define JS_JITINFO_NATIVE_PARALLEL(op) \ - {{NULL},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} + {{nullptr},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} static JS_ALWAYS_INLINE const JSJitInfo * FUNCTION_VALUE_TO_JITINFO(const JS::Value& v) @@ -1632,6 +1494,12 @@ JSID_FROM_BITS(size_t bits) return id; } +namespace js { +namespace detail { +bool IdMatchesAtom(jsid id, JSAtom *atom); +} +} + /* * Must not be used on atoms that are representable as integer jsids. * Prefer NameToId or AtomToId over this function: @@ -1658,18 +1526,18 @@ NON_INTEGER_ATOM_TO_JSID(JSAtom *atom) { JS_ASSERT(((size_t)atom & 0x7) == 0); jsid id = JSID_FROM_BITS((size_t)atom); - JS_ASSERT(id == INTERNED_STRING_TO_JSID(NULL, (JSString*)atom)); + JS_ASSERT(js::detail::IdMatchesAtom(id, atom)); return id; } /* All strings stored in jsids are atomized, but are not necessarily property names. */ -static JS_ALWAYS_INLINE JSBool +static JS_ALWAYS_INLINE bool JSID_IS_ATOM(jsid id) { return JSID_IS_STRING(id); } -static JS_ALWAYS_INLINE JSBool +static JS_ALWAYS_INLINE bool JSID_IS_ATOM(jsid id, JSAtom *atom) { return id == JSID_FROM_BITS((size_t)atom); @@ -1681,21 +1549,21 @@ JSID_TO_ATOM(jsid id) return (JSAtom *)JSID_TO_STRING(id); } -JS_STATIC_ASSERT(sizeof(jsid) == JS_BYTES_PER_WORD); +JS_STATIC_ASSERT(sizeof(jsid) == sizeof(void*)); namespace js { -static JS_ALWAYS_INLINE Value +static JS_ALWAYS_INLINE JS::Value IdToValue(jsid id) { if (JSID_IS_STRING(id)) - return StringValue(JSID_TO_STRING(id)); + return JS::StringValue(JSID_TO_STRING(id)); if (JS_LIKELY(JSID_IS_INT(id))) - return Int32Value(JSID_TO_INT(id)); + return JS::Int32Value(JSID_TO_INT(id)); if (JS_LIKELY(JSID_IS_OBJECT(id))) - return ObjectValue(*JSID_TO_OBJECT(id)); + return JS::ObjectValue(*JSID_TO_OBJECT(id)); JS_ASSERT(JSID_IS_VOID(id)); - return UndefinedValue(); + return JS::UndefinedValue(); } static JS_ALWAYS_INLINE jsval @@ -1710,6 +1578,20 @@ IsReadOnlyDateMethod(JS::IsAcceptableThis test, JS::NativeImpl method); extern JS_FRIEND_API(bool) IsTypedArrayThisCheck(JS::IsAcceptableThis test); +/* + * If the embedder has registered a default JSContext callback, returns the + * result of the callback. Otherwise, asserts that |rt| has exactly one + * JSContext associated with it, and returns that context. + */ +extern JS_FRIEND_API(JSContext *) +DefaultJSContext(JSRuntime *rt); + +typedef JSContext* +(* DefaultJSContextCallback)(JSRuntime *rt); + +JS_FRIEND_API(void) +SetDefaultJSContextCallback(JSRuntime *rt, DefaultJSContextCallback cb); + enum CTypesActivityType { CTYPES_CALL_BEGIN, CTYPES_CALL_END, @@ -1744,7 +1626,7 @@ class JS_FRIEND_API(AutoCTypesActivityCallback) { void DoEndCallback() { if (callback) { callback(cx, endType); - callback = NULL; + callback = nullptr; } } }; @@ -1777,8 +1659,8 @@ JS_FRIEND_API(JSObject *) GetObjectMetadata(JSObject *obj); /* ES5 8.12.8. */ -extern JS_FRIEND_API(JSBool) -DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, MutableHandleValue vp); +extern JS_FRIEND_API(bool) +DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, JS::MutableHandleValue vp); /* * Helper function. To approximate a call to the [[DefineOwnProperty]] internal @@ -1794,16 +1676,16 @@ DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, MutableHandleValu * js::ProxyHandler, or the JSAPI with precisely the right semantics for it. */ extern JS_FRIEND_API(bool) -CheckDefineProperty(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); +CheckDefineProperty(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue value, + JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs); } /* namespace js */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_DefineOwnProperty(JSContext *cx, JSObject *objArg, jsid idArg, - const js::PropertyDescriptor& descriptor, JSBool *bp); + JS::Handle descriptor, bool *bp); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_ReportIsNotFunction(JSContext *cx, const JS::Value& v); #ifdef JSGC_GENERATIONAL diff --git a/external/spidermonkey/include/mac/jslock.h b/external/spidermonkey/include/mac/jslock.h deleted file mode 100644 index 522034ad68..0000000000 --- a/external/spidermonkey/include/mac/jslock.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -#ifndef jslock_h -#define jslock_h - -#ifdef JS_THREADSAFE - -# include "jsapi.h" -# include "pratom.h" -# include "prcvar.h" -# include "prinit.h" -# include "prlock.h" -# include "prthread.h" - -# define JS_ATOMIC_INCREMENT(p) PR_ATOMIC_INCREMENT((int32_t *)(p)) -# define JS_ATOMIC_DECREMENT(p) PR_ATOMIC_DECREMENT((int32_t *)(p)) -# define JS_ATOMIC_ADD(p,v) PR_ATOMIC_ADD((int32_t *)(p), (int32_t)(v)) -# define JS_ATOMIC_SET(p,v) PR_ATOMIC_SET((int32_t *)(p), (int32_t)(v)) - -namespace js { - // Defined in jsgc.cpp. - unsigned GetCPUCount(); -} - -#else /* JS_THREADSAFE */ - -typedef struct PRThread PRThread; -typedef struct PRCondVar PRCondVar; -typedef struct PRLock PRLock; - -# define JS_ATOMIC_INCREMENT(p) (++*(p)) -# define JS_ATOMIC_DECREMENT(p) (--*(p)) -# define JS_ATOMIC_ADD(p,v) (*(p) += (v)) -# define JS_ATOMIC_SET(p,v) (*(p) = (v)) - -#endif /* JS_THREADSAFE */ - -#endif /* jslock_h */ diff --git a/external/spidermonkey/include/mac/jsperf.h b/external/spidermonkey/include/mac/jsperf.h index 468ce8609c..e3cbc23143 100644 --- a/external/spidermonkey/include/mac/jsperf.h +++ b/external/spidermonkey/include/mac/jsperf.h @@ -6,7 +6,10 @@ #ifndef perf_jsperf_h #define perf_jsperf_h -#include "jsapi.h" +#include "jstypes.h" + +#include "js/TypeDecls.h" +#include "js/Utility.h" namespace JS { @@ -118,12 +121,12 @@ extern JS_FRIEND_API(JSObject*) RegisterPerfMeasurement(JSContext *cx, JSObject *global); /* - * Given a jsval which contains an instance of the aforementioned - * wrapper class, extract the C++ object. Returns NULL if the - * jsval is not an instance of the wrapper. + * Given a Value which contains an instance of the aforementioned + * wrapper class, extract the C++ object. Returns nullptr if the + * Value is not an instance of the wrapper. */ extern JS_FRIEND_API(PerfMeasurement*) - ExtractPerfMeasurement(jsval wrapper); + ExtractPerfMeasurement(Value wrapper); } // namespace JS diff --git a/external/spidermonkey/include/mac/jsprf.h b/external/spidermonkey/include/mac/jsprf.h index ce159d8115..b235f0b4fb 100644 --- a/external/spidermonkey/include/mac/jsprf.h +++ b/external/spidermonkey/include/mac/jsprf.h @@ -26,7 +26,6 @@ */ #include -#include #include "jstypes.h" @@ -39,7 +38,7 @@ extern JS_PUBLIC_API(uint32_t) JS_snprintf(char *out, uint32_t outlen, const cha /* ** sprintf into a malloc'd buffer. Return a pointer to the malloc'd -** buffer on success, NULL on failure. Call "JS_smprintf_free" to release +** buffer on success, nullptr on failure. Call "JS_smprintf_free" to release ** the memory returned. */ extern JS_PUBLIC_API(char*) JS_smprintf(const char *fmt, ...); @@ -52,9 +51,9 @@ extern JS_PUBLIC_API(void) JS_smprintf_free(char *mem); /* ** "append" sprintf into a malloc'd buffer. "last" is the last value of ** the malloc'd buffer. sprintf will append data to the end of last, -** growing it as necessary using realloc. If last is NULL, JS_sprintf_append +** growing it as necessary using realloc. If last is nullptr, JS_sprintf_append ** will allocate the initial string. The return value is the new value of -** last for subsequent calls, or NULL if there is a malloc failure. +** last for subsequent calls, or nullptr if there is a malloc failure. */ extern JS_PUBLIC_API(char*) JS_sprintf_append(char *last, const char *fmt, ...); diff --git a/external/spidermonkey/include/mac/jsprototypes.h b/external/spidermonkey/include/mac/jsprototypes.h index f9bacac409..b0fee8c468 100644 --- a/external/spidermonkey/include/mac/jsprototypes.h +++ b/external/spidermonkey/include/mac/jsprototypes.h @@ -9,8 +9,6 @@ #ifndef jsprototypes_h #define jsprototypes_h -#include "jsversion.h" - /* * Enumerator codes in the second column must not change -- they are part of * the JS XDR API. Also note the symbols in the third column are extern "C"; @@ -56,20 +54,7 @@ macro(DataView, 35, js_InitTypedArrayClasses) \ macro(ParallelArray, 36, js_InitParallelArrayClass) \ macro(Intl, 37, js_InitIntlClass) \ - macro(Type, 38, js_InitBinaryDataClasses) \ - macro(Data, 39, js_InitBinaryDataClasses) \ - macro(uint8, 40, js_InitBinaryDataClasses) \ - macro(uint16, 41, js_InitBinaryDataClasses) \ - macro(uint32, 42, js_InitBinaryDataClasses) \ - macro(uint64, 43, js_InitBinaryDataClasses) \ - macro(int8, 44, js_InitBinaryDataClasses) \ - macro(int16, 45, js_InitBinaryDataClasses) \ - macro(int32, 46, js_InitBinaryDataClasses) \ - macro(int64, 47, js_InitBinaryDataClasses) \ - macro(float32, 48, js_InitBinaryDataClasses) \ - macro(float64, 49, js_InitBinaryDataClasses) \ - macro(ArrayType, 50, js_InitBinaryDataClasses) \ - macro(StructType, 51, js_InitBinaryDataClasses) \ - macro(ArrayTypeObject, 52, js_InitBinaryDataClasses) \ + macro(TypedObject, 38, js_InitTypedObjectDummy) \ + macro(GeneratorFunction, 39, js_InitIteratorClasses) \ #endif /* jsprototypes_h */ diff --git a/external/spidermonkey/include/mac/jsproxy.h b/external/spidermonkey/include/mac/jsproxy.h index 56868a05c3..c54e300d73 100644 --- a/external/spidermonkey/include/mac/jsproxy.h +++ b/external/spidermonkey/include/mac/jsproxy.h @@ -7,11 +7,29 @@ #ifndef jsproxy_h #define jsproxy_h -#include "jsapi.h" +#include "mozilla/Maybe.h" + #include "jsfriendapi.h" +#include "js/CallNonGenericMethod.h" +#include "js/Class.h" + namespace js { +using JS::AutoIdVector; +using JS::CallArgs; +using JS::HandleId; +using JS::HandleObject; +using JS::HandleValue; +using JS::IsAcceptableThis; +using JS::MutableHandle; +using JS::MutableHandleObject; +using JS::MutableHandleValue; +using JS::NativeImpl; +using JS::PrivateValue; +using JS::Value; + +class RegExpGuard; class JS_FRIEND_API(Wrapper); /* @@ -49,7 +67,7 @@ class JS_FRIEND_API(Wrapper); */ class JS_FRIEND_API(BaseProxyHandler) { - void *mFamily; + const void *mFamily; bool mHasPrototype; bool mHasPolicy; protected: @@ -58,7 +76,7 @@ class JS_FRIEND_API(BaseProxyHandler) void setHasPolicy(bool aHasPolicy) { mHasPolicy = aHasPolicy; } public: - explicit BaseProxyHandler(void *family); + explicit BaseProxyHandler(const void *family); virtual ~BaseProxyHandler(); bool hasPrototype() { @@ -69,9 +87,12 @@ class JS_FRIEND_API(BaseProxyHandler) return mHasPolicy; } - inline void *family() { + inline const void *family() { return mFamily; } + static size_t offsetOfFamily() { + return offsetof(BaseProxyHandler, mFamily); + } virtual bool isOuterWindow() { return false; @@ -106,12 +127,13 @@ class JS_FRIEND_API(BaseProxyHandler) /* ES5 Harmony fundamental proxy traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject proxy) = 0; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags) = 0; + MutableHandle desc, + unsigned flags) = 0; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, - HandleId id, PropertyDescriptor *desc, + HandleId id, MutableHandle desc, unsigned flags) = 0; virtual bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc) = 0; + MutableHandle desc) = 0; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props) = 0; virtual bool delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) = 0; @@ -144,7 +166,13 @@ class JS_FRIEND_API(BaseProxyHandler) uint32_t index, MutableHandleValue vp, bool *present); virtual bool getPrototypeOf(JSContext *cx, HandleObject proxy, MutableHandleObject protop); - /* See comment for weakmapKeyDelegateOp in jsclass.h. */ + // These two hooks must be overridden, or not overridden, in tandem -- no + // overriding just one! + virtual bool watch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id, + JS::HandleObject callable); + virtual bool unwatch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id); + + /* See comment for weakmapKeyDelegateOp in js/Class.h. */ virtual JSObject *weakmapKeyDelegate(JSObject *proxy); }; @@ -157,17 +185,17 @@ class JS_FRIEND_API(BaseProxyHandler) class JS_PUBLIC_API(DirectProxyHandler) : public BaseProxyHandler { public: - explicit DirectProxyHandler(void *family); + explicit DirectProxyHandler(const void *family); /* ES5 Harmony fundamental proxy traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject proxy) MOZ_OVERRIDE; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, unsigned flags) MOZ_OVERRIDE; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, - HandleId id, PropertyDescriptor *desc, + HandleId id, MutableHandle desc, unsigned flags) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props) MOZ_OVERRIDE; virtual bool delete_(JSContext *cx, HandleObject proxy, HandleId id, @@ -204,8 +232,6 @@ class JS_PUBLIC_API(DirectProxyHandler) : public BaseProxyHandler unsigned indent) MOZ_OVERRIDE; virtual bool regexp_toShared(JSContext *cx, HandleObject proxy, RegExpGuard *g) MOZ_OVERRIDE; - virtual bool defaultValue(JSContext *cx, HandleObject obj, JSType hint, - MutableHandleValue vp) MOZ_OVERRIDE; virtual JSObject *weakmapKeyDelegate(JSObject *proxy); }; @@ -216,14 +242,15 @@ class Proxy /* ES5 Harmony fundamental proxy traps. */ static bool preventExtensions(JSContext *cx, HandleObject proxy); static bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags); + MutableHandle desc, unsigned flags); static bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, unsigned flags, HandleId id, MutableHandleValue vp); static bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags); + MutableHandle desc, unsigned flags); static bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, unsigned flags, HandleId id, MutableHandleValue vp); - static bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, PropertyDescriptor *desc); + static bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, + MutableHandle desc); static bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, HandleValue v); static bool getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props); static bool delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp); @@ -254,32 +281,27 @@ class Proxy static bool defaultValue(JSContext *cx, HandleObject obj, JSType hint, MutableHandleValue vp); static bool getPrototypeOf(JSContext *cx, HandleObject proxy, MutableHandleObject protop); + static bool watch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id, + JS::HandleObject callable); + static bool unwatch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id); + + /* IC entry path for handling __noSuchMethod__ on access. */ + static bool callProp(JSContext *cx, HandleObject proxy, HandleObject reveiver, HandleId id, + MutableHandleValue vp); + static JSObject * const LazyProto; }; -inline bool IsObjectProxyClass(const Class *clasp) -{ - return clasp == js::ObjectProxyClassPtr || clasp == js::OuterWindowProxyClassPtr; -} - -inline bool IsFunctionProxyClass(const Class *clasp) -{ - return clasp == js::FunctionProxyClassPtr; -} +// Use these in places where you don't want to #include vm/ProxyObject.h. +extern JS_FRIEND_DATA(const js::Class* const) CallableProxyClassPtr; +extern JS_FRIEND_DATA(const js::Class* const) UncallableProxyClassPtr; +extern JS_FRIEND_DATA(const js::Class* const) OuterWindowProxyClassPtr; inline bool IsProxyClass(const Class *clasp) { - return IsObjectProxyClass(clasp) || IsFunctionProxyClass(clasp); -} - -inline bool IsObjectProxy(JSObject *obj) -{ - return IsObjectProxyClass(GetObjectClass(obj)); -} - -inline bool IsFunctionProxy(JSObject *obj) -{ - return IsFunctionProxyClass(GetObjectClass(obj)); + return clasp == CallableProxyClassPtr || + clasp == UncallableProxyClassPtr || + clasp == OuterWindowProxyClassPtr; } inline bool IsProxy(JSObject *obj) @@ -342,14 +364,42 @@ SetProxyExtra(JSObject *obj, size_t n, const Value &extra) SetReservedSlot(obj, PROXY_EXTRA_SLOT + n, extra); } -enum ProxyCallable { - ProxyNotCallable = false, - ProxyIsCallable = true +class MOZ_STACK_CLASS ProxyOptions { + public: + ProxyOptions() : callable_(false), + singleton_(false), + forceForegroundFinalization_(false) + {} + + bool callable() const { return callable_; } + ProxyOptions &setCallable(bool flag) { + callable_ = flag; + return *this; + } + + bool singleton() const { return singleton_; } + ProxyOptions &setSingleton(bool flag) { + singleton_ = flag; + return *this; + } + + bool forceForegroundFinalization() const { + return forceForegroundFinalization_; + } + ProxyOptions &setForceForegroundFinalization(bool flag) { + forceForegroundFinalization_ = true; + return *this; + } + + private: + bool callable_; + bool singleton_; + bool forceForegroundFinalization_; }; JS_FRIEND_API(JSObject *) NewProxyObject(JSContext *cx, BaseProxyHandler *handler, HandleValue priv, - JSObject *proto, JSObject *parent, ProxyCallable callable = ProxyNotCallable); + JSObject *proto, JSObject *parent, const ProxyOptions &options = ProxyOptions()); JSObject * RenewProxyObject(JSContext *cx, JSObject *obj, BaseProxyHandler *handler, Value priv); @@ -361,7 +411,7 @@ class JS_FRIEND_API(AutoEnterPolicy) AutoEnterPolicy(JSContext *cx, BaseProxyHandler *handler, HandleObject wrapper, HandleId id, Action act, bool mayThrow) #ifdef DEBUG - : context(NULL) + : context(nullptr) #endif { allow = handler->hasPolicy() ? handler->enter(cx, wrapper, id, act, &rv) @@ -372,8 +422,8 @@ class JS_FRIEND_API(AutoEnterPolicy) // * The policy set rv to false, indicating that we should throw. // * The caller did not instruct us to ignore exceptions. // * The policy did not throw itself. - if (!allow && !rv && mayThrow && !JS_IsExceptionPending(cx)) - reportError(cx, id); + if (!allow && !rv && mayThrow) + reportErrorIfExceptionIsNotPending(cx, id); } virtual ~AutoEnterPolicy() { recordLeave(); } @@ -384,10 +434,10 @@ class JS_FRIEND_API(AutoEnterPolicy) // no-op constructor for subclass AutoEnterPolicy() #ifdef DEBUG - : context(NULL) + : context(nullptr) #endif {}; - void reportError(JSContext *cx, jsid id); + void reportErrorIfExceptionIsNotPending(JSContext *cx, jsid id); bool allow; bool rv; diff --git a/external/spidermonkey/include/mac/jsprvtd.h b/external/spidermonkey/include/mac/jsprvtd.h deleted file mode 100644 index 1fbc086a7c..0000000000 --- a/external/spidermonkey/include/mac/jsprvtd.h +++ /dev/null @@ -1,297 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -#ifndef jsprvtd_h -#define jsprvtd_h -/* - * JS private typename definitions. - * - * This header is included only in other .h files, for convenience and for - * simplicity of type naming. The alternative for structures is to use tags, - * which are named the same as their typedef names (legal in C/C++, and less - * noisy than suffixing the typedef name with "Struct" or "Str"). Instead, - * all .h files that include this file may use the same typedef name, whether - * declaring a pointer to struct type, or defining a member of struct type. - * - * A few fundamental scalar types are defined here too. Neither the scalar - * nor the struct typedefs should change much, therefore the nearly-global - * make dependency induced by this file should not prove painful. - */ - -#include "jsapi.h" -#include "jsutil.h" - -#include "js/HashTable.h" -#include "js/Vector.h" - -/* - * Convenience constants. - */ -#define JS_BITS_PER_UINT32_LOG2 5 -#define JS_BITS_PER_UINT32 32 - -/* The alignment required of objects stored in GC arenas. */ -static const unsigned JS_GCTHING_ALIGN = 8; -static const unsigned JS_GCTHING_ZEROBITS = 3; - -/* Scalar typedefs. */ -typedef uint8_t jsbytecode; -typedef uint8_t jssrcnote; -typedef uintptr_t jsatomid; - -/* Struct typedefs. */ -typedef struct JSGCThing JSGCThing; -typedef struct JSGenerator JSGenerator; -typedef struct JSNativeEnumerator JSNativeEnumerator; -typedef struct JSTryNote JSTryNote; - -/* Friend "Advanced API" typedefs. */ -typedef struct JSAtomState JSAtomState; -typedef struct JSCodeSpec JSCodeSpec; -typedef struct JSPrinter JSPrinter; -typedef struct JSStackHeader JSStackHeader; -typedef struct JSSubString JSSubString; -typedef struct JSSpecializedNative JSSpecializedNative; - -/* String typedefs. */ -class JSDependentString; -class JSExtensibleString; -class JSExternalString; -class JSLinearString; -class JSRope; -class JSAtom; -class JSWrapper; - -namespace js { - -struct ArgumentsData; -struct Class; - -class AutoNameVector; -class RegExpGuard; -class RegExpObject; -class RegExpObjectBuilder; -class RegExpShared; -class RegExpStatics; -class MatchPairs; -class PropertyName; -class LazyScript; - -enum RegExpFlag -{ - IgnoreCaseFlag = 0x01, - GlobalFlag = 0x02, - MultilineFlag = 0x04, - StickyFlag = 0x08, - - NoFlags = 0x00, - AllFlags = 0x0f -}; - -class StringBuffer; - -class FrameRegs; -class StackFrame; -class ScriptFrameIter; - -class Proxy; -class JS_FRIEND_API(AutoEnterPolicy); -class JS_FRIEND_API(BaseProxyHandler); -class JS_FRIEND_API(Wrapper); -class JS_FRIEND_API(CrossCompartmentWrapper); - -class TempAllocPolicy; -class RuntimeAllocPolicy; - -class GlobalObject; - -template -class InlineMap; - -class LifoAlloc; - -class Shape; - -class Breakpoint; -class BreakpointSite; -class Debugger; -class WatchpointMap; - -/* - * Env is the type of what ES5 calls "lexical environments" (runtime - * activations of lexical scopes). This is currently just JSObject, and is - * implemented by Call, Block, With, and DeclEnv objects, among others--but - * environments and objects are really two different concepts. - */ -typedef JSObject Env; - -typedef JSNative Native; -typedef JSParallelNative ParallelNative; -typedef JSThreadSafeNative ThreadSafeNative; -typedef JSPropertyOp PropertyOp; -typedef JSStrictPropertyOp StrictPropertyOp; -typedef JSPropertyDescriptor PropertyDescriptor; - -struct SourceCompressionToken; - -namespace frontend { - -struct BytecodeEmitter; -struct Definition; -class FullParseHandler; -class FunctionBox; -class ObjectBox; -struct Token; -struct TokenPos; -class TokenStream; -class ParseMapPool; -class ParseNode; - -template -class Parser; - -} /* namespace frontend */ - -namespace analyze { - -struct LifetimeVariable; -class LoopAnalysis; -class ScriptAnalysis; -class SlotValue; -class SSAValue; -class SSAUseChain; - -} /* namespace analyze */ - -namespace types { - -class TypeSet; -struct TypeCallsite; -struct TypeObject; -struct TypeCompartment; - -} /* namespace types */ - -typedef JS::Handle HandleShape; -typedef JS::Handle HandleTypeObject; -typedef JS::Handle HandleAtom; -typedef JS::Handle HandlePropertyName; - -typedef JS::MutableHandle MutableHandleShape; -typedef JS::MutableHandle MutableHandleAtom; - -typedef JS::Rooted RootedShape; -typedef JS::Rooted RootedTypeObject; -typedef JS::Rooted RootedAtom; -typedef JS::Rooted RootedPropertyName; - -enum XDRMode { - XDR_ENCODE, - XDR_DECODE -}; - -template -class XDRState; - -class FreeOp; - -struct IdValuePair -{ - jsid id; - Value value; - - IdValuePair() {} - IdValuePair(jsid idArg) - : id(idArg), value(UndefinedValue()) - {} -}; - -} /* namespace js */ - -namespace JSC { - -class ExecutableAllocator; - -} /* namespace JSC */ - -namespace WTF { - -class BumpPointerAllocator; - -} /* namespace WTF */ - -/* "Friend" types used by jscntxt.h and jsdbgapi.h. */ -typedef enum JSTrapStatus { - JSTRAP_ERROR, - JSTRAP_CONTINUE, - JSTRAP_RETURN, - JSTRAP_THROW, - JSTRAP_LIMIT -} JSTrapStatus; - -typedef JSTrapStatus -(* JSTrapHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - jsval closure); - -typedef JSTrapStatus -(* JSInterruptHook)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - void *closure); - -typedef JSTrapStatus -(* JSDebuggerHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - void *closure); - -typedef JSTrapStatus -(* JSThrowHook)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - void *closure); - -typedef JSBool -(* JSWatchPointHandler)(JSContext *cx, JSObject *obj, jsid id, jsval old, - jsval *newp, void *closure); - -/* called just after script creation */ -typedef void -(* JSNewScriptHook)(JSContext *cx, - const char *filename, /* URL of script */ - unsigned lineno, /* first line */ - JSScript *script, - JSFunction *fun, - void *callerdata); - -/* called just before script destruction */ -typedef void -(* JSDestroyScriptHook)(JSFreeOp *fop, - JSScript *script, - void *callerdata); - -typedef void -(* JSSourceHandler)(const char *filename, unsigned lineno, const jschar *str, - size_t length, void **listenerTSData, void *closure); - -/* js::ObjectOps function pointer typedefs. */ - -/* - * A generic type for functions mapping an object to another object, or null - * if an error or exception was thrown on cx. - */ -typedef JSObject * -(* JSObjectOp)(JSContext *cx, JS::Handle obj); - -/* Signature for class initialization ops. */ -typedef JSObject * -(* JSClassInitializerOp)(JSContext *cx, JS::HandleObject obj); - -/* - * Hook that creates an iterator object for a given object. Returns the - * iterator object or null if an error or exception was thrown on cx. - */ -typedef JSObject * -(* JSIteratorOp)(JSContext *cx, JS::HandleObject obj, JSBool keysonly); - - -#endif /* jsprvtd_h */ diff --git a/external/spidermonkey/include/mac/jspubtd.h b/external/spidermonkey/include/mac/jspubtd.h index 96f5dd8297..4aa922eb84 100644 --- a/external/spidermonkey/include/mac/jspubtd.h +++ b/external/spidermonkey/include/mac/jspubtd.h @@ -11,72 +11,35 @@ * JS public API typedefs. */ +#include "mozilla/NullPtr.h" #include "mozilla/PodOperations.h" #include "jsprototypes.h" #include "jstypes.h" +#include "js/TypeDecls.h" + #if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) || defined(DEBUG) # define JSGC_TRACK_EXACT_ROOTS #endif namespace JS { -/* - * Allow headers to reference JS::Value without #including the whole jsapi.h. - * Unfortunately, typedefs (hence jsval) cannot be declared. - */ -class Value; +class AutoIdVector; +class CallArgs; template class Rooted; class JS_PUBLIC_API(AutoGCRooter); +class JS_PUBLIC_API(CompileOptions); +class JS_PUBLIC_API(CompartmentOptions); + struct Zone; } /* namespace JS */ -/* - * In release builds, jsid is defined to be an integral type. This - * prevents many bugs from being caught at compile time. E.g.: - * - * jsid id = ... - * if (id == JS_TRUE) // error - * ... - * - * size_t n = id; // error - * - * To catch more errors, jsid is given a struct type in C++ debug builds. - * Struct assignment and (in C++) operator== allow correct code to be mostly - * oblivious to the change. This feature can be explicitly disabled in debug - * builds by defining JS_NO_JSVAL_JSID_STRUCT_TYPES. - */ -// Needed for cocos2d-js -#define JS_NO_JSVAL_JSID_STRUCT_TYPES -# if defined(DEBUG) && !defined(JS_NO_JSVAL_JSID_STRUCT_TYPES) -# define JS_USE_JSID_STRUCT_TYPES -# endif - -# ifdef JS_USE_JSID_STRUCT_TYPES -struct jsid -{ - size_t asBits; - bool operator==(jsid rhs) const { return asBits == rhs.asBits; } - bool operator!=(jsid rhs) const { return asBits != rhs.asBits; } -}; -# define JSID_BITS(id) (id.asBits) -# else /* defined(JS_USE_JSID_STRUCT_TYPES) */ -typedef ptrdiff_t jsid; -# define JSID_BITS(id) (id) -# endif /* defined(JS_USE_JSID_STRUCT_TYPES) */ - -#ifdef WIN32 -typedef wchar_t jschar; -#else -typedef uint16_t jschar; -#endif - /* * Run-time version enumeration. For compile-time version checking, please use * the JS_HAS_* macros in jsversion.h, or use MOZJS_MAJOR_VERSION, @@ -109,7 +72,7 @@ typedef enum JSType { typedef enum JSProtoKey { #define PROTOKEY_AND_INITIALIZER(name,code,init) JSProto_##name = code, JS_FOR_EACH_PROTOTYPE(PROTOKEY_AND_INITIALIZER) -#undef JS_PROTO +#undef PROTOKEY_AND_INITIALIZER JSProto_LIMIT } JSProtoKey; @@ -175,7 +138,6 @@ typedef enum { typedef struct JSClass JSClass; typedef struct JSCompartment JSCompartment; typedef struct JSConstDoubleSpec JSConstDoubleSpec; -typedef struct JSContext JSContext; typedef struct JSCrossCompartmentCall JSCrossCompartmentCall; typedef struct JSErrorReport JSErrorReport; typedef struct JSExceptionState JSExceptionState; @@ -195,20 +157,32 @@ typedef struct JSStructuredCloneWriter JSStructuredCloneWriter; typedef struct JSTracer JSTracer; class JSFlatString; -class JSFunction; -class JSObject; -class JSScript; class JSStableString; // long story -class JSString; #ifdef JS_THREADSAFE -typedef struct PRCallOnceType JSCallOnceType; +typedef struct PRCallOnceType JSCallOnceType; #else -typedef JSBool JSCallOnceType; +typedef bool JSCallOnceType; #endif -typedef JSBool (*JSInitCallback)(void); +typedef bool (*JSInitCallback)(void); + +/* + * Generic trace operation that calls JS_CallTracer on each traceable thing + * stored in data. + */ +typedef void +(* JSTraceDataOp)(JSTracer *trc, void *data); + +namespace js { +namespace gc { +class StoreBuffer; +} +} namespace JS { + +typedef void (*OffThreadCompileCallback)(void *token, void *callbackData); + namespace shadow { struct Runtime @@ -220,15 +194,36 @@ struct Runtime /* Allow inlining of Nursery::isInside. */ uintptr_t gcNurseryStart_; uintptr_t gcNurseryEnd_; + + private: + js::gc::StoreBuffer *gcStoreBufferPtr_; #endif - Runtime() + public: + Runtime( +#ifdef JSGC_GENERATIONAL + js::gc::StoreBuffer *storeBuffer +#endif + ) : needsBarrier_(false) #ifdef JSGC_GENERATIONAL , gcNurseryStart_(0) , gcNurseryEnd_(0) + , gcStoreBufferPtr_(storeBuffer) #endif {} + + bool needsBarrier() const { + return needsBarrier_; + } + +#ifdef JSGC_GENERATIONAL + js::gc::StoreBuffer *gcStoreBufferPtr() { return gcStoreBufferPtr_; } +#endif + + static JS::shadow::Runtime *asShadowRuntime(JSRuntime *rt) { + return reinterpret_cast(rt); + } }; } /* namespace shadow */ @@ -270,6 +265,19 @@ enum ThingRootKind THING_ROOT_LIMIT }; +/* + * This list enumerates the different types of conceptual stacks we have in + * SpiderMonkey. In reality, they all share the C stack, but we allow different + * stack limits depending on the type of code running. + */ +enum StackKind +{ + StackForSystemCode, // C++, such as the GC, running on behalf of the VM. + StackForTrustedScript, // Script running with trusted principals. + StackForUntrustedScript, // Script running with untrusted principals. + StackKindCount +}; + template struct RootKind; @@ -305,13 +313,13 @@ struct ContextFriendFields public: explicit ContextFriendFields(JSRuntime *rt) - : runtime_(rt), compartment_(NULL), zone_(NULL), autoGCRooters(NULL) + : runtime_(rt), compartment_(nullptr), zone_(nullptr), autoGCRooters(nullptr) { #ifdef JSGC_TRACK_EXACT_ROOTS mozilla::PodArrayZero(thingGCRooters); #endif #if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) - skipGCRooters = NULL; + skipGCRooters = nullptr; #endif } @@ -395,7 +403,7 @@ struct PerThreadDataFriendFields #endif /* Limit pointer for checking native stack consumption. */ - uintptr_t nativeStackLimit; + uintptr_t nativeStackLimit[StackKindCount]; static const size_t RuntimeMainThreadOffset = offsetof(RuntimeDummy, mainThread); diff --git a/external/spidermonkey/include/mac/jstypes.h b/external/spidermonkey/include/mac/jstypes.h index 17f67f70e1..d5b15ccb1d 100644 --- a/external/spidermonkey/include/mac/jstypes.h +++ b/external/spidermonkey/include/mac/jstypes.h @@ -22,9 +22,16 @@ #define jstypes_h #include "mozilla/Attributes.h" -#include "mozilla/Util.h" +#include "mozilla/Types.h" +// jstypes.h is (or should be!) included by every file in SpiderMonkey. +// js-config.h and jsversion.h also should be included by every file. +// So include them here. +// XXX: including them in js/RequiredDefines.h should be a better option, since +// that is by definition the header file that should be included in all +// SpiderMonkey code. However, Gecko doesn't do this! See bug 909576. #include "js-config.h" +#include "jsversion.h" /*********************************************************************** ** MACROS: JS_EXTERN_API @@ -82,10 +89,6 @@ #define JS_NO_FASTCALL #endif -#ifndef JS_INLINE -#define JS_INLINE MOZ_INLINE -#endif - #ifndef JS_ALWAYS_INLINE #define JS_ALWAYS_INLINE MOZ_ALWAYS_INLINE #endif @@ -180,19 +183,6 @@ # error "Implement me" #endif - -/************************************************************************ -** TYPES: JSBool -** DESCRIPTION: -** Use JSBool for variables and parameter types. Use JS_FALSE and JS_TRUE -** for clarity of target type in assignments and actual arguments. Use -** 'if (bool)', 'while (!bool)', '(bool) ? x : y' etc., to test booleans -** just as you would C int-valued conditions. -************************************************************************/ -typedef int JSBool; -#define JS_TRUE (int)1 -#define JS_FALSE (int)0 - /*********************************************************************** ** MACROS: JS_LIKELY ** JS_UNLIKELY @@ -244,7 +234,11 @@ typedef int JSBool; #define JS_BITS_PER_BYTE 8 #define JS_BITS_PER_BYTE_LOG2 3 -#define JS_BITS_PER_WORD (JS_BITS_PER_BYTE * JS_BYTES_PER_WORD) +#if defined(JS_64BIT) +# define JS_BITS_PER_WORD 64 +#else +# define JS_BITS_PER_WORD 32 +#endif /*********************************************************************** ** MACROS: JS_FUNC_TO_DATA_PTR diff --git a/external/spidermonkey/include/mac/jsutil.h b/external/spidermonkey/include/mac/jsutil.h deleted file mode 100644 index 4020822be1..0000000000 --- a/external/spidermonkey/include/mac/jsutil.h +++ /dev/null @@ -1,385 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -/* - * PR assertion checker. - */ - -#ifndef jsutil_h -#define jsutil_h - -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/GuardObjects.h" - -#ifdef USE_ZLIB -#include -#endif - -#include "js/Utility.h" - -/* Forward declarations. */ -struct JSContext; - -static JS_ALWAYS_INLINE void * -js_memcpy(void *dst_, const void *src_, size_t len) -{ - char *dst = (char *) dst_; - const char *src = (const char *) src_; - JS_ASSERT_IF(dst >= src, (size_t) (dst - src) >= len); - JS_ASSERT_IF(src >= dst, (size_t) (src - dst) >= len); - - return memcpy(dst, src, len); -} - -namespace js { - -template -struct AlignmentTestStruct -{ - char c; - T t; -}; - -/* This macro determines the alignment requirements of a type. */ -#define JS_ALIGNMENT_OF(t_) \ - (sizeof(js::AlignmentTestStruct) - sizeof(t_)) - -template -class AlignedPtrAndFlag -{ - uintptr_t bits; - - public: - AlignedPtrAndFlag(T *t, bool aFlag) { - JS_ASSERT((uintptr_t(t) & 1) == 0); - bits = uintptr_t(t) | uintptr_t(aFlag); - } - - T *ptr() const { - return (T *)(bits & ~uintptr_t(1)); - } - - bool flag() const { - return (bits & 1) != 0; - } - - void setPtr(T *t) { - JS_ASSERT((uintptr_t(t) & 1) == 0); - bits = uintptr_t(t) | uintptr_t(flag()); - } - - void setFlag() { - bits |= 1; - } - - void unsetFlag() { - bits &= ~uintptr_t(1); - } - - void set(T *t, bool aFlag) { - JS_ASSERT((uintptr_t(t) & 1) == 0); - bits = uintptr_t(t) | aFlag; - } -}; - -template -static inline void -Reverse(T *beg, T *end) -{ - while (beg != end) { - if (--end == beg) - return; - T tmp = *beg; - *beg = *end; - *end = tmp; - ++beg; - } -} - -template -static inline T * -Find(T *beg, T *end, const T &v) -{ - for (T *p = beg; p != end; ++p) { - if (*p == v) - return p; - } - return end; -} - -template -static inline typename Container::ElementType * -Find(Container &c, const typename Container::ElementType &v) -{ - return Find(c.begin(), c.end(), v); -} - -template -void -ForEach(InputIterT begin, InputIterT end, CallableT f) -{ - for (; begin != end; ++begin) - f(*begin); -} - -template -static inline T -Min(T t1, T t2) -{ - return t1 < t2 ? t1 : t2; -} - -template -static inline T -Max(T t1, T t2) -{ - return t1 > t2 ? t1 : t2; -} - -/* Allows a const variable to be initialized after its declaration. */ -template -static T& -InitConst(const T &t) -{ - return const_cast(t); -} - -template -JS_ALWAYS_INLINE T & -ImplicitCast(U &u) -{ - T &t = u; - return t; -} - -template -class AutoScopedAssign -{ - public: - AutoScopedAssign(T *addr, const T &value - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : addr_(addr), old(*addr_) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - *addr_ = value; - } - - ~AutoScopedAssign() { *addr_ = old; } - - private: - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - T *addr_; - T old; -}; - -template -static inline bool -IsPowerOfTwo(T t) -{ - return t && !(t & (t - 1)); -} - -template -static inline U -ComputeByteAlignment(T bytes, U alignment) -{ - JS_ASSERT(IsPowerOfTwo(alignment)); - return (alignment - (bytes % alignment)) % alignment; -} - -template -static inline T -AlignBytes(T bytes, U alignment) -{ - return bytes + ComputeByteAlignment(bytes, alignment); -} - -JS_ALWAYS_INLINE static size_t -UnsignedPtrDiff(const void *bigger, const void *smaller) -{ - return size_t(bigger) - size_t(smaller); -} - -/*****************************************************************************/ - -/* A bit array is an array of bits represented by an array of words (size_t). */ - -static inline unsigned -NumWordsForBitArrayOfLength(size_t length) -{ - return (length + (JS_BITS_PER_WORD - 1)) / JS_BITS_PER_WORD; -} - -static inline unsigned -BitArrayIndexToWordIndex(size_t length, size_t bitIndex) -{ - unsigned wordIndex = bitIndex / JS_BITS_PER_WORD; - JS_ASSERT(wordIndex < length); - return wordIndex; -} - -static inline size_t -BitArrayIndexToWordMask(size_t i) -{ - return size_t(1) << (i % JS_BITS_PER_WORD); -} - -static inline bool -IsBitArrayElementSet(size_t *array, size_t length, size_t i) -{ - return array[BitArrayIndexToWordIndex(length, i)] & BitArrayIndexToWordMask(i); -} - -static inline bool -IsAnyBitArrayElementSet(size_t *array, size_t length) -{ - unsigned numWords = NumWordsForBitArrayOfLength(length); - for (unsigned i = 0; i < numWords; ++i) { - if (array[i]) - return true; - } - return false; -} - -static inline void -SetBitArrayElement(size_t *array, size_t length, size_t i) -{ - array[BitArrayIndexToWordIndex(length, i)] |= BitArrayIndexToWordMask(i); -} - -static inline void -ClearBitArrayElement(size_t *array, size_t length, size_t i) -{ - array[BitArrayIndexToWordIndex(length, i)] &= ~BitArrayIndexToWordMask(i); -} - -static inline void -ClearAllBitArrayElements(size_t *array, size_t length) -{ - for (unsigned i = 0; i < length; ++i) - array[i] = 0; -} - -#ifdef USE_ZLIB -class Compressor -{ - /* Number of bytes we should hand to zlib each compressMore() call. */ - static const size_t CHUNKSIZE = 2048; - z_stream zs; - const unsigned char *inp; - size_t inplen; - size_t outbytes; - - public: - enum Status { - MOREOUTPUT, - DONE, - CONTINUE, - OOM - }; - - Compressor(const unsigned char *inp, size_t inplen); - ~Compressor(); - bool init(); - void setOutput(unsigned char *out, size_t outlen); - size_t outWritten() const { return outbytes; } - /* Compress some of the input. Return true if it should be called again. */ - Status compressMore(); -}; - -/* - * Decompress a string. The caller must know the length of the output and - * allocate |out| to a string of that length. - */ -bool DecompressString(const unsigned char *inp, size_t inplen, - unsigned char *out, size_t outlen); -#endif - -} /* namespace js */ - -/* Crash diagnostics */ -#ifdef DEBUG -# define JS_CRASH_DIAGNOSTICS 1 -#endif -#ifdef JS_CRASH_DIAGNOSTICS -# define JS_POISON(p, val, size) memset((p), (val), (size)) -#else -# define JS_POISON(p, val, size) ((void) 0) -#endif - -/* Basic stats */ -#ifdef DEBUG -# define JS_BASIC_STATS 1 -#endif -#ifdef JS_BASIC_STATS -# include -typedef struct JSBasicStats { - uint32_t num; - uint32_t max; - double sum; - double sqsum; - uint32_t logscale; /* logarithmic scale: 0 (linear), 2, 10 */ - uint32_t hist[11]; -} JSBasicStats; -# define JS_INIT_STATIC_BASIC_STATS {0,0,0,0,0,{0,0,0,0,0,0,0,0,0,0,0}} -# define JS_BASIC_STATS_INIT(bs) memset((bs), 0, sizeof(JSBasicStats)) -# define JS_BASIC_STATS_ACCUM(bs,val) \ - JS_BasicStatsAccum(bs, val) -# define JS_MeanAndStdDevBS(bs,sigma) \ - JS_MeanAndStdDev((bs)->num, (bs)->sum, (bs)->sqsum, sigma) -extern void -JS_BasicStatsAccum(JSBasicStats *bs, uint32_t val); -extern double -JS_MeanAndStdDev(uint32_t num, double sum, double sqsum, double *sigma); -extern void -JS_DumpBasicStats(JSBasicStats *bs, const char *title, FILE *fp); -extern void -JS_DumpHistogram(JSBasicStats *bs, FILE *fp); -#else -# define JS_BASIC_STATS_ACCUM(bs,val) -#endif - -/* A jsbitmap_t is a long integer that can be used for bitmaps. */ -typedef size_t jsbitmap; -#define JS_TEST_BIT(_map,_bit) ((_map)[(_bit)>>JS_BITS_PER_WORD_LOG2] & \ - ((jsbitmap)1<<((_bit)&(JS_BITS_PER_WORD-1)))) -#define JS_SET_BIT(_map,_bit) ((_map)[(_bit)>>JS_BITS_PER_WORD_LOG2] |= \ - ((jsbitmap)1<<((_bit)&(JS_BITS_PER_WORD-1)))) -#define JS_CLEAR_BIT(_map,_bit) ((_map)[(_bit)>>JS_BITS_PER_WORD_LOG2] &= \ - ~((jsbitmap)1<<((_bit)&(JS_BITS_PER_WORD-1)))) - -/* Wrapper for various macros to stop warnings coming from their expansions. */ -#if defined(__clang__) -# define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \ - JS_BEGIN_MACRO \ - _Pragma("clang diagnostic push") \ - /* If these _Pragmas cause warnings for you, try disabling ccache. */ \ - _Pragma("clang diagnostic ignored \"-Wunused-value\"") \ - { expr; } \ - _Pragma("clang diagnostic pop") \ - JS_END_MACRO -#elif MOZ_IS_GCC - -#if MOZ_GCC_VERSION_AT_LEAST(4, 6, 0) -# define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \ - JS_BEGIN_MACRO \ - _Pragma("GCC diagnostic push") \ - _Pragma("GCC diagnostic ignored \"-Wunused-but-set-variable\"") \ - expr; \ - _Pragma("GCC diagnostic pop") \ - JS_END_MACRO -#endif -#endif - -#if !defined(JS_SILENCE_UNUSED_VALUE_IN_EXPR) -# define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \ - JS_BEGIN_MACRO \ - expr; \ - JS_END_MACRO -#endif - -#endif /* jsutil_h */ diff --git a/external/spidermonkey/include/mac/jsversion.h b/external/spidermonkey/include/mac/jsversion.h index 1780616a32..827a56981d 100644 --- a/external/spidermonkey/include/mac/jsversion.h +++ b/external/spidermonkey/include/mac/jsversion.h @@ -7,19 +7,6 @@ #ifndef jsversion_h #define jsversion_h -/* - * Deprecated JS_VERSION handler. - */ -#ifdef JS_VERSION -# if JS_VERSION == 185 -# warning "JS_VERSION defined but unsupported (legacy)" -# elif JS_VERSION < 185 -# error "Unsupported JS_VERSION" -# else -# error "Unknown JS_VERSION" -# endif -#endif - /* * JS Capability Macros. */ @@ -52,15 +39,15 @@ * Feature for Object.prototype.__{define,lookup}{G,S}etter__ legacy support; * support likely to be made opt-in at some future time. */ -#define OLD_GETTER_SETTER_METHODS 1 +#define JS_OLD_GETTER_SETTER_METHODS 1 /* A kill-switch for bug 586842. Embedders shouldn't touch this! */ -#define USE_NEW_OBJECT_REPRESENTATION 0 +#define JS_USE_NEW_OBJECT_REPRESENTATION 0 -#if USE_NEW_OBJECT_REPRESENTATION -# define NEW_OBJECT_REPRESENTATION_ONLY() ((void)0) +#if JS_USE_NEW_OBJECT_REPRESENTATION +# define JS_NEW_OBJECT_REPRESENTATION_ONLY() ((void)0) #else -# define NEW_OBJECT_REPRESENTATION_ONLY() \ +# define JS_NEW_OBJECT_REPRESENTATION_ONLY() \ MOZ_ASSUME_UNREACHABLE("don't call this! to be used in the new object representation") #endif diff --git a/external/spidermonkey/include/mac/jswrapper.h b/external/spidermonkey/include/mac/jswrapper.h index f78df7db60..938db73ec8 100644 --- a/external/spidermonkey/include/mac/jswrapper.h +++ b/external/spidermonkey/include/mac/jswrapper.h @@ -9,7 +9,6 @@ #include "mozilla/Attributes.h" -#include "jsapi.h" #include "jsproxy.h" namespace js { @@ -38,6 +37,9 @@ class JS_FRIEND_API(Wrapper) : public DirectProxyHandler LAST_USED_FLAG = CROSS_COMPARTMENT }; + virtual bool defaultValue(JSContext *cx, HandleObject obj, JSType hint, + MutableHandleValue vp) MOZ_OVERRIDE; + /* * Wrappers can explicitly specify that they are unsafe to unwrap from a * security perspective (as is the case for SecurityWrappers). If a wrapper @@ -64,6 +66,8 @@ class JS_FRIEND_API(Wrapper) : public DirectProxyHandler virtual ~Wrapper(); + virtual bool finalizeInBackground(Value priv) MOZ_OVERRIDE; + static Wrapper singleton; static Wrapper singletonWithPrototype; }; @@ -76,16 +80,16 @@ class JS_FRIEND_API(CrossCompartmentWrapper) : public Wrapper virtual ~CrossCompartmentWrapper(); - virtual bool finalizeInBackground(Value priv) MOZ_OVERRIDE; - /* ES5 Harmony fundamental wrapper traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject wrapper) MOZ_OVERRIDE; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject wrapper, AutoIdVector &props) MOZ_OVERRIDE; virtual bool delete_(JSContext *cx, HandleObject wrapper, HandleId id, bool *bp) MOZ_OVERRIDE; @@ -149,7 +153,7 @@ class JS_FRIEND_API(SecurityWrapper) : public Base JSContext *cx) MOZ_OVERRIDE; virtual bool regexp_toShared(JSContext *cx, HandleObject proxy, RegExpGuard *g) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; /* * Allow our subclasses to select the superclass behavior they want without @@ -165,18 +169,21 @@ typedef SecurityWrapper CrossCompartmentSecurityWrapper class JS_FRIEND_API(DeadObjectProxy) : public BaseProxyHandler { public: - static int sDeadObjectFamily; + // This variable exists solely to provide a unique address for use as an identifier. + static const char sDeadObjectFamily; explicit DeadObjectProxy(); /* ES5 Harmony fundamental wrapper traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject proxy) MOZ_OVERRIDE; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject wrapper, AutoIdVector &props) MOZ_OVERRIDE; virtual bool delete_(JSContext *cx, HandleObject wrapper, HandleId id, bool *bp) MOZ_OVERRIDE; @@ -213,7 +220,8 @@ TransparentObjectWrapper(JSContext *cx, HandleObject existing, HandleObject obj, // Proxy family for wrappers. Public so that IsWrapper() can be fully inlined by // jsfriendapi users. -extern JS_FRIEND_DATA(int) sWrapperFamily; +// This variable exists solely to provide a unique address for use as an identifier. +extern JS_FRIEND_DATA(const char) sWrapperFamily; inline bool IsWrapper(JSObject *obj) @@ -226,7 +234,7 @@ IsWrapper(JSObject *obj) // previously wrapped. Otherwise, this returns the first object for // which JSObject::isWrapper returns false. JS_FRIEND_API(JSObject *) -UncheckedUnwrap(JSObject *obj, bool stopAtOuter = true, unsigned *flagsp = NULL); +UncheckedUnwrap(JSObject *obj, bool stopAtOuter = true, unsigned *flagsp = nullptr); // Given a JSObject, returns that object stripped of wrappers. At each stage, // the security wrapper has the opportunity to veto the unwrap. Since checked @@ -247,7 +255,8 @@ bool IsDeadProxyObject(JSObject *obj); JSObject * -NewDeadProxyObject(JSContext *cx, JSObject *parent); +NewDeadProxyObject(JSContext *cx, JSObject *parent, + const ProxyOptions &options = ProxyOptions()); void NukeCrossCompartmentWrapper(JSContext *cx, JSObject *wrapper); diff --git a/external/spidermonkey/include/mac/mozilla/Alignment.h b/external/spidermonkey/include/mac/mozilla/Alignment.h new file mode 100644 index 0000000000..29599d0ef1 --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/Alignment.h @@ -0,0 +1,137 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=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/. */ + +/* Functionality related to memory alignment. */ + +#ifndef mozilla_Alignment_h +#define mozilla_Alignment_h + +#include +#include + +namespace mozilla { + +/* + * This class, and the corresponding macro MOZ_ALIGNOF, figures out how many + * bytes of alignment a given type needs. + */ +template +class AlignmentFinder +{ + struct Aligner + { + char c; + T t; + }; + + public: + static const size_t alignment = sizeof(Aligner) - sizeof(T); +}; + +#define MOZ_ALIGNOF(T) mozilla::AlignmentFinder::alignment + +/* + * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types. + * + * For instance, + * + * MOZ_ALIGNED_DECL(char arr[2], 8); + * + * will declare a two-character array |arr| aligned to 8 bytes. + */ + +#if defined(__GNUC__) +# define MOZ_ALIGNED_DECL(_type, _align) \ + _type __attribute__((aligned(_align))) +#elif defined(_MSC_VER) +# define MOZ_ALIGNED_DECL(_type, _align) \ + __declspec(align(_align)) _type +#else +# warning "We don't know how to align variables on this compiler." +# define MOZ_ALIGNED_DECL(_type, _align) _type +#endif + +/* + * AlignedElem is a structure whose alignment is guaranteed to be at least N + * bytes. + * + * We support 1, 2, 4, 8, and 16-bit alignment. + */ +template +struct AlignedElem; + +/* + * We have to specialize this template because GCC doesn't like __attribute__((aligned(foo))) where + * foo is a template parameter. + */ + +template<> +struct AlignedElem<1> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 1); +}; + +template<> +struct AlignedElem<2> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 2); +}; + +template<> +struct AlignedElem<4> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 4); +}; + +template<> +struct AlignedElem<8> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 8); +}; + +template<> +struct AlignedElem<16> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 16); +}; + +/* + * This utility pales in comparison to Boost's aligned_storage. The utility + * simply assumes that uint64_t is enough alignment for anyone. This may need + * to be extended one day... + * + * As an important side effect, pulling the storage into this template is + * enough obfuscation to confuse gcc's strict-aliasing analysis into not giving + * false negatives when we cast from the char buffer to whatever type we've + * constructed using the bytes. + */ +template +struct AlignedStorage +{ + union U { + char bytes[Nbytes]; + uint64_t _; + } u; + + const void* addr() const { return u.bytes; } + void* addr() { return u.bytes; } +}; + +template +struct AlignedStorage2 +{ + union U { + char bytes[sizeof(T)]; + uint64_t _; + } u; + + const T* addr() const { return reinterpret_cast(u.bytes); } + T* addr() { return static_cast(static_cast(u.bytes)); } +}; + +} /* namespace mozilla */ + +#endif /* mozilla_Alignment_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Assertions.h b/external/spidermonkey/include/mac/mozilla/Assertions.h index 00b7037802..f902199051 100644 --- a/external/spidermonkey/include/mac/mozilla/Assertions.h +++ b/external/spidermonkey/include/mac/mozilla/Assertions.h @@ -180,7 +180,7 @@ __declspec(noreturn) __inline void MOZ_NoReturn() {} # ifdef __cplusplus # define MOZ_REALLY_CRASH() \ do { \ - __debugbreak(); \ + ::__debugbreak(); \ *((volatile int*) NULL) = 123; \ ::TerminateProcess(::GetCurrentProcess(), 3); \ ::MOZ_NoReturn(); \ diff --git a/external/spidermonkey/include/mac/mozilla/Atomics.h b/external/spidermonkey/include/mac/mozilla/Atomics.h index f876683c3e..31e6a7daec 100644 --- a/external/spidermonkey/include/mac/mozilla/Atomics.h +++ b/external/spidermonkey/include/mac/mozilla/Atomics.h @@ -17,6 +17,8 @@ #define mozilla_Atomics_h #include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" +#include "mozilla/Compiler.h" #include "mozilla/TypeTraits.h" #include @@ -26,34 +28,16 @@ * does not have . So be sure to check for support * along with C++0x support. */ -#if defined(__clang__) +#if defined(__clang__) || defined(__GNUC__) /* - * clang doesn't like libstdc++'s version of before GCC 4.7, - * due to the loose typing of the __sync_* family of functions done by - * GCC. We do not have a particularly good way to detect this sort of - * case at this point, so just assume that if we're on a Linux system, - * we can't use the system's . - * - * OpenBSD uses an old libstdc++ 4.2.1 and thus doesnt have . + * Clang doesn't like from libstdc++ before 4.7 due to the + * loose typing of the atomic builtins. GCC 4.5 and 4.6 lacks inline + * definitions for unspecialized std::atomic and causes linking errors. + * Therefore, we require at least 4.7.0 for using libstdc++. */ -# if !defined(__linux__) && !defined(__OpenBSD__) && \ - (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) && \ - __has_include() +# if MOZ_USING_LIBSTDCXX && MOZ_LIBSTDCXX_VERSION_AT_LEAST(4, 7, 0) # define MOZ_HAVE_CXX11_ATOMICS -# endif -/* - * Android uses a different C++ standard library that does not provide - * support for . - * - * GCC 4.5.x and 4.6.x's unspecialized std::atomic template doesn't include - * inline definitions for the functions declared therein. This oversight - * leads to linking errors when using atomic enums. We therefore require - * GCC 4.7 or higher. - */ -#elif defined(__GNUC__) && !defined(__ANDROID__) -# include "mozilla/Compiler.h" -# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) && \ - MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) +# elif MOZ_USING_LIBCXX # define MOZ_HAVE_CXX11_ATOMICS # endif #elif defined(_MSC_VER) && _MSC_VER >= 1700 @@ -845,8 +829,8 @@ class AtomicBase typename Intrinsics::ValueType mValue; public: - AtomicBase() : mValue() {} - AtomicBase(T aInit) { Intrinsics::store(mValue, aInit); } + MOZ_CONSTEXPR AtomicBase() : mValue() {} + MOZ_CONSTEXPR AtomicBase(T aInit) : mValue(aInit) {} operator T() const { return Intrinsics::load(mValue); } @@ -889,8 +873,8 @@ class AtomicBaseIncDec : public AtomicBase typedef typename detail::AtomicBase Base; public: - AtomicBaseIncDec() : Base() {} - AtomicBaseIncDec(T aInit) : Base(aInit) {} + MOZ_CONSTEXPR AtomicBaseIncDec() : Base() {} + MOZ_CONSTEXPR AtomicBaseIncDec(T aInit) : Base(aInit) {} using Base::operator=; @@ -943,8 +927,8 @@ class Atomic::value>::Type> typedef typename detail::AtomicBaseIncDec Base; public: - Atomic() : Base() {} - Atomic(T aInit) : Base(aInit) {} + MOZ_CONSTEXPR Atomic() : Base() {} + MOZ_CONSTEXPR Atomic(T aInit) : Base(aInit) {} using Base::operator=; @@ -972,8 +956,8 @@ class Atomic : public detail::AtomicBaseIncDec typedef typename detail::AtomicBaseIncDec Base; public: - Atomic() : Base() {} - Atomic(T* aInit) : Base(aInit) {} + MOZ_CONSTEXPR Atomic() : Base() {} + MOZ_CONSTEXPR Atomic(T* aInit) : Base(aInit) {} using Base::operator=; @@ -1000,8 +984,8 @@ class Atomic::value>::Type> typedef typename detail::AtomicBase Base; public: - Atomic() : Base() {} - Atomic(T aInit) : Base(aInit) {} + MOZ_CONSTEXPR Atomic() : Base() {} + MOZ_CONSTEXPR Atomic(T aInit) : Base(aInit) {} using Base::operator=; diff --git a/external/spidermonkey/include/mac/mozilla/Attributes.h b/external/spidermonkey/include/mac/mozilla/Attributes.h index 6ea9776fbf..0786cb2fe5 100644 --- a/external/spidermonkey/include/mac/mozilla/Attributes.h +++ b/external/spidermonkey/include/mac/mozilla/Attributes.h @@ -11,26 +11,10 @@ #include "mozilla/Compiler.h" -/* - * MOZ_INLINE is a macro which expands to tell the compiler that the method - * decorated with it should be inlined. This macro is usable from C and C++ - * code, even though C89 does not support the |inline| keyword. The compiler - * may ignore this directive if it chooses. - */ -#if defined(__cplusplus) -# define MOZ_INLINE inline -#elif defined(_MSC_VER) -# define MOZ_INLINE __inline -#elif defined(__GNUC__) -# define MOZ_INLINE __inline__ -#else -# define MOZ_INLINE inline -#endif - /* * MOZ_ALWAYS_INLINE is a macro which expands to tell the compiler that the * method decorated with it must be inlined, even if the compiler thinks - * otherwise. This is only a (much) stronger version of the MOZ_INLINE hint: + * otherwise. This is only a (much) stronger version of the inline hint: * compilers are not guaranteed to respect it (although they're much more likely * to do so). * @@ -40,15 +24,17 @@ #if defined(_MSC_VER) # define MOZ_ALWAYS_INLINE_EVEN_DEBUG __forceinline #elif defined(__GNUC__) -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __attribute__((always_inline)) MOZ_INLINE +# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __attribute__((always_inline)) inline #else -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_INLINE +# define MOZ_ALWAYS_INLINE_EVEN_DEBUG inline #endif -#if defined(DEBUG) -# define MOZ_ALWAYS_INLINE MOZ_INLINE -#else +#if !defined(DEBUG) # define MOZ_ALWAYS_INLINE MOZ_ALWAYS_INLINE_EVEN_DEBUG +#elif defined(_MSC_VER) && !defined(__cplusplus) +# define MOZ_ALWAYS_INLINE __inline +#else +# define MOZ_ALWAYS_INLINE inline #endif /* @@ -170,12 +156,31 @@ * Furthermore, it will prevent the compiler from inlining the function because * inlining currently breaks the blacklisting mechanism of AddressSanitizer. */ -#if defined(MOZ_ASAN) -# define MOZ_ASAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_address_safety_analysis)) -# else -# define MOZ_ASAN_BLACKLIST +#if defined(__has_feature) +# if __has_feature(address_sanitizer) +# define MOZ_ASAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_address)) +# else +# define MOZ_ASAN_BLACKLIST /* nothing */ +# endif +#else +# define MOZ_ASAN_BLACKLIST /* nothing */ #endif +/* + * MOZ_TSAN_BLACKLIST is a macro to tell ThreadSanitizer (a compile-time + * instrumentation shipped with Clang) to not instrument the annotated function. + * Furthermore, it will prevent the compiler from inlining the function because + * inlining currently breaks the blacklisting mechanism of ThreadSanitizer. + */ +#if defined(__has_feature) +# if __has_feature(thread_sanitizer) +# define MOZ_TSAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_thread)) +# else +# define MOZ_TSAN_BLACKLIST /* nothing */ +# endif +#else +# define MOZ_TSAN_BLACKLIST /* nothing */ +#endif #ifdef __cplusplus diff --git a/external/spidermonkey/include/mac/mozilla/Char16.h b/external/spidermonkey/include/mac/mozilla/Char16.h index e4b184f950..fb182dfde2 100644 --- a/external/spidermonkey/include/mac/mozilla/Char16.h +++ b/external/spidermonkey/include/mac/mozilla/Char16.h @@ -9,16 +9,11 @@ #ifndef mozilla_Char16_h #define mozilla_Char16_h -#include "mozilla/Assertions.h" - /* * C11 and C++11 introduce a char16_t type and support for UTF-16 string and * character literals. C++11's char16_t is a distinct builtin type. C11's * char16_t is a typedef for uint_least16_t. Technically, char16_t is a 16-bit * code unit of a Unicode code point, not a "character". - * - * For now, Char16.h only supports C++ because we don't want mix different C - * and C++ definitions of char16_t in the same code base. */ #ifdef _MSC_VER @@ -26,20 +21,52 @@ * C++11 says char16_t is a distinct builtin type, but Windows's yvals.h * typedefs char16_t as an unsigned short. We would like to alias char16_t * to Windows's 16-bit wchar_t so we can declare UTF-16 literals as constant - * expressions (and pass char16_t pointers to Windows APIs). We #define our - * char16_t as a macro to override yval.h's typedef of the same name. + * expressions (and pass char16_t pointers to Windows APIs). We #define + * _CHAR16T here in order to prevent yvals.h from overriding our char16_t + * typedefs, which we set to wchar_t for C++ code and to unsigned short for + * C code. + * + * In addition, #defining _CHAR16T will prevent yvals.h from defining a + * char32_t type, so we have to undo that damage here and provide our own, + * which is identical to the yvals.h type. */ # define MOZ_UTF16_HELPER(s) L##s -# include -# define char16_t wchar_t +# define _CHAR16T +# ifdef __cplusplus + typedef wchar_t char16_t; +# else + typedef unsigned short char16_t; +# endif + typedef unsigned int char32_t; #elif defined(__cplusplus) && \ (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) /* C++11 has a builtin char16_t type. */ # define MOZ_UTF16_HELPER(s) u##s + /** + * This macro is used to distinguish when char16_t would be a distinct + * typedef from wchar_t. + */ +# define MOZ_CHAR16_IS_NOT_WCHAR +#elif !defined(__cplusplus) +# if defined(WIN32) +# include + typedef wchar_t char16_t; +# else + /** + * We can't use the stdint.h uint16_t type here because including + * stdint.h will break building some of our C libraries, such as + * sqlite. + */ + typedef unsigned short char16_t; +# endif #else # error "Char16.h requires C++11 (or something like it) for UTF-16 support." #endif +/* This is a temporary hack until bug 927728 is fixed. */ +#define __PRUNICHAR__ +typedef char16_t PRUnichar; + /* * Macro arguments used in concatenation or stringification won't be expanded. * Therefore, in order for |MOZ_UTF16(FOO)| to work as expected (which is to @@ -50,8 +77,12 @@ */ #define MOZ_UTF16(s) MOZ_UTF16_HELPER(s) +#if defined(__cplusplus) && \ + (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) static_assert(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); +static_assert(char16_t(-1) > char16_t(0), "Is char16_t type unsigned?"); static_assert(sizeof(MOZ_UTF16('A')) == 2, "Is char literal 16 bits?"); static_assert(sizeof(MOZ_UTF16("")[0]) == 2, "Is string char 16 bits?"); +#endif #endif /* mozilla_Char16_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Compiler.h b/external/spidermonkey/include/mac/mozilla/Compiler.h index d1ef1e79aa..fd5c98c98d 100644 --- a/external/spidermonkey/include/mac/mozilla/Compiler.h +++ b/external/spidermonkey/include/mac/mozilla/Compiler.h @@ -29,4 +29,77 @@ #endif +/* + * The situation with standard libraries is a lot worse than with compilers, + * particularly as clang and gcc could end up using one of three or so standard + * libraries, and they may not be up-to-snuff with newer C++11 versions. To + * detect the library, we're going to include cstddef (which is a small header + * which will be transitively included by everybody else at some point) to grab + * the version macros and deduce macros from there. + */ +#ifdef __cplusplus +# include +# ifdef _STLPORT_MAJOR +# define MOZ_USING_STLPORT 1 +# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) \ + (_STLPORT_VERSION >= ((major) << 8 | (minor) << 4 | (patch))) +# elif defined(_LIBCPP_VERSION) + /* + * libc++, unfortunately, doesn't appear to have useful versioning macros. + * Hopefully, the recommendations of N3694 with respect to standard libraries + * will get applied instead and we won't need to worry about version numbers + * here. + */ +# define MOZ_USING_LIBCXX 1 +# elif defined(__GLIBCXX__) +# define MOZ_USING_LIBSTDCXX 1 + /* + * libstdc++ is also annoying and doesn't give us useful versioning macros + * for the library. If we're using gcc, then assume that libstdc++ matches + * the compiler version. If we're using clang, we're going to have to fake + * major/minor combinations by looking for newly-defined config macros. + */ +# if MOZ_IS_GCC +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + MOZ_GCC_VERSION_AT_LEAST(major, minor, patch) +# elif defined(_GLIBCXX_THROW_OR_ABORT) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 8)) +# elif defined(_GLIBCXX_NOEXCEPT) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 7)) +# elif defined(_GLIBCXX_USE_DEPRECATED) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 6)) +# elif defined(_GLIBCXX_PSEUDO_VISIBILITY) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 5)) +# elif defined(_GLIBCXX_BEGIN_EXTERN_C) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 4)) +# elif defined(_GLIBCXX_VISIBILITY_ATTR) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 3)) +# elif defined(_GLIBCXX_VISIBILITY) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 2)) +# else +# error "Your version of libstdc++ is unknown to us and is likely too old." +# endif +# endif + + // Flesh out the defines for everyone else +# ifndef MOZ_USING_STLPORT +# define MOZ_USING_STLPORT 0 +# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) 0 +# endif +# ifndef MOZ_USING_LIBCXX +# define MOZ_USING_LIBCXX 0 +# endif +# ifndef MOZ_USING_LIBSTDCXX +# define MOZ_USING_LIBSTDCXX 0 +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) 0 +# endif +#endif /* __cplusplus */ + #endif /* mozilla_Compiler_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Compression.h b/external/spidermonkey/include/mac/mozilla/Compression.h new file mode 100644 index 0000000000..da77fa895f --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/Compression.h @@ -0,0 +1,116 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* 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/. */ + +/* Various simple compression/decompression functions. */ + +#ifndef mozilla_Compression_h_ +#define mozilla_Compression_h_ + +#include "mozilla/Types.h" +#include "mozilla/Assertions.h" + +namespace mozilla { +namespace Compression { + +/** + * LZ4 is a very fast byte-wise compression algorithm. + * + * Compared to Google's Snappy it is faster to compress and decompress and + * generally produces output of about the same size. + * + * Compared to zlib it compresses at about 10x the speed, decompresses at about + * 4x the speed and produces output of about 1.5x the size. + * + */ + +class LZ4 +{ + +public: + + /** + * Compresses 'inputSize' bytes from 'source' into 'dest'. + * Destination buffer must be already allocated, + * and must be sized to handle worst cases situations (input data not compressible) + * Worst case size evaluation is provided by function LZ4_compressBound() + * + * @param inputSize is the input size. Max supported value is ~1.9GB + * @param return the number of bytes written in buffer dest + */ + static MFBT_API size_t compress(const char* source, size_t inputSize, char* dest); + + /** + * Compress 'inputSize' bytes from 'source' into an output buffer + * 'dest' of maximum size 'maxOutputSize'. If it cannot achieve it, + * compression will stop, and result of the function will be zero, + * 'dest' will still be written to, but since the number of input + * bytes consumed is not returned the result is not usable. + * + * This function never writes outside of provided output buffer. + * + * @param inputSize is the input size. Max supported value is ~1.9GB + * @param maxOutputSize is the size of the destination buffer (which must be already allocated) + * @return the number of bytes written in buffer 'dest' + or 0 if the compression fails + */ + static MFBT_API size_t compressLimitedOutput(const char* source, size_t inputSize, char* dest, + size_t maxOutputSize); + + /** + * If the source stream is malformed, the function will stop decoding + * and return a negative result, indicating the byte position of the + * faulty instruction + * + * This function never writes outside of provided buffers, and never + * modifies input buffer. + * + * note : destination buffer must be already allocated. + * its size must be a minimum of 'outputSize' bytes. + * @param outputSize is the output size, therefore the original size + * @return the number of bytes read in the source buffer + */ + static MFBT_API bool decompress(const char* source, char* dest, size_t outputSize); + + /** + * If the source stream is malformed, the function will stop decoding + * and return false. + * + * This function never writes beyond dest + maxOutputSize, and is + * therefore protected against malicious data packets. + * + * note : Destination buffer must be already allocated. + * This version is slightly slower than the decompress + * without the maxOutputSize + * + * @param inputSize is the length of the input compressed data + * @param maxOutputSize is the size of the destination buffer (which must be already allocated) + * @param outputSize the actual number of bytes decoded in the destination buffer (necessarily <= maxOutputSize) + + */ + static MFBT_API bool decompress(const char* source, size_t inputSize, char* dest, + size_t maxOutputSize, size_t *outputSize); + + /* + Provides the maximum size that LZ4 may output in a "worst case" + scenario (input data not compressible) primarily useful for memory + allocation of output buffer. + note : this function is limited by "int" range (2^31-1) + + @param inputSize is the input size. Max supported value is ~1.9GB + @return maximum output size in a "worst case" scenario + */ + static MFBT_API size_t maxCompressedSize(size_t inputSize) + { + size_t max = ((inputSize) + ((inputSize)/255) + 16); + MOZ_ASSERT(max > inputSize); + return max; + } + +}; + +} /* namespace Compression */ +} /* namespace mozilla */ + +#endif /* mozilla_Compression_h_ */ diff --git a/external/spidermonkey/include/mac/mozilla/Endian.h b/external/spidermonkey/include/mac/mozilla/Endian.h index dc6d11d3ba..cb6bd27c05 100644 --- a/external/spidermonkey/include/mac/mozilla/Endian.h +++ b/external/spidermonkey/include/mac/mozilla/Endian.h @@ -238,9 +238,9 @@ class EndianUtils { DebugOnly byteDestPtr = static_cast(dest); DebugOnly byteSrcPtr = static_cast(src); - MOZ_ASSERT((byteDestPtr < byteSrcPtr && + MOZ_ASSERT((byteDestPtr <= byteSrcPtr && byteDestPtr + count <= byteSrcPtr) || - (byteSrcPtr < byteDestPtr && + (byteSrcPtr <= byteDestPtr && byteSrcPtr + count <= byteDestPtr)); } diff --git a/external/spidermonkey/include/mac/mozilla/FloatingPoint.h b/external/spidermonkey/include/mac/mozilla/FloatingPoint.h index d80f6a7234..eff26b4bb8 100644 --- a/external/spidermonkey/include/mac/mozilla/FloatingPoint.h +++ b/external/spidermonkey/include/mac/mozilla/FloatingPoint.h @@ -12,6 +12,7 @@ #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Casting.h" +#include "mozilla/Types.h" #include @@ -58,6 +59,30 @@ static_assert((DoubleSignBit | DoubleExponentBits | DoubleSignificandBits) == ~uint64_t(0), "all bits accounted for"); +/* + * Ditto for |float| that must be a 32-bit double format number type, compatible + * with the IEEE-754 standard. + */ +static_assert(sizeof(float) == sizeof(uint32_t), "float must be 32bits"); + +const unsigned FloatExponentBias = 127; +const unsigned FloatExponentShift = 23; + +const uint32_t FloatSignBit = 0x80000000UL; +const uint32_t FloatExponentBits = 0x7F800000UL; +const uint32_t FloatSignificandBits = 0x007FFFFFUL; + +static_assert((FloatSignBit & FloatExponentBits) == 0, + "sign bit doesn't overlap exponent bits"); +static_assert((FloatSignBit & FloatSignificandBits) == 0, + "sign bit doesn't overlap significand bits"); +static_assert((FloatExponentBits & FloatSignificandBits) == 0, + "exponent bits don't overlap significand bits"); + +static_assert((FloatSignBit | FloatExponentBits | FloatSignificandBits) == + ~uint32_t(0), + "all bits accounted for"); + /** Determines whether a double is NaN. */ static MOZ_ALWAYS_INLINE bool IsNaN(double d) @@ -115,7 +140,12 @@ IsNegativeZero(double d) return bits == DoubleSignBit; } -/** Returns the exponent portion of the double. */ +/** + * Returns the exponent portion of the double. + * + * Zero is not special-cased, so ExponentComponent(0.0) is + * -int_fast16_t(DoubleExponentBias). + */ static MOZ_ALWAYS_INLINE int_fast16_t ExponentComponent(double d) { @@ -190,7 +220,13 @@ DoubleIsInt32(double d, int32_t* i) static MOZ_ALWAYS_INLINE double UnspecifiedNaN() { - return SpecificNaN(0, 0xfffffffffffffULL); + /* + * If we can use any quiet NaN, we might as well use the all-ones NaN, + * since it's cheap to materialize on common platforms (such as x64, where + * this value can be represented in a 32-bit signed immediate field, allowing + * it to be stored to memory in a single instruction). + */ + return SpecificNaN(1, 0xfffffffffffffULL); } /** @@ -206,6 +242,46 @@ DoublesAreIdentical(double d1, double d2) return BitwiseCast(d1) == BitwiseCast(d2); } +/** Determines whether a float is NaN. */ +static MOZ_ALWAYS_INLINE bool +IsFloatNaN(float f) +{ + /* + * A float is NaN if all exponent bits are 1 and the significand contains at + * least one non-zero bit. + */ + uint32_t bits = BitwiseCast(f); + return (bits & FloatExponentBits) == FloatExponentBits && + (bits & FloatSignificandBits) != 0; +} + +/** Constructs a NaN value with the specified sign bit and significand bits. */ +static MOZ_ALWAYS_INLINE float +SpecificFloatNaN(int signbit, uint32_t significand) +{ + MOZ_ASSERT(signbit == 0 || signbit == 1); + MOZ_ASSERT((significand & ~FloatSignificandBits) == 0); + MOZ_ASSERT(significand & FloatSignificandBits); + + float f = BitwiseCast((signbit ? FloatSignBit : 0) | + FloatExponentBits | + significand); + MOZ_ASSERT(IsFloatNaN(f)); + return f; +} + +/** + * Returns true if the given value can be losslessly represented as an IEEE-754 + * single format number, false otherwise. All NaN values are considered + * representable (notwithstanding that the exact bit pattern of a double format + * NaN value can't be exactly represented in single format). + * + * This function isn't inlined to avoid buggy optimizations by MSVC. + */ +MOZ_WARN_UNUSED_RESULT +extern MFBT_API bool +IsFloat32Representable(double x); + } /* namespace mozilla */ #endif /* mozilla_FloatingPoint_h */ diff --git a/external/spidermonkey/include/mac/mozilla/HashFunctions.h b/external/spidermonkey/include/mac/mozilla/HashFunctions.h index 6d0d24e7b1..b228955ce5 100644 --- a/external/spidermonkey/include/mac/mozilla/HashFunctions.h +++ b/external/spidermonkey/include/mac/mozilla/HashFunctions.h @@ -48,6 +48,7 @@ #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/Char16.h" #include "mozilla/Types.h" #include @@ -326,6 +327,22 @@ HashString(const uint16_t* str, size_t length) return detail::HashKnownLength(str, length); } +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +MOZ_WARN_UNUSED_RESULT +inline uint32_t +HashString(const char16_t* str) +{ + return detail::HashUntilZero(str); +} + +MOZ_WARN_UNUSED_RESULT +inline uint32_t +HashString(const char16_t* str, size_t length) +{ + return detail::HashKnownLength(str, length); +} +#endif + /* * On Windows, wchar_t (PRUnichar) is not the same as uint16_t, even though it's * the same width! diff --git a/external/spidermonkey/include/mac/mozilla/IntegerPrintfMacros.h b/external/spidermonkey/include/mac/mozilla/IntegerPrintfMacros.h new file mode 100644 index 0000000000..1ae60d618e --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/IntegerPrintfMacros.h @@ -0,0 +1,40 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* 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/. */ + +/* Implements the C99 interface, minus the SCN* format macros. */ + +#ifndef mozilla_IntegerPrintfMacros_h_ +#define mozilla_IntegerPrintfMacros_h_ + +/* + * MSVC++ doesn't include , even in versions shipping , so + * we have to reimplement it there. Note: #includes . + * + * Note that this header DOES NOT implement 's scanf macros. MSVC's + * scanf doesn't have sufficient format specifier support to implement them + * (specifically, to implement scanning into an 8-bit location). + * + * http://stackoverflow.com/questions/3036396/scanfd-char-char-as-int-format-string + * + * Moreover, scanf is a footgun: if the input number exceeds the bounds of the + * target type, behavior is undefined (in the compiler sense: that is, this code + * could overwrite your hard drive with zeroes): + * + * uint8_t u; + * sscanf("256", "%" SCNu8, &u); // BAD + * + * This header will sometimes provide SCN* macros, by dint of being implemented + * using . But for these reasons, *never* use them! + */ + +#if defined(MOZ_CUSTOM_INTTYPES_H) +# include MOZ_CUSTOM_INTTYPES_H +#elif defined(_MSC_VER) +# include "mozilla/MSIntTypes.h" +#else +# include +#endif + +#endif /* mozilla_IntegerPrintfMacros_h_ */ diff --git a/external/spidermonkey/include/mac/mozilla/LinkedList.h b/external/spidermonkey/include/mac/mozilla/LinkedList.h index c29760b3e7..f35e7d56ab 100644 --- a/external/spidermonkey/include/mac/mozilla/LinkedList.h +++ b/external/spidermonkey/include/mac/mozilla/LinkedList.h @@ -58,6 +58,7 @@ #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/Move.h" #include "mozilla/NullPtr.h" #ifdef __cplusplus @@ -116,6 +117,36 @@ class LinkedListElement isSentinel(false) { } + LinkedListElement(LinkedListElement&& other) + : isSentinel(other.isSentinel) + { + if (!other.isInList()) { + next = this; + prev = this; + return; + } + + MOZ_ASSERT(other.next->prev == &other); + MOZ_ASSERT(other.prev->next == &other); + + /* + * Initialize |this| with |other|'s prev/next pointers, and adjust those + * element to point to this one. + */ + next = other.next; + prev = other.prev; + + next->prev = this; + prev->next = this; + + /* + * Adjust |other| so it doesn't think it's in a list. This makes it + * safely destructable. + */ + other.next = &other; + other.prev = &other; + } + ~LinkedListElement() { if (!isSentinel && isInList()) remove(); @@ -148,8 +179,8 @@ class LinkedListElement * linked list when you call setNext(); otherwise, this method will assert. */ void setNext(T* elem) { - MOZ_ASSERT(isInList()); - setNextUnsafe(elem); + MOZ_ASSERT(isInList()); + setNextUnsafe(elem); } /* @@ -252,8 +283,8 @@ class LinkedListElement } private: - LinkedListElement& operator=(const LinkedList& other) MOZ_DELETE; - LinkedListElement(const LinkedList& other) MOZ_DELETE; + LinkedListElement& operator=(const LinkedListElement& other) MOZ_DELETE; + LinkedListElement(const LinkedListElement& other) MOZ_DELETE; }; template @@ -265,6 +296,10 @@ class LinkedList public: LinkedList() : sentinel(LinkedListElement::NODE_KIND_SENTINEL) { } + LinkedList(LinkedList&& other) + : sentinel(mozilla::Move(other.sentinel)) + { } + ~LinkedList() { MOZ_ASSERT(isEmpty()); } @@ -361,7 +396,7 @@ class LinkedList for (slow = sentinel.next, fast1 = sentinel.next->next, fast2 = sentinel.next->next->next; - slow != sentinel && fast1 != sentinel && fast2 != sentinel; + slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; slow = slow->next, fast1 = fast2->next, fast2 = fast1->next) { MOZ_ASSERT(slow != fast1); @@ -372,7 +407,7 @@ class LinkedList for (slow = sentinel.prev, fast1 = sentinel.prev->prev, fast2 = sentinel.prev->prev->prev; - slow != sentinel && fast1 != sentinel && fast2 != sentinel; + slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; slow = slow->prev, fast1 = fast2->prev, fast2 = fast1->prev) { MOZ_ASSERT(slow != fast1); @@ -384,14 +419,14 @@ class LinkedList * isSentinel == true. */ for (const LinkedListElement* elem = sentinel.next; - elem != sentinel; + elem != &sentinel; elem = elem->next) { MOZ_ASSERT(!elem->isSentinel); } /* Check that the next/prev pointers match up. */ - const LinkedListElement* prev = sentinel; + const LinkedListElement* prev = &sentinel; const LinkedListElement* cur = sentinel.next; do { MOZ_ASSERT(cur->prev == prev); @@ -399,7 +434,7 @@ class LinkedList prev = cur; cur = cur->next; - } while (cur != sentinel); + } while (cur != &sentinel); #endif /* ifdef DEBUG */ } diff --git a/external/spidermonkey/include/mac/mozilla/MSIntTypes.h b/external/spidermonkey/include/mac/mozilla/MSIntTypes.h new file mode 100644 index 0000000000..3dfba55f58 --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/MSIntTypes.h @@ -0,0 +1,198 @@ +// ISO C9x compliant inttypes.h for Microsoft Visual Studio +// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 +// +// Copyright (c) 2006 Alexander Chemeris +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// 3. The name of the author may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef _MSC_VER // [ +#error "Use this header only with Microsoft Visual C++ compilers!" +#endif // _MSC_VER ] + +#ifndef _MSC_INTTYPES_H_ // [ +#define _MSC_INTTYPES_H_ + +#if _MSC_VER > 1000 +#pragma once +#endif + +#include + +// 7.8 Format conversion of integer types + +typedef struct { + intmax_t quot; + intmax_t rem; +} imaxdiv_t; + +// 7.8.1 Macros for format specifiers + +#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 + +// The fprintf macros for signed integers are: +#define PRId8 "d" +#define PRIi8 "i" +#define PRIdLEAST8 "d" +#define PRIiLEAST8 "i" +#define PRIdFAST8 "d" +#define PRIiFAST8 "i" + +#define PRId16 "hd" +#define PRIi16 "hi" +#define PRIdLEAST16 "hd" +#define PRIiLEAST16 "hi" +#define PRIdFAST16 "hd" +#define PRIiFAST16 "hi" + +#define PRId32 "I32d" +#define PRIi32 "I32i" +#define PRIdLEAST32 "I32d" +#define PRIiLEAST32 "I32i" +#define PRIdFAST32 "I32d" +#define PRIiFAST32 "I32i" + +#define PRId64 "I64d" +#define PRIi64 "I64i" +#define PRIdLEAST64 "I64d" +#define PRIiLEAST64 "I64i" +#define PRIdFAST64 "I64d" +#define PRIiFAST64 "I64i" + +#define PRIdMAX "I64d" +#define PRIiMAX "I64i" + +#define PRIdPTR "Id" +#define PRIiPTR "Ii" + +// The fprintf macros for unsigned integers are: +#define PRIo8 "o" +#define PRIu8 "u" +#define PRIx8 "x" +#define PRIX8 "X" +#define PRIoLEAST8 "o" +#define PRIuLEAST8 "u" +#define PRIxLEAST8 "x" +#define PRIXLEAST8 "X" +#define PRIoFAST8 "o" +#define PRIuFAST8 "u" +#define PRIxFAST8 "x" +#define PRIXFAST8 "X" + +#define PRIo16 "ho" +#define PRIu16 "hu" +#define PRIx16 "hx" +#define PRIX16 "hX" +#define PRIoLEAST16 "ho" +#define PRIuLEAST16 "hu" +#define PRIxLEAST16 "hx" +#define PRIXLEAST16 "hX" +#define PRIoFAST16 "ho" +#define PRIuFAST16 "hu" +#define PRIxFAST16 "hx" +#define PRIXFAST16 "hX" + +#define PRIo32 "I32o" +#define PRIu32 "I32u" +#define PRIx32 "I32x" +#define PRIX32 "I32X" +#define PRIoLEAST32 "I32o" +#define PRIuLEAST32 "I32u" +#define PRIxLEAST32 "I32x" +#define PRIXLEAST32 "I32X" +#define PRIoFAST32 "I32o" +#define PRIuFAST32 "I32u" +#define PRIxFAST32 "I32x" +#define PRIXFAST32 "I32X" + +#define PRIo64 "I64o" +#define PRIu64 "I64u" +#define PRIx64 "I64x" +#define PRIX64 "I64X" +#define PRIoLEAST64 "I64o" +#define PRIuLEAST64 "I64u" +#define PRIxLEAST64 "I64x" +#define PRIXLEAST64 "I64X" +#define PRIoFAST64 "I64o" +#define PRIuFAST64 "I64u" +#define PRIxFAST64 "I64x" +#define PRIXFAST64 "I64X" + +#define PRIoMAX "I64o" +#define PRIuMAX "I64u" +#define PRIxMAX "I64x" +#define PRIXMAX "I64X" + +#define PRIoPTR "Io" +#define PRIuPTR "Iu" +#define PRIxPTR "Ix" +#define PRIXPTR "IX" + +// DO NOT SUPPORT THE scanf MACROS! See the comment at the top of +// IntegerPrintfMacros.h. + +#endif // __STDC_FORMAT_MACROS ] + +// 7.8.2 Functions for greatest-width integer types + +// 7.8.2.1 The imaxabs function +#define imaxabs _abs64 + +// 7.8.2.2 The imaxdiv function + +// This is modified version of div() function from Microsoft's div.c found +// in %MSVC.NET%\crt\src\div.c +#ifdef STATIC_IMAXDIV // [ +static +#else // STATIC_IMAXDIV ][ +_inline +#endif // STATIC_IMAXDIV ] +imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) +{ + imaxdiv_t result; + + result.quot = numer / denom; + result.rem = numer % denom; + + if (numer < 0 && result.rem > 0) { + // did division wrong; must fix up + ++result.quot; + result.rem -= denom; + } + + return result; +} + +// 7.8.2.3 The strtoimax and strtoumax functions +#define strtoimax _strtoi64 +#define strtoumax _strtoui64 + +// 7.8.2.4 The wcstoimax and wcstoumax functions +#define wcstoimax _wcstoi64 +#define wcstoumax _wcstoui64 + + +#endif // _MSC_INTTYPES_H_ ] diff --git a/external/spidermonkey/include/mac/mozilla/MathAlgorithms.h b/external/spidermonkey/include/mac/mozilla/MathAlgorithms.h index 6d58691e06..941ac81271 100644 --- a/external/spidermonkey/include/mac/mozilla/MathAlgorithms.h +++ b/external/spidermonkey/include/mac/mozilla/MathAlgorithms.h @@ -186,6 +186,16 @@ namespace detail { return uint_fast8_t(index); } + inline uint_fast8_t + CountPopulation32(uint32_t u) + { + uint32_t sum2 = (u & 0x55555555) + ((u & 0xaaaaaaaa) >> 1); + uint32_t sum4 = (sum2 & 0x33333333) + ((sum2 & 0xcccccccc) >> 2); + uint32_t sum8 = (sum4 & 0x0f0f0f0f) + ((sum4 & 0xf0f0f0f0) >> 4); + uint32_t sum16 = (sum8 & 0x00ff00ff) + ((sum8 & 0xff00ff00) >> 8); + return sum16; + } + inline uint_fast8_t CountLeadingZeroes64(uint64_t u) { @@ -242,6 +252,12 @@ namespace detail { return __builtin_ctz(u); } + inline uint_fast8_t + CountPopulation32(uint32_t u) + { + return __builtin_popcount(u); + } + inline uint_fast8_t CountLeadingZeroes64(uint64_t u) { @@ -258,6 +274,7 @@ namespace detail { # error "Implement these!" inline uint_fast8_t CountLeadingZeroes32(uint32_t u) MOZ_DELETE; inline uint_fast8_t CountTrailingZeroes32(uint32_t u) MOZ_DELETE; + inline uint_fast8_t CountPopulation32(uint32_t u) MOZ_DELETE; inline uint_fast8_t CountLeadingZeroes64(uint64_t u) MOZ_DELETE; inline uint_fast8_t CountTrailingZeroes64(uint64_t u) MOZ_DELETE; #endif @@ -300,6 +317,15 @@ CountTrailingZeroes32(uint32_t u) return detail::CountTrailingZeroes32(u); } +/** + * Compute the number of one bits in the number |u|, + */ +inline uint_fast8_t +CountPopulation32(uint32_t u) +{ + return detail::CountPopulation32(u); +} + /** Analogous to CountLeadingZeroes32, but for 64-bit numbers. */ inline uint_fast8_t CountLeadingZeroes64(uint64_t u) diff --git a/external/spidermonkey/include/mac/mozilla/Maybe.h b/external/spidermonkey/include/mac/mozilla/Maybe.h new file mode 100644 index 0000000000..25683a28ab --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/Maybe.h @@ -0,0 +1,163 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=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/. */ + +/* A class for lazily constructing an object without sticking it on the heap. */ + +#ifndef mozilla_Maybe_h +#define mozilla_Maybe_h + +#include "mozilla/Alignment.h" +#include "mozilla/Assertions.h" + +// For placement new +#include + +namespace mozilla { + +/* + * Small utility for lazily constructing objects without using dynamic storage. + * When a Maybe is constructed, it is |empty()|, i.e., no value of T has + * been constructed and no T destructor will be called when the Maybe is + * destroyed. Upon calling |construct|, a T object will be constructed with the + * given arguments and that object will be destroyed when the owning Maybe + * is destroyed. + * + * N.B. GCC seems to miss some optimizations with Maybe and may generate extra + * branches/loads/stores. Use with caution on hot paths. + */ +template +class Maybe +{ + AlignedStorage2 storage; + bool constructed; + + T& asT() { return *storage.addr(); } + + public: + Maybe() { constructed = false; } + ~Maybe() { if (constructed) asT().~T(); } + + bool empty() const { return !constructed; } + + void construct() { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(); + constructed = true; + } + + template + void construct(const T1& t1) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); + constructed = true; + } + + T* addr() { + MOZ_ASSERT(constructed); + return &asT(); + } + + T& ref() { + MOZ_ASSERT(constructed); + return asT(); + } + + const T& ref() const { + MOZ_ASSERT(constructed); + return const_cast(this)->asT(); + } + + void destroy() { + ref().~T(); + constructed = false; + } + + void destroyIfConstructed() { + if (!empty()) + destroy(); + } + + private: + Maybe(const Maybe& other) MOZ_DELETE; + const Maybe& operator=(const Maybe& other) MOZ_DELETE; +}; + +} // namespace mozilla + +#endif /* mozilla_Maybe_h */ diff --git a/external/spidermonkey/include/mac/mozilla/Move.h b/external/spidermonkey/include/mac/mozilla/Move.h index 97178daaa6..a18da32ad8 100644 --- a/external/spidermonkey/include/mac/mozilla/Move.h +++ b/external/spidermonkey/include/mac/mozilla/Move.h @@ -9,11 +9,21 @@ #ifndef mozilla_Move_h #define mozilla_Move_h +#include "mozilla/TypeTraits.h" + namespace mozilla { /* * "Move" References * + * [Once upon a time, C++11 rvalue references were not implemented by all the + * compilers we cared about, so we invented mozilla::Move() (now called + * OldMove()), which does something similar. We're in the process of + * transitioning away from this to pure stl (bug 896100). Until that bug is + * completed, this header will provide both mozilla::OldMove() and + * mozilla::Move().] + * + * * Some types can be copied much more efficiently if we know the original's * value need not be preserved --- that is, if we are doing a "move", not a * "copy". For example, if we have: @@ -48,18 +58,28 @@ namespace mozilla { * efficiently than it can be copied, and provide an implementation of that * move operation. * - * The Move(T&) function takes a reference to a T, and returns a MoveRef - * referring to the same value; that's 1). A MoveRef is simply a reference + * The OldMove(T&) function takes a reference to a T, and returns a MoveRef + * referring to the same value; that's (1). A MoveRef is simply a reference * to a T, annotated to say that a copy constructor applied to it may move that * T, instead of copying it. Finally, a constructor that accepts an MoveRef - * should perform a more efficient move, instead of a copy, providing 2). + * should perform a more efficient move, instead of a copy, providing (2). * - * So, where we might define a copy constructor for a class C like this: + * The Move(T&) function takes a reference to a T and returns a T&&. It acts + * just like std::move(), which is not available on all our platforms. + * + * In new code, you should use Move(T&) and T&& instead of OldMove(T&) and + * MoveRef, where possible. + * + * Where we might define a copy constructor for a class C like this: * * C(const C& rhs) { ... copy rhs to this ... } * * we would declare a move constructor like this: * + * C(C&& rhs) { .. move rhs to this ... } + * + * or, in the deprecated OldMove style: + * * C(MoveRef rhs) { ... move rhs to this ... } * * And where we might perform a copy like this: @@ -68,7 +88,11 @@ namespace mozilla { * * we would perform a move like this: * - * C c2(Move(c1)) + * C c2(Move(c1)); + * + * or, in the deprecated OldMove style: + * + * C c2(OldMove(c1)); * * Note that MoveRef implicitly converts to T&, so you can pass a MoveRef * to an ordinary copy constructor for a type that doesn't support a special @@ -82,7 +106,7 @@ namespace mozilla { * which runs this's destructor, and then applies the move constructor to * *this's memory. A typical definition: * - * C& operator=(MoveRef rhs) { + * C& operator=(C&& rhs) { // or |MoveRef rhs| * this->~C(); * new(this) C(rhs); * return *this; @@ -90,14 +114,14 @@ namespace mozilla { * * With that in place, one can write move assignments like this: * - * c2 = Move(c1); + * c2 = Move(c1); // or OldMove() * * This destroys c1, moves c1's value to c2, and leaves c1 in an undefined but * destructible state. * - * This header file defines MoveRef and Move in the mozilla namespace. It's up - * to individual containers to annotate moves as such, by calling Move; and it's - * up to individual types to define move constructors. + * This header file defines MoveRef, Move, and OldMove in the mozilla namespace. + * It's up to individual containers to annotate moves as such, by calling Move + * or OldMove; and it's up to individual types to define move constructors. * * One hint: if you're writing a move constructor where the type has members * that should be moved themselves, it's much nicer to write this: @@ -125,14 +149,14 @@ class MoveRef template inline MoveRef -Move(T& t) +OldMove(T& t) { return MoveRef(t); } template inline MoveRef -Move(const T& t) +OldMove(const T& t) { // With some versions of gcc, for a class C, there's an (incorrect) ambiguity // between the C(const C&) constructor and the default C(C&&) C++11 move @@ -151,14 +175,45 @@ Move(const T& t) return MoveRef(const_cast(t)); } +/** + * Identical to std::Move(); this is necessary until our stlport supports + * std::move(). + */ +template +inline typename RemoveReference::Type&& +Move(T&& a) +{ + return static_cast::Type&&>(a); +} + +/** + * These two overloads are identidal to std::Forward(); they are necessary until + * our stlport supports std::forward(). + */ +template +inline T&& +Forward(typename RemoveReference::Type& a) +{ + return static_cast(a); +} + +template +inline T&& +Forward(typename RemoveReference::Type&& t) +{ + static_assert(!IsLvalueReference::value, + "misuse of Forward detected! try the other overload"); + return static_cast(t); +} + /** Swap |t| and |u| using move-construction if possible. */ template inline void Swap(T& t, T& u) { - T tmp(Move(t)); - t = Move(u); - u = Move(tmp); + T tmp(OldMove(t)); + t = OldMove(u); + u = OldMove(tmp); } } // namespace mozilla diff --git a/external/spidermonkey/include/mac/mozilla/NullPtr.h b/external/spidermonkey/include/mac/mozilla/NullPtr.h index 14c0f07df2..35faadc4c3 100644 --- a/external/spidermonkey/include/mac/mozilla/NullPtr.h +++ b/external/spidermonkey/include/mac/mozilla/NullPtr.h @@ -12,8 +12,6 @@ #ifndef mozilla_NullPtr_h #define mozilla_NullPtr_h -#include "mozilla/Compiler.h" - #if defined(__clang__) # ifndef __has_extension # define __has_extension __has_feature @@ -23,6 +21,7 @@ # endif #elif defined(__GNUC__) # if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L +# include "mozilla/Compiler.h" # if MOZ_GCC_VERSION_AT_LEAST(4, 6, 0) # define MOZ_HAVE_CXX11_NULLPTR # endif diff --git a/external/spidermonkey/include/mac/mozilla/NumericLimits.h b/external/spidermonkey/include/mac/mozilla/NumericLimits.h new file mode 100644 index 0000000000..d2ee29813e --- /dev/null +++ b/external/spidermonkey/include/mac/mozilla/NumericLimits.h @@ -0,0 +1,40 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=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/. */ + +/* Compatibility with std::numeric_limits. */ + +#ifndef mozilla_NumericLimits_h +#define mozilla_NumericLimits_h + +#include "mozilla/Char16.h" + +#include +#include + +namespace mozilla { + +/** + * The NumericLimits class provides a compatibility layer with std::numeric_limits + * for char16_t, otherwise it is exactly the same as std::numeric_limits. + * Code which does not need std::numeric_limits should avoid using + * NumericLimits. + */ +template +class NumericLimits : public std::numeric_limits +{ +}; + +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> +class NumericLimits : public std::numeric_limits +{ + // char16_t and uint16_t numeric limits should be exactly the same. +}; +#endif + +} // namespace mozilla + +#endif /* mozilla_NumericLimits_h */ diff --git a/external/spidermonkey/include/mac/mozilla/PodOperations.h b/external/spidermonkey/include/mac/mozilla/PodOperations.h index bec89fa928..668197cdc1 100644 --- a/external/spidermonkey/include/mac/mozilla/PodOperations.h +++ b/external/spidermonkey/include/mac/mozilla/PodOperations.h @@ -24,7 +24,7 @@ namespace mozilla { /** Set the contents of |t| to 0. */ template -static void +static MOZ_ALWAYS_INLINE void PodZero(T* t) { memset(t, 0, sizeof(T)); @@ -32,7 +32,7 @@ PodZero(T* t) /** Set the contents of |nelem| elements starting at |t| to 0. */ template -static void +static MOZ_ALWAYS_INLINE void PodZero(T* t, size_t nelem) { /* @@ -58,7 +58,7 @@ static void PodZero(T (&t)[N], size_t nelem) MOZ_DELETE; /** Set the contents of the array |t| to zero. */ template -static void +static MOZ_ALWAYS_INLINE void PodArrayZero(T (&t)[N]) { memset(t, 0, N * sizeof(T)); @@ -69,7 +69,7 @@ PodArrayZero(T (&t)[N]) * overlap. */ template -static void +static MOZ_ALWAYS_INLINE void PodAssign(T* dst, const T* src) { MOZ_ASSERT(dst != src); @@ -83,7 +83,7 @@ PodAssign(T* dst, const T* src) * overlap! */ template -MOZ_ALWAYS_INLINE static void +static MOZ_ALWAYS_INLINE void PodCopy(T* dst, const T* src, size_t nelem) { MOZ_ASSERT(dst != src); @@ -103,7 +103,7 @@ PodCopy(T* dst, const T* src, size_t nelem) } template -MOZ_ALWAYS_INLINE static void +static MOZ_ALWAYS_INLINE void PodCopy(volatile T* dst, const volatile T* src, size_t nelem) { MOZ_ASSERT(dst != src); @@ -127,7 +127,7 @@ PodCopy(volatile T* dst, const volatile T* src, size_t nelem) * The arrays must not overlap! */ template -static void +static MOZ_ALWAYS_INLINE void PodArrayCopy(T (&dst)[N], const T (&src)[N]) { PodCopy(dst, src, N); @@ -138,7 +138,7 @@ PodArrayCopy(T (&dst)[N], const T (&src)[N]) * |len| elements at |two|. */ template -MOZ_ALWAYS_INLINE static bool +static MOZ_ALWAYS_INLINE bool PodEqual(const T* one, const T* two, size_t len) { if (len < 128) { diff --git a/external/spidermonkey/include/mac/mozilla/RefPtr.h b/external/spidermonkey/include/mac/mozilla/RefPtr.h index 3c275afdc7..72c7904554 100644 --- a/external/spidermonkey/include/mac/mozilla/RefPtr.h +++ b/external/spidermonkey/include/mac/mozilla/RefPtr.h @@ -68,18 +68,18 @@ class RefCounted public: // Compatibility with nsRefPtr. - void AddRef() { + void AddRef() const { MOZ_ASSERT(refCnt >= 0); ++refCnt; } - void Release() { + void Release() const { MOZ_ASSERT(refCnt > 0); if (0 == --refCnt) { #ifdef DEBUG refCnt = detail::DEAD; #endif - delete static_cast(this); + delete static_cast(this); } } @@ -93,7 +93,7 @@ class RefCounted } private: - typename Conditional, int>::Type refCnt; + mutable typename Conditional, int>::Type refCnt; }; } diff --git a/external/spidermonkey/include/mac/mozilla/TypeTraits.h b/external/spidermonkey/include/mac/mozilla/TypeTraits.h index 53c0b5c2f6..1ccd0c85d1 100644 --- a/external/spidermonkey/include/mac/mozilla/TypeTraits.h +++ b/external/spidermonkey/include/mac/mozilla/TypeTraits.h @@ -63,6 +63,9 @@ template<> struct IsIntegralHelper : TrueType {}; template<> struct IsIntegralHelper : TrueType {}; template<> struct IsIntegralHelper : TrueType {}; template<> struct IsIntegralHelper : TrueType {}; +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> struct IsIntegralHelper : TrueType {}; +#endif } /* namespace detail */ @@ -218,6 +221,9 @@ template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> struct IsPod : TrueType {}; +#endif template struct IsPod : TrueType {}; namespace detail { @@ -418,6 +424,16 @@ struct IsConvertible : IntegralConstant::value> {}; +/** + * Is IsLvalueReference is true if its template param is T& and is false if + * its type is T or T&&. + */ +template +struct IsLvalueReference : FalseType {}; + +template +struct IsLvalueReference : TrueType {}; + /* 20.9.7 Transformations between types [meta.trans] */ /* 20.9.7.1 Const-volatile modifications [meta.trans.cv] */ @@ -478,6 +494,32 @@ struct RemoveCV /* 20.9.7.2 Reference modifications [meta.trans.ref] */ +/** + * Converts reference types to the underlying types. + * + * mozilla::RemoveReference::Type is T; + * mozilla::RemoveReference::Type is T; + * mozilla::RemoveReference::Type is T; + */ + +template +struct RemoveReference +{ + typedef T Type; +}; + +template +struct RemoveReference +{ + typedef T Type; +}; + +template +struct RemoveReference +{ + typedef T Type; +}; + /* 20.9.7.3 Sign modifications [meta.trans.sign] */ template diff --git a/external/spidermonkey/include/mac/mozilla/TypedEnum.h b/external/spidermonkey/include/mac/mozilla/TypedEnum.h index 6f595cb4c5..9c7590deff 100644 --- a/external/spidermonkey/include/mac/mozilla/TypedEnum.h +++ b/external/spidermonkey/include/mac/mozilla/TypedEnum.h @@ -28,7 +28,7 @@ # endif #elif defined(__GNUC__) # if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L -# if MOZ_GCC_VERSION_AT_LEAST(4, 5, 1) +# if MOZ_GCC_VERSION_AT_LEAST(4, 6, 3) # define MOZ_HAVE_CXX11_ENUM_TYPE # define MOZ_HAVE_CXX11_STRONG_ENUMS # endif @@ -72,7 +72,7 @@ * strongly-typed enumeration feature of C++11 ("enum class"). If supported * by the compiler, an enum defined using these macros will not be implicitly * converted to any other type, and its enumerators will be scoped using the - * enumeration name. Place MOZ_BEGIN_ENUM_CLASS(EnumName, type) in place of + * enumeration name. Place MOZ_BEGIN_ENUM_CLASS(EnumName [, type]) in place of * "enum EnumName {", and MOZ_END_ENUM_CLASS(EnumName) in place of the closing * "};". For example, * @@ -87,10 +87,9 @@ * fail. In other compilers, Enum itself will actually be defined as a class, * and some implicit conversions will fail while others will succeed. * - * The type argument specifies the underlying type for the enum where - * supported, as with MOZ_ENUM_TYPE(). For simplicity, it is currently - * mandatory. As with MOZ_ENUM_TYPE(), it will do nothing on compilers that do - * not support it. + * The optional type argument specifies the underlying type for the enum where + * supported, as with MOZ_ENUM_TYPE(). As with MOZ_ENUM_TYPE(), it will do + * nothing on compilers that do not support it. * * MOZ_{BEGIN,END}_ENUM_CLASS doesn't work for defining enum classes nested * inside classes. To define an enum class nested inside another class, use @@ -114,7 +113,12 @@ * All compilers that support strong enums also support an explicit * underlying type, so no extra check is needed. */ -# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ + + /* Single-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER1(Name) \ + enum class Name { + /* Two-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER2(Name, type) \ enum class Name : type { # define MOZ_END_NESTED_ENUM_CLASS(Name) \ }; @@ -154,8 +158,17 @@ * { * return Enum::A; * } - */\ -# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ + */ + + /* Single-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER1(Name) \ + class Name \ + { \ + public: \ + enum Enum \ + { + /* Two-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER2(Name, type) \ class Name \ { \ public: \ @@ -226,7 +239,36 @@ inline int& operator<<=(int&, const Name::Enum&) MOZ_DELETE; \ inline int& operator>>=(int&, const Name::Enum&) MOZ_DELETE; #endif -# define MOZ_BEGIN_ENUM_CLASS(Name, type) MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) + + /* + * Count the number of arguments passed to MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS, + * very carefully tiptoeing around an MSVC bug where it improperly expands + * __VA_ARGS__ as a single token in argument lists. See these URLs for + * details: + * + * http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement + * http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/#comment-644 + */ +# define MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL2(_1, _2, count, ...) \ + count +# define MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL(args) \ + MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL2 args +# define MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS(...) \ + MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL((__VA_ARGS__, 2, 1, 0)) + /* Pick the right helper macro to invoke. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER2(count) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER##count +# define MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER1(count) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER2(count) +# define MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER(count) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER1(count) + /* The actual macro. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_GLUE(x, y) x y +# define MOZ_BEGIN_NESTED_ENUM_CLASS(...) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_GLUE(MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER(MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS(__VA_ARGS__)), \ + (__VA_ARGS__)) + +# define MOZ_BEGIN_ENUM_CLASS(...) MOZ_BEGIN_NESTED_ENUM_CLASS(__VA_ARGS__) # define MOZ_END_ENUM_CLASS(Name) \ MOZ_END_NESTED_ENUM_CLASS(Name) \ MOZ_FINISH_NESTED_ENUM_CLASS(Name) diff --git a/external/spidermonkey/include/mac/mozilla/Util.h b/external/spidermonkey/include/mac/mozilla/Util.h index 4f1c634a59..b4cf2e425b 100644 --- a/external/spidermonkey/include/mac/mozilla/Util.h +++ b/external/spidermonkey/include/mac/mozilla/Util.h @@ -18,267 +18,10 @@ #ifdef __cplusplus +#include "mozilla/Alignment.h" + namespace mozilla { -/* - * This class, and the corresponding macro MOZ_ALIGNOF, figure out how many - * bytes of alignment a given type needs. - */ -template -class AlignmentFinder -{ - struct Aligner - { - char c; - T t; - }; - - public: - static const size_t alignment = sizeof(Aligner) - sizeof(T); -}; - -#define MOZ_ALIGNOF(T) mozilla::AlignmentFinder::alignment - -/* - * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types. - * - * For instance, - * - * MOZ_ALIGNED_DECL(char arr[2], 8); - * - * will declare a two-character array |arr| aligned to 8 bytes. - */ - -#if defined(__GNUC__) -# define MOZ_ALIGNED_DECL(_type, _align) \ - _type __attribute__((aligned(_align))) -#elif defined(_MSC_VER) -# define MOZ_ALIGNED_DECL(_type, _align) \ - __declspec(align(_align)) _type -#else -# warning "We don't know how to align variables on this compiler." -# define MOZ_ALIGNED_DECL(_type, _align) _type -#endif - -/* - * AlignedElem is a structure whose alignment is guaranteed to be at least N - * bytes. - * - * We support 1, 2, 4, 8, and 16-bit alignment. - */ -template -struct AlignedElem; - -/* - * We have to specialize this template because GCC doesn't like __attribute__((aligned(foo))) where - * foo is a template parameter. - */ - -template<> -struct AlignedElem<1> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 1); -}; - -template<> -struct AlignedElem<2> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 2); -}; - -template<> -struct AlignedElem<4> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 4); -}; - -template<> -struct AlignedElem<8> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 8); -}; - -template<> -struct AlignedElem<16> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 16); -}; - -/* - * This utility pales in comparison to Boost's aligned_storage. The utility - * simply assumes that uint64_t is enough alignment for anyone. This may need - * to be extended one day... - * - * As an important side effect, pulling the storage into this template is - * enough obfuscation to confuse gcc's strict-aliasing analysis into not giving - * false negatives when we cast from the char buffer to whatever type we've - * constructed using the bytes. - */ -template -struct AlignedStorage -{ - union U { - char bytes[nbytes]; - uint64_t _; - } u; - - const void* addr() const { return u.bytes; } - void* addr() { return u.bytes; } -}; - -template -struct AlignedStorage2 -{ - union U { - char bytes[sizeof(T)]; - uint64_t _; - } u; - - const T* addr() const { return reinterpret_cast(u.bytes); } - T* addr() { return static_cast(static_cast(u.bytes)); } -}; - -/* - * Small utility for lazily constructing objects without using dynamic storage. - * When a Maybe is constructed, it is |empty()|, i.e., no value of T has - * been constructed and no T destructor will be called when the Maybe is - * destroyed. Upon calling |construct|, a T object will be constructed with the - * given arguments and that object will be destroyed when the owning Maybe - * is destroyed. - * - * N.B. GCC seems to miss some optimizations with Maybe and may generate extra - * branches/loads/stores. Use with caution on hot paths. - */ -template -class Maybe -{ - AlignedStorage2 storage; - bool constructed; - - T& asT() { return *storage.addr(); } - - public: - Maybe() { constructed = false; } - ~Maybe() { if (constructed) asT().~T(); } - - bool empty() const { return !constructed; } - - void construct() { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(); - constructed = true; - } - - template - void construct(const T1& t1) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7, const T8& t8) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7, const T8& t8, const T9& t9) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); - constructed = true; - } - - T* addr() { - MOZ_ASSERT(constructed); - return &asT(); - } - - T& ref() { - MOZ_ASSERT(constructed); - return asT(); - } - - const T& ref() const { - MOZ_ASSERT(constructed); - return const_cast(this)->asT(); - } - - void destroy() { - ref().~T(); - constructed = false; - } - - void destroyIfConstructed() { - if (!empty()) - destroy(); - } - - private: - Maybe(const Maybe& other) MOZ_DELETE; - const Maybe& operator=(const Maybe& other) MOZ_DELETE; -}; - /* * Safely subtract two pointers when it is known that end >= begin. This avoids * the common compiler bug that if (size_t(end) - size_t(begin)) has the MSB diff --git a/external/spidermonkey/include/mac/mozilla/Vector.h b/external/spidermonkey/include/mac/mozilla/Vector.h index 8759df8c06..54e266eeb7 100644 --- a/external/spidermonkey/include/mac/mozilla/Vector.h +++ b/external/spidermonkey/include/mac/mozilla/Vector.h @@ -9,6 +9,7 @@ #ifndef mozilla_Vector_h #define mozilla_Vector_h +#include "mozilla/Alignment.h" #include "mozilla/AllocPolicy.h" #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" @@ -19,7 +20,7 @@ #include "mozilla/ReentrancyGuard.h" #include "mozilla/TemplateLib.h" #include "mozilla/TypeTraits.h" -#include "mozilla/Util.h" +#include "mozilla/Util.h" // for PointerRangeSize #include // for placement new @@ -85,7 +86,7 @@ struct VectorImpl template static inline void moveConstruct(T* dst, const U* srcbeg, const U* srcend) { for (const U* p = srcbeg; p < srcend; ++p, ++dst) - new(dst) T(Move(*p)); + new(dst) T(OldMove(*p)); } /* @@ -114,7 +115,7 @@ struct VectorImpl T* dst = newbuf; T* src = v.beginNoCheck(); for (; src < v.endNoCheck(); ++dst, ++src) - new(dst) T(Move(*src)); + new(dst) T(OldMove(*src)); VectorImpl::destroy(v.beginNoCheck(), v.endNoCheck()); v.free_(v.mBegin); v.mBegin = newbuf; @@ -547,8 +548,8 @@ class VectorBase : private AllocPolicy void swap(ThisVector& other); private: - VectorBase(const ThisVector&) MOZ_DELETE; - void operator=(const ThisVector&) MOZ_DELETE; + VectorBase(const VectorBase&) MOZ_DELETE; + void operator=(const VectorBase&) MOZ_DELETE; }; /* This does the re-entrancy check plus several other sanity checks. */ @@ -565,14 +566,15 @@ template MOZ_ALWAYS_INLINE VectorBase::VectorBase(AP ap) : AP(ap), - mBegin(static_cast(storage.addr())), mLength(0), mCapacity(sInlineCapacity) #ifdef DEBUG , mReserved(sInlineCapacity), entered(false) #endif -{} +{ + mBegin = static_cast(storage.addr()); +} /* Move constructor. */ template diff --git a/external/spidermonkey/include/mac/mozilla/WeakPtr.h b/external/spidermonkey/include/mac/mozilla/WeakPtr.h index c714ebf565..0165e3a017 100644 --- a/external/spidermonkey/include/mac/mozilla/WeakPtr.h +++ b/external/spidermonkey/include/mac/mozilla/WeakPtr.h @@ -14,9 +14,6 @@ * the WeakPtrs to it and allows the WeakReference to live beyond the lifetime * of 'Foo'. * - * AtomicSupportsWeakPtr can be used for a variant with an atomically updated - * reference counter. - * * The overhead of WeakPtr is that accesses to 'Foo' becomes an additional * dereference, and an additional heap allocated pointer sized object shared * between all of the WeakPtrs. @@ -63,7 +60,6 @@ #define mozilla_WeakPtr_h #include "mozilla/Assertions.h" -#include "mozilla/Atomics.h" #include "mozilla/NullPtr.h" #include "mozilla/RefPtr.h" #include "mozilla/TypeTraits.h" @@ -76,8 +72,8 @@ template class SupportsWeakPtrBase; namespace detail { // This can live beyond the lifetime of the class derived from SupportsWeakPtrBase. -template -class WeakReference : public RefCounted, Atomicity> +template +class WeakReference : public ::mozilla::RefCounted > { public: explicit WeakReference(T* p) : ptr(p) {} @@ -86,8 +82,8 @@ class WeakReference : public RefCounted, Atomicity> } private: - friend class WeakPtrBase; - friend class SupportsWeakPtrBase; + friend class WeakPtrBase >; + friend class SupportsWeakPtrBase >; void detach() { ptr = nullptr; } @@ -121,30 +117,10 @@ class SupportsWeakPtrBase }; template -class SupportsWeakPtr - : public SupportsWeakPtrBase > +class SupportsWeakPtr : public SupportsWeakPtrBase > { }; -template -class AtomicSupportsWeakPtr - : public SupportsWeakPtrBase > -{ -}; - -namespace detail { - -template -struct WeakReferenceCount -{ - static const RefCountAtomicity atomicity = - IsBaseOf, T>::value - ? AtomicRefCount - : NonAtomicRefCount; -}; - -} - template class WeakPtrBase { @@ -177,9 +153,9 @@ class WeakPtrBase }; template -class WeakPtr : public WeakPtrBase::atomicity> > +class WeakPtr : public WeakPtrBase > { - typedef WeakPtrBase::atomicity> > Base; + typedef WeakPtrBase > Base; public: WeakPtr(const WeakPtr& o) : Base(o) {} WeakPtr(const Base& o) : Base(o) {} diff --git a/external/spidermonkey/include/win32/js-config.h b/external/spidermonkey/include/win32/js-config.h index a581835270..155ebef4b1 100644 --- a/external/spidermonkey/include/win32/js-config.h +++ b/external/spidermonkey/include/win32/js-config.h @@ -5,8 +5,8 @@ * 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/. */ -#ifndef js_config_h___ -#define js_config_h___ +#ifndef js_config_h +#define js_config_h /* Definitions set at build time that affect SpiderMonkey's public API. This header file is generated by the SpiderMonkey configure script, @@ -34,12 +34,8 @@ useable. See jscpucfg.h. */ /* #undef JS_HAVE_SYS_ISA_DEFS_H */ -/* The configure script defines these if it doesn't #define - JS_HAVE_STDINT_H. */ -/* #undef JS_BYTES_PER_WORD */ - /* MOZILLA JSAPI version number components */ -#define MOZJS_MAJOR_VERSION 25 +#define MOZJS_MAJOR_VERSION 27 #define MOZJS_MINOR_VERSION 0 -#endif /* js_config_h___ */ +#endif /* js_config_h */ diff --git a/external/spidermonkey/include/win32/js.msg b/external/spidermonkey/include/win32/js.msg index 3f665d8d54..da7361d5df 100644 --- a/external/spidermonkey/include/win32/js.msg +++ b/external/spidermonkey/include/win32/js.msg @@ -221,8 +221,8 @@ MSG_DEF(JSMSG_CANT_DECODE_PRINCIPALS, 167, 0, JSEXN_INTERNALERR, "can't decode J MSG_DEF(JSMSG_CANT_SEAL_OBJECT, 168, 1, JSEXN_ERR, "can't seal {0} objects") MSG_DEF(JSMSG_TOO_MANY_CATCH_VARS, 169, 0, JSEXN_SYNTAXERR, "too many catch variables") MSG_DEF(JSMSG_NEGATIVE_REPETITION_COUNT, 170, 0, JSEXN_RANGEERR, "repeat count must be non-negative") -MSG_DEF(JSMSG_UNUSED171, 171, 0, JSEXN_NONE, "") -MSG_DEF(JSMSG_UNUSED172, 172, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_INVALID_FOR_OF_INIT, 171, 0, JSEXN_SYNTAXERR, "for-of loop variable declaration may not have an initializer") +MSG_DEF(JSMSG_INVALID_MAP_ITERABLE, 172, 0, JSEXN_TYPEERR, "iterable for map should have array-like objects") MSG_DEF(JSMSG_UNUSED173, 173, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED174, 174, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_NESTING_GENERATOR, 175, 0, JSEXN_TYPEERR, "already executing generator") @@ -233,8 +233,8 @@ MSG_DEF(JSMSG_UNUSED179, 179, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED180, 180, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED181, 181, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_BAD_GENERATOR_SEND, 182, 1, JSEXN_TYPEERR, "attempt to send {0} to newborn generator") -MSG_DEF(JSMSG_UNUSED183, 183, 0, JSEXN_NONE, "") -MSG_DEF(JSMSG_UNUSED184, 184, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_SC_NOT_TRANSFERABLE, 183, 0, JSEXN_TYPEERR, "invalid transferable array for structured clone") +MSG_DEF(JSMSG_SC_DUP_TRANSFERABLE, 184, 0, JSEXN_TYPEERR, "duplicate transferable for structured clone") MSG_DEF(JSMSG_CANT_REPORT_AS_NON_EXTENSIBLE, 185, 0, JSEXN_TYPEERR, "proxy can't report an extensible object as non-extensible") MSG_DEF(JSMSG_UNUSED186, 186, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_UNUSED187, 187, 0, JSEXN_NONE, "") @@ -260,7 +260,7 @@ MSG_DEF(JSMSG_USER_DEFINED_ERROR, 206, 0, JSEXN_ERR, "JS_ReportError was cal MSG_DEF(JSMSG_WRONG_CONSTRUCTOR, 207, 1, JSEXN_TYPEERR, "wrong constructor called for {0}") MSG_DEF(JSMSG_BAD_GENERATOR_RETURN, 208, 1, JSEXN_TYPEERR, "generator function {0} returns a value") MSG_DEF(JSMSG_BAD_ANON_GENERATOR_RETURN, 209, 0, JSEXN_TYPEERR, "anonymous generator function returns a value") -MSG_DEF(JSMSG_NAME_AFTER_FOR_PAREN, 210, 0, JSEXN_SYNTAXERR, "missing name after for (") +MSG_DEF(JSMSG_UNUSED210, 210, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_IN_AFTER_FOR_NAME, 211, 0, JSEXN_SYNTAXERR, "missing 'in' or 'of' after for") MSG_DEF(JSMSG_BAD_TRAP_RETURN_VALUE, 212, 2, JSEXN_TYPEERR,"trap {1} for {0} returned a primitive value") MSG_DEF(JSMSG_UNUSED213, 213, 0, JSEXN_NONE, "") @@ -269,7 +269,7 @@ MSG_DEF(JSMSG_BAD_GENERATOR_SYNTAX, 215, 1, JSEXN_SYNTAXERR, "{0} expression m MSG_DEF(JSMSG_ARRAY_COMP_LEFTSIDE, 216, 0, JSEXN_SYNTAXERR, "invalid array comprehension left-hand side") MSG_DEF(JSMSG_UNUSED217, 217, 0, JSEXN_NONE, "") MSG_DEF(JSMSG_EMPTY_ARRAY_REDUCE, 218, 0, JSEXN_TYPEERR, "reduce of empty array with no initial value") -MSG_DEF(JSMSG_UNUSED219, 219, 0, JSEXN_NONE, "") +MSG_DEF(JSMSG_BAD_SYMBOL, 219, 1, JSEXN_TYPEERR, "{0} is not a well-known @@-symbol") MSG_DEF(JSMSG_BAD_DELETE_OPERAND, 220, 0, JSEXN_REFERENCEERR, "invalid delete operand") MSG_DEF(JSMSG_BAD_INCOP_OPERAND, 221, 0, JSEXN_REFERENCEERR, "invalid increment/decrement operand") MSG_DEF(JSMSG_UNEXPECTED_TYPE, 222, 2, JSEXN_TYPEERR, "{0} is {1}") @@ -353,7 +353,7 @@ MSG_DEF(JSMSG_REST_WITH_DEFAULT, 299, 0, JSEXN_SYNTAXERR, "rest parameter m MSG_DEF(JSMSG_NONDEFAULT_FORMAL_AFTER_DEFAULT, 300, 0, JSEXN_SYNTAXERR, "parameter(s) with default followed by parameter without default") MSG_DEF(JSMSG_YIELD_IN_DEFAULT, 301, 0, JSEXN_SYNTAXERR, "yield in default expression") MSG_DEF(JSMSG_INTRINSIC_NOT_DEFINED, 302, 1, JSEXN_REFERENCEERR, "no intrinsic function {0}") -MSG_DEF(JSMSG_ALREADY_HAS_SOURCEMAP, 303, 1, JSEXN_ERR, "{0} is being assigned a source map, yet already has one") +MSG_DEF(JSMSG_ALREADY_HAS_PRAGMA, 303, 2, JSEXN_ERR, "{0} is being assigned a {1}, but already has one") MSG_DEF(JSMSG_PAR_ARRAY_BAD_ARG, 304, 1, JSEXN_RANGEERR, "invalid ParallelArray{0} argument") MSG_DEF(JSMSG_PAR_ARRAY_BAD_PARTITION, 305, 0, JSEXN_ERR, "argument must be divisible by outermost dimension") MSG_DEF(JSMSG_PAR_ARRAY_REDUCE_EMPTY, 306, 0, JSEXN_ERR, "cannot reduce ParallelArray object whose outermost dimension is empty") @@ -375,7 +375,7 @@ MSG_DEF(JSMSG_MUST_REPORT_UNDEFINED, 321, 0, JSEXN_TYPEERR, "proxy must report MSG_DEF(JSMSG_CANT_SET_NW_NC, 322, 0, JSEXN_TYPEERR, "proxy can't successfully set a non-writable, non-configurable property") MSG_DEF(JSMSG_CANT_SET_WO_SETTER, 323, 0, JSEXN_TYPEERR, "proxy can't succesfully set an accessor property without a setter") MSG_DEF(JSMSG_DEBUG_BAD_REFERENT, 324, 2, JSEXN_TYPEERR, "{0} does not refer to {1}") -MSG_DEF(JSMSG_DEBUG_WRAPPER_IN_WAY, 325, 2, JSEXN_TYPEERR, "{0} is a wrapper around {1}, but a direct reference is required") +MSG_DEF(JSMSG_DEBUG_WRAPPER_IN_WAY, 325, 3, JSEXN_TYPEERR, "{0} is {1}{2}a global object, but a direct reference is required") MSG_DEF(JSMSG_UNWRAP_DENIED, 326, 0, JSEXN_ERR, "permission denied to unwrap object") MSG_DEF(JSMSG_INTL_OBJECT_NOT_INITED, 327, 3, JSEXN_TYPEERR, "Intl.{0}.prototype.{1} called on value that's not an object initialized as a {2}") MSG_DEF(JSMSG_INVALID_LOCALES_ELEMENT,328, 0, JSEXN_TYPEERR, "invalid element in locales argument") @@ -400,12 +400,23 @@ MSG_DEF(JSMSG_YIELD_IN_ARROW, 346, 0, JSEXN_SYNTAXERR, "arrow function m MSG_DEF(JSMSG_WRONG_VALUE, 347, 2, JSEXN_ERR, "expected {0} but found {1}") MSG_DEF(JSMSG_PAR_ARRAY_SCATTER_BAD_TARGET, 348, 1, JSEXN_ERR, "target for index {0} is not an integer") MSG_DEF(JSMSG_SELFHOSTED_UNBOUND_NAME,349, 0, JSEXN_TYPEERR, "self-hosted code may not contain unbound name lookups") -MSG_DEF(JSMSG_DEPRECATED_SOURCE_MAP, 350, 0, JSEXN_SYNTAXERR, "Using //@ to indicate source map URL pragmas is deprecated. Use //# instead") +MSG_DEF(JSMSG_DEPRECATED_PRAGMA, 350, 1, JSEXN_SYNTAXERR, "Using //@ to indicate {0} pragmas is deprecated. Use //# instead") MSG_DEF(JSMSG_BAD_DESTRUCT_ASSIGN, 351, 1, JSEXN_SYNTAXERR, "can't assign to {0} using destructuring assignment") -MSG_DEF(JSMSG_BINARYDATA_ARRAYTYPE_BAD_ARGS, 352, 0, JSEXN_ERR, "Invalid arguments") -MSG_DEF(JSMSG_BINARYDATA_BINARYARRAY_BAD_INDEX, 353, 0, JSEXN_RANGEERR, "invalid or out-of-range index") -MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_ARGS, 354, 0, JSEXN_RANGEERR, "invalid field descriptor") -MSG_DEF(JSMSG_BINARYDATA_NOT_BINARYSTRUCT, 355, 1, JSEXN_TYPEERR, "{0} is not a BinaryStruct") -MSG_DEF(JSMSG_BINARYDATA_SUBARRAY_INTEGER_ARG, 356, 1, JSEXN_ERR, "argument {0} must be an integer") -MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_EMPTY_DESCRIPTOR, 357, 0, JSEXN_ERR, "field descriptor cannot be empty") -MSG_DEF(JSMSG_BINARYDATA_STRUCTTYPE_BAD_FIELD, 358, 1, JSEXN_ERR, "field {0} is not a valid BinaryData Type descriptor") +MSG_DEF(JSMSG_TYPEDOBJECT_ARRAYTYPE_BAD_ARGS, 352, 0, JSEXN_ERR, "Invalid arguments") +MSG_DEF(JSMSG_TYPEDOBJECT_BINARYARRAY_BAD_INDEX, 353, 0, JSEXN_RANGEERR, "invalid or out-of-range index") +MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_BAD_ARGS, 354, 0, JSEXN_RANGEERR, "invalid field descriptor") +MSG_DEF(JSMSG_TYPEDOBJECT_NOT_BINARYSTRUCT, 355, 1, JSEXN_TYPEERR, "{0} is not a BinaryStruct") +MSG_DEF(JSMSG_TYPEDOBJECT_SUBARRAY_INTEGER_ARG, 356, 1, JSEXN_ERR, "argument {0} must be an integer") +MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_EMPTY_DESCRIPTOR, 357, 0, JSEXN_ERR, "field descriptor cannot be empty") +MSG_DEF(JSMSG_TYPEDOBJECT_STRUCTTYPE_BAD_FIELD, 358, 1, JSEXN_ERR, "field {0} is not a valid BinaryData Type descriptor") +MSG_DEF(JSMSG_GENERATOR_FINISHED, 359, 0, JSEXN_TYPEERR, "generator has already finished") +MSG_DEF(JSMSG_TYPEDOBJECT_TOO_BIG, 360, 0, JSEXN_ERR, "Type is too large to allocate") +MSG_DEF(JSMSG_TYPEDOBJECT_NOT_TYPE_OBJECT, 361, 0, JSEXN_ERR, "Expected a type object") +MSG_DEF(JSMSG_TOO_MANY_CON_SPREADARGS, 362, 0, JSEXN_RANGEERR, "too many constructor arguments") +MSG_DEF(JSMSG_TOO_MANY_FUN_SPREADARGS, 363, 0, JSEXN_RANGEERR, "too many function arguments") +MSG_DEF(JSMSG_DEBUG_NOT_DEBUGGEE, 364, 2, JSEXN_ERR, "{0} is not a debuggee {1}") +MSG_DEF(JSMSG_TYPEDOBJECT_NOT_TYPED_OBJECT, 365, 0, JSEXN_ERR, "Expected a typed object") +MSG_DEF(JSMSG_TYPEDOBJECT_NO_SUCH_PROP, 366, 1, JSEXN_TYPEERR, "No such property: {0}") +MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_BAD_ARGS, 367, 2, JSEXN_TYPEERR, "argument {0} invalid: expected {1}") +MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_UNATTACHED, 368, 0, JSEXN_TYPEERR, "handle unattached") +MSG_DEF(JSMSG_TYPEDOBJECT_HANDLE_BAD_TYPE, 369, 0, JSEXN_TYPEERR, "handle moved to destination of incorrect type") diff --git a/external/spidermonkey/include/win32/js/Anchor.h b/external/spidermonkey/include/win32/js/Anchor.h index 0d458e6fb6..c2324fb2e9 100644 --- a/external/spidermonkey/include/win32/js/Anchor.h +++ b/external/spidermonkey/include/win32/js/Anchor.h @@ -11,12 +11,7 @@ #include "mozilla/Attributes.h" -class JSFunction; -class JSObject; -class JSScript; -class JSString; - -namespace JS { class Value; } +#include "js/TypeDecls.h" namespace JS { diff --git a/external/spidermonkey/include/win32/js/CallArgs.h b/external/spidermonkey/include/win32/js/CallArgs.h index 8027ffc71a..5c7a201101 100644 --- a/external/spidermonkey/include/win32/js/CallArgs.h +++ b/external/spidermonkey/include/win32/js/CallArgs.h @@ -38,22 +38,19 @@ #include "js/RootingAPI.h" #include "js/Value.h" -struct JSContext; -class JSObject; - /* Typedef for native functions called by the JS VM. */ -typedef JSBool +typedef bool (* JSNative)(JSContext *cx, unsigned argc, JS::Value *vp); /* Typedef for native functions that may be called in parallel. */ -typedef js::ParallelResult +typedef bool (* JSParallelNative)(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); /* * Typedef for native functions that may be called either in parallel or * sequential execution. */ -typedef JSBool +typedef bool (* JSThreadSafeNative)(js::ThreadSafeContext *cx, unsigned argc, JS::Value *vp); /* @@ -61,11 +58,11 @@ typedef JSBool * a JSNative or a JSParallelNative. */ template -inline JSBool +inline bool JSNativeThreadSafeWrapper(JSContext *cx, unsigned argc, JS::Value *vp); template -inline js::ParallelResult +inline bool JSParallelNativeThreadSafeWrapper(js::ForkJoinSlice *slice, unsigned argc, JS::Value *vp); /* @@ -89,7 +86,7 @@ extern JS_PUBLIC_DATA(const HandleValue) UndefinedHandleValue; * return value for a function call. The principal way to create a * CallReceiver is using JS::CallReceiverFromVp: * - * static JSBool + * static bool * FunctionReturningThis(JSContext *cx, unsigned argc, JS::Value *vp) * { * JS::CallReceiver rec = JS::CallReceiverFromVp(vp); @@ -282,7 +279,7 @@ CallReceiverFromVp(Value *vp) * the function call's arguments. The principal way to create a CallArgs is * like so, using JS::CallArgsFromVp: * - * static JSBool + * static bool * FunctionReturningArgcTimesArg0(JSContext *cx, unsigned argc, JS::Value *vp) * { * JS::CallArgs args = JS::CallArgsFromVp(argc, vp); diff --git a/external/spidermonkey/include/win32/js/CallNonGenericMethod.h b/external/spidermonkey/include/win32/js/CallNonGenericMethod.h new file mode 100644 index 0000000000..05097f0294 --- /dev/null +++ b/external/spidermonkey/include/win32/js/CallNonGenericMethod.h @@ -0,0 +1,117 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_CallNonGenericMethod_h +#define js_CallNonGenericMethod_h + +#include "jstypes.h" + +#include "js/CallArgs.h" + +namespace JS { + +// Returns true if |v| is considered an acceptable this-value. +typedef bool (*IsAcceptableThis)(Handle v); + +// Implements the guts of a method; guaranteed to be provided an acceptable +// this-value, as determined by a corresponding IsAcceptableThis method. +typedef bool (*NativeImpl)(JSContext *cx, CallArgs args); + +namespace detail { + +// DON'T CALL THIS DIRECTLY. It's for use only by CallNonGenericMethod! +extern JS_PUBLIC_API(bool) +CallMethodIfWrapped(JSContext *cx, IsAcceptableThis test, NativeImpl impl, CallArgs args); + +} // namespace detail + +// Methods usually act upon |this| objects only from a single global object and +// compartment. Sometimes, however, a method must act upon |this| values from +// multiple global objects or compartments. In such cases the |this| value a +// method might see will be wrapped, such that various access to the object -- +// to its class, its private data, its reserved slots, and so on -- will not +// work properly without entering that object's compartment. This method +// implements a solution to this problem. +// +// To implement a method that accepts |this| values from multiple compartments, +// define two functions. The first function matches the IsAcceptableThis type +// and indicates whether the provided value is an acceptable |this| for the +// method; it must be a pure function only of its argument. +// +// static const JSClass AnswerClass = { ... }; +// +// static bool +// IsAnswerObject(const Value &v) +// { +// if (!v.isObject()) +// return false; +// return JS_GetClass(&v.toObject()) == &AnswerClass; +// } +// +// The second function implements the NativeImpl signature and defines the +// behavior of the method when it is provided an acceptable |this| value. +// Aside from some typing niceties -- see the CallArgs interface for details -- +// its interface is the same as that of JSNative. +// +// static bool +// answer_getAnswer_impl(JSContext *cx, JS::CallArgs args) +// { +// args.rval().setInt32(42); +// return true; +// } +// +// The implementation function is guaranteed to be called *only* with a |this| +// value which is considered acceptable. +// +// Now to implement the actual method, write a JSNative that calls the method +// declared below, passing the appropriate template and runtime arguments. +// +// static bool +// answer_getAnswer(JSContext *cx, unsigned argc, JS::Value *vp) +// { +// JS::CallArgs args = JS::CallArgsFromVp(argc, vp); +// return JS::CallNonGenericMethod(cx, args); +// } +// +// Note that, because they are used as template arguments, the predicate +// and implementation functions must have external linkage. (This is +// unfortunate, but GCC wasn't inlining things as one would hope when we +// passed them as function arguments.) +// +// JS::CallNonGenericMethod will test whether |args.thisv()| is acceptable. If +// it is, it will call the provided implementation function, which will return +// a value and indicate success. If it is not, it will attempt to unwrap +// |this| and call the implementation function on the unwrapped |this|. If +// that succeeds, all well and good. If it doesn't succeed, a TypeError will +// be thrown. +// +// Note: JS::CallNonGenericMethod will only work correctly if it's called in +// tail position in a JSNative. Do not call it from any other place. +// +template +JS_ALWAYS_INLINE bool +CallNonGenericMethod(JSContext *cx, CallArgs args) +{ + HandleValue thisv = args.thisv(); + if (Test(thisv)) + return Impl(cx, args); + + return detail::CallMethodIfWrapped(cx, Test, Impl, args); +} + +JS_ALWAYS_INLINE bool +CallNonGenericMethod(JSContext *cx, IsAcceptableThis Test, NativeImpl Impl, CallArgs args) +{ + HandleValue thisv = args.thisv(); + if (Test(thisv)) + return Impl(cx, args); + + return detail::CallMethodIfWrapped(cx, Test, Impl, args); +} + +} // namespace JS + +#endif /* js_CallNonGenericMethod_h */ diff --git a/external/spidermonkey/include/win32/js/CharacterEncoding.h b/external/spidermonkey/include/win32/js/CharacterEncoding.h index e88e08e1be..7918b83484 100644 --- a/external/spidermonkey/include/win32/js/CharacterEncoding.h +++ b/external/spidermonkey/include/win32/js/CharacterEncoding.h @@ -7,11 +7,15 @@ #ifndef js_CharacterEncoding_h #define js_CharacterEncoding_h +#include "mozilla/NullPtr.h" #include "mozilla/Range.h" +#include "js/TypeDecls.h" #include "js/Utility.h" -#include "jspubtd.h" +namespace js { +struct ThreadSafeContext; +} namespace JS { @@ -41,7 +45,7 @@ class Latin1CharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: - Latin1CharsZ() : Base(NULL, 0) {} + Latin1CharsZ() : Base(nullptr, 0) {} Latin1CharsZ(char *aBytes, size_t aLength) : Base(reinterpret_cast(aBytes), aLength) @@ -80,7 +84,7 @@ class UTF8CharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: - UTF8CharsZ() : Base(NULL, 0) {} + UTF8CharsZ() : Base(nullptr, 0) {} UTF8CharsZ(char *aBytes, size_t aLength) : Base(reinterpret_cast(aBytes), aLength) @@ -138,7 +142,7 @@ class TwoByteCharsZ : public mozilla::RangedPtr typedef mozilla::RangedPtr Base; public: - TwoByteCharsZ() : Base(NULL, 0) {} + TwoByteCharsZ() : Base(nullptr, 0) {} TwoByteCharsZ(jschar *chars, size_t length) : Base(chars, length) @@ -154,7 +158,7 @@ class TwoByteCharsZ : public mozilla::RangedPtr * output. The returned string is zero terminated. The returned string or the * returned string's |start()| must be freed with JS_free or js_free, * respectively. If allocation fails, an OOM error will be set and the method - * will return a NULL chars (which can be tested for with the ! operator). + * will return a nullptr chars (which can be tested for with the ! operator). * This method cannot trigger GC. */ extern Latin1CharsZ diff --git a/external/spidermonkey/include/win32/js/Class.h b/external/spidermonkey/include/win32/js/Class.h new file mode 100644 index 0000000000..4058688e99 --- /dev/null +++ b/external/spidermonkey/include/win32/js/Class.h @@ -0,0 +1,699 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +/* JSClass definition and its component types, plus related interfaces. */ + +#ifndef js_Class_h +#define js_Class_h + +#include "mozilla/NullPtr.h" + +#include "jstypes.h" + +#include "js/CallArgs.h" +#include "js/Id.h" +#include "js/TypeDecls.h" + +/* + * A JSClass acts as a vtable for JS objects that allows JSAPI clients to + * control various aspects of the behavior of an object like property lookup. + * js::Class is an engine-private extension that allows more control over + * object behavior and, e.g., allows custom slow layout. + */ + +class JSFreeOp; + +namespace js { + +class Class; +class FreeOp; +class PropertyId; +class PropertyName; +class Shape; +class SpecialId; + +// This is equal to JSFunction::class_. Use it in places where you don't want +// to #include jsfun.h. +extern JS_FRIEND_DATA(const js::Class* const) FunctionClassPtr; + +static JS_ALWAYS_INLINE jsid +SPECIALID_TO_JSID(const SpecialId &sid); + +/* + * We partition the ways to refer to a property into three: by an index + * (uint32_t); by a string whose characters do not represent an index + * (PropertyName, see vm/String.h); and by various special values. + * + * Special values are encoded using SpecialId, which is layout-compatible but + * non-interconvertible with jsid. A SpecialId is used for JSID_VOID, which + * does not occur in JS scripts but may be used to indicate the absence of a + * valid identifier. In the future, a SpecialId may also be an object used by + * Harmony-proposed private names. + */ +class SpecialId +{ + uintptr_t bits_; + + /* Needs access to raw bits. */ + friend JS_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid); + friend class PropertyId; + + static const uintptr_t TYPE_VOID = JSID_TYPE_VOID; + static const uintptr_t TYPE_OBJECT = JSID_TYPE_OBJECT; + static const uintptr_t TYPE_MASK = JSID_TYPE_MASK; + + SpecialId(uintptr_t bits) : bits_(bits) { } + + public: + SpecialId() : bits_(TYPE_VOID) { } + + /* Object-valued */ + + SpecialId(JSObject &obj) + : bits_(uintptr_t(&obj) | TYPE_OBJECT) + { + JS_ASSERT(&obj != nullptr); + JS_ASSERT((uintptr_t(&obj) & TYPE_MASK) == 0); + } + + bool isObject() const { + return (bits_ & TYPE_MASK) == TYPE_OBJECT && bits_ != TYPE_OBJECT; + } + + JSObject *toObject() const { + JS_ASSERT(isObject()); + return reinterpret_cast(bits_ & ~TYPE_MASK); + } + + /* Empty */ + + static SpecialId empty() { + SpecialId sid(TYPE_OBJECT); + JS_ASSERT(sid.isEmpty()); + return sid; + } + + bool isEmpty() const { + return bits_ == TYPE_OBJECT; + } + + /* Void */ + + static SpecialId voidId() { + SpecialId sid(TYPE_VOID); + JS_ASSERT(sid.isVoid()); + return sid; + } + + bool isVoid() const { + return bits_ == TYPE_VOID; + } +}; + +static JS_ALWAYS_INLINE jsid +SPECIALID_TO_JSID(const SpecialId &sid) +{ + jsid id; + JSID_BITS(id) = sid.bits_; + JS_ASSERT_IF(sid.isObject(), JSID_IS_OBJECT(id) && JSID_TO_OBJECT(id) == sid.toObject()); + JS_ASSERT_IF(sid.isVoid(), JSID_IS_VOID(id)); + JS_ASSERT_IF(sid.isEmpty(), JSID_IS_EMPTY(id)); + return id; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_SPECIAL(jsid id) +{ + return JSID_IS_OBJECT(id) || JSID_IS_EMPTY(id) || JSID_IS_VOID(id); +} + +static JS_ALWAYS_INLINE SpecialId +JSID_TO_SPECIALID(jsid id) +{ + JS_ASSERT(JSID_IS_SPECIAL(id)); + if (JSID_IS_OBJECT(id)) + return SpecialId(*JSID_TO_OBJECT(id)); + if (JSID_IS_EMPTY(id)) + return SpecialId::empty(); + JS_ASSERT(JSID_IS_VOID(id)); + return SpecialId::voidId(); +} + +typedef JS::Handle HandleSpecialId; + +} // namespace js + +// JSClass operation signatures. + +// Add or get a property named by id in obj. Note the jsid id type -- id may +// be a string (Unicode property identifier) or an int (element index). The +// *vp out parameter, on success, is the new property value after the action. +typedef bool +(* JSPropertyOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + JS::MutableHandle vp); + +// Set a property named by id in obj, treating the assignment as strict +// mode code if strict is true. Note the jsid id type -- id may be a string +// (Unicode property identifier) or an int (element index). The *vp out +// parameter, on success, is the new property value after the +// set. +typedef bool +(* JSStrictPropertyOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + bool strict, JS::MutableHandle vp); + +// Delete a property named by id in obj. +// +// If an error occurred, return false as per normal JSAPI error practice. +// +// If no error occurred, but the deletion attempt wasn't allowed (perhaps +// because the property was non-configurable), set *succeeded to false and +// return true. This will cause |delete obj[id]| to evaluate to false in +// non-strict mode code, and to throw a TypeError in strict mode code. +// +// If no error occurred and the deletion wasn't disallowed (this is *not* the +// same as saying that a deletion actually occurred -- deleting a non-existent +// property, or an inherited property, is allowed -- it's just pointless), +// set *succeeded to true and return true. +typedef bool +(* JSDeletePropertyOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + bool *succeeded); + +// This function type is used for callbacks that enumerate the properties of +// a JSObject. The behavior depends on the value of enum_op: +// +// JSENUMERATE_INIT +// A new, opaque iterator state should be allocated and stored in *statep. +// (You can use PRIVATE_TO_JSVAL() to tag the pointer to be stored). +// +// The number of properties that will be enumerated should be returned as +// an integer jsval in *idp, if idp is non-null, and provided the number of +// enumerable properties is known. If idp is non-null and the number of +// enumerable properties can't be computed in advance, *idp should be set +// to JSVAL_ZERO. +// +// JSENUMERATE_INIT_ALL +// Used identically to JSENUMERATE_INIT, but exposes all properties of the +// object regardless of enumerability. +// +// JSENUMERATE_NEXT +// A previously allocated opaque iterator state is passed in via statep. +// Return the next jsid in the iteration using *idp. The opaque iterator +// state pointed at by statep is destroyed and *statep is set to JSVAL_NULL +// if there are no properties left to enumerate. +// +// JSENUMERATE_DESTROY +// Destroy the opaque iterator state previously allocated in *statep by a +// call to this function when enum_op was JSENUMERATE_INIT or +// JSENUMERATE_INIT_ALL. +// +// The return value is used to indicate success, with a value of false +// indicating failure. +typedef bool +(* JSNewEnumerateOp)(JSContext *cx, JS::Handle obj, JSIterateOp enum_op, + JS::MutableHandle statep, JS::MutableHandle idp); + +// The old-style JSClass.enumerate op should define all lazy properties not +// yet reflected in obj. +typedef bool +(* JSEnumerateOp)(JSContext *cx, JS::Handle obj); + +// Resolve a lazy property named by id in obj by defining it directly in obj. +// Lazy properties are those reflected from some peer native property space +// (e.g., the DOM attributes for a given node reflected as obj) on demand. +// +// JS looks for a property in an object, and if not found, tries to resolve +// the given id. If resolve succeeds, the engine looks again in case resolve +// defined obj[id]. If no such property exists directly in obj, the process +// is repeated with obj's prototype, etc. +// +// NB: JSNewResolveOp provides a cheaper way to resolve lazy properties. +typedef bool +(* JSResolveOp)(JSContext *cx, JS::Handle obj, JS::Handle id); + +// Like JSResolveOp, but flags provide contextual information as follows: +// +// JSRESOLVE_ASSIGNING obj[id] is on the left-hand side of an assignment +// +// The *objp out parameter, on success, should be null to indicate that id +// was not resolved; and non-null, referring to obj or one of its prototypes, +// if id was resolved. The hook may assume *objp is null on entry. +// +// This hook instead of JSResolveOp is called via the JSClass.resolve member +// if JSCLASS_NEW_RESOLVE is set in JSClass.flags. +typedef bool +(* JSNewResolveOp)(JSContext *cx, JS::Handle obj, JS::Handle id, unsigned flags, + JS::MutableHandle objp); + +// Convert obj to the given type, returning true with the resulting value in +// *vp on success, and returning false on error or exception. +typedef bool +(* JSConvertOp)(JSContext *cx, JS::Handle obj, JSType type, + JS::MutableHandle vp); + +// Finalize obj, which the garbage collector has determined to be unreachable +// from other live objects or from GC roots. Obviously, finalizers must never +// store a reference to obj. +typedef void +(* JSFinalizeOp)(JSFreeOp *fop, JSObject *obj); + +// Finalizes external strings created by JS_NewExternalString. +struct JSStringFinalizer { + void (*finalize)(const JSStringFinalizer *fin, jschar *chars); +}; + +// JSClass.checkAccess type: check whether obj[id] may be accessed per mode, +// returning false on error/exception, true on success with obj[id]'s last-got +// value in *vp, and its attributes in *attrsp. As for JSPropertyOp above, id +// is either a string or an int jsval. +typedef bool +(* JSCheckAccessOp)(JSContext *cx, JS::Handle obj, JS::Handle id, + JSAccessMode mode, JS::MutableHandle vp); + +// Return whether the first principal subsumes the second. The exact meaning of +// 'subsumes' is left up to the browser. Subsumption is checked inside the JS +// engine when determining, e.g., which stack frames to display in a backtrace. +typedef bool +(* JSSubsumesOp)(JSPrincipals *first, JSPrincipals *second); + +// Check whether v is an instance of obj. Return false on error or exception, +// true on success with true in *bp if v is an instance of obj, false in +// *bp otherwise. +typedef bool +(* JSHasInstanceOp)(JSContext *cx, JS::Handle obj, JS::MutableHandle vp, + bool *bp); + +// Function type for trace operation of the class called to enumerate all +// traceable things reachable from obj's private data structure. For each such +// thing, a trace implementation must call one of the JS_Call*Tracer variants +// on the thing. +// +// JSTraceOp implementation can assume that no other threads mutates object +// state. It must not change state of the object or corresponding native +// structures. The only exception for this rule is the case when the embedding +// needs a tight integration with GC. In that case the embedding can check if +// the traversal is a part of the marking phase through calling +// JS_IsGCMarkingTracer and apply a special code like emptying caches or +// marking its native structures. +typedef void +(* JSTraceOp)(JSTracer *trc, JSObject *obj); + +// A generic type for functions mapping an object to another object, or null +// if an error or exception was thrown on cx. +typedef JSObject * +(* JSObjectOp)(JSContext *cx, JS::Handle obj); + +// Hook that creates an iterator object for a given object. Returns the +// iterator object or null if an error or exception was thrown on cx. +typedef JSObject * +(* JSIteratorOp)(JSContext *cx, JS::HandleObject obj, bool keysonly); + +typedef JSObject * +(* JSWeakmapKeyDelegateOp)(JSObject *obj); + +/* js::Class operation signatures. */ + +namespace js { + +typedef bool +(* LookupGenericOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* LookupPropOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* LookupElementOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* LookupSpecialOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, + JS::MutableHandleObject objp, JS::MutableHandle propp); +typedef bool +(* DefineGenericOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue value, + JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs); +typedef bool +(* DefinePropOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + JS::HandleValue value, JSPropertyOp getter, JSStrictPropertyOp setter, + unsigned attrs); +typedef bool +(* DefineElementOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, JS::HandleValue value, + JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs); +typedef bool +(* DefineSpecialOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, + JS::HandleValue value, JSPropertyOp getter, JSStrictPropertyOp setter, + unsigned attrs); +typedef bool +(* GenericIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, JS::HandleId id, + JS::MutableHandleValue vp); +typedef bool +(* PropertyIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, + JS::Handle name, JS::MutableHandleValue vp); +typedef bool +(* ElementIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, uint32_t index, + JS::MutableHandleValue vp); +typedef bool +(* ElementIfPresentOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, + uint32_t index, JS::MutableHandleValue vp, bool* present); +typedef bool +(* SpecialIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleObject receiver, + HandleSpecialId sid, JS::MutableHandleValue vp); +typedef bool +(* StrictGenericIdOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* StrictPropertyIdOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* StrictElementIdOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* StrictSpecialIdOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, + JS::MutableHandleValue vp, bool strict); +typedef bool +(* GenericAttributesOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, unsigned *attrsp); +typedef bool +(* PropertyAttributesOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + unsigned *attrsp); +typedef bool +(* DeletePropertyOp)(JSContext *cx, JS::HandleObject obj, JS::Handle name, + bool *succeeded); +typedef bool +(* DeleteElementOp)(JSContext *cx, JS::HandleObject obj, uint32_t index, bool *succeeded); +typedef bool +(* DeleteSpecialOp)(JSContext *cx, JS::HandleObject obj, HandleSpecialId sid, bool *succeeded); + +typedef bool +(* WatchOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); + +typedef bool +(* UnwatchOp)(JSContext *cx, JS::HandleObject obj, JS::HandleId id); + +typedef JSObject * +(* ObjectOp)(JSContext *cx, JS::HandleObject obj); +typedef void +(* FinalizeOp)(FreeOp *fop, JSObject *obj); + +#define JS_CLASS_MEMBERS \ + const char *name; \ + uint32_t flags; \ + \ + /* Mandatory function pointer members. */ \ + JSPropertyOp addProperty; \ + JSDeletePropertyOp delProperty; \ + JSPropertyOp getProperty; \ + JSStrictPropertyOp setProperty; \ + JSEnumerateOp enumerate; \ + JSResolveOp resolve; \ + JSConvertOp convert; \ + \ + /* Optional members (may be null). */ \ + FinalizeOp finalize; \ + JSCheckAccessOp checkAccess; \ + JSNative call; \ + JSHasInstanceOp hasInstance; \ + JSNative construct; \ + JSTraceOp trace + +/* + * The helper struct to measure the size of JS_CLASS_MEMBERS to know how much + * we have to pad js::Class to match the size of JSClass. + */ +struct ClassSizeMeasurement +{ + JS_CLASS_MEMBERS; +}; + +struct ClassExtension +{ + JSObjectOp outerObject; + JSObjectOp innerObject; + JSIteratorOp iteratorObject; + + /* + * isWrappedNative is true only if the class is an XPCWrappedNative. + * WeakMaps use this to override the wrapper disposal optimization. + */ + bool isWrappedNative; + + /* + * If an object is used as a key in a weakmap, it may be desirable for the + * garbage collector to keep that object around longer than it otherwise + * would. A common case is when the key is a wrapper around an object in + * another compartment, and we want to avoid collecting the wrapper (and + * removing the weakmap entry) as long as the wrapped object is alive. In + * that case, the wrapped object is returned by the wrapper's + * weakmapKeyDelegateOp hook. As long as the wrapper is used as a weakmap + * key, it will not be collected (and remain in the weakmap) until the + * wrapped object is collected. + */ + JSWeakmapKeyDelegateOp weakmapKeyDelegateOp; +}; + +#define JS_NULL_CLASS_EXT {nullptr,nullptr,nullptr,false,nullptr} + +struct ObjectOps +{ + LookupGenericOp lookupGeneric; + LookupPropOp lookupProperty; + LookupElementOp lookupElement; + LookupSpecialOp lookupSpecial; + DefineGenericOp defineGeneric; + DefinePropOp defineProperty; + DefineElementOp defineElement; + DefineSpecialOp defineSpecial; + GenericIdOp getGeneric; + PropertyIdOp getProperty; + ElementIdOp getElement; + ElementIfPresentOp getElementIfPresent; /* can be null */ + SpecialIdOp getSpecial; + StrictGenericIdOp setGeneric; + StrictPropertyIdOp setProperty; + StrictElementIdOp setElement; + StrictSpecialIdOp setSpecial; + GenericAttributesOp getGenericAttributes; + GenericAttributesOp setGenericAttributes; + DeletePropertyOp deleteProperty; + DeleteElementOp deleteElement; + DeleteSpecialOp deleteSpecial; + WatchOp watch; + UnwatchOp unwatch; + + JSNewEnumerateOp enumerate; + ObjectOp thisObject; +}; + +#define JS_NULL_OBJECT_OPS \ + {nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr, \ + nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr, \ + nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr,nullptr} + +} // namespace js + +// Classes, objects, and properties. + +typedef void (*JSClassInternal)(); + +struct JSClass { + const char *name; + uint32_t flags; + + // Mandatory function pointer members. + JSPropertyOp addProperty; + JSDeletePropertyOp delProperty; + JSPropertyOp getProperty; + JSStrictPropertyOp setProperty; + JSEnumerateOp enumerate; + JSResolveOp resolve; + JSConvertOp convert; + + // Optional members (may be null). + JSFinalizeOp finalize; + JSCheckAccessOp checkAccess; + JSNative call; + JSHasInstanceOp hasInstance; + JSNative construct; + JSTraceOp trace; + + void *reserved[42]; +}; + +#define JSCLASS_HAS_PRIVATE (1<<0) // objects have private slot +#define JSCLASS_NEW_ENUMERATE (1<<1) // has JSNewEnumerateOp hook +#define JSCLASS_NEW_RESOLVE (1<<2) // has JSNewResolveOp hook +#define JSCLASS_PRIVATE_IS_NSISUPPORTS (1<<3) // private is (nsISupports *) +#define JSCLASS_IS_DOMJSCLASS (1<<4) // objects are DOM +#define JSCLASS_IMPLEMENTS_BARRIERS (1<<5) // Correctly implements GC read + // and write barriers +#define JSCLASS_EMULATES_UNDEFINED (1<<6) // objects of this class act + // like the value undefined, + // in some contexts +#define JSCLASS_USERBIT1 (1<<7) // Reserved for embeddings. + +// To reserve slots fetched and stored via JS_Get/SetReservedSlot, bitwise-or +// JSCLASS_HAS_RESERVED_SLOTS(n) into the initializer for JSClass.flags, where +// n is a constant in [1, 255]. Reserved slots are indexed from 0 to n-1. +#define JSCLASS_RESERVED_SLOTS_SHIFT 8 // room for 8 flags below */ +#define JSCLASS_RESERVED_SLOTS_WIDTH 8 // and 16 above this field */ +#define JSCLASS_RESERVED_SLOTS_MASK JS_BITMASK(JSCLASS_RESERVED_SLOTS_WIDTH) +#define JSCLASS_HAS_RESERVED_SLOTS(n) (((n) & JSCLASS_RESERVED_SLOTS_MASK) \ + << JSCLASS_RESERVED_SLOTS_SHIFT) +#define JSCLASS_RESERVED_SLOTS(clasp) (((clasp)->flags \ + >> JSCLASS_RESERVED_SLOTS_SHIFT) \ + & JSCLASS_RESERVED_SLOTS_MASK) + +#define JSCLASS_HIGH_FLAGS_SHIFT (JSCLASS_RESERVED_SLOTS_SHIFT + \ + JSCLASS_RESERVED_SLOTS_WIDTH) + +#define JSCLASS_IS_ANONYMOUS (1<<(JSCLASS_HIGH_FLAGS_SHIFT+0)) +#define JSCLASS_IS_GLOBAL (1<<(JSCLASS_HIGH_FLAGS_SHIFT+1)) +#define JSCLASS_INTERNAL_FLAG2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+2)) +#define JSCLASS_INTERNAL_FLAG3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+3)) + +// Indicate whether the proto or ctor should be frozen. +#define JSCLASS_FREEZE_PROTO (1<<(JSCLASS_HIGH_FLAGS_SHIFT+4)) +#define JSCLASS_FREEZE_CTOR (1<<(JSCLASS_HIGH_FLAGS_SHIFT+5)) + +// Reserved for embeddings. +#define JSCLASS_USERBIT2 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+6)) +#define JSCLASS_USERBIT3 (1<<(JSCLASS_HIGH_FLAGS_SHIFT+7)) + +#define JSCLASS_BACKGROUND_FINALIZE (1<<(JSCLASS_HIGH_FLAGS_SHIFT+8)) + +// Bits 26 through 31 are reserved for the CACHED_PROTO_KEY mechanism, see +// below. + +// ECMA-262 requires that most constructors used internally create objects +// with "the original Foo.prototype value" as their [[Prototype]] (__proto__) +// member initial value. The "original ... value" verbiage is there because +// in ECMA-262, global properties naming class objects are read/write and +// deleteable, for the most part. +// +// Implementing this efficiently requires that global objects have classes +// with the following flags. Failure to use JSCLASS_GLOBAL_FLAGS was +// previously allowed, but is now an ES5 violation and thus unsupported. +// +#define JSCLASS_GLOBAL_SLOT_COUNT (3 + JSProto_LIMIT * 3 + 28) +#define JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(n) \ + (JSCLASS_IS_GLOBAL | JSCLASS_HAS_RESERVED_SLOTS(JSCLASS_GLOBAL_SLOT_COUNT + (n))) +#define JSCLASS_GLOBAL_FLAGS \ + JSCLASS_GLOBAL_FLAGS_WITH_SLOTS(0) +#define JSCLASS_HAS_GLOBAL_FLAG_AND_SLOTS(clasp) \ + (((clasp)->flags & JSCLASS_IS_GLOBAL) \ + && JSCLASS_RESERVED_SLOTS(clasp) >= JSCLASS_GLOBAL_SLOT_COUNT) + +// Fast access to the original value of each standard class's prototype. +#define JSCLASS_CACHED_PROTO_SHIFT (JSCLASS_HIGH_FLAGS_SHIFT + 10) +#define JSCLASS_CACHED_PROTO_WIDTH 6 +#define JSCLASS_CACHED_PROTO_MASK JS_BITMASK(JSCLASS_CACHED_PROTO_WIDTH) +#define JSCLASS_HAS_CACHED_PROTO(key) (uint32_t(key) << JSCLASS_CACHED_PROTO_SHIFT) +#define JSCLASS_CACHED_PROTO_KEY(clasp) ((JSProtoKey) \ + (((clasp)->flags \ + >> JSCLASS_CACHED_PROTO_SHIFT) \ + & JSCLASS_CACHED_PROTO_MASK)) + +// Initializer for unused members of statically initialized JSClass structs. +#define JSCLASS_NO_INTERNAL_MEMBERS {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} +#define JSCLASS_NO_OPTIONAL_MEMBERS 0,0,0,0,0,JSCLASS_NO_INTERNAL_MEMBERS + +namespace js { + +struct Class +{ + JS_CLASS_MEMBERS; + ClassExtension ext; + ObjectOps ops; + uint8_t pad[sizeof(JSClass) - sizeof(ClassSizeMeasurement) - + sizeof(ClassExtension) - sizeof(ObjectOps)]; + + /* Class is not native and its map is not a scope. */ + static const uint32_t NON_NATIVE = JSCLASS_INTERNAL_FLAG2; + + bool isNative() const { + return !(flags & NON_NATIVE); + } + + bool hasPrivate() const { + return !!(flags & JSCLASS_HAS_PRIVATE); + } + + bool emulatesUndefined() const { + return flags & JSCLASS_EMULATES_UNDEFINED; + } + + bool isCallable() const { + return this == js::FunctionClassPtr || call; + } + + static size_t offsetOfFlags() { return offsetof(Class, flags); } +}; + +JS_STATIC_ASSERT(offsetof(JSClass, name) == offsetof(Class, name)); +JS_STATIC_ASSERT(offsetof(JSClass, flags) == offsetof(Class, flags)); +JS_STATIC_ASSERT(offsetof(JSClass, addProperty) == offsetof(Class, addProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, delProperty) == offsetof(Class, delProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, getProperty) == offsetof(Class, getProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, setProperty) == offsetof(Class, setProperty)); +JS_STATIC_ASSERT(offsetof(JSClass, enumerate) == offsetof(Class, enumerate)); +JS_STATIC_ASSERT(offsetof(JSClass, resolve) == offsetof(Class, resolve)); +JS_STATIC_ASSERT(offsetof(JSClass, convert) == offsetof(Class, convert)); +JS_STATIC_ASSERT(offsetof(JSClass, finalize) == offsetof(Class, finalize)); +JS_STATIC_ASSERT(offsetof(JSClass, checkAccess) == offsetof(Class, checkAccess)); +JS_STATIC_ASSERT(offsetof(JSClass, call) == offsetof(Class, call)); +JS_STATIC_ASSERT(offsetof(JSClass, construct) == offsetof(Class, construct)); +JS_STATIC_ASSERT(offsetof(JSClass, hasInstance) == offsetof(Class, hasInstance)); +JS_STATIC_ASSERT(offsetof(JSClass, trace) == offsetof(Class, trace)); +JS_STATIC_ASSERT(sizeof(JSClass) == sizeof(Class)); + +static JS_ALWAYS_INLINE const JSClass * +Jsvalify(const Class *c) +{ + return (const JSClass *)c; +} + +static JS_ALWAYS_INLINE const Class * +Valueify(const JSClass *c) +{ + return (const Class *)c; +} + +/* + * Enumeration describing possible values of the [[Class]] internal property + * value of objects. + */ +enum ESClassValue { + ESClass_Array, ESClass_Number, ESClass_String, ESClass_Boolean, + ESClass_RegExp, ESClass_ArrayBuffer, ESClass_Date +}; + +/* + * Return whether the given object has the given [[Class]] internal property + * value. Beware, this query says nothing about the js::Class of the JSObject + * so the caller must not assume anything about obj's representation (e.g., obj + * may be a proxy). + */ +inline bool +ObjectClassIs(JSObject &obj, ESClassValue classValue, JSContext *cx); + +/* Just a helper that checks v.isObject before calling ObjectClassIs. */ +inline bool +IsObjectWithClass(const JS::Value &v, ESClassValue classValue, JSContext *cx); + +inline bool +IsPoisonedSpecialId(js::SpecialId iden) +{ + if (iden.isObject()) + return JS::IsPoisonedPtr(iden.toObject()); + return false; +} + +template <> struct GCMethods +{ + static SpecialId initial() { return SpecialId(); } + static ThingRootKind kind() { return THING_ROOT_ID; } + static bool poisoned(SpecialId id) { return IsPoisonedSpecialId(id); } +}; + +} /* namespace js */ + +#endif /* js_Class_h */ diff --git a/external/spidermonkey/include/win32/js/GCAPI.h b/external/spidermonkey/include/win32/js/GCAPI.h index a9bef77c09..9cdf56bcce 100644 --- a/external/spidermonkey/include/win32/js/GCAPI.h +++ b/external/spidermonkey/include/win32/js/GCAPI.h @@ -7,7 +7,11 @@ #ifndef js_GCAPI_h #define js_GCAPI_h +#include "mozilla/NullPtr.h" + #include "js/HeapAPI.h" +#include "js/RootingAPI.h" +#include "js/Value.h" namespace JS { @@ -15,13 +19,12 @@ namespace JS { /* Reasons internal to the JS engine */ \ D(API) \ D(MAYBEGC) \ - D(LAST_CONTEXT) \ + D(DESTROY_RUNTIME) \ D(DESTROY_CONTEXT) \ D(LAST_DITCH) \ D(TOO_MUCH_MALLOC) \ D(ALLOC_TRIGGER) \ D(DEBUG_GC) \ - D(DEBUG_MODE_GC) \ D(TRANSPLANT) \ D(RESET) \ D(OUT_OF_NURSERY) \ @@ -206,12 +209,25 @@ PokeGC(JSRuntime *rt); extern JS_FRIEND_API(bool) WasIncrementalGC(JSRuntime *rt); -class ObjectPtr +extern JS_FRIEND_API(size_t) +GetGCNumber(); + +class AutoAssertNoGC { +#ifdef DEBUG + size_t gcNumber; + + public: + AutoAssertNoGC(); + ~AutoAssertNoGC(); +#endif +}; + +class JS_PUBLIC_API(ObjectPtr) { Heap value; public: - ObjectPtr() : value(NULL) {} + ObjectPtr() : value(nullptr) {} ObjectPtr(JSObject *obj) : value(obj) {} @@ -221,7 +237,7 @@ class ObjectPtr void finalize(JSRuntime *rt) { if (IsIncrementalBarrierNeeded(rt)) IncrementalObjectBarrier(value); - value = NULL; + value = nullptr; } void init(JSObject *obj) { value = obj; } @@ -232,9 +248,7 @@ class ObjectPtr IncrementalObjectBarrier(value); } - bool isAboutToBeFinalized() { - return JS_IsAboutToBeFinalized(&value); - } + bool isAboutToBeFinalized(); ObjectPtr &operator=(JSObject *obj) { IncrementalObjectBarrier(value); @@ -242,9 +256,7 @@ class ObjectPtr return *this; } - void trace(JSTracer *trc, const char *name) { - JS_CallHeapObjectTracer(trc, &value, name); - } + void trace(JSTracer *trc, const char *name); JSObject &operator*() const { return *value; } JSObject *operator->() const { return value; } @@ -255,7 +267,7 @@ class ObjectPtr * Unsets the gray bit for anything reachable from |thing|. |kind| should not be * JSTRACE_SHAPE. |thing| should be non-null. */ -extern JS_FRIEND_API(void) +extern JS_FRIEND_API(bool) UnmarkGrayGCThingRecursively(void *thing, JSGCTraceKind kind); /* @@ -276,7 +288,7 @@ ExposeGCThingToActiveJS(void *thing, JSGCTraceKind kind) * All live objects in the nursery are moved to tenured at the beginning of * each GC slice, so the gray marker never sees nursery things. */ - if (uintptr_t(thing) >= rt->gcNurseryStart_ && uintptr_t(thing) < rt->gcNurseryEnd_) + if (js::gc::IsInsideNursery(rt, thing)) return; #endif if (IsIncrementalBarrierNeededOnGCThing(rt, thing, kind)) @@ -292,6 +304,37 @@ ExposeValueToActiveJS(const Value &v) ExposeGCThingToActiveJS(v.toGCThing(), v.gcKind()); } +static JS_ALWAYS_INLINE void +ExposeObjectToActiveJS(JSObject *obj) +{ + ExposeGCThingToActiveJS(obj, JSTRACE_OBJECT); +} + +/* + * If a GC is currently marking, mark the object black. + */ +static JS_ALWAYS_INLINE void +MarkGCThingAsLive(JSRuntime *rt_, void *thing, JSGCTraceKind kind) +{ + shadow::Runtime *rt = shadow::Runtime::asShadowRuntime(rt_); +#ifdef JSGC_GENERATIONAL + /* + * Any object in the nursery will not be freed during any GC running at that time. + */ + if (js::gc::IsInsideNursery(rt, thing)) + return; +#endif + if (IsIncrementalBarrierNeededOnGCThing(rt, thing, kind)) + IncrementalReferenceBarrier(thing, kind); +} + +static JS_ALWAYS_INLINE void +MarkStringAsLive(Zone *zone, JSString *string) +{ + JSRuntime *rt = JS::shadow::Zone::asShadowZone(zone)->runtimeFromMainThread(); + MarkGCThingAsLive(rt, string, JSTRACE_STRING); +} + } /* namespace JS */ #endif /* js_GCAPI_h */ diff --git a/external/spidermonkey/include/win32/js/HashTable.h b/external/spidermonkey/include/win32/js/HashTable.h index aa05b71472..a6b4361dea 100644 --- a/external/spidermonkey/include/win32/js/HashTable.h +++ b/external/spidermonkey/include/win32/js/HashTable.h @@ -7,17 +7,18 @@ #ifndef js_HashTable_h #define js_HashTable_h +#include "mozilla/Alignment.h" #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Casting.h" #include "mozilla/DebugOnly.h" #include "mozilla/MemoryReporting.h" #include "mozilla/Move.h" +#include "mozilla/NullPtr.h" #include "mozilla/PodOperations.h" #include "mozilla/ReentrancyGuard.h" #include "mozilla/TemplateLib.h" #include "mozilla/TypeTraits.h" -#include "mozilla/Util.h" #include "js/Utility.h" @@ -60,7 +61,7 @@ class HashMap { typedef Key KeyType; static const Key &getKey(TableEntry &e) { return e.key; } - static void setKey(TableEntry &e, Key &k) { const_cast(e.key) = k; } + static void setKey(TableEntry &e, Key &k) { HashPolicy::rekey(const_cast(e.key), k); } }; typedef detail::HashTable Impl; @@ -138,18 +139,18 @@ class HashMap template bool add(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.add(p, mozilla::Move(e)); + return impl.add(p, mozilla::OldMove(e)); } bool add(AddPtr &p, const Key &k) { Entry e(k, Value()); - return impl.add(p, mozilla::Move(e)); + return impl.add(p, mozilla::OldMove(e)); } template bool relookupOrAdd(AddPtr &p, const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.relookupOrAdd(p, k, mozilla::Move(e)); + return impl.relookupOrAdd(p, k, mozilla::OldMove(e)); } // |all()| returns a Range containing |count()| elements. E.g.: @@ -213,7 +214,7 @@ class HashMap /************************************************** Shorthand operations */ bool has(const Lookup &l) const { - return impl.lookup(l) != NULL; + return impl.lookup(l) != nullptr; } // Overwrite existing value with v. Return false on oom. @@ -231,7 +232,7 @@ class HashMap template bool putNew(const KeyInput &k, const ValueInput &v) { Entry e(k, v); - return impl.putNew(k, mozilla::Move(e)); + return impl.putNew(k, mozilla::OldMove(e)); } // Add (k,defaultValue) if |k| is not found. Return a false-y Ptr on oom. @@ -249,17 +250,22 @@ class HashMap remove(p); } + // Infallibly rekey one entry, if necessary. + // Requires template parameters Key and HashPolicy::Lookup to be the same type. + void rekeyIfMoved(const Key &old_key, const Key &new_key) { + if (old_key != new_key) + rekeyAs(old_key, new_key, new_key); + } + // Infallibly rekey one entry, if present. - void rekey(const Lookup &old_key, const Key &new_key) { - if (old_key != new_key) { - if (Ptr p = lookup(old_key)) - impl.rekey(p, new_key, new_key); - } + void rekeyAs(const Lookup &old_lookup, const Lookup &new_lookup, const Key &new_key) { + if (Ptr p = lookup(old_lookup)) + impl.rekeyAndMaybeRehash(p, new_lookup, new_key); } // HashMap is movable - HashMap(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} - void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } + HashMap(mozilla::MoveRef rhs) : impl(mozilla::OldMove(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::OldMove(rhs->impl); } private: // HashMap is not copyable or assignable @@ -295,7 +301,7 @@ class HashSet { typedef T KeyType; static const KeyType &getKey(const T &t) { return t; } - static void setKey(T &t, KeyType &k) { t = k; } + static void setKey(T &t, KeyType &k) { HashPolicy::rekey(t, k); } }; typedef detail::HashTable Impl; @@ -323,6 +329,10 @@ class HashSet typedef typename Impl::Ptr Ptr; Ptr lookup(const Lookup &l) const { return impl.lookup(l); } + // Like lookup, but does not assert if two threads call lookup at the same + // time. Only use this method when none of the threads will modify the map. + Ptr readonlyThreadsafeLookup(const Lookup &l) const { return impl.readonlyThreadsafeLookup(l); } + // Assuming |p.found()|, remove |*p|. void remove(Ptr p) { impl.remove(p); } @@ -425,7 +435,7 @@ class HashSet /************************************************** Shorthand operations */ bool has(const Lookup &l) const { - return impl.lookup(l) != NULL; + return impl.lookup(l) != nullptr; } // Overwrite existing value with v. Return false on oom. @@ -449,16 +459,21 @@ class HashSet } // Infallibly rekey one entry, if present. - void rekey(const Lookup &old_key, const T &new_key) { - if (old_key != new_key) { - if (Ptr p = lookup(old_key)) - impl.rekey(p, new_key, new_key); - } + // Requires template parameters T and HashPolicy::Lookup to be the same type. + void rekeyIfMoved(const Lookup &old_value, const T &new_value) { + if (old_value != new_value) + rekeyAs(old_value, new_value, new_value); + } + + // Infallibly rekey one entry, if present. + void rekeyAs(const Lookup &old_lookup, const Lookup &new_lookup, const T &new_value) { + if (Ptr p = lookup(old_lookup)) + impl.rekeyAndMaybeRehash(p, new_lookup, new_value); } // HashSet is movable - HashSet(mozilla::MoveRef rhs) : impl(mozilla::Move(rhs->impl)) {} - void operator=(mozilla::MoveRef rhs) { impl = mozilla::Move(rhs->impl); } + HashSet(mozilla::MoveRef rhs) : impl(mozilla::OldMove(rhs->impl)) {} + void operator=(mozilla::MoveRef rhs) { impl = mozilla::OldMove(rhs->impl); } private: // HashSet is not copyable or assignable @@ -505,7 +520,7 @@ struct PointerHasher JS_ASSERT(!JS::IsPoisonedPtr(l)); size_t word = reinterpret_cast(l) >> zeroBits; JS_STATIC_ASSERT(sizeof(HashNumber) == 4); -#if JS_BYTES_PER_WORD == 4 +#if JS_BITS_PER_WORD == 32 return HashNumber(word); #else JS_STATIC_ASSERT(sizeof word == 8); @@ -517,6 +532,9 @@ struct PointerHasher JS_ASSERT(!JS::IsPoisonedPtr(l)); return k == l; } + static void rekey(Key &k, const Key& newKey) { + k = newKey; + } }; // Default hash policy: just use the 'lookup' value. This of course only @@ -535,6 +553,9 @@ struct DefaultHasher // Use builtin or overloaded operator==. return k == l; } + static void rekey(Key &k, const Key& newKey) { + k = newKey; + } }; // Specialize hashing policy for pointer types. It assumes that the type is @@ -558,6 +579,19 @@ struct DefaultHasher } }; +template <> +struct DefaultHasher +{ + typedef float Lookup; + static HashNumber hash(float f) { + JS_STATIC_ASSERT(sizeof(HashNumber) == 4); + return HashNumber(mozilla::BitwiseCast(f)); + } + static bool match(float lhs, float rhs) { + return mozilla::BitwiseCast(lhs) == mozilla::BitwiseCast(rhs); + } +}; + /*****************************************************************************/ // Both HashMap and HashSet are implemented by a single HashTable that is even @@ -579,7 +613,7 @@ class HashMapEntry HashMapEntry(const KeyInput &k, const ValueInput &v) : key(k), value(v) {} HashMapEntry(mozilla::MoveRef rhs) - : key(mozilla::Move(rhs->key)), value(mozilla::Move(rhs->value)) { } + : key(mozilla::OldMove(rhs->key)), value(mozilla::OldMove(rhs->value)) { } typedef Key KeyType; typedef Value ValueType; @@ -750,7 +784,7 @@ class HashTable : private AllocPolicy mozilla::DebugOnly validEntry; public: - Range() : cur(NULL), end(NULL), validEntry(false) {} + Range() : cur(nullptr), end(nullptr), validEntry(false) {} bool empty() const { return cur == end; @@ -808,7 +842,7 @@ class HashTable : private AllocPolicy // a new key at the new Lookup position. |front()| is invalid after // this operation until the next call to |popFront()|. void rekeyFront(const Lookup &l, const Key &k) { - table.rekey(*this->cur, l, k); + table.rekeyWithoutRehash(*this->cur, l, k); rekeyed = true; this->validEntry = false; } @@ -834,13 +868,13 @@ class HashTable : private AllocPolicy : AllocPolicy(*rhs) { mozilla::PodAssign(this, &*rhs); - rhs->table = NULL; + rhs->table = nullptr; } void operator=(mozilla::MoveRef rhs) { if (table) destroyTable(*this, table, capacity()); mozilla::PodAssign(this, &*rhs); - rhs->table = NULL; + rhs->table = nullptr; } private: @@ -941,7 +975,7 @@ class HashTable : private AllocPolicy entryCount(0), gen(0), removedCount(0), - table(NULL), + table(nullptr), entered(false), mutationCount(0) {} @@ -1067,7 +1101,7 @@ class HashTable : private AllocPolicy DoubleHash dh = hash2(keyHash); // Save the first removed entry pointer so we can recycle later. - Entry *firstRemoved = NULL; + Entry *firstRemoved = nullptr; while(true) { if (JS_UNLIKELY(entry->isRemoved())) { @@ -1163,7 +1197,7 @@ class HashTable : private AllocPolicy for (Entry *src = oldTable, *end = src + oldCap; src < end; ++src) { if (src->isLive()) { HashNumber hn = src->getKeyHash(); - findFreeEntry(hn).setLive(hn, mozilla::Move(src->get())); + findFreeEntry(hn).setLive(hn, mozilla::OldMove(src->get())); src->destroy(); } } @@ -1307,7 +1341,7 @@ class HashTable : private AllocPolicy return; destroyTable(*this, table, capacity()); - table = NULL; + table = nullptr; gen++; entryCount = 0; removedCount = 0; @@ -1456,15 +1490,21 @@ class HashTable : private AllocPolicy checkUnderloaded(); } - void rekey(Ptr p, const Lookup &l, const Key &k) + void rekeyWithoutRehash(Ptr p, const Lookup &l, const Key &k) { JS_ASSERT(table); mozilla::ReentrancyGuard g(*this); JS_ASSERT(p.found()); - typename HashTableEntry::NonConstT t(mozilla::Move(*p)); + typename HashTableEntry::NonConstT t(mozilla::OldMove(*p)); HashPolicy::setKey(t, const_cast(k)); remove(*p.entry_); - putNewInfallible(l, mozilla::Move(t)); + putNewInfallible(l, mozilla::OldMove(t)); + } + + void rekeyAndMaybeRehash(Ptr p, const Lookup &l, const Key &k) + { + rekeyWithoutRehash(p, l, k); + checkOverRemoved(); } #undef METER diff --git a/external/spidermonkey/include/win32/js/HeapAPI.h b/external/spidermonkey/include/win32/js/HeapAPI.h index 4d739304bc..438c23c05f 100644 --- a/external/spidermonkey/include/win32/js/HeapAPI.h +++ b/external/spidermonkey/include/win32/js/HeapAPI.h @@ -7,12 +7,23 @@ #ifndef js_HeapAPI_h #define js_HeapAPI_h +#include + #include "jspubtd.h" #include "js/Utility.h" /* These values are private to the JS engine. */ namespace js { + +// Whether the current thread is permitted access to any part of the specified +// runtime or zone. +JS_FRIEND_API(bool) +CurrentThreadCanAccessRuntime(JSRuntime *rt); + +JS_FRIEND_API(bool) +CurrentThreadCanAccessZone(JS::Zone *zone); + namespace gc { const size_t ArenaShift = 12; @@ -57,9 +68,43 @@ struct ArenaHeader struct Zone { + protected: + JSRuntime *const runtime_; + JSTracer *const barrierTracer_; // A pointer to the JSRuntime's |gcMarker|. + + public: bool needsBarrier_; - Zone() : needsBarrier_(false) {} + Zone(JSRuntime *runtime, JSTracer *barrierTracerArg) + : runtime_(runtime), + barrierTracer_(barrierTracerArg), + needsBarrier_(false) + {} + + bool needsBarrier() const { + return needsBarrier_; + } + + JSTracer *barrierTracer() { + JS_ASSERT(needsBarrier_); + JS_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); + return barrierTracer_; + } + + JSRuntime *runtimeFromMainThread() const { + JS_ASSERT(js::CurrentThreadCanAccessRuntime(runtime_)); + return runtime_; + } + + // Note: Unrestricted access to the zone's runtime from an arbitrary + // thread can easily lead to races. Use this method very carefully. + JSRuntime *runtimeFromAnyThread() const { + return runtime_; + } + + static JS::shadow::Zone *asShadowZone(JS::Zone *zone) { + return reinterpret_cast(zone); + } }; } /* namespace shadow */ @@ -94,8 +139,9 @@ GetGCThingMarkWordAndMask(const void *thing, uint32_t color, size_t bit = (addr & js::gc::ChunkMask) / js::gc::CellSize + color; JS_ASSERT(bit < js::gc::ChunkMarkBitmapBits); uintptr_t *bitmap = GetGCThingMarkBitmap(thing); - *maskp = uintptr_t(1) << (bit % JS_BITS_PER_WORD); - *wordp = &bitmap[bit / JS_BITS_PER_WORD]; + const uintptr_t nbits = sizeof(*bitmap) * CHAR_BIT; + *maskp = uintptr_t(1) << (bit % nbits); + *wordp = &bitmap[bit / nbits]; } static JS_ALWAYS_INLINE JS::shadow::ArenaHeader * @@ -106,6 +152,16 @@ GetGCThingArena(void *thing) return reinterpret_cast(addr); } +JS_ALWAYS_INLINE bool +IsInsideNursery(const JS::shadow::Runtime *runtime, const void *p) +{ +#ifdef JSGC_GENERATIONAL + return uintptr_t(p) >= runtime->gcNurseryStart_ && uintptr_t(p) < runtime->gcNurseryEnd_; +#else + return false; +#endif +} + } /* namespace gc */ } /* namespace js */ @@ -128,6 +184,16 @@ GetObjectZone(JSObject *obj) static JS_ALWAYS_INLINE bool GCThingIsMarkedGray(void *thing) { +#ifdef JSGC_GENERATIONAL + /* + * GC things residing in the nursery cannot be gray: they have no mark bits. + * All live objects in the nursery are moved to tenured at the beginning of + * each GC slice, so the gray marker never sees nursery things. + */ + JS::shadow::Runtime *rt = js::gc::GetGCThingRuntime(thing); + if (js::gc::IsInsideNursery(rt, thing)) + return false; +#endif uintptr_t *word, mask; js::gc::GetGCThingMarkWordAndMask(thing, js::gc::GRAY, &word, &mask); return *word & mask; diff --git a/external/spidermonkey/include/win32/js/Id.h b/external/spidermonkey/include/win32/js/Id.h new file mode 100644 index 0000000000..447deb62e6 --- /dev/null +++ b/external/spidermonkey/include/win32/js/Id.h @@ -0,0 +1,192 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_Id_h +#define js_Id_h + +// A jsid is an identifier for a property or method of an object which is +// either a 31-bit signed integer, interned string or object. +// +// Also, there is an additional jsid value, JSID_VOID, which does not occur in +// JS scripts but may be used to indicate the absence of a valid jsid. A void +// jsid is not a valid id and only arises as an exceptional API return value, +// such as in JS_NextProperty. Embeddings must not pass JSID_VOID into JSAPI +// entry points expecting a jsid and do not need to handle JSID_VOID in hooks +// receiving a jsid except when explicitly noted in the API contract. +// +// A jsid is not implicitly convertible to or from a jsval; JS_ValueToId or +// JS_IdToValue must be used instead. + +#include "mozilla/NullPtr.h" + +#include "jstypes.h" + +#include "js/RootingAPI.h" +#include "js/TypeDecls.h" +#include "js/Utility.h" + +#ifdef JS_USE_JSID_STRUCT_TYPES +struct jsid +{ + size_t asBits; + bool operator==(jsid rhs) const { return asBits == rhs.asBits; } + bool operator!=(jsid rhs) const { return asBits != rhs.asBits; } +}; +# define JSID_BITS(id) (id.asBits) +#else +# define JSID_BITS(id) (id) +#endif + +#define JSID_TYPE_STRING 0x0 +#define JSID_TYPE_INT 0x1 +#define JSID_TYPE_VOID 0x2 +#define JSID_TYPE_OBJECT 0x4 +#define JSID_TYPE_MASK 0x7 + +// Avoid using canonical 'id' for jsid parameters since this is a magic word in +// Objective-C++ which, apparently, wants to be able to #include jsapi.h. +#define id iden + +static JS_ALWAYS_INLINE bool +JSID_IS_STRING(jsid id) +{ + return (JSID_BITS(id) & JSID_TYPE_MASK) == 0; +} + +static JS_ALWAYS_INLINE JSString * +JSID_TO_STRING(jsid id) +{ + JS_ASSERT(JSID_IS_STRING(id)); + return (JSString *)JSID_BITS(id); +} + +static JS_ALWAYS_INLINE bool +JSID_IS_ZERO(jsid id) +{ + return JSID_BITS(id) == 0; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_INT(jsid id) +{ + return !!(JSID_BITS(id) & JSID_TYPE_INT); +} + +static JS_ALWAYS_INLINE int32_t +JSID_TO_INT(jsid id) +{ + JS_ASSERT(JSID_IS_INT(id)); + return ((uint32_t)JSID_BITS(id)) >> 1; +} + +#define JSID_INT_MIN 0 +#define JSID_INT_MAX INT32_MAX + +static JS_ALWAYS_INLINE bool +INT_FITS_IN_JSID(int32_t i) +{ + return i >= 0; +} + +static JS_ALWAYS_INLINE jsid +INT_TO_JSID(int32_t i) +{ + jsid id; + JS_ASSERT(INT_FITS_IN_JSID(i)); + JSID_BITS(id) = ((i << 1) | JSID_TYPE_INT); + return id; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_OBJECT(jsid id) +{ + return (JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_OBJECT && + (size_t)JSID_BITS(id) != JSID_TYPE_OBJECT; +} + +static JS_ALWAYS_INLINE JSObject * +JSID_TO_OBJECT(jsid id) +{ + JS_ASSERT(JSID_IS_OBJECT(id)); + return (JSObject *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); +} + +static JS_ALWAYS_INLINE jsid +OBJECT_TO_JSID(JSObject *obj) +{ + jsid id; + JS_ASSERT(obj != nullptr); + JS_ASSERT(((size_t)obj & JSID_TYPE_MASK) == 0); + JSID_BITS(id) = ((size_t)obj | JSID_TYPE_OBJECT); + return id; +} + +static JS_ALWAYS_INLINE bool +JSID_IS_GCTHING(jsid id) +{ + return JSID_IS_STRING(id) || JSID_IS_OBJECT(id); +} + +static JS_ALWAYS_INLINE void * +JSID_TO_GCTHING(jsid id) +{ + return (void *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK); +} + +static JS_ALWAYS_INLINE bool +JSID_IS_VOID(const jsid id) +{ + JS_ASSERT_IF(((size_t)JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_VOID, + JSID_BITS(id) == JSID_TYPE_VOID); + return ((size_t)JSID_BITS(id) == JSID_TYPE_VOID); +} + +static JS_ALWAYS_INLINE bool +JSID_IS_EMPTY(const jsid id) +{ + return ((size_t)JSID_BITS(id) == JSID_TYPE_OBJECT); +} + +#undef id + +#ifdef JS_USE_JSID_STRUCT_TYPES +extern JS_PUBLIC_DATA(const jsid) JSID_VOID; +extern JS_PUBLIC_DATA(const jsid) JSID_EMPTY; +#else +# define JSID_VOID ((jsid)JSID_TYPE_VOID) +# define JSID_EMPTY ((jsid)JSID_TYPE_OBJECT) +#endif + +extern JS_PUBLIC_DATA(const JS::Handle) JSID_VOIDHANDLE; +extern JS_PUBLIC_DATA(const JS::Handle) JSID_EMPTYHANDLE; + +namespace js { + +inline bool +IsPoisonedId(jsid iden) +{ + if (JSID_IS_STRING(iden)) + return JS::IsPoisonedPtr(JSID_TO_STRING(iden)); + if (JSID_IS_OBJECT(iden)) + return JS::IsPoisonedPtr(JSID_TO_OBJECT(iden)); + return false; +} + +template <> struct GCMethods +{ + static jsid initial() { return JSID_VOID; } + static ThingRootKind kind() { return THING_ROOT_ID; } + static bool poisoned(jsid id) { return IsPoisonedId(id); } + static bool needsPostBarrier(jsid id) { return false; } +#ifdef JSGC_GENERATIONAL + static void postBarrier(jsid *idp) {} + static void relocate(jsid *idp) {} +#endif +}; + +} + +#endif /* js_Id_h */ diff --git a/external/spidermonkey/include/win32/js/MemoryMetrics.h b/external/spidermonkey/include/win32/js/MemoryMetrics.h index ed61e1c427..2336e35624 100644 --- a/external/spidermonkey/include/win32/js/MemoryMetrics.h +++ b/external/spidermonkey/include/win32/js/MemoryMetrics.h @@ -7,20 +7,54 @@ #ifndef js_MemoryMetrics_h #define js_MemoryMetrics_h -// These declarations are not within jsapi.h because they are highly likely to -// change in the future. Depend on them at your own risk. +// These declarations are highly likely to change in the future. Depend on them +// at your own risk. #include "mozilla/MemoryReporting.h" +#include "mozilla/NullPtr.h" +#include "mozilla/PodOperations.h" #include #include "jsalloc.h" #include "jspubtd.h" +#include "js/HashTable.h" #include "js/Utility.h" #include "js/Vector.h" -class nsISupports; // This is needed for ObjectPrivateVisitor. +class nsISupports; // Needed for ObjectPrivateVisitor. + +namespace JS { + +struct TabSizes +{ + enum Kind { + Objects, + Strings, + Private, + Other + }; + + TabSizes() { mozilla::PodZero(this); } + + void add(Kind kind, size_t n) { + switch (kind) { + case Objects: objects += n; break; + case Strings: strings += n; break; + case Private: private_ += n; break; + case Other: other += n; break; + default: MOZ_CRASH("bad TabSizes kind"); + } + } + + size_t objects; + size_t strings; + size_t private_; + size_t other; +}; + +} // namespace JS namespace js { @@ -30,9 +64,86 @@ namespace js { // MemoryReportingSundriesThreshold() bytes. // // We need to define this value here, rather than in the code which actually -// generates the memory reports, because HugeStringInfo uses this value. +// generates the memory reports, because NotableStringInfo uses this value. JS_FRIEND_API(size_t) MemoryReportingSundriesThreshold(); +// This hash policy avoids flattening ropes (which perturbs the site being +// measured and requires a JSContext) at the expense of doing a FULL ROPE COPY +// on every hash and match! Beware. +struct InefficientNonFlatteningStringHashPolicy +{ + typedef JSString *Lookup; + static HashNumber hash(const Lookup &l); + static bool match(const JSString *const &k, const Lookup &l); +}; + +// This file features many classes with numerous size_t fields, and each such +// class has one or more methods that need to operate on all of these fields. +// Writing these individually is error-prone -- it's easy to add a new field +// without updating all the required methods. So we define a single macro list +// in each class to name the fields (and notable characteristics of them), and +// then use the following macros to transform those lists into the required +// methods. +// +// In some classes, one or more of the macro arguments aren't used. We use '_' +// for those. +// +#define DECL_SIZE(kind, gc, mSize) size_t mSize; +#define ZERO_SIZE(kind, gc, mSize) mSize(0), +#define COPY_OTHER_SIZE(kind, gc, mSize) mSize(other.mSize), +#define ADD_OTHER_SIZE(kind, gc, mSize) mSize += other.mSize; +#define ADD_SIZE_TO_N_IF_LIVE_GC_THING(kind, gc, mSize) n += (js::gc == js::IsLiveGCThing) ? mSize : 0; +#define ADD_TO_TAB_SIZES(kind, gc, mSize) sizes->add(JS::TabSizes::kind, mSize); + +// Used to annotate which size_t fields measure live GC things and which don't. +enum { + NotLiveGCThing = false, + IsLiveGCThing = true +}; + +struct ZoneStatsPod +{ +#define FOR_EACH_SIZE(macro) \ + macro(Other, NotLiveGCThing, gcHeapArenaAdmin) \ + macro(Other, NotLiveGCThing, unusedGCThings) \ + macro(Other, IsLiveGCThing, lazyScriptsGCHeap) \ + macro(Other, NotLiveGCThing, lazyScriptsMallocHeap) \ + macro(Other, IsLiveGCThing, ionCodesGCHeap) \ + macro(Other, IsLiveGCThing, typeObjectsGCHeap) \ + macro(Other, NotLiveGCThing, typeObjectsMallocHeap) \ + macro(Other, NotLiveGCThing, typePool) \ + macro(Strings, IsLiveGCThing, stringsShortGCHeap) \ + macro(Strings, IsLiveGCThing, stringsNormalGCHeap) \ + macro(Strings, NotLiveGCThing, stringsNormalMallocHeap) + + ZoneStatsPod() + : FOR_EACH_SIZE(ZERO_SIZE) + extra() + {} + + void add(const ZoneStatsPod &other) { + FOR_EACH_SIZE(ADD_OTHER_SIZE) + // Do nothing with |extra|. + } + + size_t sizeOfLiveGCThings() const { + size_t n = 0; + FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) + // Do nothing with |extra|. + return n; + } + + void addToTabSizes(JS::TabSizes *sizes) const { + FOR_EACH_SIZE(ADD_TO_TAB_SIZES) + // Do nothing with |extra|. + } + + FOR_EACH_SIZE(DECL_SIZE) + void *extra; // This field can be used by embedders. + +#undef FOR_EACH_SIZE +}; + } // namespace js namespace JS { @@ -40,352 +151,320 @@ namespace JS { // Data for tracking memory usage of things hanging off objects. struct ObjectsExtraSizes { - size_t slots; - size_t elementsNonAsmJS; - size_t elementsAsmJSHeap; - size_t elementsAsmJSNonHeap; - size_t argumentsData; - size_t regExpStatics; - size_t propertyIteratorData; - size_t ctypesData; - size_t private_; // The '_' suffix is required because |private| is a keyword. - // Note that this field is measured separately from the others. +#define FOR_EACH_SIZE(macro) \ + macro(Objects, NotLiveGCThing, mallocHeapSlots) \ + macro(Objects, NotLiveGCThing, mallocHeapElementsNonAsmJS) \ + macro(Objects, NotLiveGCThing, mallocHeapElementsAsmJS) \ + macro(Objects, NotLiveGCThing, nonHeapElementsAsmJS) \ + macro(Objects, NotLiveGCThing, nonHeapCodeAsmJS) \ + macro(Objects, NotLiveGCThing, mallocHeapAsmJSModuleData) \ + macro(Objects, NotLiveGCThing, mallocHeapArgumentsData) \ + macro(Objects, NotLiveGCThing, mallocHeapRegExpStatics) \ + macro(Objects, NotLiveGCThing, mallocHeapPropertyIteratorData) \ + macro(Objects, NotLiveGCThing, mallocHeapCtypesData) - ObjectsExtraSizes() { memset(this, 0, sizeof(ObjectsExtraSizes)); } + ObjectsExtraSizes() + : FOR_EACH_SIZE(ZERO_SIZE) + dummy() + {} - void add(ObjectsExtraSizes &sizes) { - this->slots += sizes.slots; - this->elementsNonAsmJS += sizes.elementsNonAsmJS; - this->elementsAsmJSHeap += sizes.elementsAsmJSHeap; - this->elementsAsmJSNonHeap += sizes.elementsAsmJSNonHeap; - this->argumentsData += sizes.argumentsData; - this->regExpStatics += sizes.regExpStatics; - this->propertyIteratorData += sizes.propertyIteratorData; - this->ctypesData += sizes.ctypesData; - this->private_ += sizes.private_; + void add(const ObjectsExtraSizes &other) { + FOR_EACH_SIZE(ADD_OTHER_SIZE) } -}; -// Data for tracking analysis/inference memory usage. -struct TypeInferenceSizes -{ - size_t typeScripts; - size_t typeResults; - size_t analysisPool; - size_t pendingArrays; - size_t allocationSiteTables; - size_t arrayTypeTables; - size_t objectTypeTables; - - TypeInferenceSizes() { memset(this, 0, sizeof(TypeInferenceSizes)); } - - void add(TypeInferenceSizes &sizes) { - this->typeScripts += sizes.typeScripts; - this->typeResults += sizes.typeResults; - this->analysisPool += sizes.analysisPool; - this->pendingArrays += sizes.pendingArrays; - this->allocationSiteTables += sizes.allocationSiteTables; - this->arrayTypeTables += sizes.arrayTypeTables; - this->objectTypeTables += sizes.objectTypeTables; + size_t sizeOfLiveGCThings() const { + size_t n = 0; + FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) + return n; } + + void addToTabSizes(TabSizes *sizes) const { + FOR_EACH_SIZE(ADD_TO_TAB_SIZES) + } + + FOR_EACH_SIZE(DECL_SIZE) + int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) + +#undef FOR_EACH_SIZE }; // Data for tracking JIT-code memory usage. struct CodeSizes { - size_t ion; - size_t asmJS; - size_t baseline; - size_t regexp; - size_t other; - size_t unused; +#define FOR_EACH_SIZE(macro) \ + macro(_, _, ion) \ + macro(_, _, baseline) \ + macro(_, _, regexp) \ + macro(_, _, other) \ + macro(_, _, unused) - CodeSizes() { memset(this, 0, sizeof(CodeSizes)); } + CodeSizes() + : FOR_EACH_SIZE(ZERO_SIZE) + dummy() + {} + + FOR_EACH_SIZE(DECL_SIZE) + int dummy; // present just to absorb the trailing comma from FOR_EACH_SIZE(ZERO_SIZE) + +#undef FOR_EACH_SIZE }; -// Holds data about a huge string (one which uses more HugeStringInfo::MinSize -// bytes of memory), so we can report it individually. -struct HugeStringInfo +// This class holds information about the memory taken up by identical copies of +// a particular string. Multiple JSStrings may have their sizes aggregated +// together into one StringInfo object. +struct StringInfo { - HugeStringInfo() : length(0), size(0) { memset(&buffer, 0, sizeof(buffer)); } + StringInfo() + : length(0), numCopies(0), shortGCHeap(0), normalGCHeap(0), normalMallocHeap(0) + {} + + StringInfo(size_t len, size_t shorts, size_t normals, size_t chars) + : length(len), + numCopies(1), + shortGCHeap(shorts), + normalGCHeap(normals), + normalMallocHeap(chars) + {} + + void add(size_t shorts, size_t normals, size_t chars) { + shortGCHeap += shorts; + normalGCHeap += normals; + normalMallocHeap += chars; + numCopies++; + } + + void add(const StringInfo& info) { + MOZ_ASSERT(length == info.length); + + shortGCHeap += info.shortGCHeap; + normalGCHeap += info.normalGCHeap; + normalMallocHeap += info.normalMallocHeap; + numCopies += info.numCopies; + } + + size_t totalSizeOf() const { + return shortGCHeap + normalGCHeap + normalMallocHeap; + } + + size_t totalGCHeapSizeOf() const { + return shortGCHeap + normalGCHeap; + } + + // The string's length, excluding the null-terminator. + size_t length; + + // How many copies of the string have we seen? + size_t numCopies; + + // These are all totals across all copies of the string we've seen. + size_t shortGCHeap; + size_t normalGCHeap; + size_t normalMallocHeap; +}; + +// Holds data about a notable string (one which uses more than +// NotableStringInfo::notableSize() bytes of memory), so we can report it +// individually. +// +// Essentially the only difference between this class and StringInfo is that +// NotableStringInfo holds a copy of the string's chars. +struct NotableStringInfo : public StringInfo +{ + NotableStringInfo(); + NotableStringInfo(JSString *str, const StringInfo &info); + NotableStringInfo(mozilla::MoveRef info); + NotableStringInfo &operator=(mozilla::MoveRef info); + + ~NotableStringInfo() { + js_free(buffer); + } // A string needs to take up this many bytes of storage before we consider - // it to be "huge". - static size_t MinSize() { + // it to be "notable". + static size_t notableSize() { return js::MemoryReportingSundriesThreshold(); } - // A string's size in memory is not necessarily equal to twice its length - // because the allocator and the JS engine both may round up. - size_t length; - size_t size; + char *buffer; - // We record the first 32 chars of the escaped string here. (We escape the - // string so we can use a char[] instead of a jschar[] here. - char buffer[32]; + private: + NotableStringInfo(const NotableStringInfo& info) MOZ_DELETE; }; -// These measurements relate directly to the JSRuntime, and not to +// These measurements relate directly to the JSRuntime, and not to zones and // compartments within it. struct RuntimeSizes { - RuntimeSizes() { memset(this, 0, sizeof(RuntimeSizes)); } +#define FOR_EACH_SIZE(macro) \ + macro(_, _, object) \ + macro(_, _, atomsTable) \ + macro(_, _, contexts) \ + macro(_, _, dtoa) \ + macro(_, _, temporary) \ + macro(_, _, regexpData) \ + macro(_, _, interpreterStack) \ + macro(_, _, gcMarker) \ + macro(_, _, mathCache) \ + macro(_, _, scriptData) \ + macro(_, _, scriptSources) - size_t object; - size_t atomsTable; - size_t contexts; - size_t dtoa; - size_t temporary; - size_t regexpData; - size_t interpreterStack; - size_t gcMarker; - size_t mathCache; - size_t scriptData; - size_t scriptSources; - - CodeSizes code; -}; - -struct ZoneStats -{ - ZoneStats() - : extra(NULL), - gcHeapArenaAdmin(0), - gcHeapUnusedGcThings(0), - gcHeapStringsNormal(0), - gcHeapStringsShort(0), - gcHeapLazyScripts(0), - gcHeapTypeObjects(0), - gcHeapIonCodes(0), - stringCharsNonHuge(0), - lazyScripts(0), - typeObjects(0), - typePool(0), - hugeStrings() + RuntimeSizes() + : FOR_EACH_SIZE(ZERO_SIZE) + code() {} - ZoneStats(const ZoneStats &other) - : extra(other.extra), - gcHeapArenaAdmin(other.gcHeapArenaAdmin), - gcHeapUnusedGcThings(other.gcHeapUnusedGcThings), - gcHeapStringsNormal(other.gcHeapStringsNormal), - gcHeapStringsShort(other.gcHeapStringsShort), - gcHeapLazyScripts(other.gcHeapLazyScripts), - gcHeapTypeObjects(other.gcHeapTypeObjects), - gcHeapIonCodes(other.gcHeapIonCodes), - stringCharsNonHuge(other.stringCharsNonHuge), - lazyScripts(other.lazyScripts), - typeObjects(other.typeObjects), - typePool(other.typePool), - hugeStrings() - { - hugeStrings.appendAll(other.hugeStrings); + FOR_EACH_SIZE(DECL_SIZE) + CodeSizes code; + +#undef FOR_EACH_SIZE +}; + +struct ZoneStats : js::ZoneStatsPod +{ + ZoneStats() { + strings.init(); } - // Add other's numbers to this object's numbers. - void add(ZoneStats &other) { - #define ADD(x) this->x += other.x + ZoneStats(mozilla::MoveRef other) + : ZoneStatsPod(other), + strings(mozilla::OldMove(other->strings)), + notableStrings(mozilla::OldMove(other->notableStrings)) + {} - ADD(gcHeapArenaAdmin); - ADD(gcHeapUnusedGcThings); + // Add other's numbers to this object's numbers. Both objects' + // notableStrings vectors must be empty at this point, because we can't + // merge them. (A NotableStringInfo contains only a prefix of the string, + // so we can't tell whether two NotableStringInfo objects correspond to the + // same string.) + void add(const ZoneStats &other) { + ZoneStatsPod::add(other); - ADD(gcHeapStringsNormal); - ADD(gcHeapStringsShort); - ADD(gcHeapLazyScripts); - ADD(gcHeapTypeObjects); - ADD(gcHeapIonCodes); + MOZ_ASSERT(notableStrings.empty()); + MOZ_ASSERT(other.notableStrings.empty()); - ADD(stringCharsNonHuge); - ADD(lazyScripts); - ADD(typeObjects); - ADD(typePool); - - #undef ADD - - hugeStrings.appendAll(other.hugeStrings); + for (StringsHashMap::Range r = other.strings.all(); !r.empty(); r.popFront()) { + StringsHashMap::AddPtr p = strings.lookupForAdd(r.front().key); + if (p) { + // We've seen this string before; add its size to our tally. + p->value.add(r.front().value); + } else { + // We haven't seen this string before; add it to the hashtable. + strings.add(p, r.front().key, r.front().value); + } + } } - // This field can be used by embedders. - void *extra; + size_t sizeOfLiveGCThings() const { + size_t n = ZoneStatsPod::sizeOfLiveGCThings(); + for (size_t i = 0; i < notableStrings.length(); i++) { + const JS::NotableStringInfo& info = notableStrings[i]; + n += info.totalGCHeapSizeOf(); + } + return n; + } - size_t gcHeapArenaAdmin; - size_t gcHeapUnusedGcThings; + typedef js::HashMap StringsHashMap; - size_t gcHeapStringsNormal; - size_t gcHeapStringsShort; - - size_t gcHeapLazyScripts; - size_t gcHeapTypeObjects; - size_t gcHeapIonCodes; - - size_t stringCharsNonHuge; - size_t lazyScripts; - size_t typeObjects; - size_t typePool; - - js::Vector hugeStrings; - - // The size of all the live things in the GC heap that don't belong to any - // compartment. - size_t GCHeapThingsSize(); + StringsHashMap strings; + js::Vector notableStrings; }; struct CompartmentStats { +#define FOR_EACH_SIZE(macro) \ + macro(Objects, IsLiveGCThing, objectsGCHeapOrdinary) \ + macro(Objects, IsLiveGCThing, objectsGCHeapFunction) \ + macro(Objects, IsLiveGCThing, objectsGCHeapDenseArray) \ + macro(Objects, IsLiveGCThing, objectsGCHeapSlowArray) \ + macro(Objects, IsLiveGCThing, objectsGCHeapCrossCompartmentWrapper) \ + macro(Private, NotLiveGCThing, objectsPrivate) \ + macro(Other, IsLiveGCThing, shapesGCHeapTreeGlobalParented) \ + macro(Other, IsLiveGCThing, shapesGCHeapTreeNonGlobalParented) \ + macro(Other, IsLiveGCThing, shapesGCHeapDict) \ + macro(Other, IsLiveGCThing, shapesGCHeapBase) \ + macro(Other, NotLiveGCThing, shapesMallocHeapTreeTables) \ + macro(Other, NotLiveGCThing, shapesMallocHeapDictTables) \ + macro(Other, NotLiveGCThing, shapesMallocHeapTreeShapeKids) \ + macro(Other, NotLiveGCThing, shapesMallocHeapCompartmentTables) \ + macro(Other, IsLiveGCThing, scriptsGCHeap) \ + macro(Other, NotLiveGCThing, scriptsMallocHeapData) \ + macro(Other, NotLiveGCThing, baselineData) \ + macro(Other, NotLiveGCThing, baselineStubsFallback) \ + macro(Other, NotLiveGCThing, baselineStubsOptimized) \ + macro(Other, NotLiveGCThing, ionData) \ + macro(Other, NotLiveGCThing, typeInferenceTypeScripts) \ + macro(Other, NotLiveGCThing, typeInferencePendingArrays) \ + macro(Other, NotLiveGCThing, typeInferenceAllocationSiteTables) \ + macro(Other, NotLiveGCThing, typeInferenceArrayTypeTables) \ + macro(Other, NotLiveGCThing, typeInferenceObjectTypeTables) \ + macro(Other, NotLiveGCThing, compartmentObject) \ + macro(Other, NotLiveGCThing, crossCompartmentWrappersTable) \ + macro(Other, NotLiveGCThing, regexpCompartment) \ + macro(Other, NotLiveGCThing, debuggeesSet) + CompartmentStats() - : extra(NULL), - gcHeapObjectsOrdinary(0), - gcHeapObjectsFunction(0), - gcHeapObjectsDenseArray(0), - gcHeapObjectsSlowArray(0), - gcHeapObjectsCrossCompartmentWrapper(0), - gcHeapShapesTreeGlobalParented(0), - gcHeapShapesTreeNonGlobalParented(0), - gcHeapShapesDict(0), - gcHeapShapesBase(0), - gcHeapScripts(0), + : FOR_EACH_SIZE(ZERO_SIZE) objectsExtra(), - shapesExtraTreeTables(0), - shapesExtraDictTables(0), - shapesExtraTreeShapeKids(0), - shapesCompartmentTables(0), - scriptData(0), - baselineData(0), - baselineStubsFallback(0), - baselineStubsOptimized(0), - ionData(0), - compartmentObject(0), - crossCompartmentWrappersTable(0), - regexpCompartment(0), - debuggeesSet(0), - typeInference() + extra() {} CompartmentStats(const CompartmentStats &other) - : extra(other.extra), - gcHeapObjectsOrdinary(other.gcHeapObjectsOrdinary), - gcHeapObjectsFunction(other.gcHeapObjectsFunction), - gcHeapObjectsDenseArray(other.gcHeapObjectsDenseArray), - gcHeapObjectsSlowArray(other.gcHeapObjectsSlowArray), - gcHeapObjectsCrossCompartmentWrapper(other.gcHeapObjectsCrossCompartmentWrapper), - gcHeapShapesTreeGlobalParented(other.gcHeapShapesTreeGlobalParented), - gcHeapShapesTreeNonGlobalParented(other.gcHeapShapesTreeNonGlobalParented), - gcHeapShapesDict(other.gcHeapShapesDict), - gcHeapShapesBase(other.gcHeapShapesBase), - gcHeapScripts(other.gcHeapScripts), + : FOR_EACH_SIZE(COPY_OTHER_SIZE) objectsExtra(other.objectsExtra), - shapesExtraTreeTables(other.shapesExtraTreeTables), - shapesExtraDictTables(other.shapesExtraDictTables), - shapesExtraTreeShapeKids(other.shapesExtraTreeShapeKids), - shapesCompartmentTables(other.shapesCompartmentTables), - scriptData(other.scriptData), - baselineData(other.baselineData), - baselineStubsFallback(other.baselineStubsFallback), - baselineStubsOptimized(other.baselineStubsOptimized), - ionData(other.ionData), - compartmentObject(other.compartmentObject), - crossCompartmentWrappersTable(other.crossCompartmentWrappersTable), - regexpCompartment(other.regexpCompartment), - debuggeesSet(other.debuggeesSet), - typeInference(other.typeInference) - { + extra(other.extra) + {} + + void add(const CompartmentStats &other) { + FOR_EACH_SIZE(ADD_OTHER_SIZE) + objectsExtra.add(other.objectsExtra); + // Do nothing with |extra|. } - // This field can be used by embedders. - void *extra; - - // If you add a new number, remember to update the constructors, add(), and - // maybe gcHeapThingsSize()! - size_t gcHeapObjectsOrdinary; - size_t gcHeapObjectsFunction; - size_t gcHeapObjectsDenseArray; - size_t gcHeapObjectsSlowArray; - size_t gcHeapObjectsCrossCompartmentWrapper; - size_t gcHeapShapesTreeGlobalParented; - size_t gcHeapShapesTreeNonGlobalParented; - size_t gcHeapShapesDict; - size_t gcHeapShapesBase; - size_t gcHeapScripts; - ObjectsExtraSizes objectsExtra; - - size_t shapesExtraTreeTables; - size_t shapesExtraDictTables; - size_t shapesExtraTreeShapeKids; - size_t shapesCompartmentTables; - size_t scriptData; - size_t baselineData; - size_t baselineStubsFallback; - size_t baselineStubsOptimized; - size_t ionData; - size_t compartmentObject; - size_t crossCompartmentWrappersTable; - size_t regexpCompartment; - size_t debuggeesSet; - - TypeInferenceSizes typeInference; - - // Add cStats's numbers to this object's numbers. - void add(CompartmentStats &cStats) { - #define ADD(x) this->x += cStats.x - - ADD(gcHeapObjectsOrdinary); - ADD(gcHeapObjectsFunction); - ADD(gcHeapObjectsDenseArray); - ADD(gcHeapObjectsSlowArray); - ADD(gcHeapObjectsCrossCompartmentWrapper); - ADD(gcHeapShapesTreeGlobalParented); - ADD(gcHeapShapesTreeNonGlobalParented); - ADD(gcHeapShapesDict); - ADD(gcHeapShapesBase); - ADD(gcHeapScripts); - objectsExtra.add(cStats.objectsExtra); - - ADD(shapesExtraTreeTables); - ADD(shapesExtraDictTables); - ADD(shapesExtraTreeShapeKids); - ADD(shapesCompartmentTables); - ADD(scriptData); - ADD(baselineData); - ADD(baselineStubsFallback); - ADD(baselineStubsOptimized); - ADD(ionData); - ADD(compartmentObject); - ADD(crossCompartmentWrappersTable); - ADD(regexpCompartment); - ADD(debuggeesSet); - - #undef ADD - - typeInference.add(cStats.typeInference); + size_t sizeOfLiveGCThings() const { + size_t n = 0; + FOR_EACH_SIZE(ADD_SIZE_TO_N_IF_LIVE_GC_THING) + n += objectsExtra.sizeOfLiveGCThings(); + // Do nothing with |extra|. + return n; } - // The size of all the live things in the GC heap. - size_t GCHeapThingsSize(); + void addToTabSizes(TabSizes *sizes) const { + FOR_EACH_SIZE(ADD_TO_TAB_SIZES); + objectsExtra.addToTabSizes(sizes); + // Do nothing with |extra|. + } + + FOR_EACH_SIZE(DECL_SIZE) + ObjectsExtraSizes objectsExtra; + void *extra; // This field can be used by embedders. + +#undef FOR_EACH_SIZE }; struct RuntimeStats { +#define FOR_EACH_SIZE(macro) \ + macro(_, _, gcHeapChunkTotal) \ + macro(_, _, gcHeapDecommittedArenas) \ + macro(_, _, gcHeapUnusedChunks) \ + macro(_, _, gcHeapUnusedArenas) \ + macro(_, _, gcHeapChunkAdmin) \ + macro(_, _, gcHeapGCThings) \ + RuntimeStats(mozilla::MallocSizeOf mallocSizeOf) - : runtime(), - gcHeapChunkTotal(0), - gcHeapDecommittedArenas(0), - gcHeapUnusedChunks(0), - gcHeapUnusedArenas(0), - gcHeapUnusedGcThings(0), - gcHeapChunkAdmin(0), - gcHeapGcThings(0), + : FOR_EACH_SIZE(ZERO_SIZE) + runtime(), cTotals(), zTotals(), compartmentStatsVector(), zoneStatsVector(), - currZoneStats(NULL), + currZoneStats(nullptr), mallocSizeOf_(mallocSizeOf) {} - RuntimeSizes runtime; - - // If you add a new number, remember to update the constructor! - // Here's a useful breakdown of the GC heap. // // - rtStats.gcHeapChunkTotal @@ -394,28 +473,24 @@ struct RuntimeStats // - unused bytes // - rtStats.gcHeapUnusedChunks (empty chunks) // - rtStats.gcHeapUnusedArenas (empty arenas within non-empty chunks) - // - rtStats.total.gcHeapUnusedGcThings (empty GC thing slots within non-empty arenas) + // - rtStats.zTotals.unusedGCThings (empty GC thing slots within non-empty arenas) // - used bytes // - rtStats.gcHeapChunkAdmin - // - rtStats.total.gcHeapArenaAdmin - // - rtStats.gcHeapGcThings (in-use GC things) + // - rtStats.zTotals.gcHeapArenaAdmin + // - rtStats.gcHeapGCThings (in-use GC things) + // == rtStats.zTotals.sizeOfLiveGCThings() + rtStats.cTotals.sizeOfLiveGCThings() // // It's possible that some arenas in empty chunks may be decommitted, but // we don't count those under rtStats.gcHeapDecommittedArenas because (a) // it's rare, and (b) this means that rtStats.gcHeapUnusedChunks is a // multiple of the chunk size, which is good. - size_t gcHeapChunkTotal; - size_t gcHeapDecommittedArenas; - size_t gcHeapUnusedChunks; - size_t gcHeapUnusedArenas; - size_t gcHeapUnusedGcThings; - size_t gcHeapChunkAdmin; - size_t gcHeapGcThings; + FOR_EACH_SIZE(DECL_SIZE) - // The sum of all compartment's measurements. - CompartmentStats cTotals; - ZoneStats zTotals; + RuntimeSizes runtime; + + CompartmentStats cTotals; // The sum of this runtime's compartments' measurements. + ZoneStats zTotals; // The sum of this runtime's zones' measurements. js::Vector compartmentStatsVector; js::Vector zoneStatsVector; @@ -426,6 +501,8 @@ struct RuntimeStats virtual void initExtraCompartmentStats(JSCompartment *c, CompartmentStats *cstats) = 0; virtual void initExtraZoneStats(JS::Zone *zone, ZoneStats *zstats) = 0; + +#undef FOR_EACH_SIZE }; class ObjectPrivateVisitor @@ -437,7 +514,7 @@ class ObjectPrivateVisitor // A callback that gets a JSObject's nsISupports pointer, if it has one. // Note: this function does *not* addref |iface|. - typedef JSBool(*GetISupportsFun)(JSObject *obj, nsISupports **iface); + typedef bool(*GetISupportsFun)(JSObject *obj, nsISupports **iface); GetISupportsFun getISupports_; ObjectPrivateVisitor(GetISupportsFun getISupports) @@ -457,6 +534,17 @@ UserCompartmentCount(JSRuntime *rt); extern JS_PUBLIC_API(size_t) PeakSizeOfTemporary(const JSRuntime *rt); +extern JS_PUBLIC_API(bool) +AddSizeOfTab(JSRuntime *rt, JSObject *obj, mozilla::MallocSizeOf mallocSizeOf, + ObjectPrivateVisitor *opv, TabSizes *sizes); + } // namespace JS +#undef DECL_SIZE +#undef ZERO_SIZE +#undef COPY_OTHER_SIZE +#undef ADD_OTHER_SIZE +#undef ADD_SIZE_TO_N_IF_LIVE_GC_THING +#undef ADD_TO_TAB_SIZES + #endif /* js_MemoryMetrics_h */ diff --git a/external/spidermonkey/include/win32/jsdbgapi.h b/external/spidermonkey/include/win32/js/OldDebugAPI.h similarity index 77% rename from external/spidermonkey/include/win32/jsdbgapi.h rename to external/spidermonkey/include/win32/js/OldDebugAPI.h index 0ce7101337..5e5bdf38d7 100644 --- a/external/spidermonkey/include/win32/jsdbgapi.h +++ b/external/spidermonkey/include/win32/js/OldDebugAPI.h @@ -4,13 +4,24 @@ * 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/. */ -#ifndef jsdbgapi_h -#define jsdbgapi_h +#ifndef js_OldDebugAPI_h +#define js_OldDebugAPI_h + /* * JS debugger API. */ -#include "jsprvtd.h" +#include "mozilla/NullPtr.h" + +#include "jsbytecode.h" + +#include "js/CallArgs.h" +#include "js/TypeDecls.h" + +class JSAtom; +class JSFreeOp; + +namespace js { class StackFrame; } namespace JS { @@ -34,21 +45,68 @@ extern JS_PUBLIC_API(void) FreeStackDescription(JSContext *cx, StackDescription *desc); extern JS_PUBLIC_API(char *) -FormatStackDump(JSContext *cx, char *buf, - JSBool showArgs, JSBool showLocals, - JSBool showThisProps); +FormatStackDump(JSContext *cx, char *buf, bool showArgs, bool showLocals, bool showThisProps); } # ifdef DEBUG -JS_FRIEND_API(void) js_DumpValue(const js::Value &val); +JS_FRIEND_API(void) js_DumpValue(const JS::Value &val); JS_FRIEND_API(void) js_DumpId(jsid id); -JS_FRIEND_API(void) js_DumpStackFrame(JSContext *cx, js::StackFrame *start = NULL); +JS_FRIEND_API(void) js_DumpStackFrame(JSContext *cx, js::StackFrame *start = nullptr); # endif JS_FRIEND_API(void) js_DumpBacktrace(JSContext *cx); +typedef enum JSTrapStatus { + JSTRAP_ERROR, + JSTRAP_CONTINUE, + JSTRAP_RETURN, + JSTRAP_THROW, + JSTRAP_LIMIT +} JSTrapStatus; + +typedef JSTrapStatus +(* JSTrapHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + JS::Value closure); + +typedef JSTrapStatus +(* JSInterruptHook)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + void *closure); + +typedef JSTrapStatus +(* JSDebuggerHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + void *closure); + +typedef JSTrapStatus +(* JSThrowHook)(JSContext *cx, JSScript *script, jsbytecode *pc, JS::Value *rval, + void *closure); + +typedef bool +(* JSWatchPointHandler)(JSContext *cx, JSObject *obj, jsid id, JS::Value old, + JS::Value *newp, void *closure); + +/* called just after script creation */ +typedef void +(* JSNewScriptHook)(JSContext *cx, + const char *filename, /* URL of script */ + unsigned lineno, /* first line */ + JSScript *script, + JSFunction *fun, + void *callerdata); + +/* called just before script destruction */ +typedef void +(* JSDestroyScriptHook)(JSFreeOp *fop, + JSScript *script, + void *callerdata); + +typedef void +(* JSSourceHandler)(const char *filename, unsigned lineno, const jschar *str, + size_t length, void **listenerTSData, void *closure); + + + extern JS_PUBLIC_API(JSCompartment *) JS_EnterCompartmentOfScript(JSContext *cx, JSScript *target); @@ -60,7 +118,7 @@ JS_DecompileScript(JSContext *cx, JSScript *script, const char *name, unsigned i * be able to support compartment-wide debugging. */ extern JS_PUBLIC_API(void) -JS_SetRuntimeDebugMode(JSRuntime *rt, JSBool debug); +JS_SetRuntimeDebugMode(JSRuntime *rt, bool debug); /* * Debug mode is a compartment-wide mode that enables a debugger to attach @@ -73,42 +131,42 @@ JS_SetRuntimeDebugMode(JSRuntime *rt, JSBool debug); */ /* Get current state of debugging mode. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_GetDebugMode(JSContext *cx); /* * Turn on/off debugging mode for all compartments. This returns false if any code * from any of the runtime's compartments is running or on the stack. */ -JS_FRIEND_API(JSBool) -JS_SetDebugModeForAllCompartments(JSContext *cx, JSBool debug); +JS_FRIEND_API(bool) +JS_SetDebugModeForAllCompartments(JSContext *cx, bool debug); /* * Turn on/off debugging mode for a single compartment. This should only be * used when no code from this compartment is running or on the stack in any * thread. */ -JS_FRIEND_API(JSBool) -JS_SetDebugModeForCompartment(JSContext *cx, JSCompartment *comp, JSBool debug); +JS_FRIEND_API(bool) +JS_SetDebugModeForCompartment(JSContext *cx, JSCompartment *comp, bool debug); /* * Turn on/off debugging mode for a context's compartment. */ -JS_FRIEND_API(JSBool) -JS_SetDebugMode(JSContext *cx, JSBool debug); +JS_FRIEND_API(bool) +JS_SetDebugMode(JSContext *cx, bool debug); /* Turn on single step mode. */ -extern JS_PUBLIC_API(JSBool) -JS_SetSingleStepMode(JSContext *cx, JSScript *script, JSBool singleStep); +extern JS_PUBLIC_API(bool) +JS_SetSingleStepMode(JSContext *cx, JSScript *script, bool singleStep); /* The closure argument will be marked. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetTrap(JSContext *cx, JSScript *script, jsbytecode *pc, - JSTrapHandler handler, jsval closure); + JSTrapHandler handler, JS::Value closure); extern JS_PUBLIC_API(void) JS_ClearTrap(JSContext *cx, JSScript *script, jsbytecode *pc, - JSTrapHandler *handlerp, jsval *closurep); + JSTrapHandler *handlerp, JS::Value *closurep); extern JS_PUBLIC_API(void) JS_ClearScriptTraps(JSRuntime *rt, JSScript *script); @@ -116,28 +174,25 @@ JS_ClearScriptTraps(JSRuntime *rt, JSScript *script); extern JS_PUBLIC_API(void) JS_ClearAllTrapsForCompartment(JSContext *cx); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetInterrupt(JSRuntime *rt, JSInterruptHook handler, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_ClearInterrupt(JSRuntime *rt, JSInterruptHook *handlerp, void **closurep); /************************************************************************/ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetWatchPoint(JSContext *cx, JSObject *obj, jsid id, JSWatchPointHandler handler, JSObject *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_ClearWatchPoint(JSContext *cx, JSObject *obj, jsid id, JSWatchPointHandler *handlerp, JSObject **closurep); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_ClearWatchPointsForObject(JSContext *cx, JSObject *obj); -extern JS_PUBLIC_API(JSBool) -JS_ClearAllWatchPoints(JSContext *cx); - /************************************************************************/ // Raw JSScript* because this needs to be callable from a signal handler. @@ -150,7 +205,7 @@ JS_LineNumberToPC(JSContext *cx, JSScript *script, unsigned lineno); extern JS_PUBLIC_API(jsbytecode *) JS_EndPC(JSContext *cx, JSScript *script); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_GetLinePCs(JSContext *cx, JSScript *script, unsigned startLine, unsigned maxLines, unsigned* count, unsigned** lines, jsbytecode*** pcs); @@ -158,7 +213,7 @@ JS_GetLinePCs(JSContext *cx, JSScript *script, extern JS_PUBLIC_API(unsigned) JS_GetFunctionArgumentCount(JSContext *cx, JSFunction *fun); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_FunctionHasLocalNames(JSContext *cx, JSFunction *fun); /* @@ -230,9 +285,8 @@ JS_GetScriptIsSelfHosted(JSScript *script); /************************************************************************/ /* - * Hook setters for script creation and destruction, see jsprvtd.h for the - * typedefs. These macros provide binary compatibility and newer, shorter - * synonyms. + * Hook setters for script creation and destruction. These macros provide + * binary compatibility and newer, shorter synonyms. */ #define JS_SetNewScriptHook JS_SetNewScriptHookProc #define JS_SetDestroyScriptHook JS_SetDestroyScriptHookProc @@ -247,11 +301,11 @@ JS_SetDestroyScriptHook(JSRuntime *rt, JSDestroyScriptHook hook, /************************************************************************/ typedef struct JSPropertyDesc { - jsval id; /* primary id, atomized string, or int */ - jsval value; /* property value */ + JS::Value id; /* primary id, atomized string, or int */ + JS::Value value; /* property value */ uint8_t flags; /* flags, see below */ uint8_t spare; /* unused */ - jsval alias; /* alias id if JSPD_ALIAS flag */ + JS::Value alias; /* alias id if JSPD_ALIAS flag */ } JSPropertyDesc; #define JSPD_ENUMERATE 0x01 /* visible to for/in loop */ @@ -260,7 +314,7 @@ typedef struct JSPropertyDesc { #define JSPD_ALIAS 0x08 /* property has an alias id */ #define JSPD_EXCEPTION 0x40 /* exception occurred fetching the property, */ /* value is exception */ -#define JSPD_ERROR 0x80 /* native getter returned JS_FALSE without */ +#define JSPD_ERROR 0x80 /* native getter returned false without */ /* throwing an exception */ typedef struct JSPropertyDescArray { @@ -270,7 +324,7 @@ typedef struct JSPropertyDescArray { typedef struct JSScopeProperty JSScopeProperty; -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_GetPropertyDescArray(JSContext *cx, JSObject *obj, JSPropertyDescArray *pda); extern JS_PUBLIC_API(void) @@ -358,8 +412,8 @@ class JS_PUBLIC_API(JSBrokenFrameIterator) * or function call: just before execution begins and just after it finishes. * In both cases the 'current' frame is that of the executing code. * - * The 'before' param is JS_TRUE for the hook invocation before the execution - * and JS_FALSE for the invocation after the code has run. + * The 'before' param is true for the hook invocation before the execution + * and false for the invocation after the code has run. * * The 'ok' param is significant only on the post execution invocation to * signify whether or not the code completed 'normally'. @@ -373,14 +427,14 @@ class JS_PUBLIC_API(JSBrokenFrameIterator) * in 'closure' to cause the 'after' invocation to be called with the same * 'closure' value as the 'before'. * - * Returning NULL in the 'before' hook will cause the 'after' hook *not* to + * Returning nullptr in the 'before' hook will cause the 'after' hook *not* to * be called. */ typedef void * (* JSInterpreterHook)(JSContext *cx, JSAbstractFramePtr frame, bool isConstructing, - JSBool before, JSBool *ok, void *closure); + bool before, bool *ok, void *closure); -typedef JSBool +typedef bool (* JSDebugErrorHook)(JSContext *cx, const char *message, JSErrorReport *report, void *closure); @@ -407,22 +461,22 @@ typedef struct JSDebugHooks { /************************************************************************/ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetDebuggerHandler(JSRuntime *rt, JSDebuggerHandler hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetSourceHandler(JSRuntime *rt, JSSourceHandler handler, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetExecuteHook(JSRuntime *rt, JSInterpreterHook hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetCallHook(JSRuntime *rt, JSInterpreterHook hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetThrowHook(JSRuntime *rt, JSThrowHook hook, void *closure); -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_SetDebugErrorHook(JSRuntime *rt, JSDebugErrorHook hook, void *closure); /************************************************************************/ @@ -433,11 +487,11 @@ JS_GetGlobalDebugHooks(JSRuntime *rt); /** * Add various profiling-related functions as properties of the given object. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_DefineProfilingFunctions(JSContext *cx, JSObject *obj); /* Defined in vm/Debugger.cpp. */ -extern JS_PUBLIC_API(JSBool) +extern JS_PUBLIC_API(bool) JS_DefineDebuggerObject(JSContext *cx, JSObject *obj); extern JS_PUBLIC_API(void) @@ -452,8 +506,13 @@ JS_DumpPCCounts(JSContext *cx, JSScript *script); extern JS_PUBLIC_API(void) JS_DumpCompartmentPCCounts(JSContext *cx); +namespace js { +extern JS_FRIEND_API(bool) +CanCallContextDebugHandler(JSContext *cx); +} + /* Call the context debug handler on the topmost scripted frame. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_CallContextDebugHandler(JSContext *cx); -#endif /* jsdbgapi_h */ +#endif /* js_OldDebugAPI_h */ diff --git a/external/spidermonkey/include/win32/js/ProfilingStack.h b/external/spidermonkey/include/win32/js/ProfilingStack.h new file mode 100644 index 0000000000..c67f98952c --- /dev/null +++ b/external/spidermonkey/include/win32/js/ProfilingStack.h @@ -0,0 +1,95 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_ProfilingStack_h +#define js_ProfilingStack_h + +#include "mozilla/NullPtr.h" + +#include "jsbytecode.h" +#include "jstypes.h" + +#include "js/Utility.h" + +struct JSRuntime; + +namespace js { + +// A call stack can be specified to the JS engine such that all JS entry/exits +// to functions push/pop an entry to/from the specified stack. +// +// For more detailed information, see vm/SPSProfiler.h. +// +class ProfileEntry +{ + // All fields are marked volatile to prevent the compiler from re-ordering + // instructions. Namely this sequence: + // + // entry[size] = ...; + // size++; + // + // If the size modification were somehow reordered before the stores, then + // if a sample were taken it would be examining bogus information. + // + // A ProfileEntry represents both a C++ profile entry and a JS one. Both use + // the string as a description, but JS uses the sp as nullptr to indicate + // that it is a JS entry. The script_ is then only ever examined for a JS + // entry, and the idx is used by both, but with different meanings. + // + const char * volatile string; // Descriptive string of this entry + void * volatile sp; // Relevant stack pointer for the entry + JSScript * volatile script_; // if js(), non-null script which is running + int32_t volatile idx; // if js(), idx of pc, otherwise line number + + public: + // All of these methods are marked with the 'volatile' keyword because SPS's + // representation of the stack is stored such that all ProfileEntry + // instances are volatile. These methods would not be available unless they + // were marked as volatile as well. + + bool js() volatile { + JS_ASSERT_IF(sp == nullptr, script_ != nullptr); + return sp == nullptr; + } + + uint32_t line() volatile { JS_ASSERT(!js()); return idx; } + JSScript *script() volatile { JS_ASSERT(js()); return script_; } + void *stackAddress() volatile { return sp; } + const char *label() volatile { return string; } + + void setLine(uint32_t aLine) volatile { JS_ASSERT(!js()); idx = aLine; } + void setLabel(const char *aString) volatile { string = aString; } + void setStackAddress(void *aSp) volatile { sp = aSp; } + void setScript(JSScript *aScript) volatile { script_ = aScript; } + + // We can't know the layout of JSScript, so look in vm/SPSProfiler.cpp. + JS_FRIEND_API(jsbytecode *) pc() volatile; + JS_FRIEND_API(void) setPC(jsbytecode *pc) volatile; + + static size_t offsetOfString() { return offsetof(ProfileEntry, string); } + static size_t offsetOfStackAddress() { return offsetof(ProfileEntry, sp); } + static size_t offsetOfPCIdx() { return offsetof(ProfileEntry, idx); } + static size_t offsetOfScript() { return offsetof(ProfileEntry, script_); } + + // The index used in the entry can either be a line number or the offset of + // a pc into a script's code. To signify a nullptr pc, use a -1 index. This + // is checked against in pc() and setPC() to set/get the right pc. + static const int32_t NullPCIndex = -1; +}; + +JS_FRIEND_API(void) +SetRuntimeProfilingStack(JSRuntime *rt, ProfileEntry *stack, uint32_t *size, + uint32_t max); + +JS_FRIEND_API(void) +EnableRuntimeProfilingStack(JSRuntime *rt, bool enabled); + +JS_FRIEND_API(jsbytecode*) +ProfilingGetPC(JSRuntime *rt, JSScript *script, void *ip); + +} // namespace js + +#endif /* js_ProfilingStack_h */ diff --git a/external/spidermonkey/include/win32/js/PropertyKey.h b/external/spidermonkey/include/win32/js/PropertyKey.h index c949db13a5..1f90653b40 100644 --- a/external/spidermonkey/include/win32/js/PropertyKey.h +++ b/external/spidermonkey/include/win32/js/PropertyKey.h @@ -9,12 +9,9 @@ #ifndef js_PropertyKey_h #define js_PropertyKey_h -#include "mozilla/Attributes.h" - +#include "js/TypeDecls.h" #include "js/Value.h" -struct JSContext; - namespace JS { class PropertyKey; diff --git a/external/spidermonkey/include/win32/js/RequiredDefines.h b/external/spidermonkey/include/win32/js/RequiredDefines.h index 6af9ca871b..3c8f429132 100644 --- a/external/spidermonkey/include/win32/js/RequiredDefines.h +++ b/external/spidermonkey/include/win32/js/RequiredDefines.h @@ -15,9 +15,17 @@ /* * The c99 defining the limit macros (UINT32_MAX for example), says: - * C++ implementations should define these macros only when __STDC_LIMIT_MACROS - * is defined before is included. + * + * C++ implementations should define these macros only when + * __STDC_LIMIT_MACROS is defined before is included. + * + * The same also occurs with __STDC_CONSTANT_MACROS for the constant macros + * (INT8_C for example) used to specify a literal constant of the proper type, + * and with __STDC_FORMAT_MACROS for the format macros (PRId32 for example) used + * with the fprintf function family. */ #define __STDC_LIMIT_MACROS +#define __STDC_CONSTANT_MACROS +#define __STDC_FORMAT_MACROS #endif /* js_RequiredDefines_h */ diff --git a/external/spidermonkey/include/win32/js/RootingAPI.h b/external/spidermonkey/include/win32/js/RootingAPI.h index c4a5925ae7..82863f020a 100644 --- a/external/spidermonkey/include/win32/js/RootingAPI.h +++ b/external/spidermonkey/include/win32/js/RootingAPI.h @@ -8,12 +8,14 @@ #define js_RootingAPI_h #include "mozilla/GuardObjects.h" +#include "mozilla/NullPtr.h" #include "mozilla/TypeTraits.h" -#include "js/Utility.h" - #include "jspubtd.h" +#include "js/TypeDecls.h" +#include "js/Utility.h" + /* * Moving GC Stack Rooting * @@ -97,7 +99,6 @@ namespace js { -class Module; class ScriptSourceObject; template @@ -116,13 +117,13 @@ template class HeapBase {}; /* - * js::NullPtr acts like a NULL pointer in contexts that require a Handle. + * js::NullPtr acts like a nullptr pointer in contexts that require a Handle. * * Handle provides an implicit constructor for js::NullPtr so that, given: * foo(Handle h); * callers can simply write: * foo(js::NullPtr()); - * which avoids creating a Rooted just to pass NULL. + * which avoids creating a Rooted just to pass nullptr. * * This is the SpiderMonkey internal variant. js::NullPtr should be used in * preference to JS::NullPtr to avoid the GOT access required for JS_PUBLIC_API @@ -143,9 +144,6 @@ namespace JS { template class Rooted; -template class Handle; -template class MutableHandle; - /* This is exposing internal state of the GC for inlining purposes. */ JS_FRIEND_API(bool) isGCEnabled(); @@ -155,13 +153,13 @@ CheckStackRoots(JSContext *cx); #endif /* - * JS::NullPtr acts like a NULL pointer in contexts that require a Handle. + * JS::NullPtr acts like a nullptr pointer in contexts that require a Handle. * * Handle provides an implicit constructor for JS::NullPtr so that, given: * foo(Handle h); * callers can simply write: * foo(JS::NullPtr()); - * which avoids creating a Rooted just to pass NULL. + * which avoids creating a Rooted just to pass nullptr. */ struct JS_PUBLIC_API(NullPtr) { @@ -377,7 +375,7 @@ class TenuredHeap : public js::HeapBase template class MOZ_NONHEAP_CLASS Handle : public js::HandleBase { - friend class MutableHandle; + friend class JS::MutableHandle; public: /* Creates a handle from a handle of a type convertible to T. */ @@ -390,14 +388,14 @@ class MOZ_NONHEAP_CLASS Handle : public js::HandleBase ptr = reinterpret_cast(handle.address()); } - /* Create a handle for a NULL pointer. */ + /* Create a handle for a nullptr pointer. */ Handle(js::NullPtr) { static_assert(mozilla::IsPointer::value, "js::NullPtr overload not valid for non-pointer types"); ptr = reinterpret_cast(&js::NullPtr::constNullValue); } - /* Create a handle for a NULL pointer. */ + /* Create a handle for a nullptr pointer. */ Handle(JS::NullPtr) { static_assert(mozilla::IsPointer::value, "JS::NullPtr overload not valid for non-pointer types"); @@ -457,24 +455,18 @@ class MOZ_NONHEAP_CLASS Handle : public js::HandleBase bool operator!=(const T &other) const { return *ptr != other; } bool operator==(const T &other) const { return *ptr == other; } + /* Change this handle to point to the same rooted location RHS does. */ + void repoint(const Handle &rhs) { ptr = rhs.address(); } + private: Handle() {} const T *ptr; - template - void operator=(S v) MOZ_DELETE; + template void operator=(S) MOZ_DELETE; + void operator=(Handle) MOZ_DELETE; }; -typedef Handle HandleObject; -typedef Handle HandleModule; -typedef Handle HandleScriptSource; -typedef Handle HandleFunction; -typedef Handle HandleScript; -typedef Handle HandleString; -typedef Handle HandleId; -typedef Handle HandleValue; - /* * Similar to a handle, but the underlying storage can be changed. This is * useful for outparams. @@ -488,6 +480,10 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase { public: inline MutableHandle(Rooted *root); + MutableHandle(int) MOZ_DELETE; +#ifdef MOZ_HAVE_CXX11_NULLPTR + MutableHandle(decltype(nullptr)) MOZ_DELETE; +#endif void set(T v) { JS_ASSERT(!js::GCMethods::poisoned(v)); @@ -526,13 +522,6 @@ class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase void operator=(MutableHandle other) MOZ_DELETE; }; -typedef MutableHandle MutableHandleObject; -typedef MutableHandle MutableHandleFunction; -typedef MutableHandle MutableHandleScript; -typedef MutableHandle MutableHandleString; -typedef MutableHandle MutableHandleId; -typedef MutableHandle MutableHandleValue; - #ifdef JSGC_GENERATIONAL JS_PUBLIC_API(void) HeapCellPostBarrier(js::gc::Cell **cellp); JS_PUBLIC_API(void) HeapCellRelocate(js::gc::Cell **cellp); @@ -614,7 +603,7 @@ struct RootKind template struct GCMethods { - static T *initial() { return NULL; } + static T *initial() { return nullptr; } static ThingRootKind kind() { return RootKind::rootKind(); } static bool poisoned(T *v) { return JS::IsPoisonedPtr(v); } static bool needsPostBarrier(T *v) { return v; } @@ -628,12 +617,11 @@ struct GCMethods #endif }; -// XXX: Needed for cocos2d JS Bindings -//#if defined(DEBUG) +#if defined(DEBUG) /* This helper allows us to assert that Rooted is scoped within a request. */ extern JS_PUBLIC_API(bool) IsInRequest(JSContext *cx); -//#endif +#endif } /* namespace js */ @@ -730,12 +718,15 @@ class MOZ_STACK_CLASS Rooted : public js::RootedBase init(js::PerThreadDataFriendFields::getMainThread(rt)); } - ~Rooted() { + // Note that we need to let the compiler generate the default destructor in + // non-exact-rooting builds because of a bug in the instrumented PGO builds + // using MSVC, see bug 915735 for more details. #ifdef JSGC_TRACK_EXACT_ROOTS + ~Rooted() { JS_ASSERT(*stack == reinterpret_cast*>(this)); *stack = prev; -#endif } +#endif #ifdef JSGC_TRACK_EXACT_ROOTS Rooted *previous() { return prev; } @@ -803,8 +794,6 @@ class Rooted; #endif typedef Rooted RootedObject; -typedef Rooted RootedModule; -typedef Rooted RootedScriptSource; typedef Rooted RootedFunction; typedef Rooted RootedScript; typedef Rooted RootedString; @@ -857,6 +846,10 @@ class SkipRoot void init(js::ContextFriendFields *cx, const T *ptr, size_t count) {} public: + ~SkipRoot() { + // An empty destructor is needed to avoid warnings from clang about + // unused local variables of this type. + } #endif /* DEBUG && JSGC_ROOT_ANALYSIS */ @@ -1063,7 +1056,7 @@ inline void MaybeCheckStackRoots(JSContext *cx) class CompilerRootNode { protected: - CompilerRootNode(js::gc::Cell *ptr) : next(NULL), ptr_(ptr) {} + CompilerRootNode(js::gc::Cell *ptr) : next(nullptr), ptr_(ptr) {} public: void **address() { return (void **)&ptr_; } diff --git a/external/spidermonkey/include/win32/js/StructuredClone.h b/external/spidermonkey/include/win32/js/StructuredClone.h new file mode 100644 index 0000000000..d32bdd8dd6 --- /dev/null +++ b/external/spidermonkey/include/win32/js/StructuredClone.h @@ -0,0 +1,163 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_StructuredClone_h +#define js_StructuredClone_h + +#include "mozilla/NullPtr.h" + +#include + +#include "jstypes.h" + +#include "js/RootingAPI.h" +#include "js/TypeDecls.h" +#include "js/Value.h" + +struct JSRuntime; +struct JSStructuredCloneReader; +struct JSStructuredCloneWriter; + +// API for the HTML5 internal structured cloning algorithm. + +// Read structured data from the reader r. This hook is used to read a value +// previously serialized by a call to the WriteStructuredCloneOp hook. +// +// tag and data are the pair of uint32_t values from the header. The callback +// may use the JS_Read* APIs to read any other relevant parts of the object +// from the reader r. closure is any value passed to the JS_ReadStructuredClone +// function. Return the new object on success, nullptr on error/exception. +typedef JSObject *(*ReadStructuredCloneOp)(JSContext *cx, JSStructuredCloneReader *r, + uint32_t tag, uint32_t data, void *closure); + +// Structured data serialization hook. The engine can write primitive values, +// Objects, Arrays, Dates, RegExps, TypedArrays, and ArrayBuffers. Any other +// type of object requires application support. This callback must first use +// the JS_WriteUint32Pair API to write an object header, passing a value +// greater than JS_SCTAG_USER to the tag parameter. Then it can use the +// JS_Write* APIs to write any other relevant parts of the value v to the +// writer w. closure is any value passed to the JS_WriteStructuredCLone function. +// +// Return true on success, false on error/exception. +typedef bool (*WriteStructuredCloneOp)(JSContext *cx, JSStructuredCloneWriter *w, + JS::Handle obj, void *closure); + +// This is called when JS_WriteStructuredClone is given an invalid transferable. +// To follow HTML5, the application must throw a DATA_CLONE_ERR DOMException +// with error set to one of the JS_SCERR_* values. +typedef void (*StructuredCloneErrorOp)(JSContext *cx, uint32_t errorid); + +// The maximum supported structured-clone serialization format version. Note +// that this does not need to be bumped for Transferable-only changes, since +// they are never saved to persistent storage. +#define JS_STRUCTURED_CLONE_VERSION 2 + +struct JSStructuredCloneCallbacks { + ReadStructuredCloneOp read; + WriteStructuredCloneOp write; + StructuredCloneErrorOp reportError; +}; + +// Note: if the *data contains transferable objects, it can be read only once. +JS_PUBLIC_API(bool) +JS_ReadStructuredClone(JSContext *cx, uint64_t *data, size_t nbytes, uint32_t version, + JS::MutableHandleValue vp, + const JSStructuredCloneCallbacks *optionalCallbacks, void *closure); + +// Note: On success, the caller is responsible for calling +// JS_ClearStructuredClone(*datap, nbytesp). +JS_PUBLIC_API(bool) +JS_WriteStructuredClone(JSContext *cx, JS::HandleValue v, uint64_t **datap, size_t *nbytesp, + const JSStructuredCloneCallbacks *optionalCallbacks, + void *closure, JS::HandleValue transferable); + +JS_PUBLIC_API(bool) +JS_ClearStructuredClone(const uint64_t *data, size_t nbytes); + +JS_PUBLIC_API(bool) +JS_StructuredCloneHasTransferables(const uint64_t *data, size_t nbytes, bool *hasTransferable); + +JS_PUBLIC_API(bool) +JS_StructuredClone(JSContext *cx, JS::HandleValue v, JS::MutableHandleValue vp, + const JSStructuredCloneCallbacks *optionalCallbacks, void *closure); + +// RAII sugar for JS_WriteStructuredClone. +class JS_PUBLIC_API(JSAutoStructuredCloneBuffer) { + uint64_t *data_; + size_t nbytes_; + uint32_t version_; + + public: + JSAutoStructuredCloneBuffer() + : data_(nullptr), nbytes_(0), version_(JS_STRUCTURED_CLONE_VERSION) {} + + ~JSAutoStructuredCloneBuffer() { clear(); } + + uint64_t *data() const { return data_; } + size_t nbytes() const { return nbytes_; } + + void clear(); + + // Copy some memory. It will be automatically freed by the destructor. + bool copy(const uint64_t *data, size_t nbytes, uint32_t version=JS_STRUCTURED_CLONE_VERSION); + + // Adopt some memory. It will be automatically freed by the destructor. + // data must have been allocated by the JS engine (e.g., extracted via + // JSAutoStructuredCloneBuffer::steal). + void adopt(uint64_t *data, size_t nbytes, uint32_t version=JS_STRUCTURED_CLONE_VERSION); + + // Remove the buffer so that it will not be automatically freed. + // After this, the caller is responsible for feeding the memory back to + // JSAutoStructuredCloneBuffer::adopt. + void steal(uint64_t **datap, size_t *nbytesp, uint32_t *versionp=nullptr); + + bool read(JSContext *cx, JS::MutableHandleValue vp, + const JSStructuredCloneCallbacks *optionalCallbacks=nullptr, void *closure=nullptr); + + bool write(JSContext *cx, JS::HandleValue v, + const JSStructuredCloneCallbacks *optionalCallbacks=nullptr, void *closure=nullptr); + + bool write(JSContext *cx, JS::HandleValue v, JS::HandleValue transferable, + const JSStructuredCloneCallbacks *optionalCallbacks=nullptr, void *closure=nullptr); + + // Swap ownership with another JSAutoStructuredCloneBuffer. + void swap(JSAutoStructuredCloneBuffer &other); + + private: + // Copy and assignment are not supported. + JSAutoStructuredCloneBuffer(const JSAutoStructuredCloneBuffer &other); + JSAutoStructuredCloneBuffer &operator=(const JSAutoStructuredCloneBuffer &other); +}; + +// The range of tag values the application may use for its own custom object types. +#define JS_SCTAG_USER_MIN ((uint32_t) 0xFFFF8000) +#define JS_SCTAG_USER_MAX ((uint32_t) 0xFFFFFFFF) + +#define JS_SCERR_RECURSION 0 +#define JS_SCERR_TRANSFERABLE 1 + +JS_PUBLIC_API(void) +JS_SetStructuredCloneCallbacks(JSRuntime *rt, const JSStructuredCloneCallbacks *callbacks); + +JS_PUBLIC_API(bool) +JS_ReadUint32Pair(JSStructuredCloneReader *r, uint32_t *p1, uint32_t *p2); + +JS_PUBLIC_API(bool) +JS_ReadBytes(JSStructuredCloneReader *r, void *p, size_t len); + +JS_PUBLIC_API(bool) +JS_ReadTypedArray(JSStructuredCloneReader *r, JS::Value *vp); + +JS_PUBLIC_API(bool) +JS_WriteUint32Pair(JSStructuredCloneWriter *w, uint32_t tag, uint32_t data); + +JS_PUBLIC_API(bool) +JS_WriteBytes(JSStructuredCloneWriter *w, const void *p, size_t len); + +JS_PUBLIC_API(bool) +JS_WriteTypedArray(JSStructuredCloneWriter *w, JS::Value v); + +#endif /* js_StructuredClone_h */ diff --git a/external/spidermonkey/include/win32/js/Tracer.h b/external/spidermonkey/include/win32/js/Tracer.h new file mode 100644 index 0000000000..89994612f6 --- /dev/null +++ b/external/spidermonkey/include/win32/js/Tracer.h @@ -0,0 +1,193 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef js_Tracer_h +#define js_Tracer_h + +#include "mozilla/NullPtr.h" + +#include "jspubtd.h" + +struct JSTracer; + +namespace JS { +template class Heap; +template class TenuredHeap; +} + +// Tracer callback, called for each traceable thing directly referenced by a +// particular object or runtime structure. It is the callback responsibility +// to ensure the traversal of the full object graph via calling eventually +// JS_TraceChildren on the passed thing. In this case the callback must be +// prepared to deal with cycles in the traversal graph. +// +// kind argument is one of JSTRACE_OBJECT, JSTRACE_STRING or a tag denoting +// internal implementation-specific traversal kind. In the latter case the only +// operations on thing that the callback can do is to call JS_TraceChildren or +// JS_GetTraceThingInfo. +// +// If eagerlyTraceWeakMaps is true, when we trace a WeakMap visit all +// of its mappings. This should be used in cases where the tracer +// wants to use the existing liveness of entries. +typedef void +(* JSTraceCallback)(JSTracer *trc, void **thingp, JSGCTraceKind kind); + +// Callback that JSTraceOp implementation can provide to return a string +// describing the reference traced with JS_CallTracer. +typedef void +(* JSTraceNamePrinter)(JSTracer *trc, char *buf, size_t bufsize); + +enum WeakMapTraceKind { + DoNotTraceWeakMaps = 0, + TraceWeakMapValues = 1, + TraceWeakMapKeysValues = 2 +}; + +struct JSTracer { + JSRuntime *runtime; + JSTraceCallback callback; + JSTraceNamePrinter debugPrinter; + const void *debugPrintArg; + size_t debugPrintIndex; + WeakMapTraceKind eagerlyTraceWeakMaps; +#ifdef JS_GC_ZEAL + void *realLocation; +#endif +}; + +// Set debugging information about a reference to a traceable thing to prepare +// for the following call to JS_CallTracer. +// +// When printer is null, arg must be const char * or char * C string naming +// the reference and index must be either (size_t)-1 indicating that the name +// alone describes the reference or it must be an index into some array vector +// that stores the reference. +// +// When printer callback is not null, the arg and index arguments are +// available to the callback as debugPrintArg and debugPrintIndex fields +// of JSTracer. +// +// The storage for name or callback's arguments needs to live only until +// the following call to JS_CallTracer returns. +// +# define JS_SET_TRACING_DETAILS(trc, printer, arg, index) \ + JS_BEGIN_MACRO \ + (trc)->debugPrinter = (printer); \ + (trc)->debugPrintArg = (arg); \ + (trc)->debugPrintIndex = (index); \ + JS_END_MACRO + +// Sets the real location for a marked reference, when passing the address +// directly is not feasable. +// +// FIXME: This is currently overcomplicated by our need to nest calls for Values +// stored as keys in hash tables, but will get simplified once we can rekey +// in-place. +// +#ifdef JS_GC_ZEAL +# define JS_SET_TRACING_LOCATION(trc, location) \ + JS_BEGIN_MACRO \ + if (!(trc)->realLocation || !(location)) \ + (trc)->realLocation = (location); \ + JS_END_MACRO +# define JS_UNSET_TRACING_LOCATION(trc) \ + JS_BEGIN_MACRO \ + (trc)->realLocation = nullptr; \ + JS_END_MACRO +#else +# define JS_SET_TRACING_LOCATION(trc, location) \ + JS_BEGIN_MACRO \ + JS_END_MACRO +# define JS_UNSET_TRACING_LOCATION(trc) \ + JS_BEGIN_MACRO \ + JS_END_MACRO +#endif + +// Convenience macro to describe the argument of JS_CallTracer using C string +// and index. +# define JS_SET_TRACING_INDEX(trc, name, index) \ + JS_SET_TRACING_DETAILS(trc, nullptr, name, index) + +// Convenience macro to describe the argument of JS_CallTracer using C string. +# define JS_SET_TRACING_NAME(trc, name) \ + JS_SET_TRACING_DETAILS(trc, nullptr, name, (size_t)-1) + +// The JS_Call*Tracer family of functions traces the given GC thing reference. +// This performs the tracing action configured on the given JSTracer: +// typically calling the JSTracer::callback or marking the thing as live. +// +// The argument to JS_Call*Tracer is an in-out param: when the function +// returns, the garbage collector might have moved the GC thing. In this case, +// the reference passed to JS_Call*Tracer will be updated to the object's new +// location. Callers of this method are responsible for updating any state +// that is dependent on the object's address. For example, if the object's +// address is used as a key in a hashtable, then the object must be removed +// and re-inserted with the correct hash. +// +extern JS_PUBLIC_API(void) +JS_CallValueTracer(JSTracer *trc, JS::Value *valuep, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallIdTracer(JSTracer *trc, jsid *idp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallObjectTracer(JSTracer *trc, JSObject **objp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallStringTracer(JSTracer *trc, JSString **strp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallScriptTracer(JSTracer *trc, JSScript **scriptp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapValueTracer(JSTracer *trc, JS::Heap *valuep, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapIdTracer(JSTracer *trc, JS::Heap *idp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapObjectTracer(JSTracer *trc, JS::Heap *objp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapStringTracer(JSTracer *trc, JS::Heap *strp, const char *name); + +extern JS_PUBLIC_API(void) +JS_CallHeapScriptTracer(JSTracer *trc, JS::Heap *scriptp, const char *name); + +template +inline void +JS_CallHashSetObjectTracer(JSTracer *trc, HashSetEnum &e, JSObject *const &key, const char *name) +{ + JSObject *updated = key; + JS_SET_TRACING_LOCATION(trc, reinterpret_cast(&const_cast(key))); + JS_CallObjectTracer(trc, &updated, name); + if (updated != key) + e.rekeyFront(key, updated); +} + +// Trace an object that is known to always be tenured. No post barriers are +// required in this case. +extern JS_PUBLIC_API(void) +JS_CallTenuredObjectTracer(JSTracer *trc, JS::TenuredHeap *objp, const char *name); + +// API for JSTraceCallback implementations. +extern JS_PUBLIC_API(void) +JS_TracerInit(JSTracer *trc, JSRuntime *rt, JSTraceCallback callback); + +extern JS_PUBLIC_API(void) +JS_TraceChildren(JSTracer *trc, void *thing, JSGCTraceKind kind); + +extern JS_PUBLIC_API(void) +JS_TraceRuntime(JSTracer *trc); + +extern JS_PUBLIC_API(void) +JS_GetTraceThingInfo(char *buf, size_t bufsize, JSTracer *trc, + void *thing, JSGCTraceKind kind, bool includeDetails); + +extern JS_PUBLIC_API(const char *) +JS_GetTraceEdgeName(JSTracer *trc, char *buffer, int bufferSize); + +#endif /* js_Tracer_h */ diff --git a/external/spidermonkey/include/win32/js/TypeDecls.h b/external/spidermonkey/include/win32/js/TypeDecls.h new file mode 100644 index 0000000000..8b198ed228 --- /dev/null +++ b/external/spidermonkey/include/win32/js/TypeDecls.h @@ -0,0 +1,81 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +// This file contains public type declarations that are used *frequently*. If +// it doesn't occur at least 10 times in Gecko, it probably shouldn't be in +// here. +// +// It includes only: +// - forward declarations of structs and classes; +// - typedefs; +// - enums (maybe). +// It does *not* contain any struct or class definitions. + +#ifndef js_TypeDecls_h +#define js_TypeDecls_h + +#include +#include + +struct JSContext; +class JSFunction; +class JSObject; +class JSScript; +class JSString; + +// In release builds, jsid is defined to be an integral type. This +// prevents many bugs from being caught at compile time. E.g.: +// +// jsid id = ... +// if (id) // error +// ... +// +// size_t n = id; // error +// +// To catch more errors, jsid is given a struct type in C++ debug builds. +// Struct assignment and (in C++) operator== allow correct code to be mostly +// oblivious to the change. This feature can be explicitly disabled in debug +// builds by defining JS_NO_JSVAL_JSID_STRUCT_TYPES. +// + +// Needed for cocos2d-js +#define JS_NO_JSVAL_JSID_STRUCT_TYPES + +#if defined(DEBUG) && !defined(JS_NO_JSVAL_JSID_STRUCT_TYPES) +# define JS_USE_JSID_STRUCT_TYPES +#endif + +#ifdef JS_USE_JSID_STRUCT_TYPES +struct jsid; +#else +typedef ptrdiff_t jsid; +#endif + +typedef wchar_t jschar; + +namespace JS { + +class Value; +template class Handle; +template class MutableHandle; + +typedef Handle HandleFunction; +typedef Handle HandleId; +typedef Handle HandleObject; +typedef Handle HandleScript; +typedef Handle HandleString; +typedef Handle HandleValue; + +typedef MutableHandle MutableHandleFunction; +typedef MutableHandle MutableHandleId; +typedef MutableHandle MutableHandleObject; +typedef MutableHandle MutableHandleScript; +typedef MutableHandle MutableHandleString; +typedef MutableHandle MutableHandleValue; + +} // namespace JS + +#endif /* js_TypeDecls_h */ diff --git a/external/spidermonkey/include/win32/js/Utility.h b/external/spidermonkey/include/win32/js/Utility.h index 9d391e5c8a..cdaf19ba5f 100644 --- a/external/spidermonkey/include/win32/js/Utility.h +++ b/external/spidermonkey/include/win32/js/Utility.h @@ -11,6 +11,7 @@ #include "mozilla/Attributes.h" #include "mozilla/Compiler.h" #include "mozilla/Move.h" +#include "mozilla/NullPtr.h" #include "mozilla/Scoped.h" #include "mozilla/TemplateLib.h" @@ -18,8 +19,8 @@ #include #ifdef JS_OOM_DO_BACKTRACES -#include #include +#include #endif #include "jstypes.h" @@ -44,16 +45,6 @@ namespace js {} #define JS_ALWAYS_TRUE(expr) MOZ_ALWAYS_TRUE(expr) #define JS_ALWAYS_FALSE(expr) MOZ_ALWAYS_FALSE(expr) -#ifdef DEBUG -# ifdef JS_THREADSAFE -# define JS_THREADSAFE_ASSERT(expr) JS_ASSERT(expr) -# else -# define JS_THREADSAFE_ASSERT(expr) ((void) 0) -# endif -#else -# define JS_THREADSAFE_ASSERT(expr) ((void) 0) -#endif - #if defined(DEBUG) # define JS_DIAGNOSTICS_ASSERT(expr) MOZ_ASSERT(expr) #elif defined(JS_CRASH_DIAGNOSTICS) @@ -96,7 +87,7 @@ static JS_ALWAYS_INLINE void PrintBacktrace() { void* OOM_trace[JS_OOM_BACKTRACE_SIZE]; - char** OOM_traceSymbols = NULL; + char** OOM_traceSymbols = nullptr; int32_t OOM_traceSize = 0; int32_t OOM_traceIdx = 0; OOM_traceSize = backtrace(OOM_trace, JS_OOM_BACKTRACE_SIZE); @@ -126,7 +117,7 @@ PrintBacktrace() { \ if (++OOM_counter > OOM_maxAllocations) { \ JS_OOM_EMIT_BACKTRACE();\ - return NULL; \ + return nullptr; \ } \ } while (0) @@ -136,7 +127,7 @@ PrintBacktrace() if (++OOM_counter > OOM_maxAllocations) { \ JS_OOM_EMIT_BACKTRACE();\ js_ReportOutOfMemory(cx);\ - return NULL; \ + return nullptr; \ } \ } while (0) @@ -145,31 +136,31 @@ PrintBacktrace() # define JS_OOM_POSSIBLY_FAIL_REPORT(cx) do {} while(0) # endif /* DEBUG */ -static JS_INLINE void* js_malloc(size_t bytes) +static inline void* js_malloc(size_t bytes) { JS_OOM_POSSIBLY_FAIL(); return malloc(bytes); } -static JS_INLINE void* js_calloc(size_t bytes) +static inline void* js_calloc(size_t bytes) { JS_OOM_POSSIBLY_FAIL(); return calloc(bytes, 1); } -static JS_INLINE void* js_calloc(size_t nmemb, size_t size) +static inline void* js_calloc(size_t nmemb, size_t size) { JS_OOM_POSSIBLY_FAIL(); return calloc(nmemb, size); } -static JS_INLINE void* js_realloc(void* p, size_t bytes) +static inline void* js_realloc(void* p, size_t bytes) { JS_OOM_POSSIBLY_FAIL(); return realloc(p, bytes); } -static JS_INLINE void js_free(void* p) +static inline void js_free(void* p) { free(p); } @@ -241,7 +232,7 @@ static JS_INLINE void js_free(void* p) #define JS_NEW_BODY(allocator, t, parms) \ void *memory = allocator(sizeof(t)); \ - return memory ? new(memory) t parms : NULL; + return memory ? new(memory) t parms : nullptr; /* * Given a class which should provide 'new' methods, add @@ -360,7 +351,7 @@ static JS_ALWAYS_INLINE T * js_pod_malloc(size_t numElems) { if (numElems & mozilla::tl::MulOverflowMask::value) - return NULL; + return nullptr; return (T *)js_malloc(numElems * sizeof(T)); } @@ -369,7 +360,7 @@ static JS_ALWAYS_INLINE T * js_pod_calloc(size_t numElems) { if (numElems & mozilla::tl::MulOverflowMask::value) - return NULL; + return nullptr; return (T *)js_calloc(numElems * sizeof(T)); } @@ -379,7 +370,7 @@ template struct ScopedFreePtrTraits { typedef T* type; - static T* empty() { return NULL; } + static T* empty() { return nullptr; } static void release(T* ptr) { js_free(ptr); } }; SCOPED_TEMPLATE(ScopedJSFreePtr, ScopedFreePtrTraits) diff --git a/external/spidermonkey/include/win32/js/Value.h b/external/spidermonkey/include/win32/js/Value.h index 9b2c5dd6f9..7a772bcfba 100644 --- a/external/spidermonkey/include/win32/js/Value.h +++ b/external/spidermonkey/include/win32/js/Value.h @@ -15,6 +15,8 @@ #include /* for std::numeric_limits */ +#include "jstypes.h" + #include "js/Anchor.h" #include "js/RootingAPI.h" #include "js/Utility.h" @@ -248,7 +250,7 @@ typedef union jsval_layout union { int32_t i32; uint32_t u32; - JSBool boo; + uint32_t boo; // Don't use |bool| -- it must be four bytes. JSString *str; JSObject *obj; void *ptr; @@ -295,7 +297,7 @@ typedef union jsval_layout union { int32_t i32; uint32_t u32; - JSBool boo; + uint32_t boo; // Don't use |bool| -- it must be four bytes. JSString *str; JSObject *obj; void *ptr; @@ -333,6 +335,49 @@ typedef union jsval_layout JS_STATIC_ASSERT(sizeof(jsval_layout) == 8); +/* + * For codesize purposes on some platforms, it's important that the + * compiler know that JS::Values constructed from constant values can be + * folded to constant bit patterns at compile time, rather than + * constructed at runtime. Doing this requires a fair amount of C++11 + * features, which are not supported on all of our compilers. Set up + * some defines and helper macros in an attempt to confine the ugliness + * here, rather than scattering it all about the file. The important + * features are: + * + * - constexpr; + * - defaulted functions; + * - C99-style designated initializers. + */ +#if defined(__clang__) +# if __has_feature(cxx_constexpr) && __has_feature(cxx_defaulted_functions) +# define JS_VALUE_IS_CONSTEXPR +# endif +#elif defined(__GNUC__) +/* + * We need 4.5 for defaulted functions, 4.6 for constexpr, 4.7 because 4.6 + * doesn't understand |(X) { .field = ... }| syntax, and 4.7.3 because + * versions prior to that have bugs in the C++ front-end that cause crashes. + */ +# if MOZ_GCC_VERSION_AT_LEAST(4, 7, 3) +# define JS_VALUE_IS_CONSTEXPR +# endif +#endif + +#if defined(JS_VALUE_IS_CONSTEXPR) +# define JS_RETURN_LAYOUT_FROM_BITS(BITS) \ + return (jsval_layout) { .asBits = (BITS) } +# define JS_VALUE_CONSTEXPR MOZ_CONSTEXPR +# define JS_VALUE_CONSTEXPR_VAR MOZ_CONSTEXPR_VAR +#else +# define JS_RETURN_LAYOUT_FROM_BITS(BITS) \ + jsval_layout l; \ + l.asBits = (BITS); \ + return l; +# define JS_VALUE_CONSTEXPR +# define JS_VALUE_CONSTEXPR_VAR const +#endif + #if JS_BITS_PER_WORD == 32 /* @@ -341,15 +386,13 @@ JS_STATIC_ASSERT(sizeof(jsval_layout) == 8); * Thus, all comparisons should explicitly cast operands to uint32_t. */ -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout BUILD_JSVAL(JSValueTag tag, uint32_t payload) { - jsval_layout l; - l.asBits = (((uint64_t)(uint32_t)tag) << 32) | payload; - return l; + JS_RETURN_LAYOUT_FROM_BITS((((uint64_t)(uint32_t)tag) << 32) | payload); } -static inline JSBool +static inline bool JSVAL_IS_DOUBLE_IMPL(jsval_layout l) { return (uint32_t)l.s.tag <= (uint32_t)JSVAL_TAG_CLEAR; @@ -364,7 +407,7 @@ DOUBLE_TO_JSVAL_IMPL(double d) return l; } -static inline JSBool +static inline bool JSVAL_IS_INT32_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_INT32; @@ -376,16 +419,20 @@ JSVAL_TO_INT32_IMPL(jsval_layout l) return l.s.payload.i32; } -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout INT32_TO_JSVAL_IMPL(int32_t i) { +#if defined(JS_VALUE_IS_CONSTEXPR) + return BUILD_JSVAL(JSVAL_TAG_INT32, i); +#else jsval_layout l; l.s.tag = JSVAL_TAG_INT32; l.s.payload.i32 = i; return l; +#endif } -static inline JSBool +static inline bool JSVAL_IS_NUMBER_IMPL(jsval_layout l) { JSValueTag tag = l.s.tag; @@ -393,13 +440,13 @@ JSVAL_IS_NUMBER_IMPL(jsval_layout l) return (uint32_t)tag <= (uint32_t)JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET; } -static inline JSBool +static inline bool JSVAL_IS_UNDEFINED_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_UNDEFINED; } -static inline JSBool +static inline bool JSVAL_IS_STRING_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_STRING; @@ -421,47 +468,46 @@ JSVAL_TO_STRING_IMPL(jsval_layout l) return l.s.payload.str; } -static inline JSBool +static inline bool JSVAL_IS_BOOLEAN_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_BOOLEAN; } -static inline JSBool +static inline bool JSVAL_TO_BOOLEAN_IMPL(jsval_layout l) { return l.s.payload.boo; } static inline jsval_layout -BOOLEAN_TO_JSVAL_IMPL(JSBool b) +BOOLEAN_TO_JSVAL_IMPL(bool b) { jsval_layout l; - MOZ_ASSERT(b == JS_TRUE || b == JS_FALSE); l.s.tag = JSVAL_TAG_BOOLEAN; l.s.payload.boo = b; return l; } -static inline JSBool +static inline bool JSVAL_IS_MAGIC_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_MAGIC; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_OBJECT; } -static inline JSBool +static inline bool JSVAL_IS_PRIMITIVE_IMPL(jsval_layout l) { return (uint32_t)l.s.tag < (uint32_t)JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_OR_NULL_IMPL(jsval_layout l) { MOZ_ASSERT((uint32_t)l.s.tag <= (uint32_t)JSVAL_TAG_OBJECT); @@ -484,7 +530,7 @@ OBJECT_TO_JSVAL_IMPL(JSObject *obj) return l; } -static inline JSBool +static inline bool JSVAL_IS_NULL_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_NULL; @@ -507,7 +553,7 @@ JSVAL_TO_PRIVATE_PTR_IMPL(jsval_layout l) return l.s.payload.ptr; } -static inline JSBool +static inline bool JSVAL_IS_GCTHING_IMPL(jsval_layout l) { /* gcc sometimes generates signed < without explicit casts. */ @@ -520,7 +566,7 @@ JSVAL_TO_GCTHING_IMPL(jsval_layout l) return l.s.payload.ptr; } -static inline JSBool +static inline bool JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) { return l.s.tag == JSVAL_TAG_STRING || l.s.tag == JSVAL_TAG_OBJECT; @@ -529,19 +575,19 @@ JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) static inline uint32_t JSVAL_TRACE_KIND_IMPL(jsval_layout l) { - return (uint32_t)(JSBool)JSVAL_IS_STRING_IMPL(l); + return (uint32_t)(bool)JSVAL_IS_STRING_IMPL(l); } -static inline JSBool +static inline bool JSVAL_IS_SPECIFIC_INT32_IMPL(jsval_layout l, int32_t i32) { return l.s.tag == JSVAL_TAG_INT32 && l.s.payload.i32 == i32; } -static inline JSBool -JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, JSBool b) +static inline bool +JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, bool b) { - return (l.s.tag == JSVAL_TAG_BOOLEAN) && (l.s.payload.boo == b); + return (l.s.tag == JSVAL_TAG_BOOLEAN) && (l.s.payload.boo == uint32_t(b)); } static inline jsval_layout @@ -553,7 +599,7 @@ MAGIC_TO_JSVAL_IMPL(JSWhyMagic why) return l; } -static inline JSBool +static inline bool JSVAL_SAME_TYPE_IMPL(jsval_layout lhs, jsval_layout rhs) { JSValueTag ltag = lhs.s.tag, rtag = rhs.s.tag; @@ -570,15 +616,13 @@ JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(jsval_layout l) #elif JS_BITS_PER_WORD == 64 -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout BUILD_JSVAL(JSValueTag tag, uint64_t payload) { - jsval_layout l; - l.asBits = (((uint64_t)(uint32_t)tag) << JSVAL_TAG_SHIFT) | payload; - return l; + JS_RETURN_LAYOUT_FROM_BITS((((uint64_t)(uint32_t)tag) << JSVAL_TAG_SHIFT) | payload); } -static inline JSBool +static inline bool JSVAL_IS_DOUBLE_IMPL(jsval_layout l) { return l.asBits <= JSVAL_SHIFTED_TAG_MAX_DOUBLE; @@ -593,7 +637,7 @@ DOUBLE_TO_JSVAL_IMPL(double d) return l; } -static inline JSBool +static inline bool JSVAL_IS_INT32_IMPL(jsval_layout l) { return (uint32_t)(l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_INT32; @@ -605,27 +649,25 @@ JSVAL_TO_INT32_IMPL(jsval_layout l) return (int32_t)l.asBits; } -static inline jsval_layout +static inline JS_VALUE_CONSTEXPR jsval_layout INT32_TO_JSVAL_IMPL(int32_t i32) { - jsval_layout l; - l.asBits = ((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32; - return l; + JS_RETURN_LAYOUT_FROM_BITS(((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32); } -static inline JSBool +static inline bool JSVAL_IS_NUMBER_IMPL(jsval_layout l) { return l.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_NUMBER_SET; } -static inline JSBool +static inline bool JSVAL_IS_UNDEFINED_IMPL(jsval_layout l) { return l.asBits == JSVAL_SHIFTED_TAG_UNDEFINED; } -static inline JSBool +static inline bool JSVAL_IS_STRING_IMPL(jsval_layout l) { return (uint32_t)(l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_STRING; @@ -648,47 +690,46 @@ JSVAL_TO_STRING_IMPL(jsval_layout l) return (JSString *)(l.asBits & JSVAL_PAYLOAD_MASK); } -static inline JSBool +static inline bool JSVAL_IS_BOOLEAN_IMPL(jsval_layout l) { return (uint32_t)(l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_BOOLEAN; } -static inline JSBool +static inline bool JSVAL_TO_BOOLEAN_IMPL(jsval_layout l) { - return (JSBool)l.asBits; + return (bool)(l.asBits & JSVAL_PAYLOAD_MASK); } static inline jsval_layout -BOOLEAN_TO_JSVAL_IMPL(JSBool b) +BOOLEAN_TO_JSVAL_IMPL(bool b) { jsval_layout l; - MOZ_ASSERT(b == JS_TRUE || b == JS_FALSE); l.asBits = ((uint64_t)(uint32_t)b) | JSVAL_SHIFTED_TAG_BOOLEAN; return l; } -static inline JSBool +static inline bool JSVAL_IS_MAGIC_IMPL(jsval_layout l) { return (l.asBits >> JSVAL_TAG_SHIFT) == JSVAL_TAG_MAGIC; } -static inline JSBool +static inline bool JSVAL_IS_PRIMITIVE_IMPL(jsval_layout l) { return l.asBits < JSVAL_UPPER_EXCL_SHIFTED_TAG_OF_PRIMITIVE_SET; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_IMPL(jsval_layout l) { MOZ_ASSERT((l.asBits >> JSVAL_TAG_SHIFT) <= JSVAL_SHIFTED_TAG_OBJECT); return l.asBits >= JSVAL_SHIFTED_TAG_OBJECT; } -static inline JSBool +static inline bool JSVAL_IS_OBJECT_OR_NULL_IMPL(jsval_layout l) { MOZ_ASSERT((l.asBits >> JSVAL_TAG_SHIFT) <= JSVAL_TAG_OBJECT); @@ -714,13 +755,13 @@ OBJECT_TO_JSVAL_IMPL(JSObject *obj) return l; } -static inline JSBool +static inline bool JSVAL_IS_NULL_IMPL(jsval_layout l) { return l.asBits == JSVAL_SHIFTED_TAG_NULL; } -static inline JSBool +static inline bool JSVAL_IS_GCTHING_IMPL(jsval_layout l) { return l.asBits >= JSVAL_LOWER_INCL_SHIFTED_TAG_OF_GCTHING_SET; @@ -734,7 +775,7 @@ JSVAL_TO_GCTHING_IMPL(jsval_layout l) return (void *)ptrBits; } -static inline JSBool +static inline bool JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) { return JSVAL_IS_GCTHING_IMPL(l) && !JSVAL_IS_NULL_IMPL(l); @@ -743,7 +784,7 @@ JSVAL_IS_TRACEABLE_IMPL(jsval_layout l) static inline uint32_t JSVAL_TRACE_KIND_IMPL(jsval_layout l) { - return (uint32_t)(JSBool)!(JSVAL_IS_OBJECT_IMPL(l)); + return (uint32_t)(bool)!(JSVAL_IS_OBJECT_IMPL(l)); } static inline jsval_layout @@ -764,14 +805,14 @@ JSVAL_TO_PRIVATE_PTR_IMPL(jsval_layout l) return (void *)(l.asBits << 1); } -static inline JSBool +static inline bool JSVAL_IS_SPECIFIC_INT32_IMPL(jsval_layout l, int32_t i32) { return l.asBits == (((uint64_t)(uint32_t)i32) | JSVAL_SHIFTED_TAG_INT32); } -static inline JSBool -JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, JSBool b) +static inline bool +JSVAL_IS_SPECIFIC_BOOLEAN(jsval_layout l, bool b) { return l.asBits == (((uint64_t)(uint32_t)b) | JSVAL_SHIFTED_TAG_BOOLEAN); } @@ -784,7 +825,7 @@ MAGIC_TO_JSVAL_IMPL(JSWhyMagic why) return l; } -static inline JSBool +static inline bool JSVAL_SAME_TYPE_IMPL(jsval_layout lhs, jsval_layout rhs) { uint64_t lbits = lhs.asBits, rbits = rhs.asBits; @@ -803,10 +844,12 @@ JSVAL_EXTRACT_NON_DOUBLE_TYPE_IMPL(jsval_layout l) #endif /* JS_BITS_PER_WORD */ static inline jsval_layout JSVAL_TO_IMPL(JS::Value v); -static inline JS::Value IMPL_TO_JSVAL(jsval_layout l); +static inline JS_VALUE_CONSTEXPR JS::Value IMPL_TO_JSVAL(jsval_layout l); namespace JS { +static inline JS_VALUE_CONSTEXPR JS::Value UndefinedValue(); + /** * Returns a generic quiet NaN value, with all payload bits set to zero. * @@ -816,7 +859,7 @@ namespace JS { static MOZ_ALWAYS_INLINE double GenericNaN() { - return mozilla::SpecificNaN(0, 0x8000000000000ULL); + return mozilla::SpecificNaN(0, 0x8000000000000ULL); } static inline double @@ -869,6 +912,10 @@ class Value * N.B. the default constructor leaves Value unitialized. Adding a default * constructor prevents Value from being stored in a union. */ +#if defined(JS_VALUE_IS_CONSTEXPR) + Value() = default; + Value(const Value& v) = default; +#endif /*** Mutators ***/ @@ -893,6 +940,10 @@ class Value data = DOUBLE_TO_JSVAL_IMPL(d); } + void setNaN() { + setDouble(GenericNaN()); + } + double &getDoubleRef() { MOZ_ASSERT(isDouble()); return data.asDouble; @@ -1173,16 +1224,20 @@ class Value jsval_layout data; private: +#if defined(JS_VALUE_IS_CONSTEXPR) + JS_VALUE_CONSTEXPR Value(jsval_layout layout) : data(layout) {} +#endif + void staticAssertions() { JS_STATIC_ASSERT(sizeof(JSValueType) == 1); JS_STATIC_ASSERT(sizeof(JSValueTag) == 4); - JS_STATIC_ASSERT(sizeof(JSBool) == 4); JS_STATIC_ASSERT(sizeof(JSWhyMagic) <= 4); JS_STATIC_ASSERT(sizeof(Value) == 8); } friend jsval_layout (::JSVAL_TO_IMPL)(Value); - friend Value (::IMPL_TO_JSVAL)(jsval_layout l); + friend Value JS_VALUE_CONSTEXPR (::IMPL_TO_JSVAL)(jsval_layout l); + friend Value JS_VALUE_CONSTEXPR (JS::UndefinedValue)(); }; inline bool @@ -1205,12 +1260,16 @@ NullValue() return v; } -static inline Value +static inline JS_VALUE_CONSTEXPR Value UndefinedValue() { - Value v; +#if defined(JS_VALUE_IS_CONSTEXPR) + return Value(BUILD_JSVAL(JSVAL_TAG_UNDEFINED, 0)); +#else + JS::Value v; v.setUndefined(); return v; +#endif } static inline Value @@ -1229,6 +1288,22 @@ DoubleValue(double dbl) return v; } +static inline Value +DoubleNaNValue() +{ + Value v; + v.setNaN(); + return v; +} + +static inline Value +Float32Value(float f) +{ + Value v; + v.setDouble(f); + return v; +} + static inline Value StringValue(JSString *str) { @@ -1499,6 +1574,7 @@ class UnbarrieredMutableValueOperations : public ValueOperations void setUndefined() { value()->setUndefined(); } void setInt32(int32_t i) { value()->setInt32(i); } void setDouble(double d) { value()->setDouble(d); } + void setNaN() { setDouble(JS::GenericNaN()); } void setBoolean(bool b) { value()->setBoolean(b); } void setMagic(JSWhyMagic why) { value()->setMagic(why); } bool setNumber(uint32_t ui) { return value()->setNumber(ui); } @@ -1620,12 +1696,16 @@ JSVAL_TO_IMPL(JS::Value v) return v.data; } -inline JS::Value +inline JS_VALUE_CONSTEXPR JS::Value IMPL_TO_JSVAL(jsval_layout l) { +#if defined(JS_VALUE_IS_CONSTEXPR) + return JS::Value(l); +#else JS::Value v; v.data = l; return v; +#endif } namespace JS { @@ -1678,19 +1758,19 @@ static_assert(sizeof(jsval_layout) == sizeof(JS::Value), /************************************************************************/ -static inline JSBool +static inline bool JSVAL_IS_NULL(jsval v) { return JSVAL_IS_NULL_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_VOID(jsval v) { return JSVAL_IS_UNDEFINED_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_INT(jsval v) { return JSVAL_IS_INT32_IMPL(JSVAL_TO_IMPL(v)); @@ -1703,13 +1783,13 @@ JSVAL_TO_INT(jsval v) return JSVAL_TO_INT32_IMPL(JSVAL_TO_IMPL(v)); } -static inline jsval +static inline JS_VALUE_CONSTEXPR jsval INT_TO_JSVAL(int32_t i) { return IMPL_TO_JSVAL(INT32_TO_JSVAL_IMPL(i)); } -static inline JSBool +static inline bool JSVAL_IS_DOUBLE(jsval v) { return JSVAL_IS_DOUBLE_IMPL(JSVAL_TO_IMPL(v)); @@ -1724,7 +1804,7 @@ JSVAL_TO_DOUBLE(jsval v) return l.asDouble; } -static inline jsval +static inline JS_VALUE_CONSTEXPR jsval DOUBLE_TO_JSVAL(double d) { /* @@ -1733,29 +1813,35 @@ DOUBLE_TO_JSVAL(double d) * return IMPL_TO_JSVAL(DOUBLE_TO_JSVAL_IMPL(d)); * because GCC from XCode 3.1.4 miscompiles the above code. */ +#if defined(JS_VALUE_IS_CONSTEXPR) + return IMPL_TO_JSVAL(MOZ_UNLIKELY(d != d) + ? (jsval_layout) { .asBits = 0x7FF8000000000000LL } + : (jsval_layout) { .asDouble = d }); +#else jsval_layout l; if (MOZ_UNLIKELY(d != d)) l.asBits = 0x7FF8000000000000LL; else l.asDouble = d; return IMPL_TO_JSVAL(l); +#endif } -static inline jsval +static inline JS_VALUE_CONSTEXPR jsval UINT_TO_JSVAL(uint32_t i) { - if (i <= JSVAL_INT_MAX) - return INT_TO_JSVAL((int32_t)i); - return DOUBLE_TO_JSVAL((double)i); + return (i <= JSVAL_INT_MAX + ? INT_TO_JSVAL((int32_t)i) + : DOUBLE_TO_JSVAL((double)i)); } -static inline JSBool +static inline bool JSVAL_IS_NUMBER(jsval v) { return JSVAL_IS_NUMBER_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_STRING(jsval v) { return JSVAL_IS_STRING_IMPL(JSVAL_TO_IMPL(v)); @@ -1789,13 +1875,13 @@ OBJECT_TO_JSVAL(JSObject *obj) return IMPL_TO_JSVAL(BUILD_JSVAL(JSVAL_TAG_NULL, 0)); } -static inline JSBool +static inline bool JSVAL_IS_BOOLEAN(jsval v) { return JSVAL_IS_BOOLEAN_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_TO_BOOLEAN(jsval v) { MOZ_ASSERT(JSVAL_IS_BOOLEAN(v)); @@ -1803,18 +1889,18 @@ JSVAL_TO_BOOLEAN(jsval v) } static inline jsval -BOOLEAN_TO_JSVAL(JSBool b) +BOOLEAN_TO_JSVAL(bool b) { return IMPL_TO_JSVAL(BOOLEAN_TO_JSVAL_IMPL(b)); } -static inline JSBool +static inline bool JSVAL_IS_PRIMITIVE(jsval v) { return JSVAL_IS_PRIMITIVE_IMPL(JSVAL_TO_IMPL(v)); } -static inline JSBool +static inline bool JSVAL_IS_GCTHING(jsval v) { return JSVAL_IS_GCTHING_IMPL(JSVAL_TO_IMPL(v)); @@ -1842,4 +1928,25 @@ JSVAL_TO_PRIVATE(jsval v) return JSVAL_TO_PRIVATE_PTR_IMPL(JSVAL_TO_IMPL(v)); } +// JS constants. For efficiency, prefer predicates (e.g. v.isNull()) and +// constructing values from scratch (e.g. Int32Value(0)). These constants are +// stored in memory and initialized at startup, so testing against them and +// using them requires memory loads and will be correspondingly slow. +extern JS_PUBLIC_DATA(const jsval) JSVAL_NULL; +extern JS_PUBLIC_DATA(const jsval) JSVAL_ZERO; +extern JS_PUBLIC_DATA(const jsval) JSVAL_ONE; +extern JS_PUBLIC_DATA(const jsval) JSVAL_FALSE; +extern JS_PUBLIC_DATA(const jsval) JSVAL_TRUE; +extern JS_PUBLIC_DATA(const jsval) JSVAL_VOID; + +namespace JS { + +extern JS_PUBLIC_DATA(const Handle) NullHandleValue; +extern JS_PUBLIC_DATA(const Handle) UndefinedHandleValue; + +} + +#undef JS_VALUE_IS_CONSTEXPR +#undef JS_RETURN_LAYOUT_FROM_BITS + #endif /* js_Value_h */ diff --git a/external/spidermonkey/include/win32/jsalloc.h b/external/spidermonkey/include/win32/jsalloc.h index 3abc4966d1..03b6b569e1 100644 --- a/external/spidermonkey/include/win32/jsalloc.h +++ b/external/spidermonkey/include/win32/jsalloc.h @@ -9,12 +9,9 @@ #ifndef jsalloc_h #define jsalloc_h -#include "mozilla/AllocPolicy.h" - +#include "js/TypeDecls.h" #include "js/Utility.h" -struct JSContext; - namespace js { class ContextFriendFields; @@ -56,14 +53,14 @@ class TempAllocPolicy void *malloc_(size_t bytes) { void *p = js_malloc(bytes); if (JS_UNLIKELY(!p)) - p = onOutOfMemory(NULL, bytes); + p = onOutOfMemory(nullptr, bytes); return p; } void *calloc_(size_t bytes) { void *p = js_calloc(bytes); if (JS_UNLIKELY(!p)) - p = onOutOfMemory(NULL, bytes); + p = onOutOfMemory(nullptr, bytes); return p; } diff --git a/external/spidermonkey/include/win32/jsapi.h.REMOVED.git-id b/external/spidermonkey/include/win32/jsapi.h.REMOVED.git-id index 27b6bbed78..f73a8c745e 100644 --- a/external/spidermonkey/include/win32/jsapi.h.REMOVED.git-id +++ b/external/spidermonkey/include/win32/jsapi.h.REMOVED.git-id @@ -1 +1 @@ -e14ea931f699b1808c06886e55e977c9819f3774 \ No newline at end of file +38fc2004d49d7c513aff0f7f43d79524ec667c2c \ No newline at end of file diff --git a/external/spidermonkey/include/win32/jsbytecode.h b/external/spidermonkey/include/win32/jsbytecode.h new file mode 100644 index 0000000000..8e4f4cf90b --- /dev/null +++ b/external/spidermonkey/include/win32/jsbytecode.h @@ -0,0 +1,14 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * vim: set ts=8 sts=4 et sw=4 tw=99: + * 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/. */ + +#ifndef jsbytecode_h +#define jsbytecode_h + +#include + +typedef uint8_t jsbytecode; + +#endif /* jsbytecode_h */ diff --git a/external/spidermonkey/include/win32/jsclass.h b/external/spidermonkey/include/win32/jsclass.h deleted file mode 100644 index def641715d..0000000000 --- a/external/spidermonkey/include/win32/jsclass.h +++ /dev/null @@ -1,405 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -#ifndef jsclass_h -#define jsclass_h -/* - * A JSClass acts as a vtable for JS objects that allows JSAPI clients to - * control various aspects of the behavior of an object like property lookup. - * js::Class is an engine-private extension that allows more control over - * object behavior and, e.g., allows custom slow layout. - */ - -#include "jsapi.h" -#include "jsprvtd.h" - -namespace js { - -class PropertyName; -class SpecialId; -class PropertyId; - -// This is equal to JSFunction::class_. Use it in places where you don't want -// to #include jsfun.h. -extern JS_FRIEND_DATA(js::Class* const) FunctionClassPtr; - -static JS_ALWAYS_INLINE jsid -SPECIALID_TO_JSID(const SpecialId &sid); - -/* - * We partition the ways to refer to a property into three: by an index - * (uint32_t); by a string whose characters do not represent an index - * (PropertyName, see vm/String.h); and by various special values. - * - * Special values are encoded using SpecialId, which is layout-compatible but - * non-interconvertible with jsid. A SpecialId is used for JSID_VOID, which - * does not occur in JS scripts but may be used to indicate the absence of a - * valid identifier. In the future, a SpecialId may also be an object used by - * Harmony-proposed private names. - */ -class SpecialId -{ - uintptr_t bits_; - - /* Needs access to raw bits. */ - friend JS_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid); - friend class PropertyId; - - static const uintptr_t TYPE_VOID = JSID_TYPE_VOID; - static const uintptr_t TYPE_OBJECT = JSID_TYPE_OBJECT; - static const uintptr_t TYPE_MASK = JSID_TYPE_MASK; - - SpecialId(uintptr_t bits) : bits_(bits) { } - - public: - SpecialId() : bits_(TYPE_VOID) { } - - /* Object-valued */ - - SpecialId(JSObject &obj) - : bits_(uintptr_t(&obj) | TYPE_OBJECT) - { - JS_ASSERT(&obj != NULL); - JS_ASSERT((uintptr_t(&obj) & TYPE_MASK) == 0); - } - - bool isObject() const { - return (bits_ & TYPE_MASK) == TYPE_OBJECT && bits_ != TYPE_OBJECT; - } - - JSObject *toObject() const { - JS_ASSERT(isObject()); - return reinterpret_cast(bits_ & ~TYPE_MASK); - } - - /* Empty */ - - static SpecialId empty() { - SpecialId sid(TYPE_OBJECT); - JS_ASSERT(sid.isEmpty()); - return sid; - } - - bool isEmpty() const { - return bits_ == TYPE_OBJECT; - } - - /* Void */ - - static SpecialId voidId() { - SpecialId sid(TYPE_VOID); - JS_ASSERT(sid.isVoid()); - return sid; - } - - bool isVoid() const { - return bits_ == TYPE_VOID; - } -}; - -static JS_ALWAYS_INLINE jsid -SPECIALID_TO_JSID(const SpecialId &sid) -{ - jsid id; - JSID_BITS(id) = sid.bits_; - JS_ASSERT_IF(sid.isObject(), JSID_IS_OBJECT(id) && JSID_TO_OBJECT(id) == sid.toObject()); - JS_ASSERT_IF(sid.isVoid(), JSID_IS_VOID(id)); - JS_ASSERT_IF(sid.isEmpty(), JSID_IS_EMPTY(id)); - return id; -} - -static JS_ALWAYS_INLINE bool -JSID_IS_SPECIAL(jsid id) -{ - return JSID_IS_OBJECT(id) || JSID_IS_EMPTY(id) || JSID_IS_VOID(id); -} - -static JS_ALWAYS_INLINE SpecialId -JSID_TO_SPECIALID(jsid id) -{ - JS_ASSERT(JSID_IS_SPECIAL(id)); - if (JSID_IS_OBJECT(id)) - return SpecialId(*JSID_TO_OBJECT(id)); - if (JSID_IS_EMPTY(id)) - return SpecialId::empty(); - JS_ASSERT(JSID_IS_VOID(id)); - return SpecialId::voidId(); -} - -typedef JS::Handle HandleSpecialId; - -/* js::Class operation signatures. */ - -typedef JSBool -(* LookupGenericOp)(JSContext *cx, HandleObject obj, HandleId id, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* LookupPropOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* LookupElementOp)(JSContext *cx, HandleObject obj, uint32_t index, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* LookupSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, - MutableHandleObject objp, MutableHandleShape propp); -typedef JSBool -(* DefineGenericOp)(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* DefinePropOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* DefineElementOp)(JSContext *cx, HandleObject obj, uint32_t index, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* DefineSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); -typedef JSBool -(* GenericIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandleId id, MutableHandleValue vp); -typedef JSBool -(* PropertyIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandlePropertyName name, MutableHandleValue vp); -typedef JSBool -(* ElementIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, uint32_t index, MutableHandleValue vp); -typedef JSBool -(* ElementIfPresentOp)(JSContext *cx, HandleObject obj, HandleObject receiver, uint32_t index, MutableHandleValue vp, bool* present); -typedef JSBool -(* SpecialIdOp)(JSContext *cx, HandleObject obj, HandleObject receiver, HandleSpecialId sid, MutableHandleValue vp); -typedef JSBool -(* StrictGenericIdOp)(JSContext *cx, HandleObject obj, HandleId id, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* StrictPropertyIdOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* StrictElementIdOp)(JSContext *cx, HandleObject obj, uint32_t index, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* StrictSpecialIdOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, MutableHandleValue vp, JSBool strict); -typedef JSBool -(* GenericAttributesOp)(JSContext *cx, HandleObject obj, HandleId id, unsigned *attrsp); -typedef JSBool -(* PropertyAttributesOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, unsigned *attrsp); -typedef JSBool -(* ElementAttributesOp)(JSContext *cx, HandleObject obj, uint32_t index, unsigned *attrsp); -typedef JSBool -(* SpecialAttributesOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, unsigned *attrsp); -typedef JSBool -(* DeletePropertyOp)(JSContext *cx, HandleObject obj, HandlePropertyName name, JSBool *succeeded); -typedef JSBool -(* DeleteElementOp)(JSContext *cx, HandleObject obj, uint32_t index, JSBool *succeeded); -typedef JSBool -(* DeleteSpecialOp)(JSContext *cx, HandleObject obj, HandleSpecialId sid, JSBool *succeeded); - - -typedef JSObject * -(* ObjectOp)(JSContext *cx, HandleObject obj); -typedef void -(* FinalizeOp)(FreeOp *fop, JSObject *obj); - -#define JS_CLASS_MEMBERS \ - const char *name; \ - uint32_t flags; \ - \ - /* Mandatory function pointer members. */ \ - JSPropertyOp addProperty; \ - JSDeletePropertyOp delProperty; \ - JSPropertyOp getProperty; \ - JSStrictPropertyOp setProperty; \ - JSEnumerateOp enumerate; \ - JSResolveOp resolve; \ - JSConvertOp convert; \ - \ - /* Optional members (may be null). */ \ - FinalizeOp finalize; \ - JSCheckAccessOp checkAccess; \ - JSNative call; \ - JSHasInstanceOp hasInstance; \ - JSNative construct; \ - JSTraceOp trace - -/* - * The helper struct to measure the size of JS_CLASS_MEMBERS to know how much - * we have to pad js::Class to match the size of JSClass. - */ -struct ClassSizeMeasurement -{ - JS_CLASS_MEMBERS; -}; - -struct ClassExtension -{ - JSObjectOp outerObject; - JSObjectOp innerObject; - JSIteratorOp iteratorObject; - - /* - * isWrappedNative is true only if the class is an XPCWrappedNative. - * WeakMaps use this to override the wrapper disposal optimization. - */ - bool isWrappedNative; - - /* - * If an object is used as a key in a weakmap, it may be desirable for the - * garbage collector to keep that object around longer than it otherwise - * would. A common case is when the key is a wrapper around an object in - * another compartment, and we want to avoid collecting the wrapper (and - * removing the weakmap entry) as long as the wrapped object is alive. In - * that case, the wrapped object is returned by the wrapper's - * weakmapKeyDelegateOp hook. As long as the wrapper is used as a weakmap - * key, it will not be collected (and remain in the weakmap) until the - * wrapped object is collected. - */ - JSWeakmapKeyDelegateOp weakmapKeyDelegateOp; -}; - -#define JS_NULL_CLASS_EXT {NULL,NULL,NULL,false,NULL} - -struct ObjectOps -{ - LookupGenericOp lookupGeneric; - LookupPropOp lookupProperty; - LookupElementOp lookupElement; - LookupSpecialOp lookupSpecial; - DefineGenericOp defineGeneric; - DefinePropOp defineProperty; - DefineElementOp defineElement; - DefineSpecialOp defineSpecial; - GenericIdOp getGeneric; - PropertyIdOp getProperty; - ElementIdOp getElement; - ElementIfPresentOp getElementIfPresent; /* can be null */ - SpecialIdOp getSpecial; - StrictGenericIdOp setGeneric; - StrictPropertyIdOp setProperty; - StrictElementIdOp setElement; - StrictSpecialIdOp setSpecial; - GenericAttributesOp getGenericAttributes; - PropertyAttributesOp getPropertyAttributes; - ElementAttributesOp getElementAttributes; - SpecialAttributesOp getSpecialAttributes; - GenericAttributesOp setGenericAttributes; - PropertyAttributesOp setPropertyAttributes; - ElementAttributesOp setElementAttributes; - SpecialAttributesOp setSpecialAttributes; - DeletePropertyOp deleteProperty; - DeleteElementOp deleteElement; - DeleteSpecialOp deleteSpecial; - - JSNewEnumerateOp enumerate; - ObjectOp thisObject; -}; - -#define JS_NULL_OBJECT_OPS \ - {NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, \ - NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, \ - NULL,NULL,NULL} - -struct Class -{ - JS_CLASS_MEMBERS; - ClassExtension ext; - ObjectOps ops; - uint8_t pad[sizeof(JSClass) - sizeof(ClassSizeMeasurement) - - sizeof(ClassExtension) - sizeof(ObjectOps)]; - - /* Class is not native and its map is not a scope. */ - static const uint32_t NON_NATIVE = JSCLASS_INTERNAL_FLAG2; - - bool isNative() const { - return !(flags & NON_NATIVE); - } - - bool hasPrivate() const { - return !!(flags & JSCLASS_HAS_PRIVATE); - } - - bool emulatesUndefined() const { - return flags & JSCLASS_EMULATES_UNDEFINED; - } - - bool isCallable() const { - return this == js::FunctionClassPtr || call; - } - - static size_t offsetOfFlags() { return offsetof(Class, flags); } -}; - -JS_STATIC_ASSERT(offsetof(JSClass, name) == offsetof(Class, name)); -JS_STATIC_ASSERT(offsetof(JSClass, flags) == offsetof(Class, flags)); -JS_STATIC_ASSERT(offsetof(JSClass, addProperty) == offsetof(Class, addProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, delProperty) == offsetof(Class, delProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, getProperty) == offsetof(Class, getProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, setProperty) == offsetof(Class, setProperty)); -JS_STATIC_ASSERT(offsetof(JSClass, enumerate) == offsetof(Class, enumerate)); -JS_STATIC_ASSERT(offsetof(JSClass, resolve) == offsetof(Class, resolve)); -JS_STATIC_ASSERT(offsetof(JSClass, convert) == offsetof(Class, convert)); -JS_STATIC_ASSERT(offsetof(JSClass, finalize) == offsetof(Class, finalize)); -JS_STATIC_ASSERT(offsetof(JSClass, checkAccess) == offsetof(Class, checkAccess)); -JS_STATIC_ASSERT(offsetof(JSClass, call) == offsetof(Class, call)); -JS_STATIC_ASSERT(offsetof(JSClass, construct) == offsetof(Class, construct)); -JS_STATIC_ASSERT(offsetof(JSClass, hasInstance) == offsetof(Class, hasInstance)); -JS_STATIC_ASSERT(offsetof(JSClass, trace) == offsetof(Class, trace)); -JS_STATIC_ASSERT(sizeof(JSClass) == sizeof(Class)); - -static JS_ALWAYS_INLINE JSClass * -Jsvalify(Class *c) -{ - return (JSClass *)c; -} -static JS_ALWAYS_INLINE const JSClass * -Jsvalify(const Class *c) -{ - return (const JSClass *)c; -} - -static JS_ALWAYS_INLINE Class * -Valueify(JSClass *c) -{ - return (Class *)c; -} -static JS_ALWAYS_INLINE const Class * -Valueify(const JSClass *c) -{ - return (const Class *)c; -} - -/* - * Enumeration describing possible values of the [[Class]] internal property - * value of objects. - */ -enum ESClassValue { - ESClass_Array, ESClass_Number, ESClass_String, ESClass_Boolean, - ESClass_RegExp, ESClass_ArrayBuffer, ESClass_Date -}; - -/* - * Return whether the given object has the given [[Class]] internal property - * value. Beware, this query says nothing about the js::Class of the JSObject - * so the caller must not assume anything about obj's representation (e.g., obj - * may be a proxy). - */ -inline bool -ObjectClassIs(JSObject &obj, ESClassValue classValue, JSContext *cx); - -/* Just a helper that checks v.isObject before calling ObjectClassIs. */ -inline bool -IsObjectWithClass(const Value &v, ESClassValue classValue, JSContext *cx); - -inline bool -IsPoisonedSpecialId(js::SpecialId iden) -{ - if (iden.isObject()) - return IsPoisonedPtr(iden.toObject()); - return false; -} - -template <> struct GCMethods -{ - static SpecialId initial() { return SpecialId(); } - static ThingRootKind kind() { return THING_ROOT_ID; } - static bool poisoned(SpecialId id) { return IsPoisonedSpecialId(id); } -}; - -} /* namespace js */ - -#endif /* jsclass_h */ diff --git a/external/spidermonkey/include/win32/jscpucfg.h b/external/spidermonkey/include/win32/jscpucfg.h index c79bd7ad14..ccacab3482 100644 --- a/external/spidermonkey/include/win32/jscpucfg.h +++ b/external/spidermonkey/include/win32/jscpucfg.h @@ -14,8 +14,6 @@ # if defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_) # define IS_LITTLE_ENDIAN 1 # undef IS_BIG_ENDIAN -# define JS_BYTES_PER_WORD 8 -# define JS_BITS_PER_WORD_LOG2 6 # else /* !(defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)) */ # error "CPU type is unknown" # endif /* !(defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)) */ @@ -28,8 +26,6 @@ # define IS_LITTLE_ENDIAN 1 # undef IS_BIG_ENDIAN -# define JS_BYTES_PER_WORD 4 -# define JS_BITS_PER_WORD_LOG2 5 #elif defined(__APPLE__) # if __LITTLE_ENDIAN__ @@ -57,8 +53,8 @@ /* BSDs */ #elif defined(JS_HAVE_MACHINE_ENDIAN_H) -# include # include +# include # if defined(_BYTE_ORDER) # if _BYTE_ORDER == _LITTLE_ENDIAN diff --git a/external/spidermonkey/include/win32/jsfriendapi.h b/external/spidermonkey/include/win32/jsfriendapi.h index a1c3024fed..811275d332 100644 --- a/external/spidermonkey/include/win32/jsfriendapi.h +++ b/external/spidermonkey/include/win32/jsfriendapi.h @@ -9,11 +9,12 @@ #include "mozilla/MemoryReporting.h" -#include "jsclass.h" -#include "jsprvtd.h" +#include "jsbytecode.h" #include "jspubtd.h" #include "js/CallArgs.h" +#include "js/CallNonGenericMethod.h" +#include "js/Class.h" /* * This macro checks if the stack pointer has exceeded a given limit. If @@ -30,6 +31,12 @@ #define JS_CHECK_STACK_SIZE(limit, lval) JS_CHECK_STACK_SIZE_WITH_TOLERANCE(limit, lval, 0) +class JSAtom; +struct JSErrorFormatString; +class JSLinearString; +struct JSJitInfo; +class JSErrorReport; + namespace JS { template class Heap; @@ -47,11 +54,11 @@ JS_FindCompilationScope(JSContext *cx, JSObject *obj); extern JS_FRIEND_API(JSFunction *) JS_GetObjectFunction(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_SplicePrototype(JSContext *cx, JSObject *obj, JSObject *proto); extern JS_FRIEND_API(JSObject *) -JS_NewObjectWithUniqueType(JSContext *cx, JSClass *clasp, JSObject *proto, JSObject *parent); +JS_NewObjectWithUniqueType(JSContext *cx, const JSClass *clasp, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(uint32_t) JS_ObjectCountDynamicSlots(JS::HandleObject obj); @@ -62,7 +69,7 @@ JS_SetProtoCalled(JSContext *cx); extern JS_FRIEND_API(size_t) JS_GetCustomIteratorCount(JSContext *cx); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_NondeterministicGetWeakMapKeys(JSContext *cx, JSObject *obj, JSObject **ret); /* @@ -71,7 +78,7 @@ JS_NondeterministicGetWeakMapKeys(JSContext *cx, JSObject *obj, JSObject **ret); * Such objects hold no other objects (they have no outgoing reference edges) * and will throw if you touch them (e.g. by reading/writing a property). */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsDeadWrapper(JSObject *obj); /* @@ -112,11 +119,11 @@ JS_GetCompartmentPrincipals(JSCompartment *compartment); extern JS_FRIEND_API(void) JS_SetCompartmentPrincipals(JSCompartment *compartment, JSPrincipals *principals); -/* Safe to call with input obj == NULL. Returns non-NULL iff obj != NULL. */ +/* Safe to call with input obj == nullptr. Returns non-nullptr iff obj != nullptr. */ extern JS_FRIEND_API(JSObject *) JS_ObjectToInnerObject(JSContext *cx, JSObject *obj); -/* Requires obj != NULL. */ +/* Requires obj != nullptr. */ extern JS_FRIEND_API(JSObject *) JS_ObjectToOuterObject(JSContext *cx, JSObject *obj); @@ -126,8 +133,8 @@ JS_CloneObject(JSContext *cx, JSObject *obj, JSObject *proto, JSObject *parent); extern JS_FRIEND_API(JSString *) JS_BasicObjectToString(JSContext *cx, JS::HandleObject obj); -extern JS_FRIEND_API(JSBool) -js_GetterOnlyPropertyStub(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JSBool strict, +extern JS_FRIEND_API(bool) +js_GetterOnlyPropertyStub(JSContext *cx, JS::HandleObject obj, JS::HandleId id, bool strict, JS::MutableHandleValue vp); JS_FRIEND_API(void) @@ -166,18 +173,32 @@ extern JS_FRIEND_API(void) js_DumpChars(const jschar *s, size_t n); #endif +/* + * Copies all own properties from |obj| to |target|. |obj| must be a "native" + * object (that is to say, normal-ish - not an Array or a Proxy). + * + * On entry, |cx| must be in the compartment of |target|. + */ extern JS_FRIEND_API(bool) JS_CopyPropertiesFrom(JSContext *cx, JSObject *target, JSObject *obj); -extern JS_FRIEND_API(JSBool) -JS_WrapPropertyDescriptor(JSContext *cx, js::PropertyDescriptor *desc); +/* + * Single-property version of the above. This function asserts that an |own| + * property of the given name exists on |obj|. + */ +extern JS_FRIEND_API(bool) +JS_CopyPropertyFrom(JSContext *cx, JS::HandleId id, JS::HandleObject target, + JS::HandleObject obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) +JS_WrapPropertyDescriptor(JSContext *cx, JS::MutableHandle desc); + +extern JS_FRIEND_API(bool) JS_WrapAutoIdVector(JSContext *cx, JS::AutoIdVector &props); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_EnumerateState(JSContext *cx, JS::HandleObject obj, JSIterateOp enum_op, - js::MutableHandleValue statep, js::MutableHandleId idp); + JS::MutableHandleValue statep, JS::MutableHandleId idp); struct JSFunctionSpecWithHelp { const char *name; @@ -191,19 +212,49 @@ struct JSFunctionSpecWithHelp { #define JS_FN_HELP(name,call,nargs,flags,usage,help) \ {name, call, nargs, (flags) | JSPROP_ENUMERATE | JSFUN_STUB_GSOPS, usage, help} #define JS_FS_HELP_END \ - {NULL, NULL, 0, 0, NULL, NULL} + {nullptr, nullptr, 0, 0, nullptr, nullptr} extern JS_FRIEND_API(bool) JS_DefineFunctionsWithHelp(JSContext *cx, JSObject *obj, const JSFunctionSpecWithHelp *fs); -typedef bool (* JS_SourceHook)(JSContext *cx, JS::Handle script, - jschar **src, uint32_t *length); - -extern JS_FRIEND_API(void) -JS_SetSourceHook(JSRuntime *rt, JS_SourceHook hook); - namespace js { +/* + * A class of objects that return source code on demand. + * + * When code is compiled with CompileOptions::LAZY_SOURCE, SpiderMonkey + * doesn't retain the source code (and doesn't do lazy bytecode + * generation). If we ever need the source code, say, in response to a call + * to Function.prototype.toSource or Debugger.Source.prototype.text, then + * we call the 'load' member function of the instance of this class that + * has hopefully been registered with the runtime, passing the code's URL, + * and hope that it will be able to find the source. + */ +class SourceHook { + public: + virtual ~SourceHook() { } + + /* + * Set |*src| and |*length| to refer to the source code for |filename|. + * On success, the caller owns the buffer to which |*src| points, and + * should use JS_free to free it. + */ + virtual bool load(JSContext *cx, const char *filename, jschar **src, size_t *length) = 0; +}; + +/* + * Have |rt| use |hook| to retrieve LAZY_SOURCE source code. See the + * comments for SourceHook. The runtime takes ownership of the hook, and + * will delete it when the runtime itself is deleted, or when a new hook is + * set. + */ +extern JS_FRIEND_API(void) +SetSourceHook(JSRuntime *rt, SourceHook *hook); + +/* Remove |rt|'s source hook, and return it. The caller now owns the hook. */ +extern JS_FRIEND_API(SourceHook *) +ForgetSourceHook(JSRuntime *rt); + inline JSRuntime * GetRuntime(const JSContext *cx) { @@ -228,16 +279,21 @@ GetCompartmentZone(JSCompartment *comp); typedef bool (* PreserveWrapperCallback)(JSContext *cx, JSObject *obj); +typedef enum { + CollectNurseryBeforeDump, + IgnoreNurseryObjects +} DumpHeapNurseryBehaviour; + /* * Dump the complete object graph of heap-allocated things. * fp is the file for the dump output. */ extern JS_FRIEND_API(void) -DumpHeapComplete(JSRuntime *rt, FILE *fp); +DumpHeapComplete(JSRuntime *rt, FILE *fp, DumpHeapNurseryBehaviour nurseryBehaviour); -#ifdef OLD_GETTER_SETTER_METHODS -JS_FRIEND_API(JSBool) obj_defineGetter(JSContext *cx, unsigned argc, js::Value *vp); -JS_FRIEND_API(JSBool) obj_defineSetter(JSContext *cx, unsigned argc, js::Value *vp); +#ifdef JS_OLD_GETTER_SETTER_METHODS +JS_FRIEND_API(bool) obj_defineGetter(JSContext *cx, unsigned argc, JS::Value *vp); +JS_FRIEND_API(bool) obj_defineSetter(JSContext *cx, unsigned argc, JS::Value *vp); #endif extern JS_FRIEND_API(bool) @@ -257,7 +313,7 @@ IsAtomsCompartment(JSCompartment *comp); * particularly, always reports when it returns false). */ extern JS_FRIEND_API(bool) -ReportIfUndeclaredVarAssignment(JSContext *cx, HandleString propname); +ReportIfUndeclaredVarAssignment(JSContext *cx, JS::HandleString propname); /* * Returns whether we're in a non-strict property set (in that we're in a @@ -274,7 +330,7 @@ struct WeakMapTracer; * Weak map tracer callback, called once for every binding of every * weak map that was live at the time of the last garbage collection. * - * m will be NULL if the weak map is not contained in a JS Object. + * m will be nullptr if the weak map is not contained in a JS Object. */ typedef void (* WeakMapTraceCallback)(WeakMapTracer *trc, JSObject *m, @@ -330,12 +386,12 @@ GetAnyCompartmentInZone(JS::Zone *zone); namespace shadow { struct TypeObject { - Class *clasp; + const Class *clasp; JSObject *proto; }; struct BaseShape { - js::Class *clasp; + const js::Class *clasp; JSObject *parent; JSObject *_1; JSCompartment *compartment; @@ -353,15 +409,15 @@ public: struct Object { shadow::Shape *shape; shadow::TypeObject *type; - js::Value *slots; - js::Value *_1; + JS::Value *slots; + JS::Value *_1; size_t numFixedSlots() const { return shape->slotInfo >> Shape::FIXED_SLOTS_SHIFT; } - Value *fixedSlots() const { - return (Value *)(uintptr_t(this) + sizeof(shadow::Object)); + JS::Value *fixedSlots() const { + return (JS::Value *)(uintptr_t(this) + sizeof(shadow::Object)); } - js::Value &slotRef(size_t slot) const { + JS::Value &slotRef(size_t slot) const { size_t nfixed = numFixedSlots(); if (slot < nfixed) return fixedSlots()[slot]; @@ -374,7 +430,7 @@ struct Function { uint16_t nargs; uint16_t flags; /* Used only for natives */ - Native native; + JSNative native; const JSJitInfo *jitinfo; void *_1; }; @@ -387,23 +443,17 @@ struct Atom { } /* namespace shadow */ -// These are equal to |&{Function,Object,OuterWindow}ProxyObject::class_|. Use -// them in places where you don't want to #include vm/ProxyObject.h. -extern JS_FRIEND_DATA(js::Class* const) FunctionProxyClassPtr; -extern JS_FRIEND_DATA(js::Class* const) ObjectProxyClassPtr; -extern JS_FRIEND_DATA(js::Class* const) OuterWindowProxyClassPtr; - // This is equal to |&JSObject::class_|. Use it in places where you don't want // to #include jsobj.h. -extern JS_FRIEND_DATA(js::Class* const) ObjectClassPtr; +extern JS_FRIEND_DATA(const js::Class* const) ObjectClassPtr; -inline js::Class * +inline const js::Class * GetObjectClass(JSObject *obj) { return reinterpret_cast(obj)->type->clasp; } -inline JSClass * +inline const JSClass * GetObjectJSClass(JSObject *obj) { return js::Jsvalify(GetObjectClass(obj)); @@ -447,6 +497,16 @@ GetObjectParentMaybeScope(JSObject *obj); JS_FRIEND_API(JSObject *) GetGlobalForObjectCrossCompartment(JSObject *obj); +JS_FRIEND_API(void) +AssertSameCompartment(JSContext *cx, JSObject *obj); + +#ifdef DEBUG +JS_FRIEND_API(void) +AssertSameCompartment(JSObject *objA, JSObject *objB); +#else +inline void AssertSameCompartment(JSObject *objA, JSObject *objB) {} +#endif + // For legacy consumers only. This whole concept is going away soon. JS_FRIEND_API(JSObject *) DefaultObjectForContextOrNull(JSContext *cx); @@ -462,7 +522,7 @@ IsOriginalScriptFunction(JSFunction *fun); /* * Return the outermost enclosing function (script) of the scripted caller. - * This function returns NULL in several cases: + * This function returns nullptr in several cases: * - no script is running on the context * - the caller is in global or eval code * In particular, this function will "stop" its outermost search at eval() and @@ -486,30 +546,18 @@ NewFunctionByIdWithReserved(JSContext *cx, JSNative native, unsigned nargs, unsi JS_FRIEND_API(JSObject *) InitClassWithReserved(JSContext *cx, JSObject *obj, JSObject *parent_proto, - JSClass *clasp, JSNative constructor, unsigned nargs, + const JSClass *clasp, JSNative constructor, unsigned nargs, const JSPropertySpec *ps, const JSFunctionSpec *fs, const JSPropertySpec *static_ps, const JSFunctionSpec *static_fs); -JS_FRIEND_API(const Value &) +JS_FRIEND_API(const JS::Value &) GetFunctionNativeReserved(JSObject *fun, size_t which); JS_FRIEND_API(void) -SetFunctionNativeReserved(JSObject *fun, size_t which, const Value &val); +SetFunctionNativeReserved(JSObject *fun, size_t which, const JS::Value &val); -inline bool -GetObjectProto(JSContext *cx, JS::Handle obj, JS::MutableHandle proto) -{ - js::Class *clasp = GetObjectClass(obj); - if (clasp == js::ObjectProxyClassPtr || - clasp == js::OuterWindowProxyClassPtr || - clasp == js::FunctionProxyClassPtr) - { - return JS_GetPrototype(cx, obj, proto); - } - - proto.set(reinterpret_cast(obj.get())->type->proto); - return true; -} +JS_FRIEND_API(bool) +GetObjectProto(JSContext *cx, JS::Handle obj, JS::MutableHandle proto); inline void * GetObjectPrivate(JSObject *obj) @@ -523,7 +571,7 @@ GetObjectPrivate(JSObject *obj) * Get a slot that is both reserved for object's clasp *and* is fixed (fits * within the maximum capacity for the object's fixed slots). */ -inline const Value & +inline const JS::Value & GetReservedSlot(JSObject *obj, size_t slot) { JS_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); @@ -531,10 +579,10 @@ GetReservedSlot(JSObject *obj, size_t slot) } JS_FRIEND_API(void) -SetReservedSlotWithBarrier(JSObject *obj, size_t slot, const Value &value); +SetReservedSlotWithBarrier(JSObject *obj, size_t slot, const JS::Value &value); inline void -SetReservedSlot(JSObject *obj, size_t slot, const Value &value) +SetReservedSlot(JSObject *obj, size_t slot, const JS::Value &value) { JS_ASSERT(slot < JSCLASS_RESERVED_SLOTS(GetObjectClass(obj))); shadow::Object *sobj = reinterpret_cast(obj); @@ -553,7 +601,7 @@ SetReservedSlot(JSObject *obj, size_t slot, const Value &value) JS_FRIEND_API(uint32_t) GetObjectSlotSpan(JSObject *obj); -inline const Value & +inline const JS::Value & GetObjectSlot(JSObject *obj, size_t slot) { JS_ASSERT(slot < GetObjectSlotSpan(obj)); @@ -579,26 +627,14 @@ AtomToLinearString(JSAtom *atom) return reinterpret_cast(atom); } -static inline js::PropertyOp -CastAsJSPropertyOp(JSObject *object) -{ - return JS_DATA_TO_FUNC_PTR(js::PropertyOp, object); -} - -static inline js::StrictPropertyOp -CastAsJSStrictPropertyOp(JSObject *object) -{ - return JS_DATA_TO_FUNC_PTR(js::StrictPropertyOp, object); -} +JS_FRIEND_API(bool) +GetPropertyNames(JSContext *cx, JSObject *obj, unsigned flags, JS::AutoIdVector *props); JS_FRIEND_API(bool) -GetPropertyNames(JSContext *cx, JSObject *obj, unsigned flags, js::AutoIdVector *props); +AppendUnique(JSContext *cx, JS::AutoIdVector &base, JS::AutoIdVector &others); JS_FRIEND_API(bool) -AppendUnique(JSContext *cx, AutoIdVector &base, AutoIdVector &others); - -JS_FRIEND_API(bool) -GetGeneric(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id, Value *vp); +GetGeneric(JSContext *cx, JSObject *obj, JSObject *receiver, jsid id, JS::Value *vp); JS_FRIEND_API(bool) StringIsArrayIndex(JSLinearString *str, uint32_t *indexp); @@ -609,6 +645,14 @@ SetPreserveWrapperCallback(JSRuntime *rt, PreserveWrapperCallback callback); JS_FRIEND_API(bool) IsObjectInContextCompartment(JSObject *obj, const JSContext *cx); +/* + * ErrorFromException takes a raw Value so that it's possible to call it during + * GC/CC/whatever, when it may not be possible to get a JSContext to create a + * Rooted. It promises to never ever GC. + */ +JS_FRIEND_API(JSErrorReport*) +ErrorFromException(JS::Value val); + /* * NB: these flag bits are encoded into the bytecode stream in the immediate * operand of JSOP_ITER, so don't change them without advancing vm/Xdr.h's @@ -619,18 +663,18 @@ IsObjectInContextCompartment(JSObject *obj, const JSContext *cx); #define JSITER_KEYVALUE 0x4 /* destructuring for-in wants [key, value] */ #define JSITER_OWNONLY 0x8 /* iterate over obj's own properties only */ #define JSITER_HIDDEN 0x10 /* also enumerate non-enumerable properties */ -#define JSITER_FOR_OF 0x20 /* harmony for-of loop */ -inline uintptr_t -GetNativeStackLimit(const JSRuntime *rt) -{ - return PerThreadDataFriendFields::getMainThread(rt)->nativeStackLimit; -} +JS_FRIEND_API(bool) +RunningWithTrustedPrincipals(JSContext *cx); inline uintptr_t GetNativeStackLimit(JSContext *cx) { - return GetNativeStackLimit(GetRuntime(cx)); + StackKind kind = RunningWithTrustedPrincipals(cx) ? StackForTrustedScript + : StackForUntrustedScript; + PerThreadDataFriendFields *mainThread = + PerThreadDataFriendFields::getMainThread(GetRuntime(cx)); + return mainThread->nativeStackLimit[kind]; } /* @@ -655,6 +699,14 @@ GetNativeStackLimit(JSContext *cx) } \ JS_END_MACRO +#define JS_CHECK_RECURSION_WITH_SP(cx, sp, onerror) \ + JS_BEGIN_MACRO \ + if (!JS_CHECK_STACK_SIZE(js::GetNativeStackLimit(cx), sp)) { \ + js_ReportOverRecursed(cx); \ + onerror; \ + } \ + JS_END_MACRO + #define JS_CHECK_CHROME_RECURSION(cx, onerror) \ JS_BEGIN_MACRO \ int stackDummy_; \ @@ -685,94 +737,13 @@ GetPCCountScriptSummary(JSContext *cx, size_t script); JS_FRIEND_API(JSString *) GetPCCountScriptContents(JSContext *cx, size_t script); -/* - * A call stack can be specified to the JS engine such that all JS entry/exits - * to functions push/pop an entry to/from the specified stack. - * - * For more detailed information, see vm/SPSProfiler.h - */ -class ProfileEntry -{ - /* - * All fields are marked volatile to prevent the compiler from re-ordering - * instructions. Namely this sequence: - * - * entry[size] = ...; - * size++; - * - * If the size modification were somehow reordered before the stores, then - * if a sample were taken it would be examining bogus information. - * - * A ProfileEntry represents both a C++ profile entry and a JS one. Both use - * the string as a description, but JS uses the sp as NULL to indicate that - * it is a JS entry. The script_ is then only ever examined for a JS entry, - * and the idx is used by both, but with different meanings. - */ - const char * volatile string; // Descriptive string of this entry - void * volatile sp; // Relevant stack pointer for the entry - JSScript * volatile script_; // if js(), non-null script which is running - int32_t volatile idx; // if js(), idx of pc, otherwise line number - - public: - /* - * All of these methods are marked with the 'volatile' keyword because SPS's - * representation of the stack is stored such that all ProfileEntry - * instances are volatile. These methods would not be available unless they - * were marked as volatile as well - */ - - bool js() volatile { - JS_ASSERT_IF(sp == NULL, script_ != NULL); - return sp == NULL; - } - - uint32_t line() volatile { JS_ASSERT(!js()); return idx; } - JSScript *script() volatile { JS_ASSERT(js()); return script_; } - void *stackAddress() volatile { return sp; } - const char *label() volatile { return string; } - - void setLine(uint32_t aLine) volatile { JS_ASSERT(!js()); idx = aLine; } - void setLabel(const char *aString) volatile { string = aString; } - void setStackAddress(void *aSp) volatile { sp = aSp; } - void setScript(JSScript *aScript) volatile { script_ = aScript; } - - /* we can't know the layout of JSScript, so look in vm/SPSProfiler.cpp */ - JS_FRIEND_API(jsbytecode *) pc() volatile; - JS_FRIEND_API(void) setPC(jsbytecode *pc) volatile; - - static size_t offsetOfString() { return offsetof(ProfileEntry, string); } - static size_t offsetOfStackAddress() { return offsetof(ProfileEntry, sp); } - static size_t offsetOfPCIdx() { return offsetof(ProfileEntry, idx); } - static size_t offsetOfScript() { return offsetof(ProfileEntry, script_); } - - /* - * The index used in the entry can either be a line number or the offset of - * a pc into a script's code. To signify a NULL pc, use a -1 index. This is - * checked against in pc() and setPC() to set/get the right pc. - */ - static const int32_t NullPCIndex = -1; -}; - -JS_FRIEND_API(void) -SetRuntimeProfilingStack(JSRuntime *rt, ProfileEntry *stack, uint32_t *size, - uint32_t max); - -JS_FRIEND_API(void) -EnableRuntimeProfilingStack(JSRuntime *rt, bool enabled); - -JS_FRIEND_API(jsbytecode*) -ProfilingGetPC(JSRuntime *rt, JSScript *script, void *ip); - #ifdef JS_THREADSAFE JS_FRIEND_API(bool) ContextHasOutstandingRequests(const JSContext *cx); #endif -JS_FRIEND_API(bool) -HasUnrootedGlobal(const JSContext *cx); - typedef void -(* ActivityCallback)(void *arg, JSBool active); +(* ActivityCallback)(void *arg, bool active); /* * Sets a callback that is run whenever the runtime goes idle - the @@ -785,22 +756,10 @@ SetActivityCallback(JSRuntime *rt, ActivityCallback cb, void *arg); extern JS_FRIEND_API(const JSStructuredCloneCallbacks *) GetContextStructuredCloneCallbacks(JSContext *cx); -extern JS_FRIEND_API(bool) -CanCallContextDebugHandler(JSContext *cx); - -extern JS_FRIEND_API(JSTrapStatus) -CallContextDebugHandler(JSContext *cx, JSScript *script, jsbytecode *bc, Value *rval); - extern JS_FRIEND_API(bool) IsContextRunningJS(JSContext *cx); -typedef void -(* AnalysisPurgeCallback)(JSRuntime *rt, JS::Handle desc); - -extern JS_FRIEND_API(AnalysisPurgeCallback) -SetAnalysisPurgeCallback(JSRuntime *rt, AnalysisPurgeCallback callback); - -typedef JSBool +typedef bool (* DOMInstanceClassMatchesProto)(JS::HandleObject protoObject, uint32_t protoID, uint32_t depth); struct JSDOMCallbacks { @@ -832,10 +791,10 @@ CastToJSFreeOp(FreeOp *fop) /* * Get an error type name from a JSExnType constant. - * Returns NULL for invalid arguments and JSEXN_INTERNALERR + * Returns nullptr for invalid arguments and JSEXN_INTERNALERR */ extern JS_FRIEND_API(const jschar*) -GetErrorTypeName(JSContext* cx, int16_t exnType); +GetErrorTypeName(JSRuntime* rt, int16_t exnType); #ifdef DEBUG extern JS_FRIEND_API(unsigned) @@ -886,7 +845,7 @@ struct CompartmentsWithPrincipals : public CompartmentFilter { } }; -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) NukeCrossCompartmentWrappers(JSContext* cx, const CompartmentFilter& sourceFilter, const CompartmentFilter& targetFilter, @@ -910,7 +869,7 @@ NukeCrossCompartmentWrappers(JSContext* cx, struct ExpandoAndGeneration { ExpandoAndGeneration() - : expando(UndefinedValue()), + : expando(JS::UndefinedValue()), generation(0) {} @@ -933,10 +892,10 @@ typedef enum DOMProxyShadowsResult { typedef DOMProxyShadowsResult (* DOMProxyShadowsCheck)(JSContext* cx, JS::HandleObject object, JS::HandleId id); JS_FRIEND_API(void) -SetDOMProxyInformation(void *domProxyHandlerFamily, uint32_t domProxyExpandoSlot, +SetDOMProxyInformation(const void *domProxyHandlerFamily, uint32_t domProxyExpandoSlot, DOMProxyShadowsCheck domProxyShadowsCheck); -void *GetDOMProxyHandlerFamily(); +const void *GetDOMProxyHandlerFamily(); uint32_t GetDOMProxyExpandoSlot(); DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); @@ -948,7 +907,7 @@ DOMProxyShadowsCheck GetDOMProxyShadowsCheck(); * Detect whether the internal date value is NaN. (Because failure is * out-of-band for js_DateGet*) */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_DateIsValid(JSObject* obj); extern JS_FRIEND_API(double) @@ -1008,136 +967,6 @@ enum ViewType { } /* namespace ArrayBufferView */ -/* - * A helper for building up an ArrayBuffer object's data - * before creating the ArrayBuffer itself. Will do doubling - * based reallocation, up to an optional maximum growth given. - * - * When all the data has been appended, call getArrayBuffer, - * passing in the JSContext* for which the ArrayBuffer object - * is to be created. This also implicitly resets the builder, - * or it can be reset explicitly at any point by calling reset(). - */ -class ArrayBufferBuilder -{ - void *rawcontents_; - uint8_t *dataptr_; - uint32_t capacity_; - uint32_t length_; - public: - ArrayBufferBuilder() - : rawcontents_(NULL), - dataptr_(NULL), - capacity_(0), - length_(0) - { - } - - ~ArrayBufferBuilder() { - reset(); - } - - void reset() { - if (rawcontents_) - JS_free(NULL, rawcontents_); - rawcontents_ = dataptr_ = NULL; - capacity_ = length_ = 0; - } - - // will truncate if newcap is < length() - bool setCapacity(uint32_t newcap) { - if (!JS_ReallocateArrayBufferContents(NULL, newcap, &rawcontents_, &dataptr_)) - return false; - - capacity_ = newcap; - if (length_ > newcap) - length_ = newcap; - - return true; - } - - // Append datalen bytes from data to the current buffer. If we - // need to grow the buffer, grow by doubling the size up to a - // maximum of maxgrowth (if given). If datalen is greater than - // what the new capacity would end up as, then grow by datalen. - // - // The data parameter must not overlap with anything beyond the - // builder's current valid contents [0..length) - bool append(const uint8_t *newdata, uint32_t datalen, uint32_t maxgrowth = 0) { - if (length_ + datalen > capacity_) { - uint32_t newcap; - // double while under maxgrowth or if not specified - if (!maxgrowth || capacity_ < maxgrowth) - newcap = capacity_ * 2; - else - newcap = capacity_ + maxgrowth; - - // but make sure there's always enough to satisfy our request - if (newcap < length_ + datalen) - newcap = length_ + datalen; - - // did we overflow? - if (newcap < capacity_) - return false; - - if (!setCapacity(newcap)) - return false; - } - - // assert that the region isn't overlapping so we can memcpy; - JS_ASSERT(!areOverlappingRegions(newdata, datalen, dataptr_ + length_, datalen)); - - memcpy(dataptr_ + length_, newdata, datalen); - length_ += datalen; - - return true; - } - - uint8_t *data() { - return dataptr_; - } - - uint32_t length() { - return length_; - } - - uint32_t capacity() { - return capacity_; - } - - JSObject* getArrayBuffer(JSContext *cx) { - // we need to check for length_ == 0, because nothing may have been - // added - if (capacity_ > length_ || length_ == 0) { - if (!setCapacity(length_)) - return NULL; - } - - JSObject* obj = JS_NewArrayBufferWithContents(cx, rawcontents_); - if (!obj) - return NULL; - - rawcontents_ = dataptr_ = NULL; - length_ = capacity_ = 0; - - return obj; - } - -protected: - - static bool areOverlappingRegions(const uint8_t *start1, uint32_t length1, - const uint8_t *start2, uint32_t length2) - { - const uint8_t *end1 = start1 + length1; - const uint8_t *end2 = start2 + length2; - - const uint8_t *max_start = start1 > start2 ? start1 : start2; - const uint8_t *min_end = end1 < end2 ? end1 : end2; - - return max_start < min_end; - } -}; - } /* namespace js */ typedef js::ArrayBufferView::ViewType JSArrayBufferViewType; @@ -1241,7 +1070,7 @@ JS_NewArrayBuffer(JSContext *cx, uint32_t nbytes); * this test or one of the JS_Is*Array tests succeeds, then it is safe to call * the various accessor JSAPI calls defined below. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsTypedArrayObject(JSObject *obj); /* @@ -1251,36 +1080,36 @@ JS_IsTypedArrayObject(JSObject *obj); * is safe to call the various ArrayBufferView accessor JSAPI calls defined * below. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsArrayBufferViewObject(JSObject *obj); /* * Test for specific typed array types (ArrayBufferView subtypes) */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsInt8Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint8Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint8ClampedArray(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsInt16Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint16Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsInt32Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsUint32Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsFloat32Array(JSObject *obj); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsFloat64Array(JSObject *obj); /* - * Unwrap Typed arrays all at once. Return NULL without throwing if the object - * cannot be viewed as the correct typed array, or the typed array object on - * success, filling both outparameters. + * Unwrap Typed arrays all at once. Return nullptr without throwing if the + * object cannot be viewed as the correct typed array, or the typed array + * object on success, filling both outparameters. */ extern JS_FRIEND_API(JSObject *) JS_GetObjectAsInt8Array(JSObject *obj, uint32_t *length, int8_t **data); @@ -1321,7 +1150,7 @@ JS_GetArrayBufferViewType(JSObject *obj); * unwrapping. If this test succeeds, then it is safe to call the various * accessor JSAPI calls defined below. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsArrayBufferObject(JSObject *obj); /* @@ -1382,7 +1211,7 @@ JS_GetTypedArrayByteLength(JSObject *obj); * return false if a security wrapper is encountered that denies the * unwrapping. */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) JS_IsArrayBufferViewObject(JSObject *obj); /* @@ -1435,10 +1264,16 @@ JS_GetArrayBufferViewData(JSObject *obj); extern JS_FRIEND_API(JSObject *) JS_GetArrayBufferViewBuffer(JSObject *obj); +/* + * Set an ArrayBuffer's length to 0 and neuter all of its views. + */ +extern JS_FRIEND_API(void) +JS_NeuterArrayBuffer(JSObject *obj, JSContext *cx); + /* * Check whether obj supports JS_GetDataView* APIs. */ -JS_FRIEND_API(JSBool) +JS_FRIEND_API(bool) JS_IsDataViewObject(JSObject *obj); /* @@ -1457,7 +1292,7 @@ JS_GetDataViewByteOffset(JSObject *obj); * * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is NULL, then DEBUG builds may be + * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be * unable to assert when unwrapping should be disallowed. */ JS_FRIEND_API(uint32_t) @@ -1468,12 +1303,39 @@ JS_GetDataViewByteLength(JSObject *obj); * * |obj| must have passed a JS_IsDataViewObject test, or somehow be known that * it would pass such a test: it is a data view or a wrapper of a data view, - * and the unwrapping will succeed. If cx is NULL, then DEBUG builds may be + * and the unwrapping will succeed. If cx is nullptr, then DEBUG builds may be * unable to assert when unwrapping should be disallowed. */ JS_FRIEND_API(void *) JS_GetDataViewData(JSObject *obj); +namespace js { + +/* + * Add a watchpoint -- in the Object.prototype.watch sense -- to |obj| for the + * property |id|, using the callable object |callable| as the function to be + * called for notifications. + * + * This is an internal function exposed -- temporarily -- only so that DOM + * proxies can be watchable. Don't use it! We'll soon kill off the + * Object.prototype.{,un}watch functions, at which point this will go too. + */ +extern JS_FRIEND_API(bool) +WatchGuts(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject callable); + +/* + * Remove a watchpoint -- in the Object.prototype.watch sense -- from |obj| for + * the property |id|. + * + * This is an internal function exposed -- temporarily -- only so that DOM + * proxies can be watchable. Don't use it! We'll soon kill off the + * Object.prototype.{,un}watch functions, at which point this will go too. + */ +extern JS_FRIEND_API(bool) +UnwatchGuts(JSContext *cx, JS::HandleObject obj, JS::HandleId id); + +} // namespace js + /* * A class, expected to be passed by value, which represents the CallArgs for a * JSJitGetterOp. @@ -1599,7 +1461,7 @@ struct JSJitInfo { }; #define JS_JITINFO_NATIVE_PARALLEL(op) \ - {{NULL},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} + {{nullptr},0,0,JSJitInfo::OpType_None,false,false,false,JSVAL_TYPE_MISSING,op} static JS_ALWAYS_INLINE const JSJitInfo * FUNCTION_VALUE_TO_JITINFO(const JS::Value& v) @@ -1632,6 +1494,12 @@ JSID_FROM_BITS(size_t bits) return id; } +namespace js { +namespace detail { +bool IdMatchesAtom(jsid id, JSAtom *atom); +} +} + /* * Must not be used on atoms that are representable as integer jsids. * Prefer NameToId or AtomToId over this function: @@ -1658,18 +1526,18 @@ NON_INTEGER_ATOM_TO_JSID(JSAtom *atom) { JS_ASSERT(((size_t)atom & 0x7) == 0); jsid id = JSID_FROM_BITS((size_t)atom); - JS_ASSERT(id == INTERNED_STRING_TO_JSID(NULL, (JSString*)atom)); + JS_ASSERT(js::detail::IdMatchesAtom(id, atom)); return id; } /* All strings stored in jsids are atomized, but are not necessarily property names. */ -static JS_ALWAYS_INLINE JSBool +static JS_ALWAYS_INLINE bool JSID_IS_ATOM(jsid id) { return JSID_IS_STRING(id); } -static JS_ALWAYS_INLINE JSBool +static JS_ALWAYS_INLINE bool JSID_IS_ATOM(jsid id, JSAtom *atom) { return id == JSID_FROM_BITS((size_t)atom); @@ -1681,21 +1549,21 @@ JSID_TO_ATOM(jsid id) return (JSAtom *)JSID_TO_STRING(id); } -JS_STATIC_ASSERT(sizeof(jsid) == JS_BYTES_PER_WORD); +JS_STATIC_ASSERT(sizeof(jsid) == sizeof(void*)); namespace js { -static JS_ALWAYS_INLINE Value +static JS_ALWAYS_INLINE JS::Value IdToValue(jsid id) { if (JSID_IS_STRING(id)) - return StringValue(JSID_TO_STRING(id)); + return JS::StringValue(JSID_TO_STRING(id)); if (JS_LIKELY(JSID_IS_INT(id))) - return Int32Value(JSID_TO_INT(id)); + return JS::Int32Value(JSID_TO_INT(id)); if (JS_LIKELY(JSID_IS_OBJECT(id))) - return ObjectValue(*JSID_TO_OBJECT(id)); + return JS::ObjectValue(*JSID_TO_OBJECT(id)); JS_ASSERT(JSID_IS_VOID(id)); - return UndefinedValue(); + return JS::UndefinedValue(); } static JS_ALWAYS_INLINE jsval @@ -1710,6 +1578,20 @@ IsReadOnlyDateMethod(JS::IsAcceptableThis test, JS::NativeImpl method); extern JS_FRIEND_API(bool) IsTypedArrayThisCheck(JS::IsAcceptableThis test); +/* + * If the embedder has registered a default JSContext callback, returns the + * result of the callback. Otherwise, asserts that |rt| has exactly one + * JSContext associated with it, and returns that context. + */ +extern JS_FRIEND_API(JSContext *) +DefaultJSContext(JSRuntime *rt); + +typedef JSContext* +(* DefaultJSContextCallback)(JSRuntime *rt); + +JS_FRIEND_API(void) +SetDefaultJSContextCallback(JSRuntime *rt, DefaultJSContextCallback cb); + enum CTypesActivityType { CTYPES_CALL_BEGIN, CTYPES_CALL_END, @@ -1744,7 +1626,7 @@ class JS_FRIEND_API(AutoCTypesActivityCallback) { void DoEndCallback() { if (callback) { callback(cx, endType); - callback = NULL; + callback = nullptr; } } }; @@ -1777,8 +1659,8 @@ JS_FRIEND_API(JSObject *) GetObjectMetadata(JSObject *obj); /* ES5 8.12.8. */ -extern JS_FRIEND_API(JSBool) -DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, MutableHandleValue vp); +extern JS_FRIEND_API(bool) +DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, JS::MutableHandleValue vp); /* * Helper function. To approximate a call to the [[DefineOwnProperty]] internal @@ -1794,16 +1676,16 @@ DefaultValue(JSContext *cx, JS::HandleObject obj, JSType hint, MutableHandleValu * js::ProxyHandler, or the JSAPI with precisely the right semantics for it. */ extern JS_FRIEND_API(bool) -CheckDefineProperty(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, - PropertyOp getter, StrictPropertyOp setter, unsigned attrs); +CheckDefineProperty(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue value, + JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs); } /* namespace js */ -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_DefineOwnProperty(JSContext *cx, JSObject *objArg, jsid idArg, - const js::PropertyDescriptor& descriptor, JSBool *bp); + JS::Handle descriptor, bool *bp); -extern JS_FRIEND_API(JSBool) +extern JS_FRIEND_API(bool) js_ReportIsNotFunction(JSContext *cx, const JS::Value& v); #ifdef JSGC_GENERATIONAL diff --git a/external/spidermonkey/include/win32/jslock.h b/external/spidermonkey/include/win32/jslock.h deleted file mode 100644 index 522034ad68..0000000000 --- a/external/spidermonkey/include/win32/jslock.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -#ifndef jslock_h -#define jslock_h - -#ifdef JS_THREADSAFE - -# include "jsapi.h" -# include "pratom.h" -# include "prcvar.h" -# include "prinit.h" -# include "prlock.h" -# include "prthread.h" - -# define JS_ATOMIC_INCREMENT(p) PR_ATOMIC_INCREMENT((int32_t *)(p)) -# define JS_ATOMIC_DECREMENT(p) PR_ATOMIC_DECREMENT((int32_t *)(p)) -# define JS_ATOMIC_ADD(p,v) PR_ATOMIC_ADD((int32_t *)(p), (int32_t)(v)) -# define JS_ATOMIC_SET(p,v) PR_ATOMIC_SET((int32_t *)(p), (int32_t)(v)) - -namespace js { - // Defined in jsgc.cpp. - unsigned GetCPUCount(); -} - -#else /* JS_THREADSAFE */ - -typedef struct PRThread PRThread; -typedef struct PRCondVar PRCondVar; -typedef struct PRLock PRLock; - -# define JS_ATOMIC_INCREMENT(p) (++*(p)) -# define JS_ATOMIC_DECREMENT(p) (--*(p)) -# define JS_ATOMIC_ADD(p,v) (*(p) += (v)) -# define JS_ATOMIC_SET(p,v) (*(p) = (v)) - -#endif /* JS_THREADSAFE */ - -#endif /* jslock_h */ diff --git a/external/spidermonkey/include/win32/jsperf.h b/external/spidermonkey/include/win32/jsperf.h index 468ce8609c..e3cbc23143 100644 --- a/external/spidermonkey/include/win32/jsperf.h +++ b/external/spidermonkey/include/win32/jsperf.h @@ -6,7 +6,10 @@ #ifndef perf_jsperf_h #define perf_jsperf_h -#include "jsapi.h" +#include "jstypes.h" + +#include "js/TypeDecls.h" +#include "js/Utility.h" namespace JS { @@ -118,12 +121,12 @@ extern JS_FRIEND_API(JSObject*) RegisterPerfMeasurement(JSContext *cx, JSObject *global); /* - * Given a jsval which contains an instance of the aforementioned - * wrapper class, extract the C++ object. Returns NULL if the - * jsval is not an instance of the wrapper. + * Given a Value which contains an instance of the aforementioned + * wrapper class, extract the C++ object. Returns nullptr if the + * Value is not an instance of the wrapper. */ extern JS_FRIEND_API(PerfMeasurement*) - ExtractPerfMeasurement(jsval wrapper); + ExtractPerfMeasurement(Value wrapper); } // namespace JS diff --git a/external/spidermonkey/include/win32/jsprf.h b/external/spidermonkey/include/win32/jsprf.h index ce159d8115..b235f0b4fb 100644 --- a/external/spidermonkey/include/win32/jsprf.h +++ b/external/spidermonkey/include/win32/jsprf.h @@ -26,7 +26,6 @@ */ #include -#include #include "jstypes.h" @@ -39,7 +38,7 @@ extern JS_PUBLIC_API(uint32_t) JS_snprintf(char *out, uint32_t outlen, const cha /* ** sprintf into a malloc'd buffer. Return a pointer to the malloc'd -** buffer on success, NULL on failure. Call "JS_smprintf_free" to release +** buffer on success, nullptr on failure. Call "JS_smprintf_free" to release ** the memory returned. */ extern JS_PUBLIC_API(char*) JS_smprintf(const char *fmt, ...); @@ -52,9 +51,9 @@ extern JS_PUBLIC_API(void) JS_smprintf_free(char *mem); /* ** "append" sprintf into a malloc'd buffer. "last" is the last value of ** the malloc'd buffer. sprintf will append data to the end of last, -** growing it as necessary using realloc. If last is NULL, JS_sprintf_append +** growing it as necessary using realloc. If last is nullptr, JS_sprintf_append ** will allocate the initial string. The return value is the new value of -** last for subsequent calls, or NULL if there is a malloc failure. +** last for subsequent calls, or nullptr if there is a malloc failure. */ extern JS_PUBLIC_API(char*) JS_sprintf_append(char *last, const char *fmt, ...); diff --git a/external/spidermonkey/include/win32/jsprototypes.h b/external/spidermonkey/include/win32/jsprototypes.h index f9bacac409..b0fee8c468 100644 --- a/external/spidermonkey/include/win32/jsprototypes.h +++ b/external/spidermonkey/include/win32/jsprototypes.h @@ -9,8 +9,6 @@ #ifndef jsprototypes_h #define jsprototypes_h -#include "jsversion.h" - /* * Enumerator codes in the second column must not change -- they are part of * the JS XDR API. Also note the symbols in the third column are extern "C"; @@ -56,20 +54,7 @@ macro(DataView, 35, js_InitTypedArrayClasses) \ macro(ParallelArray, 36, js_InitParallelArrayClass) \ macro(Intl, 37, js_InitIntlClass) \ - macro(Type, 38, js_InitBinaryDataClasses) \ - macro(Data, 39, js_InitBinaryDataClasses) \ - macro(uint8, 40, js_InitBinaryDataClasses) \ - macro(uint16, 41, js_InitBinaryDataClasses) \ - macro(uint32, 42, js_InitBinaryDataClasses) \ - macro(uint64, 43, js_InitBinaryDataClasses) \ - macro(int8, 44, js_InitBinaryDataClasses) \ - macro(int16, 45, js_InitBinaryDataClasses) \ - macro(int32, 46, js_InitBinaryDataClasses) \ - macro(int64, 47, js_InitBinaryDataClasses) \ - macro(float32, 48, js_InitBinaryDataClasses) \ - macro(float64, 49, js_InitBinaryDataClasses) \ - macro(ArrayType, 50, js_InitBinaryDataClasses) \ - macro(StructType, 51, js_InitBinaryDataClasses) \ - macro(ArrayTypeObject, 52, js_InitBinaryDataClasses) \ + macro(TypedObject, 38, js_InitTypedObjectDummy) \ + macro(GeneratorFunction, 39, js_InitIteratorClasses) \ #endif /* jsprototypes_h */ diff --git a/external/spidermonkey/include/win32/jsproxy.h b/external/spidermonkey/include/win32/jsproxy.h index 56868a05c3..c54e300d73 100644 --- a/external/spidermonkey/include/win32/jsproxy.h +++ b/external/spidermonkey/include/win32/jsproxy.h @@ -7,11 +7,29 @@ #ifndef jsproxy_h #define jsproxy_h -#include "jsapi.h" +#include "mozilla/Maybe.h" + #include "jsfriendapi.h" +#include "js/CallNonGenericMethod.h" +#include "js/Class.h" + namespace js { +using JS::AutoIdVector; +using JS::CallArgs; +using JS::HandleId; +using JS::HandleObject; +using JS::HandleValue; +using JS::IsAcceptableThis; +using JS::MutableHandle; +using JS::MutableHandleObject; +using JS::MutableHandleValue; +using JS::NativeImpl; +using JS::PrivateValue; +using JS::Value; + +class RegExpGuard; class JS_FRIEND_API(Wrapper); /* @@ -49,7 +67,7 @@ class JS_FRIEND_API(Wrapper); */ class JS_FRIEND_API(BaseProxyHandler) { - void *mFamily; + const void *mFamily; bool mHasPrototype; bool mHasPolicy; protected: @@ -58,7 +76,7 @@ class JS_FRIEND_API(BaseProxyHandler) void setHasPolicy(bool aHasPolicy) { mHasPolicy = aHasPolicy; } public: - explicit BaseProxyHandler(void *family); + explicit BaseProxyHandler(const void *family); virtual ~BaseProxyHandler(); bool hasPrototype() { @@ -69,9 +87,12 @@ class JS_FRIEND_API(BaseProxyHandler) return mHasPolicy; } - inline void *family() { + inline const void *family() { return mFamily; } + static size_t offsetOfFamily() { + return offsetof(BaseProxyHandler, mFamily); + } virtual bool isOuterWindow() { return false; @@ -106,12 +127,13 @@ class JS_FRIEND_API(BaseProxyHandler) /* ES5 Harmony fundamental proxy traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject proxy) = 0; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags) = 0; + MutableHandle desc, + unsigned flags) = 0; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, - HandleId id, PropertyDescriptor *desc, + HandleId id, MutableHandle desc, unsigned flags) = 0; virtual bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc) = 0; + MutableHandle desc) = 0; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props) = 0; virtual bool delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp) = 0; @@ -144,7 +166,13 @@ class JS_FRIEND_API(BaseProxyHandler) uint32_t index, MutableHandleValue vp, bool *present); virtual bool getPrototypeOf(JSContext *cx, HandleObject proxy, MutableHandleObject protop); - /* See comment for weakmapKeyDelegateOp in jsclass.h. */ + // These two hooks must be overridden, or not overridden, in tandem -- no + // overriding just one! + virtual bool watch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id, + JS::HandleObject callable); + virtual bool unwatch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id); + + /* See comment for weakmapKeyDelegateOp in js/Class.h. */ virtual JSObject *weakmapKeyDelegate(JSObject *proxy); }; @@ -157,17 +185,17 @@ class JS_FRIEND_API(BaseProxyHandler) class JS_PUBLIC_API(DirectProxyHandler) : public BaseProxyHandler { public: - explicit DirectProxyHandler(void *family); + explicit DirectProxyHandler(const void *family); /* ES5 Harmony fundamental proxy traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject proxy) MOZ_OVERRIDE; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, unsigned flags) MOZ_OVERRIDE; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, - HandleId id, PropertyDescriptor *desc, + HandleId id, MutableHandle desc, unsigned flags) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props) MOZ_OVERRIDE; virtual bool delete_(JSContext *cx, HandleObject proxy, HandleId id, @@ -204,8 +232,6 @@ class JS_PUBLIC_API(DirectProxyHandler) : public BaseProxyHandler unsigned indent) MOZ_OVERRIDE; virtual bool regexp_toShared(JSContext *cx, HandleObject proxy, RegExpGuard *g) MOZ_OVERRIDE; - virtual bool defaultValue(JSContext *cx, HandleObject obj, JSType hint, - MutableHandleValue vp) MOZ_OVERRIDE; virtual JSObject *weakmapKeyDelegate(JSObject *proxy); }; @@ -216,14 +242,15 @@ class Proxy /* ES5 Harmony fundamental proxy traps. */ static bool preventExtensions(JSContext *cx, HandleObject proxy); static bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags); + MutableHandle desc, unsigned flags); static bool getPropertyDescriptor(JSContext *cx, HandleObject proxy, unsigned flags, HandleId id, MutableHandleValue vp); static bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, HandleId id, - PropertyDescriptor *desc, unsigned flags); + MutableHandle desc, unsigned flags); static bool getOwnPropertyDescriptor(JSContext *cx, HandleObject proxy, unsigned flags, HandleId id, MutableHandleValue vp); - static bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, PropertyDescriptor *desc); + static bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, + MutableHandle desc); static bool defineProperty(JSContext *cx, HandleObject proxy, HandleId id, HandleValue v); static bool getOwnPropertyNames(JSContext *cx, HandleObject proxy, AutoIdVector &props); static bool delete_(JSContext *cx, HandleObject proxy, HandleId id, bool *bp); @@ -254,32 +281,27 @@ class Proxy static bool defaultValue(JSContext *cx, HandleObject obj, JSType hint, MutableHandleValue vp); static bool getPrototypeOf(JSContext *cx, HandleObject proxy, MutableHandleObject protop); + static bool watch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id, + JS::HandleObject callable); + static bool unwatch(JSContext *cx, JS::HandleObject proxy, JS::HandleId id); + + /* IC entry path for handling __noSuchMethod__ on access. */ + static bool callProp(JSContext *cx, HandleObject proxy, HandleObject reveiver, HandleId id, + MutableHandleValue vp); + static JSObject * const LazyProto; }; -inline bool IsObjectProxyClass(const Class *clasp) -{ - return clasp == js::ObjectProxyClassPtr || clasp == js::OuterWindowProxyClassPtr; -} - -inline bool IsFunctionProxyClass(const Class *clasp) -{ - return clasp == js::FunctionProxyClassPtr; -} +// Use these in places where you don't want to #include vm/ProxyObject.h. +extern JS_FRIEND_DATA(const js::Class* const) CallableProxyClassPtr; +extern JS_FRIEND_DATA(const js::Class* const) UncallableProxyClassPtr; +extern JS_FRIEND_DATA(const js::Class* const) OuterWindowProxyClassPtr; inline bool IsProxyClass(const Class *clasp) { - return IsObjectProxyClass(clasp) || IsFunctionProxyClass(clasp); -} - -inline bool IsObjectProxy(JSObject *obj) -{ - return IsObjectProxyClass(GetObjectClass(obj)); -} - -inline bool IsFunctionProxy(JSObject *obj) -{ - return IsFunctionProxyClass(GetObjectClass(obj)); + return clasp == CallableProxyClassPtr || + clasp == UncallableProxyClassPtr || + clasp == OuterWindowProxyClassPtr; } inline bool IsProxy(JSObject *obj) @@ -342,14 +364,42 @@ SetProxyExtra(JSObject *obj, size_t n, const Value &extra) SetReservedSlot(obj, PROXY_EXTRA_SLOT + n, extra); } -enum ProxyCallable { - ProxyNotCallable = false, - ProxyIsCallable = true +class MOZ_STACK_CLASS ProxyOptions { + public: + ProxyOptions() : callable_(false), + singleton_(false), + forceForegroundFinalization_(false) + {} + + bool callable() const { return callable_; } + ProxyOptions &setCallable(bool flag) { + callable_ = flag; + return *this; + } + + bool singleton() const { return singleton_; } + ProxyOptions &setSingleton(bool flag) { + singleton_ = flag; + return *this; + } + + bool forceForegroundFinalization() const { + return forceForegroundFinalization_; + } + ProxyOptions &setForceForegroundFinalization(bool flag) { + forceForegroundFinalization_ = true; + return *this; + } + + private: + bool callable_; + bool singleton_; + bool forceForegroundFinalization_; }; JS_FRIEND_API(JSObject *) NewProxyObject(JSContext *cx, BaseProxyHandler *handler, HandleValue priv, - JSObject *proto, JSObject *parent, ProxyCallable callable = ProxyNotCallable); + JSObject *proto, JSObject *parent, const ProxyOptions &options = ProxyOptions()); JSObject * RenewProxyObject(JSContext *cx, JSObject *obj, BaseProxyHandler *handler, Value priv); @@ -361,7 +411,7 @@ class JS_FRIEND_API(AutoEnterPolicy) AutoEnterPolicy(JSContext *cx, BaseProxyHandler *handler, HandleObject wrapper, HandleId id, Action act, bool mayThrow) #ifdef DEBUG - : context(NULL) + : context(nullptr) #endif { allow = handler->hasPolicy() ? handler->enter(cx, wrapper, id, act, &rv) @@ -372,8 +422,8 @@ class JS_FRIEND_API(AutoEnterPolicy) // * The policy set rv to false, indicating that we should throw. // * The caller did not instruct us to ignore exceptions. // * The policy did not throw itself. - if (!allow && !rv && mayThrow && !JS_IsExceptionPending(cx)) - reportError(cx, id); + if (!allow && !rv && mayThrow) + reportErrorIfExceptionIsNotPending(cx, id); } virtual ~AutoEnterPolicy() { recordLeave(); } @@ -384,10 +434,10 @@ class JS_FRIEND_API(AutoEnterPolicy) // no-op constructor for subclass AutoEnterPolicy() #ifdef DEBUG - : context(NULL) + : context(nullptr) #endif {}; - void reportError(JSContext *cx, jsid id); + void reportErrorIfExceptionIsNotPending(JSContext *cx, jsid id); bool allow; bool rv; diff --git a/external/spidermonkey/include/win32/jsprvtd.h b/external/spidermonkey/include/win32/jsprvtd.h deleted file mode 100644 index 1fbc086a7c..0000000000 --- a/external/spidermonkey/include/win32/jsprvtd.h +++ /dev/null @@ -1,297 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -#ifndef jsprvtd_h -#define jsprvtd_h -/* - * JS private typename definitions. - * - * This header is included only in other .h files, for convenience and for - * simplicity of type naming. The alternative for structures is to use tags, - * which are named the same as their typedef names (legal in C/C++, and less - * noisy than suffixing the typedef name with "Struct" or "Str"). Instead, - * all .h files that include this file may use the same typedef name, whether - * declaring a pointer to struct type, or defining a member of struct type. - * - * A few fundamental scalar types are defined here too. Neither the scalar - * nor the struct typedefs should change much, therefore the nearly-global - * make dependency induced by this file should not prove painful. - */ - -#include "jsapi.h" -#include "jsutil.h" - -#include "js/HashTable.h" -#include "js/Vector.h" - -/* - * Convenience constants. - */ -#define JS_BITS_PER_UINT32_LOG2 5 -#define JS_BITS_PER_UINT32 32 - -/* The alignment required of objects stored in GC arenas. */ -static const unsigned JS_GCTHING_ALIGN = 8; -static const unsigned JS_GCTHING_ZEROBITS = 3; - -/* Scalar typedefs. */ -typedef uint8_t jsbytecode; -typedef uint8_t jssrcnote; -typedef uintptr_t jsatomid; - -/* Struct typedefs. */ -typedef struct JSGCThing JSGCThing; -typedef struct JSGenerator JSGenerator; -typedef struct JSNativeEnumerator JSNativeEnumerator; -typedef struct JSTryNote JSTryNote; - -/* Friend "Advanced API" typedefs. */ -typedef struct JSAtomState JSAtomState; -typedef struct JSCodeSpec JSCodeSpec; -typedef struct JSPrinter JSPrinter; -typedef struct JSStackHeader JSStackHeader; -typedef struct JSSubString JSSubString; -typedef struct JSSpecializedNative JSSpecializedNative; - -/* String typedefs. */ -class JSDependentString; -class JSExtensibleString; -class JSExternalString; -class JSLinearString; -class JSRope; -class JSAtom; -class JSWrapper; - -namespace js { - -struct ArgumentsData; -struct Class; - -class AutoNameVector; -class RegExpGuard; -class RegExpObject; -class RegExpObjectBuilder; -class RegExpShared; -class RegExpStatics; -class MatchPairs; -class PropertyName; -class LazyScript; - -enum RegExpFlag -{ - IgnoreCaseFlag = 0x01, - GlobalFlag = 0x02, - MultilineFlag = 0x04, - StickyFlag = 0x08, - - NoFlags = 0x00, - AllFlags = 0x0f -}; - -class StringBuffer; - -class FrameRegs; -class StackFrame; -class ScriptFrameIter; - -class Proxy; -class JS_FRIEND_API(AutoEnterPolicy); -class JS_FRIEND_API(BaseProxyHandler); -class JS_FRIEND_API(Wrapper); -class JS_FRIEND_API(CrossCompartmentWrapper); - -class TempAllocPolicy; -class RuntimeAllocPolicy; - -class GlobalObject; - -template -class InlineMap; - -class LifoAlloc; - -class Shape; - -class Breakpoint; -class BreakpointSite; -class Debugger; -class WatchpointMap; - -/* - * Env is the type of what ES5 calls "lexical environments" (runtime - * activations of lexical scopes). This is currently just JSObject, and is - * implemented by Call, Block, With, and DeclEnv objects, among others--but - * environments and objects are really two different concepts. - */ -typedef JSObject Env; - -typedef JSNative Native; -typedef JSParallelNative ParallelNative; -typedef JSThreadSafeNative ThreadSafeNative; -typedef JSPropertyOp PropertyOp; -typedef JSStrictPropertyOp StrictPropertyOp; -typedef JSPropertyDescriptor PropertyDescriptor; - -struct SourceCompressionToken; - -namespace frontend { - -struct BytecodeEmitter; -struct Definition; -class FullParseHandler; -class FunctionBox; -class ObjectBox; -struct Token; -struct TokenPos; -class TokenStream; -class ParseMapPool; -class ParseNode; - -template -class Parser; - -} /* namespace frontend */ - -namespace analyze { - -struct LifetimeVariable; -class LoopAnalysis; -class ScriptAnalysis; -class SlotValue; -class SSAValue; -class SSAUseChain; - -} /* namespace analyze */ - -namespace types { - -class TypeSet; -struct TypeCallsite; -struct TypeObject; -struct TypeCompartment; - -} /* namespace types */ - -typedef JS::Handle HandleShape; -typedef JS::Handle HandleTypeObject; -typedef JS::Handle HandleAtom; -typedef JS::Handle HandlePropertyName; - -typedef JS::MutableHandle MutableHandleShape; -typedef JS::MutableHandle MutableHandleAtom; - -typedef JS::Rooted RootedShape; -typedef JS::Rooted RootedTypeObject; -typedef JS::Rooted RootedAtom; -typedef JS::Rooted RootedPropertyName; - -enum XDRMode { - XDR_ENCODE, - XDR_DECODE -}; - -template -class XDRState; - -class FreeOp; - -struct IdValuePair -{ - jsid id; - Value value; - - IdValuePair() {} - IdValuePair(jsid idArg) - : id(idArg), value(UndefinedValue()) - {} -}; - -} /* namespace js */ - -namespace JSC { - -class ExecutableAllocator; - -} /* namespace JSC */ - -namespace WTF { - -class BumpPointerAllocator; - -} /* namespace WTF */ - -/* "Friend" types used by jscntxt.h and jsdbgapi.h. */ -typedef enum JSTrapStatus { - JSTRAP_ERROR, - JSTRAP_CONTINUE, - JSTRAP_RETURN, - JSTRAP_THROW, - JSTRAP_LIMIT -} JSTrapStatus; - -typedef JSTrapStatus -(* JSTrapHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - jsval closure); - -typedef JSTrapStatus -(* JSInterruptHook)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - void *closure); - -typedef JSTrapStatus -(* JSDebuggerHandler)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - void *closure); - -typedef JSTrapStatus -(* JSThrowHook)(JSContext *cx, JSScript *script, jsbytecode *pc, jsval *rval, - void *closure); - -typedef JSBool -(* JSWatchPointHandler)(JSContext *cx, JSObject *obj, jsid id, jsval old, - jsval *newp, void *closure); - -/* called just after script creation */ -typedef void -(* JSNewScriptHook)(JSContext *cx, - const char *filename, /* URL of script */ - unsigned lineno, /* first line */ - JSScript *script, - JSFunction *fun, - void *callerdata); - -/* called just before script destruction */ -typedef void -(* JSDestroyScriptHook)(JSFreeOp *fop, - JSScript *script, - void *callerdata); - -typedef void -(* JSSourceHandler)(const char *filename, unsigned lineno, const jschar *str, - size_t length, void **listenerTSData, void *closure); - -/* js::ObjectOps function pointer typedefs. */ - -/* - * A generic type for functions mapping an object to another object, or null - * if an error or exception was thrown on cx. - */ -typedef JSObject * -(* JSObjectOp)(JSContext *cx, JS::Handle obj); - -/* Signature for class initialization ops. */ -typedef JSObject * -(* JSClassInitializerOp)(JSContext *cx, JS::HandleObject obj); - -/* - * Hook that creates an iterator object for a given object. Returns the - * iterator object or null if an error or exception was thrown on cx. - */ -typedef JSObject * -(* JSIteratorOp)(JSContext *cx, JS::HandleObject obj, JSBool keysonly); - - -#endif /* jsprvtd_h */ diff --git a/external/spidermonkey/include/win32/jspubtd.h b/external/spidermonkey/include/win32/jspubtd.h index 3ff5b3428c..4aa922eb84 100644 --- a/external/spidermonkey/include/win32/jspubtd.h +++ b/external/spidermonkey/include/win32/jspubtd.h @@ -11,72 +11,35 @@ * JS public API typedefs. */ +#include "mozilla/NullPtr.h" #include "mozilla/PodOperations.h" #include "jsprototypes.h" #include "jstypes.h" -#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) || (defined(DEBUG) && !defined(_WIN32)) +#include "js/TypeDecls.h" + +#if defined(JSGC_ROOT_ANALYSIS) || defined(JSGC_USE_EXACT_ROOTING) || defined(DEBUG) # define JSGC_TRACK_EXACT_ROOTS #endif namespace JS { -/* - * Allow headers to reference JS::Value without #including the whole jsapi.h. - * Unfortunately, typedefs (hence jsval) cannot be declared. - */ -class Value; +class AutoIdVector; +class CallArgs; template class Rooted; class JS_PUBLIC_API(AutoGCRooter); +class JS_PUBLIC_API(CompileOptions); +class JS_PUBLIC_API(CompartmentOptions); + struct Zone; } /* namespace JS */ -/* - * In release builds, jsid is defined to be an integral type. This - * prevents many bugs from being caught at compile time. E.g.: - * - * jsid id = ... - * if (id == JS_TRUE) // error - * ... - * - * size_t n = id; // error - * - * To catch more errors, jsid is given a struct type in C++ debug builds. - * Struct assignment and (in C++) operator== allow correct code to be mostly - * oblivious to the change. This feature can be explicitly disabled in debug - * builds by defining JS_NO_JSVAL_JSID_STRUCT_TYPES. - */ -// Needed for cocos2d-js -#define JS_NO_JSVAL_JSID_STRUCT_TYPES -# if defined(DEBUG) && !defined(JS_NO_JSVAL_JSID_STRUCT_TYPES) -# define JS_USE_JSID_STRUCT_TYPES -# endif - -# ifdef JS_USE_JSID_STRUCT_TYPES -struct jsid -{ - size_t asBits; - bool operator==(jsid rhs) const { return asBits == rhs.asBits; } - bool operator!=(jsid rhs) const { return asBits != rhs.asBits; } -}; -# define JSID_BITS(id) (id.asBits) -# else /* defined(JS_USE_JSID_STRUCT_TYPES) */ -typedef ptrdiff_t jsid; -# define JSID_BITS(id) (id) -# endif /* defined(JS_USE_JSID_STRUCT_TYPES) */ - -#ifdef WIN32 -typedef wchar_t jschar; -#else -typedef uint16_t jschar; -#endif - /* * Run-time version enumeration. For compile-time version checking, please use * the JS_HAS_* macros in jsversion.h, or use MOZJS_MAJOR_VERSION, @@ -109,7 +72,7 @@ typedef enum JSType { typedef enum JSProtoKey { #define PROTOKEY_AND_INITIALIZER(name,code,init) JSProto_##name = code, JS_FOR_EACH_PROTOTYPE(PROTOKEY_AND_INITIALIZER) -#undef JS_PROTO +#undef PROTOKEY_AND_INITIALIZER JSProto_LIMIT } JSProtoKey; @@ -175,7 +138,6 @@ typedef enum { typedef struct JSClass JSClass; typedef struct JSCompartment JSCompartment; typedef struct JSConstDoubleSpec JSConstDoubleSpec; -typedef struct JSContext JSContext; typedef struct JSCrossCompartmentCall JSCrossCompartmentCall; typedef struct JSErrorReport JSErrorReport; typedef struct JSExceptionState JSExceptionState; @@ -195,20 +157,32 @@ typedef struct JSStructuredCloneWriter JSStructuredCloneWriter; typedef struct JSTracer JSTracer; class JSFlatString; -class JSFunction; -class JSObject; -class JSScript; class JSStableString; // long story -class JSString; #ifdef JS_THREADSAFE -typedef struct PRCallOnceType JSCallOnceType; +typedef struct PRCallOnceType JSCallOnceType; #else -typedef JSBool JSCallOnceType; +typedef bool JSCallOnceType; #endif -typedef JSBool (*JSInitCallback)(void); +typedef bool (*JSInitCallback)(void); + +/* + * Generic trace operation that calls JS_CallTracer on each traceable thing + * stored in data. + */ +typedef void +(* JSTraceDataOp)(JSTracer *trc, void *data); + +namespace js { +namespace gc { +class StoreBuffer; +} +} namespace JS { + +typedef void (*OffThreadCompileCallback)(void *token, void *callbackData); + namespace shadow { struct Runtime @@ -220,15 +194,36 @@ struct Runtime /* Allow inlining of Nursery::isInside. */ uintptr_t gcNurseryStart_; uintptr_t gcNurseryEnd_; + + private: + js::gc::StoreBuffer *gcStoreBufferPtr_; #endif - Runtime() + public: + Runtime( +#ifdef JSGC_GENERATIONAL + js::gc::StoreBuffer *storeBuffer +#endif + ) : needsBarrier_(false) #ifdef JSGC_GENERATIONAL , gcNurseryStart_(0) , gcNurseryEnd_(0) + , gcStoreBufferPtr_(storeBuffer) #endif {} + + bool needsBarrier() const { + return needsBarrier_; + } + +#ifdef JSGC_GENERATIONAL + js::gc::StoreBuffer *gcStoreBufferPtr() { return gcStoreBufferPtr_; } +#endif + + static JS::shadow::Runtime *asShadowRuntime(JSRuntime *rt) { + return reinterpret_cast(rt); + } }; } /* namespace shadow */ @@ -270,6 +265,19 @@ enum ThingRootKind THING_ROOT_LIMIT }; +/* + * This list enumerates the different types of conceptual stacks we have in + * SpiderMonkey. In reality, they all share the C stack, but we allow different + * stack limits depending on the type of code running. + */ +enum StackKind +{ + StackForSystemCode, // C++, such as the GC, running on behalf of the VM. + StackForTrustedScript, // Script running with trusted principals. + StackForUntrustedScript, // Script running with untrusted principals. + StackKindCount +}; + template struct RootKind; @@ -305,13 +313,13 @@ struct ContextFriendFields public: explicit ContextFriendFields(JSRuntime *rt) - : runtime_(rt), compartment_(NULL), zone_(NULL), autoGCRooters(NULL) + : runtime_(rt), compartment_(nullptr), zone_(nullptr), autoGCRooters(nullptr) { #ifdef JSGC_TRACK_EXACT_ROOTS mozilla::PodArrayZero(thingGCRooters); #endif #if defined(DEBUG) && defined(JS_GC_ZEAL) && defined(JSGC_ROOT_ANALYSIS) && !defined(JS_THREADSAFE) - skipGCRooters = NULL; + skipGCRooters = nullptr; #endif } @@ -395,7 +403,7 @@ struct PerThreadDataFriendFields #endif /* Limit pointer for checking native stack consumption. */ - uintptr_t nativeStackLimit; + uintptr_t nativeStackLimit[StackKindCount]; static const size_t RuntimeMainThreadOffset = offsetof(RuntimeDummy, mainThread); diff --git a/external/spidermonkey/include/win32/jstypes.h b/external/spidermonkey/include/win32/jstypes.h index 17f67f70e1..d5b15ccb1d 100644 --- a/external/spidermonkey/include/win32/jstypes.h +++ b/external/spidermonkey/include/win32/jstypes.h @@ -22,9 +22,16 @@ #define jstypes_h #include "mozilla/Attributes.h" -#include "mozilla/Util.h" +#include "mozilla/Types.h" +// jstypes.h is (or should be!) included by every file in SpiderMonkey. +// js-config.h and jsversion.h also should be included by every file. +// So include them here. +// XXX: including them in js/RequiredDefines.h should be a better option, since +// that is by definition the header file that should be included in all +// SpiderMonkey code. However, Gecko doesn't do this! See bug 909576. #include "js-config.h" +#include "jsversion.h" /*********************************************************************** ** MACROS: JS_EXTERN_API @@ -82,10 +89,6 @@ #define JS_NO_FASTCALL #endif -#ifndef JS_INLINE -#define JS_INLINE MOZ_INLINE -#endif - #ifndef JS_ALWAYS_INLINE #define JS_ALWAYS_INLINE MOZ_ALWAYS_INLINE #endif @@ -180,19 +183,6 @@ # error "Implement me" #endif - -/************************************************************************ -** TYPES: JSBool -** DESCRIPTION: -** Use JSBool for variables and parameter types. Use JS_FALSE and JS_TRUE -** for clarity of target type in assignments and actual arguments. Use -** 'if (bool)', 'while (!bool)', '(bool) ? x : y' etc., to test booleans -** just as you would C int-valued conditions. -************************************************************************/ -typedef int JSBool; -#define JS_TRUE (int)1 -#define JS_FALSE (int)0 - /*********************************************************************** ** MACROS: JS_LIKELY ** JS_UNLIKELY @@ -244,7 +234,11 @@ typedef int JSBool; #define JS_BITS_PER_BYTE 8 #define JS_BITS_PER_BYTE_LOG2 3 -#define JS_BITS_PER_WORD (JS_BITS_PER_BYTE * JS_BYTES_PER_WORD) +#if defined(JS_64BIT) +# define JS_BITS_PER_WORD 64 +#else +# define JS_BITS_PER_WORD 32 +#endif /*********************************************************************** ** MACROS: JS_FUNC_TO_DATA_PTR diff --git a/external/spidermonkey/include/win32/jsutil.h b/external/spidermonkey/include/win32/jsutil.h deleted file mode 100644 index 4020822be1..0000000000 --- a/external/spidermonkey/include/win32/jsutil.h +++ /dev/null @@ -1,385 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set ts=8 sts=4 et sw=4 tw=99: - * 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/. */ - -/* - * PR assertion checker. - */ - -#ifndef jsutil_h -#define jsutil_h - -#include "mozilla/Attributes.h" -#include "mozilla/Compiler.h" -#include "mozilla/GuardObjects.h" - -#ifdef USE_ZLIB -#include -#endif - -#include "js/Utility.h" - -/* Forward declarations. */ -struct JSContext; - -static JS_ALWAYS_INLINE void * -js_memcpy(void *dst_, const void *src_, size_t len) -{ - char *dst = (char *) dst_; - const char *src = (const char *) src_; - JS_ASSERT_IF(dst >= src, (size_t) (dst - src) >= len); - JS_ASSERT_IF(src >= dst, (size_t) (src - dst) >= len); - - return memcpy(dst, src, len); -} - -namespace js { - -template -struct AlignmentTestStruct -{ - char c; - T t; -}; - -/* This macro determines the alignment requirements of a type. */ -#define JS_ALIGNMENT_OF(t_) \ - (sizeof(js::AlignmentTestStruct) - sizeof(t_)) - -template -class AlignedPtrAndFlag -{ - uintptr_t bits; - - public: - AlignedPtrAndFlag(T *t, bool aFlag) { - JS_ASSERT((uintptr_t(t) & 1) == 0); - bits = uintptr_t(t) | uintptr_t(aFlag); - } - - T *ptr() const { - return (T *)(bits & ~uintptr_t(1)); - } - - bool flag() const { - return (bits & 1) != 0; - } - - void setPtr(T *t) { - JS_ASSERT((uintptr_t(t) & 1) == 0); - bits = uintptr_t(t) | uintptr_t(flag()); - } - - void setFlag() { - bits |= 1; - } - - void unsetFlag() { - bits &= ~uintptr_t(1); - } - - void set(T *t, bool aFlag) { - JS_ASSERT((uintptr_t(t) & 1) == 0); - bits = uintptr_t(t) | aFlag; - } -}; - -template -static inline void -Reverse(T *beg, T *end) -{ - while (beg != end) { - if (--end == beg) - return; - T tmp = *beg; - *beg = *end; - *end = tmp; - ++beg; - } -} - -template -static inline T * -Find(T *beg, T *end, const T &v) -{ - for (T *p = beg; p != end; ++p) { - if (*p == v) - return p; - } - return end; -} - -template -static inline typename Container::ElementType * -Find(Container &c, const typename Container::ElementType &v) -{ - return Find(c.begin(), c.end(), v); -} - -template -void -ForEach(InputIterT begin, InputIterT end, CallableT f) -{ - for (; begin != end; ++begin) - f(*begin); -} - -template -static inline T -Min(T t1, T t2) -{ - return t1 < t2 ? t1 : t2; -} - -template -static inline T -Max(T t1, T t2) -{ - return t1 > t2 ? t1 : t2; -} - -/* Allows a const variable to be initialized after its declaration. */ -template -static T& -InitConst(const T &t) -{ - return const_cast(t); -} - -template -JS_ALWAYS_INLINE T & -ImplicitCast(U &u) -{ - T &t = u; - return t; -} - -template -class AutoScopedAssign -{ - public: - AutoScopedAssign(T *addr, const T &value - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) - : addr_(addr), old(*addr_) - { - MOZ_GUARD_OBJECT_NOTIFIER_INIT; - *addr_ = value; - } - - ~AutoScopedAssign() { *addr_ = old; } - - private: - MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER - T *addr_; - T old; -}; - -template -static inline bool -IsPowerOfTwo(T t) -{ - return t && !(t & (t - 1)); -} - -template -static inline U -ComputeByteAlignment(T bytes, U alignment) -{ - JS_ASSERT(IsPowerOfTwo(alignment)); - return (alignment - (bytes % alignment)) % alignment; -} - -template -static inline T -AlignBytes(T bytes, U alignment) -{ - return bytes + ComputeByteAlignment(bytes, alignment); -} - -JS_ALWAYS_INLINE static size_t -UnsignedPtrDiff(const void *bigger, const void *smaller) -{ - return size_t(bigger) - size_t(smaller); -} - -/*****************************************************************************/ - -/* A bit array is an array of bits represented by an array of words (size_t). */ - -static inline unsigned -NumWordsForBitArrayOfLength(size_t length) -{ - return (length + (JS_BITS_PER_WORD - 1)) / JS_BITS_PER_WORD; -} - -static inline unsigned -BitArrayIndexToWordIndex(size_t length, size_t bitIndex) -{ - unsigned wordIndex = bitIndex / JS_BITS_PER_WORD; - JS_ASSERT(wordIndex < length); - return wordIndex; -} - -static inline size_t -BitArrayIndexToWordMask(size_t i) -{ - return size_t(1) << (i % JS_BITS_PER_WORD); -} - -static inline bool -IsBitArrayElementSet(size_t *array, size_t length, size_t i) -{ - return array[BitArrayIndexToWordIndex(length, i)] & BitArrayIndexToWordMask(i); -} - -static inline bool -IsAnyBitArrayElementSet(size_t *array, size_t length) -{ - unsigned numWords = NumWordsForBitArrayOfLength(length); - for (unsigned i = 0; i < numWords; ++i) { - if (array[i]) - return true; - } - return false; -} - -static inline void -SetBitArrayElement(size_t *array, size_t length, size_t i) -{ - array[BitArrayIndexToWordIndex(length, i)] |= BitArrayIndexToWordMask(i); -} - -static inline void -ClearBitArrayElement(size_t *array, size_t length, size_t i) -{ - array[BitArrayIndexToWordIndex(length, i)] &= ~BitArrayIndexToWordMask(i); -} - -static inline void -ClearAllBitArrayElements(size_t *array, size_t length) -{ - for (unsigned i = 0; i < length; ++i) - array[i] = 0; -} - -#ifdef USE_ZLIB -class Compressor -{ - /* Number of bytes we should hand to zlib each compressMore() call. */ - static const size_t CHUNKSIZE = 2048; - z_stream zs; - const unsigned char *inp; - size_t inplen; - size_t outbytes; - - public: - enum Status { - MOREOUTPUT, - DONE, - CONTINUE, - OOM - }; - - Compressor(const unsigned char *inp, size_t inplen); - ~Compressor(); - bool init(); - void setOutput(unsigned char *out, size_t outlen); - size_t outWritten() const { return outbytes; } - /* Compress some of the input. Return true if it should be called again. */ - Status compressMore(); -}; - -/* - * Decompress a string. The caller must know the length of the output and - * allocate |out| to a string of that length. - */ -bool DecompressString(const unsigned char *inp, size_t inplen, - unsigned char *out, size_t outlen); -#endif - -} /* namespace js */ - -/* Crash diagnostics */ -#ifdef DEBUG -# define JS_CRASH_DIAGNOSTICS 1 -#endif -#ifdef JS_CRASH_DIAGNOSTICS -# define JS_POISON(p, val, size) memset((p), (val), (size)) -#else -# define JS_POISON(p, val, size) ((void) 0) -#endif - -/* Basic stats */ -#ifdef DEBUG -# define JS_BASIC_STATS 1 -#endif -#ifdef JS_BASIC_STATS -# include -typedef struct JSBasicStats { - uint32_t num; - uint32_t max; - double sum; - double sqsum; - uint32_t logscale; /* logarithmic scale: 0 (linear), 2, 10 */ - uint32_t hist[11]; -} JSBasicStats; -# define JS_INIT_STATIC_BASIC_STATS {0,0,0,0,0,{0,0,0,0,0,0,0,0,0,0,0}} -# define JS_BASIC_STATS_INIT(bs) memset((bs), 0, sizeof(JSBasicStats)) -# define JS_BASIC_STATS_ACCUM(bs,val) \ - JS_BasicStatsAccum(bs, val) -# define JS_MeanAndStdDevBS(bs,sigma) \ - JS_MeanAndStdDev((bs)->num, (bs)->sum, (bs)->sqsum, sigma) -extern void -JS_BasicStatsAccum(JSBasicStats *bs, uint32_t val); -extern double -JS_MeanAndStdDev(uint32_t num, double sum, double sqsum, double *sigma); -extern void -JS_DumpBasicStats(JSBasicStats *bs, const char *title, FILE *fp); -extern void -JS_DumpHistogram(JSBasicStats *bs, FILE *fp); -#else -# define JS_BASIC_STATS_ACCUM(bs,val) -#endif - -/* A jsbitmap_t is a long integer that can be used for bitmaps. */ -typedef size_t jsbitmap; -#define JS_TEST_BIT(_map,_bit) ((_map)[(_bit)>>JS_BITS_PER_WORD_LOG2] & \ - ((jsbitmap)1<<((_bit)&(JS_BITS_PER_WORD-1)))) -#define JS_SET_BIT(_map,_bit) ((_map)[(_bit)>>JS_BITS_PER_WORD_LOG2] |= \ - ((jsbitmap)1<<((_bit)&(JS_BITS_PER_WORD-1)))) -#define JS_CLEAR_BIT(_map,_bit) ((_map)[(_bit)>>JS_BITS_PER_WORD_LOG2] &= \ - ~((jsbitmap)1<<((_bit)&(JS_BITS_PER_WORD-1)))) - -/* Wrapper for various macros to stop warnings coming from their expansions. */ -#if defined(__clang__) -# define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \ - JS_BEGIN_MACRO \ - _Pragma("clang diagnostic push") \ - /* If these _Pragmas cause warnings for you, try disabling ccache. */ \ - _Pragma("clang diagnostic ignored \"-Wunused-value\"") \ - { expr; } \ - _Pragma("clang diagnostic pop") \ - JS_END_MACRO -#elif MOZ_IS_GCC - -#if MOZ_GCC_VERSION_AT_LEAST(4, 6, 0) -# define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \ - JS_BEGIN_MACRO \ - _Pragma("GCC diagnostic push") \ - _Pragma("GCC diagnostic ignored \"-Wunused-but-set-variable\"") \ - expr; \ - _Pragma("GCC diagnostic pop") \ - JS_END_MACRO -#endif -#endif - -#if !defined(JS_SILENCE_UNUSED_VALUE_IN_EXPR) -# define JS_SILENCE_UNUSED_VALUE_IN_EXPR(expr) \ - JS_BEGIN_MACRO \ - expr; \ - JS_END_MACRO -#endif - -#endif /* jsutil_h */ diff --git a/external/spidermonkey/include/win32/jsversion.h b/external/spidermonkey/include/win32/jsversion.h index 1780616a32..827a56981d 100644 --- a/external/spidermonkey/include/win32/jsversion.h +++ b/external/spidermonkey/include/win32/jsversion.h @@ -7,19 +7,6 @@ #ifndef jsversion_h #define jsversion_h -/* - * Deprecated JS_VERSION handler. - */ -#ifdef JS_VERSION -# if JS_VERSION == 185 -# warning "JS_VERSION defined but unsupported (legacy)" -# elif JS_VERSION < 185 -# error "Unsupported JS_VERSION" -# else -# error "Unknown JS_VERSION" -# endif -#endif - /* * JS Capability Macros. */ @@ -52,15 +39,15 @@ * Feature for Object.prototype.__{define,lookup}{G,S}etter__ legacy support; * support likely to be made opt-in at some future time. */ -#define OLD_GETTER_SETTER_METHODS 1 +#define JS_OLD_GETTER_SETTER_METHODS 1 /* A kill-switch for bug 586842. Embedders shouldn't touch this! */ -#define USE_NEW_OBJECT_REPRESENTATION 0 +#define JS_USE_NEW_OBJECT_REPRESENTATION 0 -#if USE_NEW_OBJECT_REPRESENTATION -# define NEW_OBJECT_REPRESENTATION_ONLY() ((void)0) +#if JS_USE_NEW_OBJECT_REPRESENTATION +# define JS_NEW_OBJECT_REPRESENTATION_ONLY() ((void)0) #else -# define NEW_OBJECT_REPRESENTATION_ONLY() \ +# define JS_NEW_OBJECT_REPRESENTATION_ONLY() \ MOZ_ASSUME_UNREACHABLE("don't call this! to be used in the new object representation") #endif diff --git a/external/spidermonkey/include/win32/jswrapper.h b/external/spidermonkey/include/win32/jswrapper.h index f78df7db60..938db73ec8 100644 --- a/external/spidermonkey/include/win32/jswrapper.h +++ b/external/spidermonkey/include/win32/jswrapper.h @@ -9,7 +9,6 @@ #include "mozilla/Attributes.h" -#include "jsapi.h" #include "jsproxy.h" namespace js { @@ -38,6 +37,9 @@ class JS_FRIEND_API(Wrapper) : public DirectProxyHandler LAST_USED_FLAG = CROSS_COMPARTMENT }; + virtual bool defaultValue(JSContext *cx, HandleObject obj, JSType hint, + MutableHandleValue vp) MOZ_OVERRIDE; + /* * Wrappers can explicitly specify that they are unsafe to unwrap from a * security perspective (as is the case for SecurityWrappers). If a wrapper @@ -64,6 +66,8 @@ class JS_FRIEND_API(Wrapper) : public DirectProxyHandler virtual ~Wrapper(); + virtual bool finalizeInBackground(Value priv) MOZ_OVERRIDE; + static Wrapper singleton; static Wrapper singletonWithPrototype; }; @@ -76,16 +80,16 @@ class JS_FRIEND_API(CrossCompartmentWrapper) : public Wrapper virtual ~CrossCompartmentWrapper(); - virtual bool finalizeInBackground(Value priv) MOZ_OVERRIDE; - /* ES5 Harmony fundamental wrapper traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject wrapper) MOZ_OVERRIDE; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject wrapper, AutoIdVector &props) MOZ_OVERRIDE; virtual bool delete_(JSContext *cx, HandleObject wrapper, HandleId id, bool *bp) MOZ_OVERRIDE; @@ -149,7 +153,7 @@ class JS_FRIEND_API(SecurityWrapper) : public Base JSContext *cx) MOZ_OVERRIDE; virtual bool regexp_toShared(JSContext *cx, HandleObject proxy, RegExpGuard *g) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; /* * Allow our subclasses to select the superclass behavior they want without @@ -165,18 +169,21 @@ typedef SecurityWrapper CrossCompartmentSecurityWrapper class JS_FRIEND_API(DeadObjectProxy) : public BaseProxyHandler { public: - static int sDeadObjectFamily; + // This variable exists solely to provide a unique address for use as an identifier. + static const char sDeadObjectFamily; explicit DeadObjectProxy(); /* ES5 Harmony fundamental wrapper traps. */ virtual bool preventExtensions(JSContext *cx, HandleObject proxy) MOZ_OVERRIDE; virtual bool getPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool getOwnPropertyDescriptor(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc, unsigned flags) MOZ_OVERRIDE; + MutableHandle desc, + unsigned flags) MOZ_OVERRIDE; virtual bool defineProperty(JSContext *cx, HandleObject wrapper, HandleId id, - PropertyDescriptor *desc) MOZ_OVERRIDE; + MutableHandle desc) MOZ_OVERRIDE; virtual bool getOwnPropertyNames(JSContext *cx, HandleObject wrapper, AutoIdVector &props) MOZ_OVERRIDE; virtual bool delete_(JSContext *cx, HandleObject wrapper, HandleId id, bool *bp) MOZ_OVERRIDE; @@ -213,7 +220,8 @@ TransparentObjectWrapper(JSContext *cx, HandleObject existing, HandleObject obj, // Proxy family for wrappers. Public so that IsWrapper() can be fully inlined by // jsfriendapi users. -extern JS_FRIEND_DATA(int) sWrapperFamily; +// This variable exists solely to provide a unique address for use as an identifier. +extern JS_FRIEND_DATA(const char) sWrapperFamily; inline bool IsWrapper(JSObject *obj) @@ -226,7 +234,7 @@ IsWrapper(JSObject *obj) // previously wrapped. Otherwise, this returns the first object for // which JSObject::isWrapper returns false. JS_FRIEND_API(JSObject *) -UncheckedUnwrap(JSObject *obj, bool stopAtOuter = true, unsigned *flagsp = NULL); +UncheckedUnwrap(JSObject *obj, bool stopAtOuter = true, unsigned *flagsp = nullptr); // Given a JSObject, returns that object stripped of wrappers. At each stage, // the security wrapper has the opportunity to veto the unwrap. Since checked @@ -247,7 +255,8 @@ bool IsDeadProxyObject(JSObject *obj); JSObject * -NewDeadProxyObject(JSContext *cx, JSObject *parent); +NewDeadProxyObject(JSContext *cx, JSObject *parent, + const ProxyOptions &options = ProxyOptions()); void NukeCrossCompartmentWrapper(JSContext *cx, JSObject *wrapper); diff --git a/external/spidermonkey/include/win32/mozilla/Alignment.h b/external/spidermonkey/include/win32/mozilla/Alignment.h new file mode 100644 index 0000000000..29599d0ef1 --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/Alignment.h @@ -0,0 +1,137 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=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/. */ + +/* Functionality related to memory alignment. */ + +#ifndef mozilla_Alignment_h +#define mozilla_Alignment_h + +#include +#include + +namespace mozilla { + +/* + * This class, and the corresponding macro MOZ_ALIGNOF, figures out how many + * bytes of alignment a given type needs. + */ +template +class AlignmentFinder +{ + struct Aligner + { + char c; + T t; + }; + + public: + static const size_t alignment = sizeof(Aligner) - sizeof(T); +}; + +#define MOZ_ALIGNOF(T) mozilla::AlignmentFinder::alignment + +/* + * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types. + * + * For instance, + * + * MOZ_ALIGNED_DECL(char arr[2], 8); + * + * will declare a two-character array |arr| aligned to 8 bytes. + */ + +#if defined(__GNUC__) +# define MOZ_ALIGNED_DECL(_type, _align) \ + _type __attribute__((aligned(_align))) +#elif defined(_MSC_VER) +# define MOZ_ALIGNED_DECL(_type, _align) \ + __declspec(align(_align)) _type +#else +# warning "We don't know how to align variables on this compiler." +# define MOZ_ALIGNED_DECL(_type, _align) _type +#endif + +/* + * AlignedElem is a structure whose alignment is guaranteed to be at least N + * bytes. + * + * We support 1, 2, 4, 8, and 16-bit alignment. + */ +template +struct AlignedElem; + +/* + * We have to specialize this template because GCC doesn't like __attribute__((aligned(foo))) where + * foo is a template parameter. + */ + +template<> +struct AlignedElem<1> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 1); +}; + +template<> +struct AlignedElem<2> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 2); +}; + +template<> +struct AlignedElem<4> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 4); +}; + +template<> +struct AlignedElem<8> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 8); +}; + +template<> +struct AlignedElem<16> +{ + MOZ_ALIGNED_DECL(uint8_t elem, 16); +}; + +/* + * This utility pales in comparison to Boost's aligned_storage. The utility + * simply assumes that uint64_t is enough alignment for anyone. This may need + * to be extended one day... + * + * As an important side effect, pulling the storage into this template is + * enough obfuscation to confuse gcc's strict-aliasing analysis into not giving + * false negatives when we cast from the char buffer to whatever type we've + * constructed using the bytes. + */ +template +struct AlignedStorage +{ + union U { + char bytes[Nbytes]; + uint64_t _; + } u; + + const void* addr() const { return u.bytes; } + void* addr() { return u.bytes; } +}; + +template +struct AlignedStorage2 +{ + union U { + char bytes[sizeof(T)]; + uint64_t _; + } u; + + const T* addr() const { return reinterpret_cast(u.bytes); } + T* addr() { return static_cast(static_cast(u.bytes)); } +}; + +} /* namespace mozilla */ + +#endif /* mozilla_Alignment_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Assertions.h b/external/spidermonkey/include/win32/mozilla/Assertions.h index 00b7037802..f902199051 100644 --- a/external/spidermonkey/include/win32/mozilla/Assertions.h +++ b/external/spidermonkey/include/win32/mozilla/Assertions.h @@ -180,7 +180,7 @@ __declspec(noreturn) __inline void MOZ_NoReturn() {} # ifdef __cplusplus # define MOZ_REALLY_CRASH() \ do { \ - __debugbreak(); \ + ::__debugbreak(); \ *((volatile int*) NULL) = 123; \ ::TerminateProcess(::GetCurrentProcess(), 3); \ ::MOZ_NoReturn(); \ diff --git a/external/spidermonkey/include/win32/mozilla/Atomics.h b/external/spidermonkey/include/win32/mozilla/Atomics.h index f876683c3e..31e6a7daec 100644 --- a/external/spidermonkey/include/win32/mozilla/Atomics.h +++ b/external/spidermonkey/include/win32/mozilla/Atomics.h @@ -17,6 +17,8 @@ #define mozilla_Atomics_h #include "mozilla/Assertions.h" +#include "mozilla/Attributes.h" +#include "mozilla/Compiler.h" #include "mozilla/TypeTraits.h" #include @@ -26,34 +28,16 @@ * does not have . So be sure to check for support * along with C++0x support. */ -#if defined(__clang__) +#if defined(__clang__) || defined(__GNUC__) /* - * clang doesn't like libstdc++'s version of before GCC 4.7, - * due to the loose typing of the __sync_* family of functions done by - * GCC. We do not have a particularly good way to detect this sort of - * case at this point, so just assume that if we're on a Linux system, - * we can't use the system's . - * - * OpenBSD uses an old libstdc++ 4.2.1 and thus doesnt have . + * Clang doesn't like from libstdc++ before 4.7 due to the + * loose typing of the atomic builtins. GCC 4.5 and 4.6 lacks inline + * definitions for unspecialized std::atomic and causes linking errors. + * Therefore, we require at least 4.7.0 for using libstdc++. */ -# if !defined(__linux__) && !defined(__OpenBSD__) && \ - (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) && \ - __has_include() +# if MOZ_USING_LIBSTDCXX && MOZ_LIBSTDCXX_VERSION_AT_LEAST(4, 7, 0) # define MOZ_HAVE_CXX11_ATOMICS -# endif -/* - * Android uses a different C++ standard library that does not provide - * support for . - * - * GCC 4.5.x and 4.6.x's unspecialized std::atomic template doesn't include - * inline definitions for the functions declared therein. This oversight - * leads to linking errors when using atomic enums. We therefore require - * GCC 4.7 or higher. - */ -#elif defined(__GNUC__) && !defined(__ANDROID__) -# include "mozilla/Compiler.h" -# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) && \ - MOZ_GCC_VERSION_AT_LEAST(4, 7, 0) +# elif MOZ_USING_LIBCXX # define MOZ_HAVE_CXX11_ATOMICS # endif #elif defined(_MSC_VER) && _MSC_VER >= 1700 @@ -845,8 +829,8 @@ class AtomicBase typename Intrinsics::ValueType mValue; public: - AtomicBase() : mValue() {} - AtomicBase(T aInit) { Intrinsics::store(mValue, aInit); } + MOZ_CONSTEXPR AtomicBase() : mValue() {} + MOZ_CONSTEXPR AtomicBase(T aInit) : mValue(aInit) {} operator T() const { return Intrinsics::load(mValue); } @@ -889,8 +873,8 @@ class AtomicBaseIncDec : public AtomicBase typedef typename detail::AtomicBase Base; public: - AtomicBaseIncDec() : Base() {} - AtomicBaseIncDec(T aInit) : Base(aInit) {} + MOZ_CONSTEXPR AtomicBaseIncDec() : Base() {} + MOZ_CONSTEXPR AtomicBaseIncDec(T aInit) : Base(aInit) {} using Base::operator=; @@ -943,8 +927,8 @@ class Atomic::value>::Type> typedef typename detail::AtomicBaseIncDec Base; public: - Atomic() : Base() {} - Atomic(T aInit) : Base(aInit) {} + MOZ_CONSTEXPR Atomic() : Base() {} + MOZ_CONSTEXPR Atomic(T aInit) : Base(aInit) {} using Base::operator=; @@ -972,8 +956,8 @@ class Atomic : public detail::AtomicBaseIncDec typedef typename detail::AtomicBaseIncDec Base; public: - Atomic() : Base() {} - Atomic(T* aInit) : Base(aInit) {} + MOZ_CONSTEXPR Atomic() : Base() {} + MOZ_CONSTEXPR Atomic(T* aInit) : Base(aInit) {} using Base::operator=; @@ -1000,8 +984,8 @@ class Atomic::value>::Type> typedef typename detail::AtomicBase Base; public: - Atomic() : Base() {} - Atomic(T aInit) : Base(aInit) {} + MOZ_CONSTEXPR Atomic() : Base() {} + MOZ_CONSTEXPR Atomic(T aInit) : Base(aInit) {} using Base::operator=; diff --git a/external/spidermonkey/include/win32/mozilla/Attributes.h b/external/spidermonkey/include/win32/mozilla/Attributes.h index 6ea9776fbf..0786cb2fe5 100644 --- a/external/spidermonkey/include/win32/mozilla/Attributes.h +++ b/external/spidermonkey/include/win32/mozilla/Attributes.h @@ -11,26 +11,10 @@ #include "mozilla/Compiler.h" -/* - * MOZ_INLINE is a macro which expands to tell the compiler that the method - * decorated with it should be inlined. This macro is usable from C and C++ - * code, even though C89 does not support the |inline| keyword. The compiler - * may ignore this directive if it chooses. - */ -#if defined(__cplusplus) -# define MOZ_INLINE inline -#elif defined(_MSC_VER) -# define MOZ_INLINE __inline -#elif defined(__GNUC__) -# define MOZ_INLINE __inline__ -#else -# define MOZ_INLINE inline -#endif - /* * MOZ_ALWAYS_INLINE is a macro which expands to tell the compiler that the * method decorated with it must be inlined, even if the compiler thinks - * otherwise. This is only a (much) stronger version of the MOZ_INLINE hint: + * otherwise. This is only a (much) stronger version of the inline hint: * compilers are not guaranteed to respect it (although they're much more likely * to do so). * @@ -40,15 +24,17 @@ #if defined(_MSC_VER) # define MOZ_ALWAYS_INLINE_EVEN_DEBUG __forceinline #elif defined(__GNUC__) -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __attribute__((always_inline)) MOZ_INLINE +# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __attribute__((always_inline)) inline #else -# define MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_INLINE +# define MOZ_ALWAYS_INLINE_EVEN_DEBUG inline #endif -#if defined(DEBUG) -# define MOZ_ALWAYS_INLINE MOZ_INLINE -#else +#if !defined(DEBUG) # define MOZ_ALWAYS_INLINE MOZ_ALWAYS_INLINE_EVEN_DEBUG +#elif defined(_MSC_VER) && !defined(__cplusplus) +# define MOZ_ALWAYS_INLINE __inline +#else +# define MOZ_ALWAYS_INLINE inline #endif /* @@ -170,12 +156,31 @@ * Furthermore, it will prevent the compiler from inlining the function because * inlining currently breaks the blacklisting mechanism of AddressSanitizer. */ -#if defined(MOZ_ASAN) -# define MOZ_ASAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_address_safety_analysis)) -# else -# define MOZ_ASAN_BLACKLIST +#if defined(__has_feature) +# if __has_feature(address_sanitizer) +# define MOZ_ASAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_address)) +# else +# define MOZ_ASAN_BLACKLIST /* nothing */ +# endif +#else +# define MOZ_ASAN_BLACKLIST /* nothing */ #endif +/* + * MOZ_TSAN_BLACKLIST is a macro to tell ThreadSanitizer (a compile-time + * instrumentation shipped with Clang) to not instrument the annotated function. + * Furthermore, it will prevent the compiler from inlining the function because + * inlining currently breaks the blacklisting mechanism of ThreadSanitizer. + */ +#if defined(__has_feature) +# if __has_feature(thread_sanitizer) +# define MOZ_TSAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_sanitize_thread)) +# else +# define MOZ_TSAN_BLACKLIST /* nothing */ +# endif +#else +# define MOZ_TSAN_BLACKLIST /* nothing */ +#endif #ifdef __cplusplus diff --git a/external/spidermonkey/include/win32/mozilla/Char16.h b/external/spidermonkey/include/win32/mozilla/Char16.h index e4b184f950..fb182dfde2 100644 --- a/external/spidermonkey/include/win32/mozilla/Char16.h +++ b/external/spidermonkey/include/win32/mozilla/Char16.h @@ -9,16 +9,11 @@ #ifndef mozilla_Char16_h #define mozilla_Char16_h -#include "mozilla/Assertions.h" - /* * C11 and C++11 introduce a char16_t type and support for UTF-16 string and * character literals. C++11's char16_t is a distinct builtin type. C11's * char16_t is a typedef for uint_least16_t. Technically, char16_t is a 16-bit * code unit of a Unicode code point, not a "character". - * - * For now, Char16.h only supports C++ because we don't want mix different C - * and C++ definitions of char16_t in the same code base. */ #ifdef _MSC_VER @@ -26,20 +21,52 @@ * C++11 says char16_t is a distinct builtin type, but Windows's yvals.h * typedefs char16_t as an unsigned short. We would like to alias char16_t * to Windows's 16-bit wchar_t so we can declare UTF-16 literals as constant - * expressions (and pass char16_t pointers to Windows APIs). We #define our - * char16_t as a macro to override yval.h's typedef of the same name. + * expressions (and pass char16_t pointers to Windows APIs). We #define + * _CHAR16T here in order to prevent yvals.h from overriding our char16_t + * typedefs, which we set to wchar_t for C++ code and to unsigned short for + * C code. + * + * In addition, #defining _CHAR16T will prevent yvals.h from defining a + * char32_t type, so we have to undo that damage here and provide our own, + * which is identical to the yvals.h type. */ # define MOZ_UTF16_HELPER(s) L##s -# include -# define char16_t wchar_t +# define _CHAR16T +# ifdef __cplusplus + typedef wchar_t char16_t; +# else + typedef unsigned short char16_t; +# endif + typedef unsigned int char32_t; #elif defined(__cplusplus) && \ (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) /* C++11 has a builtin char16_t type. */ # define MOZ_UTF16_HELPER(s) u##s + /** + * This macro is used to distinguish when char16_t would be a distinct + * typedef from wchar_t. + */ +# define MOZ_CHAR16_IS_NOT_WCHAR +#elif !defined(__cplusplus) +# if defined(WIN32) +# include + typedef wchar_t char16_t; +# else + /** + * We can't use the stdint.h uint16_t type here because including + * stdint.h will break building some of our C libraries, such as + * sqlite. + */ + typedef unsigned short char16_t; +# endif #else # error "Char16.h requires C++11 (or something like it) for UTF-16 support." #endif +/* This is a temporary hack until bug 927728 is fixed. */ +#define __PRUNICHAR__ +typedef char16_t PRUnichar; + /* * Macro arguments used in concatenation or stringification won't be expanded. * Therefore, in order for |MOZ_UTF16(FOO)| to work as expected (which is to @@ -50,8 +77,12 @@ */ #define MOZ_UTF16(s) MOZ_UTF16_HELPER(s) +#if defined(__cplusplus) && \ + (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) static_assert(sizeof(char16_t) == 2, "Is char16_t type 16 bits?"); +static_assert(char16_t(-1) > char16_t(0), "Is char16_t type unsigned?"); static_assert(sizeof(MOZ_UTF16('A')) == 2, "Is char literal 16 bits?"); static_assert(sizeof(MOZ_UTF16("")[0]) == 2, "Is string char 16 bits?"); +#endif #endif /* mozilla_Char16_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Compiler.h b/external/spidermonkey/include/win32/mozilla/Compiler.h index d1ef1e79aa..fd5c98c98d 100644 --- a/external/spidermonkey/include/win32/mozilla/Compiler.h +++ b/external/spidermonkey/include/win32/mozilla/Compiler.h @@ -29,4 +29,77 @@ #endif +/* + * The situation with standard libraries is a lot worse than with compilers, + * particularly as clang and gcc could end up using one of three or so standard + * libraries, and they may not be up-to-snuff with newer C++11 versions. To + * detect the library, we're going to include cstddef (which is a small header + * which will be transitively included by everybody else at some point) to grab + * the version macros and deduce macros from there. + */ +#ifdef __cplusplus +# include +# ifdef _STLPORT_MAJOR +# define MOZ_USING_STLPORT 1 +# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) \ + (_STLPORT_VERSION >= ((major) << 8 | (minor) << 4 | (patch))) +# elif defined(_LIBCPP_VERSION) + /* + * libc++, unfortunately, doesn't appear to have useful versioning macros. + * Hopefully, the recommendations of N3694 with respect to standard libraries + * will get applied instead and we won't need to worry about version numbers + * here. + */ +# define MOZ_USING_LIBCXX 1 +# elif defined(__GLIBCXX__) +# define MOZ_USING_LIBSTDCXX 1 + /* + * libstdc++ is also annoying and doesn't give us useful versioning macros + * for the library. If we're using gcc, then assume that libstdc++ matches + * the compiler version. If we're using clang, we're going to have to fake + * major/minor combinations by looking for newly-defined config macros. + */ +# if MOZ_IS_GCC +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + MOZ_GCC_VERSION_AT_LEAST(major, minor, patch) +# elif defined(_GLIBCXX_THROW_OR_ABORT) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 8)) +# elif defined(_GLIBCXX_NOEXCEPT) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 7)) +# elif defined(_GLIBCXX_USE_DEPRECATED) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 6)) +# elif defined(_GLIBCXX_PSEUDO_VISIBILITY) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 5)) +# elif defined(_GLIBCXX_BEGIN_EXTERN_C) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 4)) +# elif defined(_GLIBCXX_VISIBILITY_ATTR) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 3)) +# elif defined(_GLIBCXX_VISIBILITY) +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) \ + ((major) < 4 || ((major) == 4 && (minor) <= 2)) +# else +# error "Your version of libstdc++ is unknown to us and is likely too old." +# endif +# endif + + // Flesh out the defines for everyone else +# ifndef MOZ_USING_STLPORT +# define MOZ_USING_STLPORT 0 +# define MOZ_STLPORT_VERSION_AT_LEAST(major, minor, patch) 0 +# endif +# ifndef MOZ_USING_LIBCXX +# define MOZ_USING_LIBCXX 0 +# endif +# ifndef MOZ_USING_LIBSTDCXX +# define MOZ_USING_LIBSTDCXX 0 +# define MOZ_LIBSTDCXX_VERSION_AT_LEAST(major, minor, patch) 0 +# endif +#endif /* __cplusplus */ + #endif /* mozilla_Compiler_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Compression.h b/external/spidermonkey/include/win32/mozilla/Compression.h new file mode 100644 index 0000000000..da77fa895f --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/Compression.h @@ -0,0 +1,116 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* 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/. */ + +/* Various simple compression/decompression functions. */ + +#ifndef mozilla_Compression_h_ +#define mozilla_Compression_h_ + +#include "mozilla/Types.h" +#include "mozilla/Assertions.h" + +namespace mozilla { +namespace Compression { + +/** + * LZ4 is a very fast byte-wise compression algorithm. + * + * Compared to Google's Snappy it is faster to compress and decompress and + * generally produces output of about the same size. + * + * Compared to zlib it compresses at about 10x the speed, decompresses at about + * 4x the speed and produces output of about 1.5x the size. + * + */ + +class LZ4 +{ + +public: + + /** + * Compresses 'inputSize' bytes from 'source' into 'dest'. + * Destination buffer must be already allocated, + * and must be sized to handle worst cases situations (input data not compressible) + * Worst case size evaluation is provided by function LZ4_compressBound() + * + * @param inputSize is the input size. Max supported value is ~1.9GB + * @param return the number of bytes written in buffer dest + */ + static MFBT_API size_t compress(const char* source, size_t inputSize, char* dest); + + /** + * Compress 'inputSize' bytes from 'source' into an output buffer + * 'dest' of maximum size 'maxOutputSize'. If it cannot achieve it, + * compression will stop, and result of the function will be zero, + * 'dest' will still be written to, but since the number of input + * bytes consumed is not returned the result is not usable. + * + * This function never writes outside of provided output buffer. + * + * @param inputSize is the input size. Max supported value is ~1.9GB + * @param maxOutputSize is the size of the destination buffer (which must be already allocated) + * @return the number of bytes written in buffer 'dest' + or 0 if the compression fails + */ + static MFBT_API size_t compressLimitedOutput(const char* source, size_t inputSize, char* dest, + size_t maxOutputSize); + + /** + * If the source stream is malformed, the function will stop decoding + * and return a negative result, indicating the byte position of the + * faulty instruction + * + * This function never writes outside of provided buffers, and never + * modifies input buffer. + * + * note : destination buffer must be already allocated. + * its size must be a minimum of 'outputSize' bytes. + * @param outputSize is the output size, therefore the original size + * @return the number of bytes read in the source buffer + */ + static MFBT_API bool decompress(const char* source, char* dest, size_t outputSize); + + /** + * If the source stream is malformed, the function will stop decoding + * and return false. + * + * This function never writes beyond dest + maxOutputSize, and is + * therefore protected against malicious data packets. + * + * note : Destination buffer must be already allocated. + * This version is slightly slower than the decompress + * without the maxOutputSize + * + * @param inputSize is the length of the input compressed data + * @param maxOutputSize is the size of the destination buffer (which must be already allocated) + * @param outputSize the actual number of bytes decoded in the destination buffer (necessarily <= maxOutputSize) + + */ + static MFBT_API bool decompress(const char* source, size_t inputSize, char* dest, + size_t maxOutputSize, size_t *outputSize); + + /* + Provides the maximum size that LZ4 may output in a "worst case" + scenario (input data not compressible) primarily useful for memory + allocation of output buffer. + note : this function is limited by "int" range (2^31-1) + + @param inputSize is the input size. Max supported value is ~1.9GB + @return maximum output size in a "worst case" scenario + */ + static MFBT_API size_t maxCompressedSize(size_t inputSize) + { + size_t max = ((inputSize) + ((inputSize)/255) + 16); + MOZ_ASSERT(max > inputSize); + return max; + } + +}; + +} /* namespace Compression */ +} /* namespace mozilla */ + +#endif /* mozilla_Compression_h_ */ diff --git a/external/spidermonkey/include/win32/mozilla/Endian.h b/external/spidermonkey/include/win32/mozilla/Endian.h index dc6d11d3ba..cb6bd27c05 100644 --- a/external/spidermonkey/include/win32/mozilla/Endian.h +++ b/external/spidermonkey/include/win32/mozilla/Endian.h @@ -238,9 +238,9 @@ class EndianUtils { DebugOnly byteDestPtr = static_cast(dest); DebugOnly byteSrcPtr = static_cast(src); - MOZ_ASSERT((byteDestPtr < byteSrcPtr && + MOZ_ASSERT((byteDestPtr <= byteSrcPtr && byteDestPtr + count <= byteSrcPtr) || - (byteSrcPtr < byteDestPtr && + (byteSrcPtr <= byteDestPtr && byteSrcPtr + count <= byteDestPtr)); } diff --git a/external/spidermonkey/include/win32/mozilla/FloatingPoint.h b/external/spidermonkey/include/win32/mozilla/FloatingPoint.h index d80f6a7234..eff26b4bb8 100644 --- a/external/spidermonkey/include/win32/mozilla/FloatingPoint.h +++ b/external/spidermonkey/include/win32/mozilla/FloatingPoint.h @@ -12,6 +12,7 @@ #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" #include "mozilla/Casting.h" +#include "mozilla/Types.h" #include @@ -58,6 +59,30 @@ static_assert((DoubleSignBit | DoubleExponentBits | DoubleSignificandBits) == ~uint64_t(0), "all bits accounted for"); +/* + * Ditto for |float| that must be a 32-bit double format number type, compatible + * with the IEEE-754 standard. + */ +static_assert(sizeof(float) == sizeof(uint32_t), "float must be 32bits"); + +const unsigned FloatExponentBias = 127; +const unsigned FloatExponentShift = 23; + +const uint32_t FloatSignBit = 0x80000000UL; +const uint32_t FloatExponentBits = 0x7F800000UL; +const uint32_t FloatSignificandBits = 0x007FFFFFUL; + +static_assert((FloatSignBit & FloatExponentBits) == 0, + "sign bit doesn't overlap exponent bits"); +static_assert((FloatSignBit & FloatSignificandBits) == 0, + "sign bit doesn't overlap significand bits"); +static_assert((FloatExponentBits & FloatSignificandBits) == 0, + "exponent bits don't overlap significand bits"); + +static_assert((FloatSignBit | FloatExponentBits | FloatSignificandBits) == + ~uint32_t(0), + "all bits accounted for"); + /** Determines whether a double is NaN. */ static MOZ_ALWAYS_INLINE bool IsNaN(double d) @@ -115,7 +140,12 @@ IsNegativeZero(double d) return bits == DoubleSignBit; } -/** Returns the exponent portion of the double. */ +/** + * Returns the exponent portion of the double. + * + * Zero is not special-cased, so ExponentComponent(0.0) is + * -int_fast16_t(DoubleExponentBias). + */ static MOZ_ALWAYS_INLINE int_fast16_t ExponentComponent(double d) { @@ -190,7 +220,13 @@ DoubleIsInt32(double d, int32_t* i) static MOZ_ALWAYS_INLINE double UnspecifiedNaN() { - return SpecificNaN(0, 0xfffffffffffffULL); + /* + * If we can use any quiet NaN, we might as well use the all-ones NaN, + * since it's cheap to materialize on common platforms (such as x64, where + * this value can be represented in a 32-bit signed immediate field, allowing + * it to be stored to memory in a single instruction). + */ + return SpecificNaN(1, 0xfffffffffffffULL); } /** @@ -206,6 +242,46 @@ DoublesAreIdentical(double d1, double d2) return BitwiseCast(d1) == BitwiseCast(d2); } +/** Determines whether a float is NaN. */ +static MOZ_ALWAYS_INLINE bool +IsFloatNaN(float f) +{ + /* + * A float is NaN if all exponent bits are 1 and the significand contains at + * least one non-zero bit. + */ + uint32_t bits = BitwiseCast(f); + return (bits & FloatExponentBits) == FloatExponentBits && + (bits & FloatSignificandBits) != 0; +} + +/** Constructs a NaN value with the specified sign bit and significand bits. */ +static MOZ_ALWAYS_INLINE float +SpecificFloatNaN(int signbit, uint32_t significand) +{ + MOZ_ASSERT(signbit == 0 || signbit == 1); + MOZ_ASSERT((significand & ~FloatSignificandBits) == 0); + MOZ_ASSERT(significand & FloatSignificandBits); + + float f = BitwiseCast((signbit ? FloatSignBit : 0) | + FloatExponentBits | + significand); + MOZ_ASSERT(IsFloatNaN(f)); + return f; +} + +/** + * Returns true if the given value can be losslessly represented as an IEEE-754 + * single format number, false otherwise. All NaN values are considered + * representable (notwithstanding that the exact bit pattern of a double format + * NaN value can't be exactly represented in single format). + * + * This function isn't inlined to avoid buggy optimizations by MSVC. + */ +MOZ_WARN_UNUSED_RESULT +extern MFBT_API bool +IsFloat32Representable(double x); + } /* namespace mozilla */ #endif /* mozilla_FloatingPoint_h */ diff --git a/external/spidermonkey/include/win32/mozilla/HashFunctions.h b/external/spidermonkey/include/win32/mozilla/HashFunctions.h index 6d0d24e7b1..b228955ce5 100644 --- a/external/spidermonkey/include/win32/mozilla/HashFunctions.h +++ b/external/spidermonkey/include/win32/mozilla/HashFunctions.h @@ -48,6 +48,7 @@ #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/Char16.h" #include "mozilla/Types.h" #include @@ -326,6 +327,22 @@ HashString(const uint16_t* str, size_t length) return detail::HashKnownLength(str, length); } +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +MOZ_WARN_UNUSED_RESULT +inline uint32_t +HashString(const char16_t* str) +{ + return detail::HashUntilZero(str); +} + +MOZ_WARN_UNUSED_RESULT +inline uint32_t +HashString(const char16_t* str, size_t length) +{ + return detail::HashKnownLength(str, length); +} +#endif + /* * On Windows, wchar_t (PRUnichar) is not the same as uint16_t, even though it's * the same width! diff --git a/external/spidermonkey/include/win32/mozilla/IntegerPrintfMacros.h b/external/spidermonkey/include/win32/mozilla/IntegerPrintfMacros.h new file mode 100644 index 0000000000..1ae60d618e --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/IntegerPrintfMacros.h @@ -0,0 +1,40 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* 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/. */ + +/* Implements the C99 interface, minus the SCN* format macros. */ + +#ifndef mozilla_IntegerPrintfMacros_h_ +#define mozilla_IntegerPrintfMacros_h_ + +/* + * MSVC++ doesn't include , even in versions shipping , so + * we have to reimplement it there. Note: #includes . + * + * Note that this header DOES NOT implement 's scanf macros. MSVC's + * scanf doesn't have sufficient format specifier support to implement them + * (specifically, to implement scanning into an 8-bit location). + * + * http://stackoverflow.com/questions/3036396/scanfd-char-char-as-int-format-string + * + * Moreover, scanf is a footgun: if the input number exceeds the bounds of the + * target type, behavior is undefined (in the compiler sense: that is, this code + * could overwrite your hard drive with zeroes): + * + * uint8_t u; + * sscanf("256", "%" SCNu8, &u); // BAD + * + * This header will sometimes provide SCN* macros, by dint of being implemented + * using . But for these reasons, *never* use them! + */ + +#if defined(MOZ_CUSTOM_INTTYPES_H) +# include MOZ_CUSTOM_INTTYPES_H +#elif defined(_MSC_VER) +# include "mozilla/MSIntTypes.h" +#else +# include +#endif + +#endif /* mozilla_IntegerPrintfMacros_h_ */ diff --git a/external/spidermonkey/include/win32/mozilla/LinkedList.h b/external/spidermonkey/include/win32/mozilla/LinkedList.h index c29760b3e7..f35e7d56ab 100644 --- a/external/spidermonkey/include/win32/mozilla/LinkedList.h +++ b/external/spidermonkey/include/win32/mozilla/LinkedList.h @@ -58,6 +58,7 @@ #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" +#include "mozilla/Move.h" #include "mozilla/NullPtr.h" #ifdef __cplusplus @@ -116,6 +117,36 @@ class LinkedListElement isSentinel(false) { } + LinkedListElement(LinkedListElement&& other) + : isSentinel(other.isSentinel) + { + if (!other.isInList()) { + next = this; + prev = this; + return; + } + + MOZ_ASSERT(other.next->prev == &other); + MOZ_ASSERT(other.prev->next == &other); + + /* + * Initialize |this| with |other|'s prev/next pointers, and adjust those + * element to point to this one. + */ + next = other.next; + prev = other.prev; + + next->prev = this; + prev->next = this; + + /* + * Adjust |other| so it doesn't think it's in a list. This makes it + * safely destructable. + */ + other.next = &other; + other.prev = &other; + } + ~LinkedListElement() { if (!isSentinel && isInList()) remove(); @@ -148,8 +179,8 @@ class LinkedListElement * linked list when you call setNext(); otherwise, this method will assert. */ void setNext(T* elem) { - MOZ_ASSERT(isInList()); - setNextUnsafe(elem); + MOZ_ASSERT(isInList()); + setNextUnsafe(elem); } /* @@ -252,8 +283,8 @@ class LinkedListElement } private: - LinkedListElement& operator=(const LinkedList& other) MOZ_DELETE; - LinkedListElement(const LinkedList& other) MOZ_DELETE; + LinkedListElement& operator=(const LinkedListElement& other) MOZ_DELETE; + LinkedListElement(const LinkedListElement& other) MOZ_DELETE; }; template @@ -265,6 +296,10 @@ class LinkedList public: LinkedList() : sentinel(LinkedListElement::NODE_KIND_SENTINEL) { } + LinkedList(LinkedList&& other) + : sentinel(mozilla::Move(other.sentinel)) + { } + ~LinkedList() { MOZ_ASSERT(isEmpty()); } @@ -361,7 +396,7 @@ class LinkedList for (slow = sentinel.next, fast1 = sentinel.next->next, fast2 = sentinel.next->next->next; - slow != sentinel && fast1 != sentinel && fast2 != sentinel; + slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; slow = slow->next, fast1 = fast2->next, fast2 = fast1->next) { MOZ_ASSERT(slow != fast1); @@ -372,7 +407,7 @@ class LinkedList for (slow = sentinel.prev, fast1 = sentinel.prev->prev, fast2 = sentinel.prev->prev->prev; - slow != sentinel && fast1 != sentinel && fast2 != sentinel; + slow != &sentinel && fast1 != &sentinel && fast2 != &sentinel; slow = slow->prev, fast1 = fast2->prev, fast2 = fast1->prev) { MOZ_ASSERT(slow != fast1); @@ -384,14 +419,14 @@ class LinkedList * isSentinel == true. */ for (const LinkedListElement* elem = sentinel.next; - elem != sentinel; + elem != &sentinel; elem = elem->next) { MOZ_ASSERT(!elem->isSentinel); } /* Check that the next/prev pointers match up. */ - const LinkedListElement* prev = sentinel; + const LinkedListElement* prev = &sentinel; const LinkedListElement* cur = sentinel.next; do { MOZ_ASSERT(cur->prev == prev); @@ -399,7 +434,7 @@ class LinkedList prev = cur; cur = cur->next; - } while (cur != sentinel); + } while (cur != &sentinel); #endif /* ifdef DEBUG */ } diff --git a/external/spidermonkey/include/win32/mozilla/MSIntTypes.h b/external/spidermonkey/include/win32/mozilla/MSIntTypes.h new file mode 100644 index 0000000000..3dfba55f58 --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/MSIntTypes.h @@ -0,0 +1,198 @@ +// ISO C9x compliant inttypes.h for Microsoft Visual Studio +// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124 +// +// Copyright (c) 2006 Alexander Chemeris +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// 3. The name of the author may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////////// + +#ifndef _MSC_VER // [ +#error "Use this header only with Microsoft Visual C++ compilers!" +#endif // _MSC_VER ] + +#ifndef _MSC_INTTYPES_H_ // [ +#define _MSC_INTTYPES_H_ + +#if _MSC_VER > 1000 +#pragma once +#endif + +#include + +// 7.8 Format conversion of integer types + +typedef struct { + intmax_t quot; + intmax_t rem; +} imaxdiv_t; + +// 7.8.1 Macros for format specifiers + +#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198 + +// The fprintf macros for signed integers are: +#define PRId8 "d" +#define PRIi8 "i" +#define PRIdLEAST8 "d" +#define PRIiLEAST8 "i" +#define PRIdFAST8 "d" +#define PRIiFAST8 "i" + +#define PRId16 "hd" +#define PRIi16 "hi" +#define PRIdLEAST16 "hd" +#define PRIiLEAST16 "hi" +#define PRIdFAST16 "hd" +#define PRIiFAST16 "hi" + +#define PRId32 "I32d" +#define PRIi32 "I32i" +#define PRIdLEAST32 "I32d" +#define PRIiLEAST32 "I32i" +#define PRIdFAST32 "I32d" +#define PRIiFAST32 "I32i" + +#define PRId64 "I64d" +#define PRIi64 "I64i" +#define PRIdLEAST64 "I64d" +#define PRIiLEAST64 "I64i" +#define PRIdFAST64 "I64d" +#define PRIiFAST64 "I64i" + +#define PRIdMAX "I64d" +#define PRIiMAX "I64i" + +#define PRIdPTR "Id" +#define PRIiPTR "Ii" + +// The fprintf macros for unsigned integers are: +#define PRIo8 "o" +#define PRIu8 "u" +#define PRIx8 "x" +#define PRIX8 "X" +#define PRIoLEAST8 "o" +#define PRIuLEAST8 "u" +#define PRIxLEAST8 "x" +#define PRIXLEAST8 "X" +#define PRIoFAST8 "o" +#define PRIuFAST8 "u" +#define PRIxFAST8 "x" +#define PRIXFAST8 "X" + +#define PRIo16 "ho" +#define PRIu16 "hu" +#define PRIx16 "hx" +#define PRIX16 "hX" +#define PRIoLEAST16 "ho" +#define PRIuLEAST16 "hu" +#define PRIxLEAST16 "hx" +#define PRIXLEAST16 "hX" +#define PRIoFAST16 "ho" +#define PRIuFAST16 "hu" +#define PRIxFAST16 "hx" +#define PRIXFAST16 "hX" + +#define PRIo32 "I32o" +#define PRIu32 "I32u" +#define PRIx32 "I32x" +#define PRIX32 "I32X" +#define PRIoLEAST32 "I32o" +#define PRIuLEAST32 "I32u" +#define PRIxLEAST32 "I32x" +#define PRIXLEAST32 "I32X" +#define PRIoFAST32 "I32o" +#define PRIuFAST32 "I32u" +#define PRIxFAST32 "I32x" +#define PRIXFAST32 "I32X" + +#define PRIo64 "I64o" +#define PRIu64 "I64u" +#define PRIx64 "I64x" +#define PRIX64 "I64X" +#define PRIoLEAST64 "I64o" +#define PRIuLEAST64 "I64u" +#define PRIxLEAST64 "I64x" +#define PRIXLEAST64 "I64X" +#define PRIoFAST64 "I64o" +#define PRIuFAST64 "I64u" +#define PRIxFAST64 "I64x" +#define PRIXFAST64 "I64X" + +#define PRIoMAX "I64o" +#define PRIuMAX "I64u" +#define PRIxMAX "I64x" +#define PRIXMAX "I64X" + +#define PRIoPTR "Io" +#define PRIuPTR "Iu" +#define PRIxPTR "Ix" +#define PRIXPTR "IX" + +// DO NOT SUPPORT THE scanf MACROS! See the comment at the top of +// IntegerPrintfMacros.h. + +#endif // __STDC_FORMAT_MACROS ] + +// 7.8.2 Functions for greatest-width integer types + +// 7.8.2.1 The imaxabs function +#define imaxabs _abs64 + +// 7.8.2.2 The imaxdiv function + +// This is modified version of div() function from Microsoft's div.c found +// in %MSVC.NET%\crt\src\div.c +#ifdef STATIC_IMAXDIV // [ +static +#else // STATIC_IMAXDIV ][ +_inline +#endif // STATIC_IMAXDIV ] +imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom) +{ + imaxdiv_t result; + + result.quot = numer / denom; + result.rem = numer % denom; + + if (numer < 0 && result.rem > 0) { + // did division wrong; must fix up + ++result.quot; + result.rem -= denom; + } + + return result; +} + +// 7.8.2.3 The strtoimax and strtoumax functions +#define strtoimax _strtoi64 +#define strtoumax _strtoui64 + +// 7.8.2.4 The wcstoimax and wcstoumax functions +#define wcstoimax _wcstoi64 +#define wcstoumax _wcstoui64 + + +#endif // _MSC_INTTYPES_H_ ] diff --git a/external/spidermonkey/include/win32/mozilla/MathAlgorithms.h b/external/spidermonkey/include/win32/mozilla/MathAlgorithms.h index 6d58691e06..941ac81271 100644 --- a/external/spidermonkey/include/win32/mozilla/MathAlgorithms.h +++ b/external/spidermonkey/include/win32/mozilla/MathAlgorithms.h @@ -186,6 +186,16 @@ namespace detail { return uint_fast8_t(index); } + inline uint_fast8_t + CountPopulation32(uint32_t u) + { + uint32_t sum2 = (u & 0x55555555) + ((u & 0xaaaaaaaa) >> 1); + uint32_t sum4 = (sum2 & 0x33333333) + ((sum2 & 0xcccccccc) >> 2); + uint32_t sum8 = (sum4 & 0x0f0f0f0f) + ((sum4 & 0xf0f0f0f0) >> 4); + uint32_t sum16 = (sum8 & 0x00ff00ff) + ((sum8 & 0xff00ff00) >> 8); + return sum16; + } + inline uint_fast8_t CountLeadingZeroes64(uint64_t u) { @@ -242,6 +252,12 @@ namespace detail { return __builtin_ctz(u); } + inline uint_fast8_t + CountPopulation32(uint32_t u) + { + return __builtin_popcount(u); + } + inline uint_fast8_t CountLeadingZeroes64(uint64_t u) { @@ -258,6 +274,7 @@ namespace detail { # error "Implement these!" inline uint_fast8_t CountLeadingZeroes32(uint32_t u) MOZ_DELETE; inline uint_fast8_t CountTrailingZeroes32(uint32_t u) MOZ_DELETE; + inline uint_fast8_t CountPopulation32(uint32_t u) MOZ_DELETE; inline uint_fast8_t CountLeadingZeroes64(uint64_t u) MOZ_DELETE; inline uint_fast8_t CountTrailingZeroes64(uint64_t u) MOZ_DELETE; #endif @@ -300,6 +317,15 @@ CountTrailingZeroes32(uint32_t u) return detail::CountTrailingZeroes32(u); } +/** + * Compute the number of one bits in the number |u|, + */ +inline uint_fast8_t +CountPopulation32(uint32_t u) +{ + return detail::CountPopulation32(u); +} + /** Analogous to CountLeadingZeroes32, but for 64-bit numbers. */ inline uint_fast8_t CountLeadingZeroes64(uint64_t u) diff --git a/external/spidermonkey/include/win32/mozilla/Maybe.h b/external/spidermonkey/include/win32/mozilla/Maybe.h new file mode 100644 index 0000000000..25683a28ab --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/Maybe.h @@ -0,0 +1,163 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=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/. */ + +/* A class for lazily constructing an object without sticking it on the heap. */ + +#ifndef mozilla_Maybe_h +#define mozilla_Maybe_h + +#include "mozilla/Alignment.h" +#include "mozilla/Assertions.h" + +// For placement new +#include + +namespace mozilla { + +/* + * Small utility for lazily constructing objects without using dynamic storage. + * When a Maybe is constructed, it is |empty()|, i.e., no value of T has + * been constructed and no T destructor will be called when the Maybe is + * destroyed. Upon calling |construct|, a T object will be constructed with the + * given arguments and that object will be destroyed when the owning Maybe + * is destroyed. + * + * N.B. GCC seems to miss some optimizations with Maybe and may generate extra + * branches/loads/stores. Use with caution on hot paths. + */ +template +class Maybe +{ + AlignedStorage2 storage; + bool constructed; + + T& asT() { return *storage.addr(); } + + public: + Maybe() { constructed = false; } + ~Maybe() { if (constructed) asT().~T(); } + + bool empty() const { return !constructed; } + + void construct() { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(); + constructed = true; + } + + template + void construct(const T1& t1) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9); + constructed = true; + } + + template + void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, + const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) { + MOZ_ASSERT(!constructed); + ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); + constructed = true; + } + + T* addr() { + MOZ_ASSERT(constructed); + return &asT(); + } + + T& ref() { + MOZ_ASSERT(constructed); + return asT(); + } + + const T& ref() const { + MOZ_ASSERT(constructed); + return const_cast(this)->asT(); + } + + void destroy() { + ref().~T(); + constructed = false; + } + + void destroyIfConstructed() { + if (!empty()) + destroy(); + } + + private: + Maybe(const Maybe& other) MOZ_DELETE; + const Maybe& operator=(const Maybe& other) MOZ_DELETE; +}; + +} // namespace mozilla + +#endif /* mozilla_Maybe_h */ diff --git a/external/spidermonkey/include/win32/mozilla/Move.h b/external/spidermonkey/include/win32/mozilla/Move.h index 97178daaa6..a18da32ad8 100644 --- a/external/spidermonkey/include/win32/mozilla/Move.h +++ b/external/spidermonkey/include/win32/mozilla/Move.h @@ -9,11 +9,21 @@ #ifndef mozilla_Move_h #define mozilla_Move_h +#include "mozilla/TypeTraits.h" + namespace mozilla { /* * "Move" References * + * [Once upon a time, C++11 rvalue references were not implemented by all the + * compilers we cared about, so we invented mozilla::Move() (now called + * OldMove()), which does something similar. We're in the process of + * transitioning away from this to pure stl (bug 896100). Until that bug is + * completed, this header will provide both mozilla::OldMove() and + * mozilla::Move().] + * + * * Some types can be copied much more efficiently if we know the original's * value need not be preserved --- that is, if we are doing a "move", not a * "copy". For example, if we have: @@ -48,18 +58,28 @@ namespace mozilla { * efficiently than it can be copied, and provide an implementation of that * move operation. * - * The Move(T&) function takes a reference to a T, and returns a MoveRef - * referring to the same value; that's 1). A MoveRef is simply a reference + * The OldMove(T&) function takes a reference to a T, and returns a MoveRef + * referring to the same value; that's (1). A MoveRef is simply a reference * to a T, annotated to say that a copy constructor applied to it may move that * T, instead of copying it. Finally, a constructor that accepts an MoveRef - * should perform a more efficient move, instead of a copy, providing 2). + * should perform a more efficient move, instead of a copy, providing (2). * - * So, where we might define a copy constructor for a class C like this: + * The Move(T&) function takes a reference to a T and returns a T&&. It acts + * just like std::move(), which is not available on all our platforms. + * + * In new code, you should use Move(T&) and T&& instead of OldMove(T&) and + * MoveRef, where possible. + * + * Where we might define a copy constructor for a class C like this: * * C(const C& rhs) { ... copy rhs to this ... } * * we would declare a move constructor like this: * + * C(C&& rhs) { .. move rhs to this ... } + * + * or, in the deprecated OldMove style: + * * C(MoveRef rhs) { ... move rhs to this ... } * * And where we might perform a copy like this: @@ -68,7 +88,11 @@ namespace mozilla { * * we would perform a move like this: * - * C c2(Move(c1)) + * C c2(Move(c1)); + * + * or, in the deprecated OldMove style: + * + * C c2(OldMove(c1)); * * Note that MoveRef implicitly converts to T&, so you can pass a MoveRef * to an ordinary copy constructor for a type that doesn't support a special @@ -82,7 +106,7 @@ namespace mozilla { * which runs this's destructor, and then applies the move constructor to * *this's memory. A typical definition: * - * C& operator=(MoveRef rhs) { + * C& operator=(C&& rhs) { // or |MoveRef rhs| * this->~C(); * new(this) C(rhs); * return *this; @@ -90,14 +114,14 @@ namespace mozilla { * * With that in place, one can write move assignments like this: * - * c2 = Move(c1); + * c2 = Move(c1); // or OldMove() * * This destroys c1, moves c1's value to c2, and leaves c1 in an undefined but * destructible state. * - * This header file defines MoveRef and Move in the mozilla namespace. It's up - * to individual containers to annotate moves as such, by calling Move; and it's - * up to individual types to define move constructors. + * This header file defines MoveRef, Move, and OldMove in the mozilla namespace. + * It's up to individual containers to annotate moves as such, by calling Move + * or OldMove; and it's up to individual types to define move constructors. * * One hint: if you're writing a move constructor where the type has members * that should be moved themselves, it's much nicer to write this: @@ -125,14 +149,14 @@ class MoveRef template inline MoveRef -Move(T& t) +OldMove(T& t) { return MoveRef(t); } template inline MoveRef -Move(const T& t) +OldMove(const T& t) { // With some versions of gcc, for a class C, there's an (incorrect) ambiguity // between the C(const C&) constructor and the default C(C&&) C++11 move @@ -151,14 +175,45 @@ Move(const T& t) return MoveRef(const_cast(t)); } +/** + * Identical to std::Move(); this is necessary until our stlport supports + * std::move(). + */ +template +inline typename RemoveReference::Type&& +Move(T&& a) +{ + return static_cast::Type&&>(a); +} + +/** + * These two overloads are identidal to std::Forward(); they are necessary until + * our stlport supports std::forward(). + */ +template +inline T&& +Forward(typename RemoveReference::Type& a) +{ + return static_cast(a); +} + +template +inline T&& +Forward(typename RemoveReference::Type&& t) +{ + static_assert(!IsLvalueReference::value, + "misuse of Forward detected! try the other overload"); + return static_cast(t); +} + /** Swap |t| and |u| using move-construction if possible. */ template inline void Swap(T& t, T& u) { - T tmp(Move(t)); - t = Move(u); - u = Move(tmp); + T tmp(OldMove(t)); + t = OldMove(u); + u = OldMove(tmp); } } // namespace mozilla diff --git a/external/spidermonkey/include/win32/mozilla/NullPtr.h b/external/spidermonkey/include/win32/mozilla/NullPtr.h index 14c0f07df2..35faadc4c3 100644 --- a/external/spidermonkey/include/win32/mozilla/NullPtr.h +++ b/external/spidermonkey/include/win32/mozilla/NullPtr.h @@ -12,8 +12,6 @@ #ifndef mozilla_NullPtr_h #define mozilla_NullPtr_h -#include "mozilla/Compiler.h" - #if defined(__clang__) # ifndef __has_extension # define __has_extension __has_feature @@ -23,6 +21,7 @@ # endif #elif defined(__GNUC__) # if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L +# include "mozilla/Compiler.h" # if MOZ_GCC_VERSION_AT_LEAST(4, 6, 0) # define MOZ_HAVE_CXX11_NULLPTR # endif diff --git a/external/spidermonkey/include/win32/mozilla/NumericLimits.h b/external/spidermonkey/include/win32/mozilla/NumericLimits.h new file mode 100644 index 0000000000..d2ee29813e --- /dev/null +++ b/external/spidermonkey/include/win32/mozilla/NumericLimits.h @@ -0,0 +1,40 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=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/. */ + +/* Compatibility with std::numeric_limits. */ + +#ifndef mozilla_NumericLimits_h +#define mozilla_NumericLimits_h + +#include "mozilla/Char16.h" + +#include +#include + +namespace mozilla { + +/** + * The NumericLimits class provides a compatibility layer with std::numeric_limits + * for char16_t, otherwise it is exactly the same as std::numeric_limits. + * Code which does not need std::numeric_limits should avoid using + * NumericLimits. + */ +template +class NumericLimits : public std::numeric_limits +{ +}; + +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> +class NumericLimits : public std::numeric_limits +{ + // char16_t and uint16_t numeric limits should be exactly the same. +}; +#endif + +} // namespace mozilla + +#endif /* mozilla_NumericLimits_h */ diff --git a/external/spidermonkey/include/win32/mozilla/PodOperations.h b/external/spidermonkey/include/win32/mozilla/PodOperations.h index bec89fa928..668197cdc1 100644 --- a/external/spidermonkey/include/win32/mozilla/PodOperations.h +++ b/external/spidermonkey/include/win32/mozilla/PodOperations.h @@ -24,7 +24,7 @@ namespace mozilla { /** Set the contents of |t| to 0. */ template -static void +static MOZ_ALWAYS_INLINE void PodZero(T* t) { memset(t, 0, sizeof(T)); @@ -32,7 +32,7 @@ PodZero(T* t) /** Set the contents of |nelem| elements starting at |t| to 0. */ template -static void +static MOZ_ALWAYS_INLINE void PodZero(T* t, size_t nelem) { /* @@ -58,7 +58,7 @@ static void PodZero(T (&t)[N], size_t nelem) MOZ_DELETE; /** Set the contents of the array |t| to zero. */ template -static void +static MOZ_ALWAYS_INLINE void PodArrayZero(T (&t)[N]) { memset(t, 0, N * sizeof(T)); @@ -69,7 +69,7 @@ PodArrayZero(T (&t)[N]) * overlap. */ template -static void +static MOZ_ALWAYS_INLINE void PodAssign(T* dst, const T* src) { MOZ_ASSERT(dst != src); @@ -83,7 +83,7 @@ PodAssign(T* dst, const T* src) * overlap! */ template -MOZ_ALWAYS_INLINE static void +static MOZ_ALWAYS_INLINE void PodCopy(T* dst, const T* src, size_t nelem) { MOZ_ASSERT(dst != src); @@ -103,7 +103,7 @@ PodCopy(T* dst, const T* src, size_t nelem) } template -MOZ_ALWAYS_INLINE static void +static MOZ_ALWAYS_INLINE void PodCopy(volatile T* dst, const volatile T* src, size_t nelem) { MOZ_ASSERT(dst != src); @@ -127,7 +127,7 @@ PodCopy(volatile T* dst, const volatile T* src, size_t nelem) * The arrays must not overlap! */ template -static void +static MOZ_ALWAYS_INLINE void PodArrayCopy(T (&dst)[N], const T (&src)[N]) { PodCopy(dst, src, N); @@ -138,7 +138,7 @@ PodArrayCopy(T (&dst)[N], const T (&src)[N]) * |len| elements at |two|. */ template -MOZ_ALWAYS_INLINE static bool +static MOZ_ALWAYS_INLINE bool PodEqual(const T* one, const T* two, size_t len) { if (len < 128) { diff --git a/external/spidermonkey/include/win32/mozilla/RefPtr.h b/external/spidermonkey/include/win32/mozilla/RefPtr.h index 3c275afdc7..72c7904554 100644 --- a/external/spidermonkey/include/win32/mozilla/RefPtr.h +++ b/external/spidermonkey/include/win32/mozilla/RefPtr.h @@ -68,18 +68,18 @@ class RefCounted public: // Compatibility with nsRefPtr. - void AddRef() { + void AddRef() const { MOZ_ASSERT(refCnt >= 0); ++refCnt; } - void Release() { + void Release() const { MOZ_ASSERT(refCnt > 0); if (0 == --refCnt) { #ifdef DEBUG refCnt = detail::DEAD; #endif - delete static_cast(this); + delete static_cast(this); } } @@ -93,7 +93,7 @@ class RefCounted } private: - typename Conditional, int>::Type refCnt; + mutable typename Conditional, int>::Type refCnt; }; } diff --git a/external/spidermonkey/include/win32/mozilla/TypeTraits.h b/external/spidermonkey/include/win32/mozilla/TypeTraits.h index 53c0b5c2f6..1ccd0c85d1 100644 --- a/external/spidermonkey/include/win32/mozilla/TypeTraits.h +++ b/external/spidermonkey/include/win32/mozilla/TypeTraits.h @@ -63,6 +63,9 @@ template<> struct IsIntegralHelper : TrueType {}; template<> struct IsIntegralHelper : TrueType {}; template<> struct IsIntegralHelper : TrueType {}; template<> struct IsIntegralHelper : TrueType {}; +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> struct IsIntegralHelper : TrueType {}; +#endif } /* namespace detail */ @@ -218,6 +221,9 @@ template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; template<> struct IsPod : TrueType {}; +#ifdef MOZ_CHAR16_IS_NOT_WCHAR +template<> struct IsPod : TrueType {}; +#endif template struct IsPod : TrueType {}; namespace detail { @@ -418,6 +424,16 @@ struct IsConvertible : IntegralConstant::value> {}; +/** + * Is IsLvalueReference is true if its template param is T& and is false if + * its type is T or T&&. + */ +template +struct IsLvalueReference : FalseType {}; + +template +struct IsLvalueReference : TrueType {}; + /* 20.9.7 Transformations between types [meta.trans] */ /* 20.9.7.1 Const-volatile modifications [meta.trans.cv] */ @@ -478,6 +494,32 @@ struct RemoveCV /* 20.9.7.2 Reference modifications [meta.trans.ref] */ +/** + * Converts reference types to the underlying types. + * + * mozilla::RemoveReference::Type is T; + * mozilla::RemoveReference::Type is T; + * mozilla::RemoveReference::Type is T; + */ + +template +struct RemoveReference +{ + typedef T Type; +}; + +template +struct RemoveReference +{ + typedef T Type; +}; + +template +struct RemoveReference +{ + typedef T Type; +}; + /* 20.9.7.3 Sign modifications [meta.trans.sign] */ template diff --git a/external/spidermonkey/include/win32/mozilla/TypedEnum.h b/external/spidermonkey/include/win32/mozilla/TypedEnum.h index 6f595cb4c5..9c7590deff 100644 --- a/external/spidermonkey/include/win32/mozilla/TypedEnum.h +++ b/external/spidermonkey/include/win32/mozilla/TypedEnum.h @@ -28,7 +28,7 @@ # endif #elif defined(__GNUC__) # if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L -# if MOZ_GCC_VERSION_AT_LEAST(4, 5, 1) +# if MOZ_GCC_VERSION_AT_LEAST(4, 6, 3) # define MOZ_HAVE_CXX11_ENUM_TYPE # define MOZ_HAVE_CXX11_STRONG_ENUMS # endif @@ -72,7 +72,7 @@ * strongly-typed enumeration feature of C++11 ("enum class"). If supported * by the compiler, an enum defined using these macros will not be implicitly * converted to any other type, and its enumerators will be scoped using the - * enumeration name. Place MOZ_BEGIN_ENUM_CLASS(EnumName, type) in place of + * enumeration name. Place MOZ_BEGIN_ENUM_CLASS(EnumName [, type]) in place of * "enum EnumName {", and MOZ_END_ENUM_CLASS(EnumName) in place of the closing * "};". For example, * @@ -87,10 +87,9 @@ * fail. In other compilers, Enum itself will actually be defined as a class, * and some implicit conversions will fail while others will succeed. * - * The type argument specifies the underlying type for the enum where - * supported, as with MOZ_ENUM_TYPE(). For simplicity, it is currently - * mandatory. As with MOZ_ENUM_TYPE(), it will do nothing on compilers that do - * not support it. + * The optional type argument specifies the underlying type for the enum where + * supported, as with MOZ_ENUM_TYPE(). As with MOZ_ENUM_TYPE(), it will do + * nothing on compilers that do not support it. * * MOZ_{BEGIN,END}_ENUM_CLASS doesn't work for defining enum classes nested * inside classes. To define an enum class nested inside another class, use @@ -114,7 +113,12 @@ * All compilers that support strong enums also support an explicit * underlying type, so no extra check is needed. */ -# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ + + /* Single-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER1(Name) \ + enum class Name { + /* Two-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER2(Name, type) \ enum class Name : type { # define MOZ_END_NESTED_ENUM_CLASS(Name) \ }; @@ -154,8 +158,17 @@ * { * return Enum::A; * } - */\ -# define MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) \ + */ + + /* Single-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER1(Name) \ + class Name \ + { \ + public: \ + enum Enum \ + { + /* Two-argument form. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER2(Name, type) \ class Name \ { \ public: \ @@ -226,7 +239,36 @@ inline int& operator<<=(int&, const Name::Enum&) MOZ_DELETE; \ inline int& operator>>=(int&, const Name::Enum&) MOZ_DELETE; #endif -# define MOZ_BEGIN_ENUM_CLASS(Name, type) MOZ_BEGIN_NESTED_ENUM_CLASS(Name, type) + + /* + * Count the number of arguments passed to MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS, + * very carefully tiptoeing around an MSVC bug where it improperly expands + * __VA_ARGS__ as a single token in argument lists. See these URLs for + * details: + * + * http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement + * http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/#comment-644 + */ +# define MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL2(_1, _2, count, ...) \ + count +# define MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL(args) \ + MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL2 args +# define MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS(...) \ + MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS_IMPL((__VA_ARGS__, 2, 1, 0)) + /* Pick the right helper macro to invoke. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER2(count) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_HELPER##count +# define MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER1(count) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER2(count) +# define MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER(count) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER1(count) + /* The actual macro. */ +# define MOZ_BEGIN_NESTED_ENUM_CLASS_GLUE(x, y) x y +# define MOZ_BEGIN_NESTED_ENUM_CLASS(...) \ + MOZ_BEGIN_NESTED_ENUM_CLASS_GLUE(MOZ_BEGIN_NESTED_ENUM_CLASS_CHOOSE_HELPER(MOZ_COUNT_BEGIN_ENUM_CLASS_ARGS(__VA_ARGS__)), \ + (__VA_ARGS__)) + +# define MOZ_BEGIN_ENUM_CLASS(...) MOZ_BEGIN_NESTED_ENUM_CLASS(__VA_ARGS__) # define MOZ_END_ENUM_CLASS(Name) \ MOZ_END_NESTED_ENUM_CLASS(Name) \ MOZ_FINISH_NESTED_ENUM_CLASS(Name) diff --git a/external/spidermonkey/include/win32/mozilla/Util.h b/external/spidermonkey/include/win32/mozilla/Util.h index 4f1c634a59..b4cf2e425b 100644 --- a/external/spidermonkey/include/win32/mozilla/Util.h +++ b/external/spidermonkey/include/win32/mozilla/Util.h @@ -18,267 +18,10 @@ #ifdef __cplusplus +#include "mozilla/Alignment.h" + namespace mozilla { -/* - * This class, and the corresponding macro MOZ_ALIGNOF, figure out how many - * bytes of alignment a given type needs. - */ -template -class AlignmentFinder -{ - struct Aligner - { - char c; - T t; - }; - - public: - static const size_t alignment = sizeof(Aligner) - sizeof(T); -}; - -#define MOZ_ALIGNOF(T) mozilla::AlignmentFinder::alignment - -/* - * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types. - * - * For instance, - * - * MOZ_ALIGNED_DECL(char arr[2], 8); - * - * will declare a two-character array |arr| aligned to 8 bytes. - */ - -#if defined(__GNUC__) -# define MOZ_ALIGNED_DECL(_type, _align) \ - _type __attribute__((aligned(_align))) -#elif defined(_MSC_VER) -# define MOZ_ALIGNED_DECL(_type, _align) \ - __declspec(align(_align)) _type -#else -# warning "We don't know how to align variables on this compiler." -# define MOZ_ALIGNED_DECL(_type, _align) _type -#endif - -/* - * AlignedElem is a structure whose alignment is guaranteed to be at least N - * bytes. - * - * We support 1, 2, 4, 8, and 16-bit alignment. - */ -template -struct AlignedElem; - -/* - * We have to specialize this template because GCC doesn't like __attribute__((aligned(foo))) where - * foo is a template parameter. - */ - -template<> -struct AlignedElem<1> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 1); -}; - -template<> -struct AlignedElem<2> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 2); -}; - -template<> -struct AlignedElem<4> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 4); -}; - -template<> -struct AlignedElem<8> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 8); -}; - -template<> -struct AlignedElem<16> -{ - MOZ_ALIGNED_DECL(uint8_t elem, 16); -}; - -/* - * This utility pales in comparison to Boost's aligned_storage. The utility - * simply assumes that uint64_t is enough alignment for anyone. This may need - * to be extended one day... - * - * As an important side effect, pulling the storage into this template is - * enough obfuscation to confuse gcc's strict-aliasing analysis into not giving - * false negatives when we cast from the char buffer to whatever type we've - * constructed using the bytes. - */ -template -struct AlignedStorage -{ - union U { - char bytes[nbytes]; - uint64_t _; - } u; - - const void* addr() const { return u.bytes; } - void* addr() { return u.bytes; } -}; - -template -struct AlignedStorage2 -{ - union U { - char bytes[sizeof(T)]; - uint64_t _; - } u; - - const T* addr() const { return reinterpret_cast(u.bytes); } - T* addr() { return static_cast(static_cast(u.bytes)); } -}; - -/* - * Small utility for lazily constructing objects without using dynamic storage. - * When a Maybe is constructed, it is |empty()|, i.e., no value of T has - * been constructed and no T destructor will be called when the Maybe is - * destroyed. Upon calling |construct|, a T object will be constructed with the - * given arguments and that object will be destroyed when the owning Maybe - * is destroyed. - * - * N.B. GCC seems to miss some optimizations with Maybe and may generate extra - * branches/loads/stores. Use with caution on hot paths. - */ -template -class Maybe -{ - AlignedStorage2 storage; - bool constructed; - - T& asT() { return *storage.addr(); } - - public: - Maybe() { constructed = false; } - ~Maybe() { if (constructed) asT().~T(); } - - bool empty() const { return !constructed; } - - void construct() { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(); - constructed = true; - } - - template - void construct(const T1& t1) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7, const T8& t8) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7, const T8& t8, const T9& t9) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9); - constructed = true; - } - - template - void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, - const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) { - MOZ_ASSERT(!constructed); - ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10); - constructed = true; - } - - T* addr() { - MOZ_ASSERT(constructed); - return &asT(); - } - - T& ref() { - MOZ_ASSERT(constructed); - return asT(); - } - - const T& ref() const { - MOZ_ASSERT(constructed); - return const_cast(this)->asT(); - } - - void destroy() { - ref().~T(); - constructed = false; - } - - void destroyIfConstructed() { - if (!empty()) - destroy(); - } - - private: - Maybe(const Maybe& other) MOZ_DELETE; - const Maybe& operator=(const Maybe& other) MOZ_DELETE; -}; - /* * Safely subtract two pointers when it is known that end >= begin. This avoids * the common compiler bug that if (size_t(end) - size_t(begin)) has the MSB diff --git a/external/spidermonkey/include/win32/mozilla/Vector.h b/external/spidermonkey/include/win32/mozilla/Vector.h index 8759df8c06..54e266eeb7 100644 --- a/external/spidermonkey/include/win32/mozilla/Vector.h +++ b/external/spidermonkey/include/win32/mozilla/Vector.h @@ -9,6 +9,7 @@ #ifndef mozilla_Vector_h #define mozilla_Vector_h +#include "mozilla/Alignment.h" #include "mozilla/AllocPolicy.h" #include "mozilla/Assertions.h" #include "mozilla/Attributes.h" @@ -19,7 +20,7 @@ #include "mozilla/ReentrancyGuard.h" #include "mozilla/TemplateLib.h" #include "mozilla/TypeTraits.h" -#include "mozilla/Util.h" +#include "mozilla/Util.h" // for PointerRangeSize #include // for placement new @@ -85,7 +86,7 @@ struct VectorImpl template static inline void moveConstruct(T* dst, const U* srcbeg, const U* srcend) { for (const U* p = srcbeg; p < srcend; ++p, ++dst) - new(dst) T(Move(*p)); + new(dst) T(OldMove(*p)); } /* @@ -114,7 +115,7 @@ struct VectorImpl T* dst = newbuf; T* src = v.beginNoCheck(); for (; src < v.endNoCheck(); ++dst, ++src) - new(dst) T(Move(*src)); + new(dst) T(OldMove(*src)); VectorImpl::destroy(v.beginNoCheck(), v.endNoCheck()); v.free_(v.mBegin); v.mBegin = newbuf; @@ -547,8 +548,8 @@ class VectorBase : private AllocPolicy void swap(ThisVector& other); private: - VectorBase(const ThisVector&) MOZ_DELETE; - void operator=(const ThisVector&) MOZ_DELETE; + VectorBase(const VectorBase&) MOZ_DELETE; + void operator=(const VectorBase&) MOZ_DELETE; }; /* This does the re-entrancy check plus several other sanity checks. */ @@ -565,14 +566,15 @@ template MOZ_ALWAYS_INLINE VectorBase::VectorBase(AP ap) : AP(ap), - mBegin(static_cast(storage.addr())), mLength(0), mCapacity(sInlineCapacity) #ifdef DEBUG , mReserved(sInlineCapacity), entered(false) #endif -{} +{ + mBegin = static_cast(storage.addr()); +} /* Move constructor. */ template diff --git a/external/spidermonkey/include/win32/mozilla/WeakPtr.h b/external/spidermonkey/include/win32/mozilla/WeakPtr.h index c714ebf565..0165e3a017 100644 --- a/external/spidermonkey/include/win32/mozilla/WeakPtr.h +++ b/external/spidermonkey/include/win32/mozilla/WeakPtr.h @@ -14,9 +14,6 @@ * the WeakPtrs to it and allows the WeakReference to live beyond the lifetime * of 'Foo'. * - * AtomicSupportsWeakPtr can be used for a variant with an atomically updated - * reference counter. - * * The overhead of WeakPtr is that accesses to 'Foo' becomes an additional * dereference, and an additional heap allocated pointer sized object shared * between all of the WeakPtrs. @@ -63,7 +60,6 @@ #define mozilla_WeakPtr_h #include "mozilla/Assertions.h" -#include "mozilla/Atomics.h" #include "mozilla/NullPtr.h" #include "mozilla/RefPtr.h" #include "mozilla/TypeTraits.h" @@ -76,8 +72,8 @@ template class SupportsWeakPtrBase; namespace detail { // This can live beyond the lifetime of the class derived from SupportsWeakPtrBase. -template -class WeakReference : public RefCounted, Atomicity> +template +class WeakReference : public ::mozilla::RefCounted > { public: explicit WeakReference(T* p) : ptr(p) {} @@ -86,8 +82,8 @@ class WeakReference : public RefCounted, Atomicity> } private: - friend class WeakPtrBase; - friend class SupportsWeakPtrBase; + friend class WeakPtrBase >; + friend class SupportsWeakPtrBase >; void detach() { ptr = nullptr; } @@ -121,30 +117,10 @@ class SupportsWeakPtrBase }; template -class SupportsWeakPtr - : public SupportsWeakPtrBase > +class SupportsWeakPtr : public SupportsWeakPtrBase > { }; -template -class AtomicSupportsWeakPtr - : public SupportsWeakPtrBase > -{ -}; - -namespace detail { - -template -struct WeakReferenceCount -{ - static const RefCountAtomicity atomicity = - IsBaseOf, T>::value - ? AtomicRefCount - : NonAtomicRefCount; -}; - -} - template class WeakPtrBase { @@ -177,9 +153,9 @@ class WeakPtrBase }; template -class WeakPtr : public WeakPtrBase::atomicity> > +class WeakPtr : public WeakPtrBase > { - typedef WeakPtrBase::atomicity> > Base; + typedef WeakPtrBase > Base; public: WeakPtr(const WeakPtr& o) : Base(o) {} WeakPtr(const Base& o) : Base(o) {} diff --git a/external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id index 66d2ff3161..6bbb419c6a 100644 --- a/external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/android/armeabi-v7a/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -0e1091b9f67b4d348d01b69e998be70c9e0b2dad \ No newline at end of file +4b3fc16c923b538ff3a3d9e92edb34f7f3667c7d \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id index 8a8f30faca..c1b52596e4 100644 --- a/external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/android/armeabi/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -23bfd06f14371832fa99b4efb76133ade10887ec \ No newline at end of file +dcc9ffddbaadb4ee17587e6aaf603411a3e01c20 \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id index fbdaca36eb..240dfdfb93 100644 --- a/external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/android/x86/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -1eb9de4a5ab182f329be479e736c06ac8ab83a00 \ No newline at end of file +6f92f63db1d08b638c61e8ca9fe26f90358a21f6 \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/ios/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/ios/libjs_static.a.REMOVED.git-id index 3aa7da9b21..48c46d31ba 100644 --- a/external/spidermonkey/prebuilt/ios/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/ios/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -1267f1437ae315da4c23e0fc5e7e3f70b4b3c8e2 \ No newline at end of file +92967ef8f12af067e815956bdef215e2f7f0525b \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/mac/libjs_static.a.REMOVED.git-id b/external/spidermonkey/prebuilt/mac/libjs_static.a.REMOVED.git-id index e3f35605ac..2757eb75ba 100644 --- a/external/spidermonkey/prebuilt/mac/libjs_static.a.REMOVED.git-id +++ b/external/spidermonkey/prebuilt/mac/libjs_static.a.REMOVED.git-id @@ -1 +1 @@ -2385a209e3aa59896599e079658d761fd2985c9a \ No newline at end of file +35fccdda36785c75f49b4a44deb8cfc4566d1669 \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/win32/mozjs-25.0.dll.REMOVED.git-id b/external/spidermonkey/prebuilt/win32/mozjs-25.0.dll.REMOVED.git-id deleted file mode 100644 index e9a69561f8..0000000000 --- a/external/spidermonkey/prebuilt/win32/mozjs-25.0.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -66328744e55deaa5397a58a7e0a49b34a602697b \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/win32/mozjs-25.0.lib.REMOVED.git-id b/external/spidermonkey/prebuilt/win32/mozjs-25.0.lib.REMOVED.git-id deleted file mode 100644 index 729e48a68d..0000000000 --- a/external/spidermonkey/prebuilt/win32/mozjs-25.0.lib.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -746eb762bc48a27219221c08bd8ada90727f3921 \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/win32/mozjs-27.dll.REMOVED.git-id b/external/spidermonkey/prebuilt/win32/mozjs-27.dll.REMOVED.git-id new file mode 100644 index 0000000000..d40e508f3e --- /dev/null +++ b/external/spidermonkey/prebuilt/win32/mozjs-27.dll.REMOVED.git-id @@ -0,0 +1 @@ +73f32205167241267f37efa8614cd1b2cf8ea086 \ No newline at end of file diff --git a/external/spidermonkey/prebuilt/win32/mozjs-27.lib.REMOVED.git-id b/external/spidermonkey/prebuilt/win32/mozjs-27.lib.REMOVED.git-id new file mode 100644 index 0000000000..378f426097 --- /dev/null +++ b/external/spidermonkey/prebuilt/win32/mozjs-27.lib.REMOVED.git-id @@ -0,0 +1 @@ +d48c31cf52e13540f8f09156dcaf2b594851fa77 \ No newline at end of file diff --git a/licenses/LICENSE_LuaSocket.txt b/licenses/LICENSE_LuaSocket.txt new file mode 100644 index 0000000000..b0b5367393 --- /dev/null +++ b/licenses/LICENSE_LuaSocket.txt @@ -0,0 +1,20 @@ +LuaSocket 2.0.2 license +Copyright © 2004-2007 Diego Nehab + +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. diff --git a/plugin b/plugin index 47efb364e3..a914bd4ca3 160000 --- a/plugin +++ b/plugin @@ -1 +1 @@ -Subproject commit 47efb364e3b037ed7d9e529c1c2697582fa00c95 +Subproject commit a914bd4ca3416e0a91f88a0ad906559a5140a5bb diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt deleted file mode 100644 index 198764a991..0000000000 --- a/samples/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -if(BUILD_HelloCpp) -add_subdirectory(Cpp/HelloCpp) -endif(BUILD_HelloCpp) - -if(BUILD_TestCpp) -add_subdirectory(Cpp/TestCpp) -endif(BUILD_TestCpp) - -if(BUILD_HelloLua) -add_subdirectory(Lua/HelloLua) -endif(BUILD_HelloLua) - -if(BUILD_TestLua) -add_subdirectory(Lua/TestLua) -endif(BUILD_TestLua) \ No newline at end of file diff --git a/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.cpp b/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.cpp deleted file mode 100644 index 3e9381a865..0000000000 --- a/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.cpp +++ /dev/null @@ -1,221 +0,0 @@ -// -// AssetsManagerTestAppDelegate.cpp -// AssetsManagerTest -// - -#include "AppDelegate.h" - -#include "cocos2d.h" -#include "SimpleAudioEngine.h" -#include "ScriptingCore.h" -#include "jsb_cocos2dx_auto.hpp" -#include "cocos2d_specifics.hpp" - -#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) -#include -#include -#endif - -USING_NS_CC; -USING_NS_CC_EXT; -using namespace std; -using namespace CocosDenshion; - -AppDelegate::AppDelegate() -{ - -} - -AppDelegate::~AppDelegate() -{ -} - -bool AppDelegate::applicationDidFinishLaunching() -{ - // initialize director - auto director = Director::getInstance(); - director->setOpenGLView(EGLView::getInstance()); - - // turn on display FPS - //director->setDisplayStats(true); - - // set FPS. the default value is 1.0/60 if you don't call this - director->setAnimationInterval(1.0 / 60); - - ScriptingCore* sc = ScriptingCore::getInstance(); - sc->addRegisterCallback(register_all_cocos2dx); - sc->addRegisterCallback(register_cocos2dx_js_extensions); - - - sc->start(); - - auto scene = Scene::create(); - auto updateLayer = new UpdateLayer(); - scene->addChild(updateLayer); - updateLayer->release(); - - director->runWithScene(scene); - - return true; -} - -// This function will be called when the app is inactive. When comes a phone call,it's be invoked too -void AppDelegate::applicationDidEnterBackground() -{ - Director::getInstance()->stopAnimation(); - SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); - SimpleAudioEngine::getInstance()->pauseAllEffects(); -} - -// this function will be called when the app is active again -void AppDelegate::applicationWillEnterForeground() -{ - Director::getInstance()->startAnimation(); - SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); - SimpleAudioEngine::getInstance()->resumeAllEffects(); -} - -UpdateLayer::UpdateLayer() -: pItemEnter(NULL) -, pItemReset(NULL) -, pItemUpdate(NULL) -, pProgressLabel(NULL) -, isUpdateItemClicked(false) -{ - init(); -} - -UpdateLayer::~UpdateLayer() -{ -} - -void UpdateLayer::update(cocos2d::Object *pSender) -{ - pProgressLabel->setString(""); - - // update resources - pAssetsManager->update(); - - isUpdateItemClicked = true; -} - -void UpdateLayer::reset(cocos2d::Object *pSender) -{ - pProgressLabel->setString(" "); - - // Remove downloaded files -#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) - string command = "rm -r "; - // Path may include space. - command += "\"" + pathToSave + "\""; - system(command.c_str()); -#else - string command = "rd /s /q "; - // Path may include space. - command += "\"" + pathToSave + "\""; - system(command.c_str()); -#endif - // Delete recorded version codes. - pAssetsManager->deleteVersion(); - - createDownloadedDir(); -} - -void UpdateLayer::enter(cocos2d::Object *pSender) -{ - // Should set search resource path before running script if "update" is not clicked. - // Because AssetsManager will set - if (! isUpdateItemClicked) - { - vector searchPaths = FileUtils::getInstance()->getSearchPaths(); - searchPaths.insert(searchPaths.begin(), pathToSave); - FileUtils::getInstance()->setSearchPaths(searchPaths); - } - - auto pEngine = ScriptingCore::getInstance(); - ScriptEngineManager::getInstance()->setScriptEngine(pEngine); - ScriptingCore::getInstance()->runScript("main.js"); -} - -bool UpdateLayer::init() -{ - Layer::init(); - - /** Creates assets manager */ - pAssetsManager = new AssetsManager("https://raw.github.com/minggo/AssetsManagerTest/master/package.zip", - "https://raw.github.com/minggo/AssetsManagerTest/master/version", - pathToSave.c_str()); - pAssetsManager->setDelegate(this); - pAssetsManager->setConnectionTimeout(3); - addChild(pAssetsManager); - pAssetsManager->release(); - - createDownloadedDir(); - - auto size = Director::getInstance()->getWinSize(); - - pItemReset = MenuItemFont::create("reset", CC_CALLBACK_1(UpdateLayer::reset,this)); - pItemEnter = MenuItemFont::create("enter", CC_CALLBACK_1(UpdateLayer::enter, this)); - pItemUpdate = MenuItemFont::create("update", CC_CALLBACK_1(UpdateLayer::update, this)); - - pItemEnter->setPosition(Point(size.width/2, size.height/2 + 50)); - pItemReset->setPosition(Point(size.width/2, size.height/2)); - pItemUpdate->setPosition(Point(size.width/2, size.height/2 - 50)); - - auto menu = Menu::create(pItemUpdate, pItemEnter, pItemReset, NULL); - menu->setPosition(Point(0,0)); - addChild(menu); - - pProgressLabel = LabelTTF::create("", "Arial", 20); - pProgressLabel->setPosition(Point(100, 50)); - addChild(pProgressLabel); - - return true; -} - -void UpdateLayer::createDownloadedDir() -{ - pathToSave = FileUtils::getInstance()->getWritablePath(); - pathToSave += "tmpdir"; - - // Create the folder if it doesn't exist -#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) - DIR *pDir = NULL; - - pDir = opendir (pathToSave.c_str()); - if (! pDir) - { - mkdir(pathToSave.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); - } -#else - if ((GetFileAttributesA(pathToSave.c_str())) == INVALID_FILE_ATTRIBUTES) - { - CreateDirectoryA(pathToSave.c_str(), 0); - } -#endif -} - -void UpdateLayer::onError(AssetsManager::ErrorCode errorCode) -{ - if (errorCode == AssetsManager::ErrorCode::NO_NEW_VERSION) - { - pProgressLabel->setString("no new version"); - } - - if (errorCode == AssetsManager::ErrorCode::NETWORK) - { - pProgressLabel->setString("network error"); - } -} - -void UpdateLayer::onProgress(int percent) -{ - char progress[20]; - snprintf(progress, 20, "downloading %d%%", percent); - pProgressLabel->setString(progress); -} - -void UpdateLayer::onSuccess() -{ - pProgressLabel->setString("download ok"); -} diff --git a/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.h b/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.h deleted file mode 100644 index 2a0dae6d7b..0000000000 --- a/samples/Cpp/AssetsManagerTest/Classes/AppDelegate.h +++ /dev/null @@ -1,75 +0,0 @@ -// -// AssetsManagerTestAppDelegate.h -// AssetsManagerTest -// -// Created by minggo on 2/5/13. -// Copyright __MyCompanyName__ 2013. All rights reserved. -// - -#ifndef _APP_DELEGATE_H_ -#define _APP_DELEGATE_H_ - -#include "CCApplication.h" -#include "cocos2d.h" -#include "extensions/assets-manager/AssetsManager.h" - -/** -@brief The cocos2d Application. - -The reason to implement with private inheritance is to hide some interface details of Director. -*/ -class AppDelegate : private cocos2d::Application -{ -public: - AppDelegate(); - virtual ~AppDelegate(); - - /** - @brief Implement Director and Scene init code here. - @return true Initialize success, app continue. - @return false Initialize failed, app terminate. - */ - virtual bool applicationDidFinishLaunching(); - - /** - @brief The function is called when the application enters the background - @param the pointer of the application instance - */ - virtual void applicationDidEnterBackground(); - - /** - @brief The function is called when the application enters the foreground - @param the pointer of the application instance - */ - virtual void applicationWillEnterForeground(); -}; - -class UpdateLayer : public cocos2d::Layer, public cocos2d::extension::AssetsManagerDelegateProtocol -{ -public: - UpdateLayer(); - ~UpdateLayer(); - virtual bool init(); - - void enter(cocos2d::Object *pSender); - void reset(cocos2d::Object *pSender); - void update(cocos2d::Object *pSender); - - virtual void onError(cocos2d::extension::AssetsManager::ErrorCode errorCode); - virtual void onProgress(int percent); - virtual void onSuccess(); - -private: - cocos2d::extension::AssetsManager* pAssetsManager; - void createDownloadedDir(); - - cocos2d::MenuItemFont *pItemEnter; - cocos2d::MenuItemFont *pItemReset; - cocos2d::MenuItemFont *pItemUpdate; - cocos2d::LabelTTF *pProgressLabel; - std::string pathToSave; - bool isUpdateItemClicked; -}; - -#endif // _APP_DELEGATE_H_ - diff --git a/samples/Cpp/AssetsManagerTest/README.md b/samples/Cpp/AssetsManagerTest/README.md deleted file mode 100644 index 9d39a99748..0000000000 --- a/samples/Cpp/AssetsManagerTest/README.md +++ /dev/null @@ -1,37 +0,0 @@ -This sample shows how to use AssetsManager to auto-update application resources(pictures or scripts). - -In this sample, there is a scene which contains three items: -* enter - - Start to run script. -* reset - - Delete downloaded resources and delete recorded version code. -* update - - Download new version of package if it exits. - -You can use this sample like this: -* Run original version application(refered as v1) - -``` -start application -click "enter" -``` -* Run new version application(v2) - -``` -start application -click "update" -click "enter" -``` -You will find the changes. -* Run v1 again after running v2 - -``` -start application -click "reset" -click "enter" -``` -The application turns back to v1. Ofcourse you can run v2 again as mentioned abave. - diff --git a/samples/Cpp/AssetsManagerTest/Resources/Background.png.REMOVED.git-id b/samples/Cpp/AssetsManagerTest/Resources/Background.png.REMOVED.git-id deleted file mode 100644 index f02d84fd8f..0000000000 --- a/samples/Cpp/AssetsManagerTest/Resources/Background.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -5fe89fb5bd58cedf13b0363f97b20e3ea7ff255d \ No newline at end of file diff --git a/samples/Cpp/AssetsManagerTest/Resources/main.js b/samples/Cpp/AssetsManagerTest/Resources/main.js deleted file mode 100644 index a796a32e50..0000000000 --- a/samples/Cpp/AssetsManagerTest/Resources/main.js +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - - 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. - ****************************************************************************/ - -// boot code needed for cocos2d + JS bindings. -// Not needed by cocos2d-html5 - -require('jsb_cocos2d.js'); - -var appFiles = [ - 'myApp.js' -]; - -cc.dumpConfig(); - -for( var i=0; i < appFiles.length; i++) { - require( appFiles[i] ); -} - -var director = cc.Director.getInstance(); -director.setDisplayStats(true); - -// set FPS. the default value is 1.0/60 if you don't call this -director.setAnimationInterval(1.0 / 60); - -// create a scene. it's an autorelease object -var myScene = new MyScene(); - -// run -director.replaceScene(myScene); - diff --git a/samples/Cpp/AssetsManagerTest/Resources/myApp.js b/samples/Cpp/AssetsManagerTest/Resources/myApp.js deleted file mode 100644 index e2e6342648..0000000000 --- a/samples/Cpp/AssetsManagerTest/Resources/myApp.js +++ /dev/null @@ -1,99 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2012 cocos2d-x.org - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2011 Zynga 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. - ****************************************************************************/ - -var MyLayer = cc.Layer.extend({ - isMouseDown:false, - helloImg:null, - helloLabel:null, - circle:null, - sprite:null, - - ctor:function() { - this._super(); - cc.associateWithNative( this, cc.Layer ); - }, - - init:function () { - - ////////////////////////////// - // 1. super init first - this._super(); - - ///////////////////////////// - // 2. add a menu item with "X" image, which is clicked to quit the program - // you may modify it. - // ask director the window size - var size = cc.Director.getInstance().getWinSize(); - - // add a "close" icon to exit the progress. it's an autorelease object - var closeItem = cc.MenuItemImage.create( - "CloseNormal.png", - "CloseSelected.png", - function () { - cc.log("close button was clicked."); - },this); - closeItem.setAnchorPoint(cc.p(0.5, 0.5)); - - var menu = cc.Menu.create(closeItem); - menu.setPosition(cc.p(0, 0)); - this.addChild(menu, 1); - closeItem.setPosition(cc.p(size.width - 20, 20)); - - ///////////////////////////// - // 3. add your codes below... - // add a label shows "Hello World" - // create and initialize a label - this.helloLabel = cc.LabelTTF.create("Hello World", "Arial", 38); - // position the label on the center of the screen - this.helloLabel.setPosition(cc.p(size.width / 2, size.height - 40)); - // add the label as a child to this layer - this.addChild(this.helloLabel, 5); - - // add "Helloworld" splash screen" - this.sprite = cc.Sprite.create("Background.png"); - this.sprite.setAnchorPoint(cc.p(0.5, 0.5)); - this.sprite.setPosition(cc.p(size.width / 2, size.height / 2)); - - this.addChild(this.sprite, 0); - - return true; - } - -}); - -var MyScene = cc.Scene.extend({ - ctor:function() { - this._super(); - cc.associateWithNative( this, cc.Scene ); - }, - - onEnter:function () { - this._super(); - var layer = new MyLayer(); - this.addChild(layer); - layer.init(); - } -}); diff --git a/samples/Cpp/AssetsManagerTest/proj.android/.project b/samples/Cpp/AssetsManagerTest/proj.android/.project deleted file mode 100644 index 515077d245..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/.project +++ /dev/null @@ -1,70 +0,0 @@ - - - AssetsManagerTest - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - Classes - 2 - COCOS2DX/samples/Cpp/AssetsManagerTest/Classes - - - cocos2dx - 2 - COCOS2DX/cocos2dx - - - cocosdenshion - 2 - COCOS2DX/CocosDenshion - - - extensions - 2 - COCOS2DX/extensions - - - scripting - 2 - COCOS2DX/scripting - - - diff --git a/samples/Cpp/AssetsManagerTest/proj.android/.settings/org.eclipse.cdt.codan.core.prefs b/samples/Cpp/AssetsManagerTest/proj.android/.settings/org.eclipse.cdt.codan.core.prefs deleted file mode 100644 index bad4196993..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/.settings/org.eclipse.cdt.codan.core.prefs +++ /dev/null @@ -1,68 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.cdt.codan.checkers.errnoreturn=-Warning -org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.checkers.errreturnvalue=-Error -org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.checkers.noreturn=-Error -org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=-Error -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},no_break_comment\=>"no break",last_case_param\=>true,empty_case_param\=>false} -org.eclipse.cdt.codan.internal.checkers.CatchByReference=-Warning -org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},unknown\=>false,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=-Error -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=-Warning -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},skip\=>true} -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidArguments=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.OverloadProblem=-Error -org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},paramNot\=>false} -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},else\=>false,afterelse\=>false} -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>("@(\#)","$Id")} -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -useParentScope=false diff --git a/samples/Cpp/AssetsManagerTest/proj.android/AndroidManifest.xml b/samples/Cpp/AssetsManagerTest/proj.android/AndroidManifest.xml deleted file mode 100644 index b6b69e4442..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/AndroidManifest.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Cpp/AssetsManagerTest/proj.android/build.xml b/samples/Cpp/AssetsManagerTest/proj.android/build.xml deleted file mode 100644 index 94460967a5..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/build.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk b/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk deleted file mode 100644 index 28588e400a..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/jni/Android.mk +++ /dev/null @@ -1,30 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := game_shared - -LOCAL_MODULE_FILENAME := libgame - -LOCAL_SRC_FILES := hellocpp/main.cpp \ - ../../Classes/AppDelegate.cpp - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes - -LOCAL_WHOLE_STATIC_LIBRARIES := cocos_jsb_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_chipmunk_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_extension_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_localstorage_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_network_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_builder_static - -LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT - -include $(BUILD_SHARED_LIBRARY) - -$(call import-module,scripting/javascript/bindings) -$(call import-module,scripting/javascript/bindings/chipmunk) -$(call import-module,scripting/javascript/bindings/extension) -$(call import-module,scripting/javascript/bindings/localstorage) -$(call import-module,scripting/javascript/bindings/network) -$(call import-module,scripting/javascript/bindings/cocosbuilder) diff --git a/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk b/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk deleted file mode 100644 index 74af9626ab..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/jni/Application.mk +++ /dev/null @@ -1,5 +0,0 @@ -APP_STL := gnustl_static - -# add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] -# in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Cpp/AssetsManagerTest/proj.android/jni/hellocpp/main.cpp b/samples/Cpp/AssetsManagerTest/proj.android/jni/hellocpp/main.cpp deleted file mode 100644 index 0d0564246f..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/jni/hellocpp/main.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include "AppDelegate.h" -#include "platform/android/jni/JniHelper.h" -#include -#include - -#define LOG_TAG "main" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) - -using namespace cocos2d; - -void cocos_android_app_init (struct android_app* app) { - LOGD("cocos_android_app_init"); - AppDelegate *pAppDelegate = new AppDelegate(); -} diff --git a/samples/Cpp/AssetsManagerTest/proj.android/project.properties b/samples/Cpp/AssetsManagerTest/proj.android/project.properties deleted file mode 100644 index f7e62936d0..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/project.properties +++ /dev/null @@ -1,15 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system edit -# "ant.properties", and override values to adapt the script to your -# project structure. -# -# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): -#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt - -# Project target. -target=android-10 -android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Cpp/AssetsManagerTest/proj.android/res/values/strings.xml b/samples/Cpp/AssetsManagerTest/proj.android/res/values/strings.xml deleted file mode 100644 index 99a292d37c..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/res/values/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - AssetsManager - diff --git a/samples/Cpp/AssetsManagerTest/proj.android/src/org/cocos2dx/AssetsManagerTest/Cocos2dxActivity.java b/samples/Cpp/AssetsManagerTest/proj.android/src/org/cocos2dx/AssetsManagerTest/Cocos2dxActivity.java deleted file mode 100644 index c30457e9fb..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.android/src/org/cocos2dx/AssetsManagerTest/Cocos2dxActivity.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.cocos2dx.AssetsManagerTest; - -import android.app.NativeActivity; -import android.graphics.PixelFormat; -import android.os.Bundle; - -public class Cocos2dxActivity extends NativeActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - //For supports translucency - - //1.change "attribs" in cocos\2d\platform\android\nativeactivity.cpp - /*const EGLint attribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - //EGL_BLUE_SIZE, 5, -->delete - //EGL_GREEN_SIZE, 6, -->delete - //EGL_RED_SIZE, 5, -->delete - EGL_BUFFER_SIZE, 32, //-->new field - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - };*/ - - //2.Set the format of window - // getWindow().setFormat(PixelFormat.TRANSLUCENT); - - } -} diff --git a/samples/Cpp/AssetsManagerTest/proj.ios/AppController.h b/samples/Cpp/AssetsManagerTest/proj.ios/AppController.h deleted file mode 100644 index 0979818386..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.ios/AppController.h +++ /dev/null @@ -1,20 +0,0 @@ -// -// AssetsManagerTestAppController.h -// AssetsManagerTest -// -// Created by minggo on 2/5/13. -// Copyright __MyCompanyName__ 2013. All rights reserved. -// - -@class RootViewController; - -@interface AppController : NSObject { - UIWindow *window; - RootViewController *viewController; -} - -@property (nonatomic, retain) UIWindow *window; -@property (nonatomic, retain) RootViewController *viewController; - -@end - diff --git a/samples/Cpp/AssetsManagerTest/proj.ios/AppController.mm b/samples/Cpp/AssetsManagerTest/proj.ios/AppController.mm deleted file mode 100644 index e009328669..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.ios/AppController.mm +++ /dev/null @@ -1,122 +0,0 @@ -// -// AssetsManagerTestAppController.mm -// AssetsManagerTest -// -// Created by minggo on 2/5/13. -// Copyright __MyCompanyName__ 2013. All rights reserved. -// -#import -#import "AppController.h" -#import "cocos2d.h" -#import "EAGLView.h" -#import "AppDelegate.h" - -#import "RootViewController.h" - -@implementation AppController - -@synthesize window; -@synthesize viewController; - -#pragma mark - -#pragma mark Application lifecycle - -// cocos2d application instance -static AppDelegate s_sharedApplication; - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - - // Override point for customization after application launch. - - // Add the view controller's view to the window and display. - window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; - CCEAGLView *__glView = [CCEAGLView viewWithFrame: [window bounds] - pixelFormat: kEAGLColorFormatRGBA8 - depthFormat: GL_DEPTH_COMPONENT16 - preserveBackbuffer: NO - sharegroup: nil - multiSampling: NO - numberOfSamples:0 ]; - - // Use RootViewController manage CCEAGLView - viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; - viewController.wantsFullScreenLayout = YES; - viewController.view = __glView; - - // Set RootViewController to window - if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) - { - // warning: addSubView doesn't work on iOS6 - [window addSubview: viewController.view]; - } - else - { - // use this method on ios6 - [window setRootViewController:viewController]; - } - - [window makeKeyAndVisible]; - - [[UIApplication sharedApplication] setStatusBarHidden: YES]; - - cocos2d::Application::getInstance()->run(); - return YES; -} - - -- (void)applicationWillResignActive:(UIApplication *)application { - /* - Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. - */ - cocos2d::Director::getInstance()->pause(); -} - -- (void)applicationDidBecomeActive:(UIApplication *)application { - /* - Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - */ - cocos2d::Director::getInstance()->resume(); -} - -- (void)applicationDidEnterBackground:(UIApplication *)application { - /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - If your application supports background execution, called instead of applicationWillTerminate: when the user quits. - */ - cocos2d::Application::getInstance()->applicationDidEnterBackground(); -} - -- (void)applicationWillEnterForeground:(UIApplication *)application { - /* - Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. - */ - cocos2d::Application::getInstance()->applicationWillEnterForeground(); -} - -- (void)applicationWillTerminate:(UIApplication *)application { - /* - Called when the application is about to terminate. - See also applicationDidEnterBackground:. - */ -} - - -#pragma mark - -#pragma mark Memory management - -- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { - /* - Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. - */ - cocos2d::Director::getInstance()->purgeCachedData(); -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end - diff --git a/samples/Cpp/AssetsManagerTest/proj.ios/Prefix.pch b/samples/Cpp/AssetsManagerTest/proj.ios/Prefix.pch deleted file mode 100644 index 5d8be4921e..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.ios/Prefix.pch +++ /dev/null @@ -1,8 +0,0 @@ -// -// Prefix header for all source files of the 'AssetsManagerTest' target in the 'AssetsManagerTest' project -// - -#ifdef __OBJC__ - #import - #import -#endif diff --git a/samples/Cpp/AssetsManagerTest/proj.ios/RootViewController.h b/samples/Cpp/AssetsManagerTest/proj.ios/RootViewController.h deleted file mode 100644 index 17d8b1ca23..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.ios/RootViewController.h +++ /dev/null @@ -1,16 +0,0 @@ -// -// AssetsManagerTestAppController.h -// AssetsManagerTest -// -// Created by minggo on 2/5/13. -// Copyright __MyCompanyName__ 2013. All rights reserved. -// - -#import - - -@interface RootViewController : UIViewController { - -} -- (BOOL)prefersStatusBarHidden; -@end diff --git a/samples/Cpp/AssetsManagerTest/proj.ios/RootViewController.mm b/samples/Cpp/AssetsManagerTest/proj.ios/RootViewController.mm deleted file mode 100644 index 779facc5b7..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.ios/RootViewController.mm +++ /dev/null @@ -1,79 +0,0 @@ -// -// AssetsManagerTestAppController.h -// AssetsManagerTest -// -// Created by minggo on 2/5/13. -// Copyright __MyCompanyName__ 2013. All rights reserved. -// - -#import "RootViewController.h" - - -@implementation RootViewController - -/* - // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { - if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { - // Custom initialization - } - return self; -} -*/ - -/* -// Implement loadView to create a view hierarchy programmatically, without using a nib. -- (void)loadView { -} -*/ - -/* -// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -- (void)viewDidLoad { - [super viewDidLoad]; -} - -*/ -// Override to allow orientations other than the default portrait orientation. -// This method is deprecated on ios6 -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { - return UIInterfaceOrientationIsLandscape( interfaceOrientation ); -} - -// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead -- (NSUInteger) supportedInterfaceOrientations{ -#ifdef __IPHONE_6_0 - return UIInterfaceOrientationMaskLandscape; -#endif -} - -- (BOOL) shouldAutorotate { - return YES; -} - -//fix not hide status on ios7 -- (BOOL)prefersStatusBarHidden -{ - return YES; -} - -- (void)didReceiveMemoryWarning { - // Releases the view if it doesn't have a superview. - [super didReceiveMemoryWarning]; - - // Release any cached data, images, etc that aren't in use. -} - -- (void)viewDidUnload { - [super viewDidUnload]; - // Release any retained subviews of the main view. - // e.g. self.myOutlet = nil; -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end diff --git a/samples/Cpp/AssetsManagerTest/proj.ios/iTunesArtwork b/samples/Cpp/AssetsManagerTest/proj.ios/iTunesArtwork deleted file mode 100644 index b1cc056ba5..0000000000 Binary files a/samples/Cpp/AssetsManagerTest/proj.ios/iTunesArtwork and /dev/null differ diff --git a/samples/Cpp/AssetsManagerTest/proj.ios/main.m b/samples/Cpp/AssetsManagerTest/proj.ios/main.m deleted file mode 100644 index 2f4612f6a2..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.ios/main.m +++ /dev/null @@ -1,17 +0,0 @@ -// -// main.m -// AssetsManagerTest -// -// Created by minggo on 2/5/13. -// Copyright __MyCompanyName__ 2013. All rights reserved. -// - -#import - -int main(int argc, char *argv[]) { - - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - int retVal = UIApplicationMain(argc, argv, nil, @"AppController"); - [pool release]; - return retVal; -} diff --git a/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj b/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj deleted file mode 100644 index 7851565229..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj +++ /dev/null @@ -1,217 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {6D37505F-A890-441D-BD3F-A61E2C0469CE} - AssetsManagerTest - - - - Application - Unicode - v100 - v110 - v110_xp - - - Application - Unicode - v100 - v110 - v110_xp - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.40219.1 - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - false - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - false - AllRules.ruleset - - - AllRules.ruleset - - - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - - _DEBUG;%(PreprocessorDefinitions) - false - Win32 - true - $(IntDir)res.tlb - res.h - - - res_i.c - res_p.c - - - Disabled - $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\audio\include;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;DEBUG;_DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - - - Level3 - EditAndContinue - 4267;4251;4244;%(DisableSpecificWarnings) - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - - - - mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;libcurl_imp.lib;%(AdditionalDependencies) - $(OutDir);%(AdditionalLibraryDirectories) - true - Windows - MachineX86 - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -if exist "$(OutDir)\AssetsManagerTestRes" rd /s /q "$(OutDir)\AssetsManagerTestRes" -mkdir "$(OutDir)\AssetsManagerTestRes" -xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\AssetsManagerTestRes\" /e /Y -xcopy "$(ProjectDir)..\Resources" "$(OutDir)\AssetsManagerTestRes\" /e /Y - - - Copy js and resource files. - - - - - NDEBUG;%(PreprocessorDefinitions) - false - Win32 - true - $(IntDir)res.tlb - res.h - - - res_i.c - res_p.c - - - $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\audio\include;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;NDEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - MultiThreadedDLL - - - Level3 - - - 4267;4251;4244;%(DisableSpecificWarnings) - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(EngineRoot)external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - - - - mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;libcurl_imp.lib;%(AdditionalDependencies) - $(OutDir);%(AdditionalLibraryDirectories) - Windows - MachineX86 - true - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -if exist "$(OutDir)\AssetsManagerTestRes" rd /s /q "$(OutDir)\AssetsManagerTestRes" -mkdir "$(OutDir)\AssetsManagerTestRes" -xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\AssetsManagerTestRes\" /e /Y -xcopy "$(ProjectDir)..\Resources" "$(OutDir)\AssetsManagerTestRes\" /e /Y - Copy js and resource files. - - - - - - - - - - - - - - - - - - - - {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - false - - - {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - - - {625f7391-9a91-48a1-8cfc-79508c822637} - - - {39379840-825a-45a0-b363-c09ffef864bd} - - - {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} - - - {21b2c324-891f-48ea-ad1a-5ae13de12e28} - - - {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} - - - - - - \ No newline at end of file diff --git a/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj.filters b/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj.filters deleted file mode 100644 index de7f9d6f3e..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj.filters +++ /dev/null @@ -1,44 +0,0 @@ - - - - - {ca9c9e15-d942-43a1-aa7a-5f0b74ca1afd} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;jpg;jpeg;jpe;png;manifest - - - {ccb2323b-1cfa-41ea-bcf4-ba5f07309396} - - - {e93a77e1-af1e-4400-87d3-504b62ebdbb0} - - - - - win32 - - - Classes - - - - - win32 - - - Classes - - - win32 - - - - - resource - - - - - resource - - - \ No newline at end of file diff --git a/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj.user b/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj.user deleted file mode 100644 index 806c7a2dd6..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.win32/AssetsManagerTest.vcxproj.user +++ /dev/null @@ -1,11 +0,0 @@ - - - - $(OutDir)\AssetsManagerTestRes - WindowsLocalDebugger - - - $(OutDir)\AssetsManagerTestRes - WindowsLocalDebugger - - \ No newline at end of file diff --git a/samples/Cpp/AssetsManagerTest/proj.win32/main.cpp b/samples/Cpp/AssetsManagerTest/proj.win32/main.cpp deleted file mode 100644 index 48e2af43a1..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.win32/main.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "main.h" -#include "AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -// uncomment below line, open debug console -// #define USE_WIN32_CONSOLE - -int APIENTRY _tWinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - UNREFERENCED_PARAMETER(hPrevInstance); - UNREFERENCED_PARAMETER(lpCmdLine); - -#ifdef USE_WIN32_CONSOLE - AllocConsole(); - freopen("CONIN$", "r", stdin); - freopen("CONOUT$", "w", stdout); - freopen("CONOUT$", "w", stderr); -#endif - - // create the application instance - AppDelegate app; - EGLView eglView; - eglView.init("AssetsManagerTest",900,640); - - int ret = Application::getInstance()->run(); - -#ifdef USE_WIN32_CONSOLE - FreeConsole(); -#endif - - return ret; -} diff --git a/samples/Cpp/AssetsManagerTest/proj.win32/res.rc b/samples/Cpp/AssetsManagerTest/proj.win32/res.rc deleted file mode 100644 index 8bb32cb5e8..0000000000 --- a/samples/Cpp/AssetsManagerTest/proj.win32/res.rc +++ /dev/null @@ -1,86 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#define APSTUDIO_HIDDEN_SYMBOLS -#include "windows.h" -#undef APSTUDIO_HIDDEN_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -#endif // APSTUDIO_INVOKED - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDR_MAINFRAME ICON "res\\res.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "CompanyName", "\0" - VALUE "FileDescription", "res Module\0" - VALUE "FileVersion", "1, 0, 0, 1\0" - VALUE "InternalName", "res\0" - VALUE "LegalCopyright", "Copyright \0" - VALUE "OriginalFilename", "AssetsManagerTest.exe\0" - VALUE "ProductName", "AssetsManagerTest Module\0" - VALUE "ProductVersion", "1, 0, 0, 1\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 0x04B0 - END -END - -///////////////////////////////////////////////////////////////////////////// -#endif // !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) diff --git a/samples/Cpp/AssetsManagerTest/proj.win32/res/res.ico b/samples/Cpp/AssetsManagerTest/proj.win32/res/res.ico deleted file mode 100644 index feaf932a74..0000000000 Binary files a/samples/Cpp/AssetsManagerTest/proj.win32/res/res.ico and /dev/null differ diff --git a/samples/Cpp/HelloCpp/CMakeLists.txt b/samples/Cpp/HelloCpp/CMakeLists.txt deleted file mode 100644 index 861118b09b..0000000000 --- a/samples/Cpp/HelloCpp/CMakeLists.txt +++ /dev/null @@ -1,75 +0,0 @@ -set(APP_NAME hellocpp) - -if(QT) - set(PLATFORM_SRC - proj.qt/main.cpp - ) -elseif(ANDROID) - set(PLATFORM_SRC - proj.android/jni/hellocpp/main.cpp - ) -elseif(WIN32) - set(PLATFORM_SRC - proj.win32/main.cpp - ) -elseif(APPLE) - if(IOS) - set(PLATFORM_SRC - proj.ios/main.m - proj.ios/AppController.mm - proj.ios/RootViewController.mm - ) - else() - set(PLATFORM_SRC - proj.mac/main.m - ) - endif() -else() - set(PLATFORM_SRC - proj.linux/main.cpp - ) - endif() - -set(SAMPLE_SRC - ${PLATFORM_SRC} - Classes/AppDelegate.cpp - Classes/HelloWorldScene.cpp -) - -# add the executable -add_executable(${APP_NAME} - ${SAMPLE_SRC} -) - -if(WIN32 AND MSVC) - #get our resources - add_custom_command(TARGET ${APP_NAME} PRE_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_directory - ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${CMAKE_CURRENT_BINARY_DIR}) - #get our dlls - add_custom_command(TARGET ${APP_NAME} PRE_BUILD - COMMAND ${CMAKE_COMMAND} -E copy - ${CMAKE_CURRENT_SOURCE_DIR}/../../../external/win32-specific/gles/prebuilt/glew32.dll - ${CMAKE_CURRENT_BINARY_DIR}) - - add_custom_command(TARGET ${APP_NAME} PRE_BUILD - COMMAND ${CMAKE_COMMAND} -E copy - ${CMAKE_CURRENT_SOURCE_DIR}/../../../external/win32-specific/zlib/prebuilt/zlib1.dll - ${CMAKE_CURRENT_BINARY_DIR}/Debug) - - #Visual Studio Defaults to wrong type - set_target_properties(${APP_NAME} PROPERTIES LINK_FLAGS_DEBUG "/SUBSYSTEM:WINDOWS") - set_target_properties(${APP_NAME} PROPERTIES LINK_FLAGS_RELEASE "/SUBSYSTEM:WINDOWS") -else() - set(APP_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${APP_NAME}") - - set_target_properties(${APP_NAME} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") - - pre_build(${APP_NAME} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources - COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources - ) -endif() - -target_link_libraries(${APP_NAME} audio cocos2d) diff --git a/samples/Cpp/HelloCpp/Classes/AppDelegate.cpp b/samples/Cpp/HelloCpp/Classes/AppDelegate.cpp deleted file mode 100644 index 97fb7366c3..0000000000 --- a/samples/Cpp/HelloCpp/Classes/AppDelegate.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include "AppDelegate.h" - -#include -#include - -#include "HelloWorldScene.h" -#include "AppMacros.h" - -USING_NS_CC; -using namespace std; - -AppDelegate::AppDelegate() { - -} - -AppDelegate::~AppDelegate() -{ -} - -bool AppDelegate::applicationDidFinishLaunching() { - // initialize director - auto director = Director::getInstance(); - auto glView = EGLView::getInstance(); - - director->setOpenGLView(glView); - - // Set the design resolution - glView->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER); - - Size frameSize = glView->getFrameSize(); - - vector searchPath; - - // In this demo, we select resource according to the frame's height. - // If the resource size is different from design resolution size, you need to set contentScaleFactor. - // We use the ratio of resource's height to the height of design resolution, - // this can make sure that the resource's height could fit for the height of design resolution. - - // if the frame's height is larger than the height of medium resource size, select large resource. - if (frameSize.height > mediumResource.size.height) - { - searchPath.push_back(largeResource.directory); - - director->setContentScaleFactor(MIN(largeResource.size.height/designResolutionSize.height, largeResource.size.width/designResolutionSize.width)); - } - // if the frame's height is larger than the height of small resource size, select medium resource. - else if (frameSize.height > smallResource.size.height) - { - searchPath.push_back(mediumResource.directory); - - director->setContentScaleFactor(MIN(mediumResource.size.height/designResolutionSize.height, mediumResource.size.width/designResolutionSize.width)); - } - // if the frame's height is smaller than the height of medium resource size, select small resource. - else - { - searchPath.push_back(smallResource.directory); - - director->setContentScaleFactor(MIN(smallResource.size.height/designResolutionSize.height, smallResource.size.width/designResolutionSize.width)); - } - - // set searching path - FileUtils::getInstance()->setSearchPaths(searchPath); - - // turn on display FPS - director->setDisplayStats(true); - - // set FPS. the default value is 1.0/60 if you don't call this - director->setAnimationInterval(1.0 / 60); - - // create a scene. it's an autorelease object - auto scene = HelloWorld::scene(); - - // run - director->runWithScene(scene); - - return true; -} - -// This function will be called when the app is inactive. When comes a phone call,it's be invoked too -void AppDelegate::applicationDidEnterBackground() { - Director::getInstance()->stopAnimation(); - - // if you use SimpleAudioEngine, it must be pause - // SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); -} - -// this function will be called when the app is active again -void AppDelegate::applicationWillEnterForeground() { - Director::getInstance()->startAnimation(); - - // if you use SimpleAudioEngine, it must resume here - // SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); -} diff --git a/samples/Cpp/HelloCpp/Classes/AppDelegate.h b/samples/Cpp/HelloCpp/Classes/AppDelegate.h deleted file mode 100644 index 18ee8aeb63..0000000000 --- a/samples/Cpp/HelloCpp/Classes/AppDelegate.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef _APP_DELEGATE_H_ -#define _APP_DELEGATE_H_ - -#include "cocos2d.h" - -/** -@brief The cocos2d Application. - -The reason for implement as private inheritance is to hide some interface call by Director. -*/ -class AppDelegate : private cocos2d::Application -{ -public: - AppDelegate(); - virtual ~AppDelegate(); - - /** - @brief Implement Director and Scene init code here. - @return true Initialize success, app continue. - @return false Initialize failed, app terminate. - */ - virtual bool applicationDidFinishLaunching(); - - /** - @brief The function be called when the application enter background - @param the pointer of the application - */ - virtual void applicationDidEnterBackground(); - - /** - @brief The function be called when the application enter foreground - @param the pointer of the application - */ - virtual void applicationWillEnterForeground(); -}; - -#endif // _APP_DELEGATE_H_ - diff --git a/samples/Cpp/HelloCpp/Classes/AppMacros.h b/samples/Cpp/HelloCpp/Classes/AppMacros.h deleted file mode 100644 index 6e6aa0ea2e..0000000000 --- a/samples/Cpp/HelloCpp/Classes/AppMacros.h +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef __APPMACROS_H__ -#define __APPMACROS_H__ - -#include "cocos2d.h" - -/* For demonstrating using one design resolution to match different resources, - or one resource to match different design resolutions. - - [Situation 1] Using one design resolution to match different resources. - Please look into Appdelegate::applicationDidFinishLaunching. - We check current device frame size to decide which resource need to be selected. - So if you want to test this situation which said in title '[Situation 1]', - you should change ios simulator to different device(e.g. iphone, iphone-retina3.5, iphone-retina4.0, ipad, ipad-retina), - or change the window size in "proj.XXX/main.cpp" by "CCEGLView::setFrameSize" if you are using win32 or linux plaform - and modify "proj.mac/AppController.mm" by changing the window rectangle. - - [Situation 2] Using one resource to match different design resolutions. - The coordinates in your codes is based on your current design resolution rather than resource size. - Therefore, your design resolution could be very large and your resource size could be small. - To test this, just define the marco 'TARGET_DESIGN_RESOLUTION_SIZE' to 'DESIGN_RESOLUTION_2048X1536' - and open iphone simulator or create a window of 480x320 size. - - [Note] Normally, developer just need to define one design resolution(e.g. 960x640) with one or more resources. - */ - -#define DESIGN_RESOLUTION_480X320 0 -#define DESIGN_RESOLUTION_1024X768 1 -#define DESIGN_RESOLUTION_2048X1536 2 - -/* If you want to switch design resolution, change next line */ -#define TARGET_DESIGN_RESOLUTION_SIZE DESIGN_RESOLUTION_480X320 - -typedef struct tagResource -{ - cocos2d::Size size; - char directory[100]; -}Resource; - -static Resource smallResource = { cocos2d::Size(480, 320), "iphone" }; -static Resource mediumResource = { cocos2d::Size(1024, 768), "ipad" }; -static Resource largeResource = { cocos2d::Size(2048, 1536), "ipadhd" }; - -#if (TARGET_DESIGN_RESOLUTION_SIZE == DESIGN_RESOLUTION_480X320) -static cocos2d::Size designResolutionSize = cocos2d::Size(480, 320); -#elif (TARGET_DESIGN_RESOLUTION_SIZE == DESIGN_RESOLUTION_1024X768) -static cocos2d::Size designResolutionSize = cocos2d::Size(1024, 768); -#elif (TARGET_DESIGN_RESOLUTION_SIZE == DESIGN_RESOLUTION_2048X1536) -static cocos2d::Size designResolutionSize = cocos2d::Size(2048, 1536); -#else -#error unknown target design resolution! -#endif - -// The font size 24 is designed for small resolution, so we should change it to fit for current design resolution -#define TITLE_FONT_SIZE (cocos2d::EGLView::getInstance()->getDesignResolutionSize().width / smallResource.size.width * 24) - -#endif /* __APPMACROS_H__ */ diff --git a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp b/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp deleted file mode 100644 index 077a92aa11..0000000000 --- a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.cpp +++ /dev/null @@ -1,88 +0,0 @@ -#include "HelloWorldScene.h" -#include "AppMacros.h" - -#include "CCEventListenerTouch.h" - -USING_NS_CC; - - -Scene* HelloWorld::scene() -{ - // 'scene' is an autorelease object - auto scene = Scene::create(); - - // 'layer' is an autorelease object - HelloWorld *layer = HelloWorld::create(); - - // add layer as a child to scene - scene->addChild(layer); - - // return the scene - return scene; -} - -// on "init" you need to initialize your instance -bool HelloWorld::init() -{ - ////////////////////////////// - // 1. super init first - if ( !Layer::init() ) - { - return false; - } - - auto visibleSize = Director::getInstance()->getVisibleSize(); - auto origin = Director::getInstance()->getVisibleOrigin(); - - ///////////////////////////// - // 2. add a menu item with "X" image, which is clicked to quit the program - // you may modify it. - - // add a "close" icon to exit the progress. it's an autorelease object - auto closeItem = MenuItemImage::create( - "CloseNormal.png", - "CloseSelected.png", - CC_CALLBACK_1(HelloWorld::menuCloseCallback,this)); - - closeItem->setPosition(origin + Point(visibleSize) - Point(closeItem->getContentSize() / 2)); - - // create menu, it's an autorelease object - auto menu = Menu::create(closeItem, NULL); - menu->setPosition(Point::ZERO); - this->addChild(menu, 1); - - ///////////////////////////// - // 3. add your codes below... - - // add a label shows "Hello World" - // create and initialize a label - - auto label = LabelTTF::create("Hello World", "Arial", TITLE_FONT_SIZE); - - // position the label on the center of the screen - label->setPosition(Point(origin.x + visibleSize.width/2, - origin.y + visibleSize.height - label->getContentSize().height)); - - // add the label as a child to this layer - this->addChild(label, 1); - - // add "HelloWorld" splash screen" - auto sprite = Sprite::create("HelloWorld.png"); - - // position the sprite on the center of the screen - sprite->setPosition(Point(visibleSize / 2) + origin); - - // add the sprite as a child to this layer - this->addChild(sprite); - - return true; -} - -void HelloWorld::menuCloseCallback(Object* sender) -{ - Director::getInstance()->end(); - -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) - exit(0); -#endif -} diff --git a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.h b/samples/Cpp/HelloCpp/Classes/HelloWorldScene.h deleted file mode 100644 index 876073cdb5..0000000000 --- a/samples/Cpp/HelloCpp/Classes/HelloWorldScene.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef __HELLOWORLD_SCENE_H__ -#define __HELLOWORLD_SCENE_H__ - -#include "cocos2d.h" - -class HelloWorld : public cocos2d::Layer -{ -public: - // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone - virtual bool init(); - - // there's no 'id' in cpp, so we recommend returning the class instance pointer - static cocos2d::Scene* scene(); - - // a selector callback - void menuCloseCallback(Object* sender); - - // implement the "static node()" method manually - CREATE_FUNC(HelloWorld); -}; - -#endif // __HELLOWORLD_SCENE_H__ diff --git a/samples/Cpp/HelloCpp/Resources/ipad/HelloWorld.png.REMOVED.git-id b/samples/Cpp/HelloCpp/Resources/ipad/HelloWorld.png.REMOVED.git-id deleted file mode 100644 index fda9923fa3..0000000000 --- a/samples/Cpp/HelloCpp/Resources/ipad/HelloWorld.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -709d78b7f3eab27056a98d63e9153b35d57b84bc \ No newline at end of file diff --git a/samples/Cpp/HelloCpp/Resources/ipadhd/HelloWorld.png.REMOVED.git-id b/samples/Cpp/HelloCpp/Resources/ipadhd/HelloWorld.png.REMOVED.git-id deleted file mode 100644 index 45e6087f95..0000000000 --- a/samples/Cpp/HelloCpp/Resources/ipadhd/HelloWorld.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -7aa1e9dc799acf384a1c4603054242cc09c1b63e \ No newline at end of file diff --git a/samples/Cpp/HelloCpp/Resources/iphone/HelloWorld.png.REMOVED.git-id b/samples/Cpp/HelloCpp/Resources/iphone/HelloWorld.png.REMOVED.git-id deleted file mode 100644 index d391882e7d..0000000000 --- a/samples/Cpp/HelloCpp/Resources/iphone/HelloWorld.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -9d6facb31897d010352e7b57f4a82715c260408a \ No newline at end of file diff --git a/samples/Cpp/HelloCpp/proj.android/.settings/org.eclipse.cdt.codan.core.prefs b/samples/Cpp/HelloCpp/proj.android/.settings/org.eclipse.cdt.codan.core.prefs deleted file mode 100644 index bad4196993..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/.settings/org.eclipse.cdt.codan.core.prefs +++ /dev/null @@ -1,68 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.cdt.codan.checkers.errnoreturn=-Warning -org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.checkers.errreturnvalue=-Error -org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.checkers.noreturn=-Error -org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=-Error -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},no_break_comment\=>"no break",last_case_param\=>true,empty_case_param\=>false} -org.eclipse.cdt.codan.internal.checkers.CatchByReference=-Warning -org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},unknown\=>false,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=-Error -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=-Warning -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},skip\=>true} -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidArguments=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.OverloadProblem=-Error -org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},paramNot\=>false} -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},else\=>false,afterelse\=>false} -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>("@(\#)","$Id")} -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -useParentScope=false diff --git a/samples/Cpp/HelloCpp/proj.android/AndroidManifest.xml b/samples/Cpp/HelloCpp/proj.android/AndroidManifest.xml deleted file mode 100644 index ae64f07a84..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/AndroidManifest.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Cpp/HelloCpp/proj.android/build.xml b/samples/Cpp/HelloCpp/proj.android/build.xml deleted file mode 100644 index e225e378da..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/build.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Cpp/HelloCpp/proj.android/jni/Android.mk b/samples/Cpp/HelloCpp/proj.android/jni/Android.mk deleted file mode 100644 index cfd4cb14b5..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/jni/Android.mk +++ /dev/null @@ -1,20 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := hellocpp_shared - -LOCAL_MODULE_FILENAME := libhellocpp - -LOCAL_SRC_FILES := hellocpp/main.cpp \ - ../../Classes/AppDelegate.cpp \ - ../../Classes/HelloWorldScene.cpp - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes - -LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocosdenshion_static - -include $(BUILD_SHARED_LIBRARY) - -$(call import-module,2d) -$(call import-module,audio/android) diff --git a/samples/Cpp/HelloCpp/proj.android/jni/Application.mk b/samples/Cpp/HelloCpp/proj.android/jni/Application.mk deleted file mode 100644 index 74af9626ab..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/jni/Application.mk +++ /dev/null @@ -1,5 +0,0 @@ -APP_STL := gnustl_static - -# add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] -# in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Cpp/HelloCpp/proj.android/jni/hellocpp/main.cpp b/samples/Cpp/HelloCpp/proj.android/jni/hellocpp/main.cpp deleted file mode 100644 index 2b344d9e04..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/jni/hellocpp/main.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "AppDelegate.h" -#include "platform/android/jni/JniHelper.h" -#include -#include - -#include "cocos2d.h" - -#define LOG_TAG "main" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) - -using namespace cocos2d; - -void cocos_android_app_init (struct android_app* app) { - LOGD("cocos_android_app_init"); - AppDelegate *pAppDelegate = new AppDelegate(); -} diff --git a/samples/Cpp/HelloCpp/proj.android/jni/list.sh b/samples/Cpp/HelloCpp/proj.android/jni/list.sh deleted file mode 100755 index b29f678cb8..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/jni/list.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash - -append_str=' \' - -list_alldir() -{ - for file in $1/* - do - if [ -f $file ]; then - echo $file$append_str | grep .cpp - fi - - if [ -d $file ]; then - list_alldir $file - fi - done -} - -if [ $# -gt 0 ]; then - list_alldir "$1" -else - list_alldir "." -fi diff --git a/samples/Cpp/HelloCpp/proj.android/ndkgdb.sh b/samples/Cpp/HelloCpp/proj.android/ndkgdb.sh deleted file mode 100755 index de49075f36..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/ndkgdb.sh +++ /dev/null @@ -1,47 +0,0 @@ -APPNAME="HelloCpp" -APP_ANDROID_NAME="org.cocos2dx.hellocpp" - -if [ -z "${SDK_ROOT+aaa}" ]; then -# ... if SDK_ROOT is not set, use "$HOME/bin/android-sdk" - SDK_ROOT="$HOME/bin/android-sdk" -fi - -if [ -z "${NDK_ROOT+aaa}" ]; then -# ... if NDK_ROOT is not set, use "$HOME/bin/android-ndk" - NDK_ROOT="$HOME/bin/android-ndk" -fi - -if [ -z "${COCOS2DX_ROOT+aaa}" ]; then -# ... if COCOS2DX_ROOT is not set -# ... find current working directory - DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory - COCOS2DX_ROOT="$DIR/../../../.." - APP_ROOT="$DIR/.." - APP_ANDROID_ROOT="$DIR" -else - APP_ROOT="$COCOS2DX_ROOT/samples/$APPNAME" - APP_ANDROID_ROOT="$COCOS2DX_ROOT/samples/$APPNAME/proj.android" -fi - -echo "NDK_ROOT = $NDK_ROOT" -echo "SDK_ROOT = $SDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" -echo "APP_ANDROID_NAME = $APP_ANDROID_NAME" - -echo -echo "Killing and restarting ${APP_ANDROID_NAME}" -echo - -set -x - -"${SDK_ROOT}"/platform-tools/adb shell am force-stop "${APP_ANDROID_NAME}" - -NDK_MODULE_PATH="${COCOS2DX_ROOT}":"${COCOS2DX_ROOT}"/cocos2dx/platform/third_party/android/prebuilt \ - "${NDK_ROOT}"/ndk-gdb \ - --adb="${SDK_ROOT}"/platform-tools/adb \ - --verbose \ - --start \ - --force diff --git a/samples/Cpp/HelloCpp/proj.android/res/values/strings.xml b/samples/Cpp/HelloCpp/proj.android/res/values/strings.xml deleted file mode 100644 index d70da2da7a..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/res/values/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - HelloCpp - diff --git a/samples/Cpp/HelloCpp/proj.android/src/org/cocos2dx/hellocpp/Cocos2dxActivity.java b/samples/Cpp/HelloCpp/proj.android/src/org/cocos2dx/hellocpp/Cocos2dxActivity.java deleted file mode 100644 index ed4f339cee..0000000000 --- a/samples/Cpp/HelloCpp/proj.android/src/org/cocos2dx/hellocpp/Cocos2dxActivity.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.cocos2dx.hellocpp; - -import android.app.NativeActivity; -import android.os.Bundle; - -public class Cocos2dxActivity extends NativeActivity{ - - @Override - protected void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - //For supports translucency - - //1.change "attribs" in cocos\2d\platform\android\nativeactivity.cpp - /*const EGLint attribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - //EGL_BLUE_SIZE, 5, -->delete - //EGL_GREEN_SIZE, 6, -->delete - //EGL_RED_SIZE, 5, -->delete - EGL_BUFFER_SIZE, 32, //-->new field - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - };*/ - - //2.Set the format of window - // getWindow().setFormat(PixelFormat.TRANSLUCENT); - - } -} diff --git a/samples/Cpp/HelloCpp/proj.ios/AppController.mm b/samples/Cpp/HelloCpp/proj.ios/AppController.mm deleted file mode 100644 index 5e2010ba4c..0000000000 --- a/samples/Cpp/HelloCpp/proj.ios/AppController.mm +++ /dev/null @@ -1,134 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010 cocos2d-x.org - - 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. - ****************************************************************************/ -#import -#import "AppController.h" -#import "cocos2d.h" -#import "EAGLView.h" -#import "AppDelegate.h" - -#import "RootViewController.h" - -@implementation AppController - -#pragma mark - -#pragma mark Application lifecycle - -// cocos2d application instance -static AppDelegate s_sharedApplication; - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - - // Override point for customization after application launch. - - // Add the view controller's view to the window and display. - window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; - CCEAGLView *__glView = [CCEAGLView viewWithFrame: [window bounds] - pixelFormat: kEAGLColorFormatRGBA8 - depthFormat: GL_DEPTH_COMPONENT16 - preserveBackbuffer: NO - sharegroup:nil - multiSampling:NO - numberOfSamples:0]; - - // Use RootViewController manage CCEAGLView - viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; - viewController.wantsFullScreenLayout = YES; - viewController.view = __glView; - - // Set RootViewController to window - if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) - { - // warning: addSubView doesn't work on iOS6 - [window addSubview: viewController.view]; - } - else - { - // use this method on ios6 - [window setRootViewController:viewController]; - } - - [window makeKeyAndVisible]; - - [[UIApplication sharedApplication] setStatusBarHidden: YES]; - - cocos2d::Application::getInstance()->run(); - return YES; -} - - -- (void)applicationWillResignActive:(UIApplication *)application { - /* - Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. - */ - cocos2d::Director::getInstance()->pause(); -} - -- (void)applicationDidBecomeActive:(UIApplication *)application { - /* - Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - */ - cocos2d::Director::getInstance()->resume(); -} - -- (void)applicationDidEnterBackground:(UIApplication *)application { - /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - If your application supports background execution, called instead of applicationWillTerminate: when the user quits. - */ - cocos2d::Application::getInstance()->applicationDidEnterBackground(); -} - -- (void)applicationWillEnterForeground:(UIApplication *)application { - /* - Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. - */ - cocos2d::Application::getInstance()->applicationWillEnterForeground(); -} - -- (void)applicationWillTerminate:(UIApplication *)application { - /* - Called when the application is about to terminate. - See also applicationDidEnterBackground:. - */ -} - - -#pragma mark - -#pragma mark Memory management - -- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { - /* - Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. - */ -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end - diff --git a/samples/Cpp/HelloCpp/proj.ios/HelloCpp_Prefix.pch b/samples/Cpp/HelloCpp/proj.ios/HelloCpp_Prefix.pch deleted file mode 100644 index b8914281d2..0000000000 --- a/samples/Cpp/HelloCpp/proj.ios/HelloCpp_Prefix.pch +++ /dev/null @@ -1,8 +0,0 @@ -// -// Prefix header for all source files of the 'HelloWorld' target in the 'HelloWorld' project -// - -#ifdef __OBJC__ - #import - #import -#endif diff --git a/samples/Cpp/HelloCpp/proj.ios/RootViewController.mm b/samples/Cpp/HelloCpp/proj.ios/RootViewController.mm deleted file mode 100644 index 4984955c8a..0000000000 --- a/samples/Cpp/HelloCpp/proj.ios/RootViewController.mm +++ /dev/null @@ -1,97 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2010 Ricardo Quesada - - 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. - ****************************************************************************/ - -#import "RootViewController.h" - - -@implementation RootViewController - -/* - // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { - if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { - // Custom initialization - } - return self; -} -*/ - -/* -// Implement loadView to create a view hierarchy programmatically, without using a nib. -- (void)loadView { -} -*/ - -/* -// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -- (void)viewDidLoad { - [super viewDidLoad]; -} - -*/ -// Override to allow orientations other than the default portrait orientation. -// This method is deprecated on ios6 -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { - return UIInterfaceOrientationIsLandscape( interfaceOrientation ); -} - -// For ios6.0 and higher, use supportedInterfaceOrientations & shouldAutorotate instead -- (NSUInteger) supportedInterfaceOrientations -{ -#ifdef __IPHONE_6_0 - return UIInterfaceOrientationMaskAllButUpsideDown; -#endif -} - -- (BOOL) shouldAutorotate { - return YES; -} - -//fix not hide status on ios7 -- (BOOL)prefersStatusBarHidden -{ - return YES; -} - -- (void)didReceiveMemoryWarning { - // Releases the view if it doesn't have a superview. - [super didReceiveMemoryWarning]; - - // Release any cached data, images, etc that aren't in use. -} - -- (void)viewDidUnload { - [super viewDidUnload]; - // Release any retained subviews of the main view. - // e.g. self.myOutlet = nil; -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end diff --git a/samples/Cpp/HelloCpp/proj.ios/main.m b/samples/Cpp/HelloCpp/proj.ios/main.m deleted file mode 100644 index bd577a036e..0000000000 --- a/samples/Cpp/HelloCpp/proj.ios/main.m +++ /dev/null @@ -1,17 +0,0 @@ -// -// main.m -// iphone -// -// Created by Walzer on 10-11-16. -// Copyright 2010 __MyCompanyName__. All rights reserved. -// - -#import - -int main(int argc, char *argv[]) { - - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - int retVal = UIApplicationMain(argc, argv, nil, @"AppController"); - [pool release]; - return retVal; -} diff --git a/samples/Cpp/HelloCpp/proj.mac/HelloCpp_Prefix.pch b/samples/Cpp/HelloCpp/proj.mac/HelloCpp_Prefix.pch deleted file mode 100644 index 46c36a7e99..0000000000 --- a/samples/Cpp/HelloCpp/proj.mac/HelloCpp_Prefix.pch +++ /dev/null @@ -1,7 +0,0 @@ -// -// Prefix header for all source files of the 'Paralaxer' target in the 'Paralaxer' project -// - -#ifdef __OBJC__ - #import -#endif diff --git a/samples/Cpp/HelloCpp/proj.mac/main.cpp b/samples/Cpp/HelloCpp/proj.mac/main.cpp deleted file mode 100644 index 19faf80e3b..0000000000 --- a/samples/Cpp/HelloCpp/proj.mac/main.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010 cocos2d-x.org - - 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 "AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -int main(int argc, char *argv[]) -{ - AppDelegate app; - EGLView eglView; - eglView.init("HelloCpp",900,640); - return Application::getInstance()->run(); -} - diff --git a/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj b/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj deleted file mode 100644 index 6da099a164..0000000000 --- a/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj +++ /dev/null @@ -1,147 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {B8BF9E81-35FD-4582-BA1C-B85FA365BABB} - HelloCppwin32 - Win32Proj - - - - Application - Unicode - true - v100 - v110 - v110_xp - - - Application - Unicode - v100 - v110 - v110_xp - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.40219.1 - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - true - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - false - AllRules.ruleset - - - AllRules.ruleset - - - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - - Disabled - ..\Classes;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_WINDOWS;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - - - Level3 - EditAndContinue - 4267;4251;4244;%(DisableSpecificWarnings) - - - $(OutDir)$(ProjectName).exe - $(OutDir);%(AdditionalLibraryDirectories) - true - Windows - MachineX86 - libcocos2d.lib;libchipmunk.lib;%(AdditionalDependencies) - - - - - - - - - MaxSpeed - true - ..\Classes;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - - - Level3 - ProgramDatabase - 4267;4251;4244;%(DisableSpecificWarnings) - - - libcocos2d.lib;%(AdditionalDependencies) - $(OutDir)$(ProjectName).exe - $(OutDir);%(AdditionalLibraryDirectories) - true - Windows - true - true - MachineX86 - - - - - - - - - - - - - - - - - - - - {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - false - - - {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} - - - - - - \ No newline at end of file diff --git a/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj.filters b/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj.filters deleted file mode 100644 index eb52c5e24c..0000000000 --- a/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj.filters +++ /dev/null @@ -1,38 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - - - Classes - - - Classes - - - win32 - - - - - Classes - - - Classes - - - win32 - - - Classes - - - \ No newline at end of file diff --git a/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj.user b/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj.user deleted file mode 100644 index 32a6296820..0000000000 --- a/samples/Cpp/HelloCpp/proj.win32/HelloCpp.vcxproj.user +++ /dev/null @@ -1,11 +0,0 @@ - - - - $(ProjectDir)..\Resources - WindowsLocalDebugger - - - $(ProjectDir)..\Resources - WindowsLocalDebugger - - \ No newline at end of file diff --git a/samples/Cpp/HelloCpp/proj.win32/main.cpp b/samples/Cpp/HelloCpp/proj.win32/main.cpp deleted file mode 100644 index bcc0e091d4..0000000000 --- a/samples/Cpp/HelloCpp/proj.win32/main.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "main.h" -#include "../Classes/AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -int APIENTRY _tWinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - UNREFERENCED_PARAMETER(hPrevInstance); - UNREFERENCED_PARAMETER(lpCmdLine); - - // create the application instance - AppDelegate app; - EGLView eglView; - eglView.init("HelloCpp",900,640); - return Application::getInstance()->run(); -} diff --git a/samples/Cpp/SimpleGame/Classes/AppDelegate.cpp b/samples/Cpp/SimpleGame/Classes/AppDelegate.cpp deleted file mode 100644 index 03b9b81ae4..0000000000 --- a/samples/Cpp/SimpleGame/Classes/AppDelegate.cpp +++ /dev/null @@ -1,70 +0,0 @@ -#include "AppDelegate.h" -#include "HelloWorldScene.h" - -USING_NS_CC; - - -AppDelegate::AppDelegate() { - -} - -AppDelegate::~AppDelegate() -{ -} - -bool AppDelegate::applicationDidFinishLaunching() { - // initialize director - auto director = Director::getInstance(); - - director->setOpenGLView(EGLView::getInstance()); - - auto screenSize = EGLView::getInstance()->getFrameSize(); - auto designSize = Size(480, 320); - std::vector searchPaths; - - if (screenSize.height > 320) - { - searchPaths.push_back("hd"); - searchPaths.push_back("sd"); - director->setContentScaleFactor(640.0f/designSize.height); - } - else - { - searchPaths.push_back("sd"); - director->setContentScaleFactor(320.0f/designSize.height); - } - - FileUtils::getInstance()->setSearchPaths(searchPaths); - - EGLView::getInstance()->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); - - // turn on display FPS - director->setDisplayStats(true); - - // set FPS. the default value is 1.0/60 if you don't call this - director->setAnimationInterval(1.0 / 60); - - // create a scene. it's an autorelease object - auto scene = HelloWorld::scene(); - - // run - director->runWithScene(scene); - - return true; -} - -// This function will be called when the app is inactive. When comes a phone call,it's be invoked too -void AppDelegate::applicationDidEnterBackground() { - Director::getInstance()->stopAnimation(); - - // if you use SimpleAudioEngine, it must be pause - // CocosDenshion::SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); -} - -// this function will be called when the app is active again -void AppDelegate::applicationWillEnterForeground() { - Director::getInstance()->startAnimation(); - - // if you use SimpleAudioEngine, it must resume here - // CocosDenshion::SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); -} diff --git a/samples/Cpp/SimpleGame/Classes/AppDelegate.h b/samples/Cpp/SimpleGame/Classes/AppDelegate.h deleted file mode 100644 index 18ee8aeb63..0000000000 --- a/samples/Cpp/SimpleGame/Classes/AppDelegate.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef _APP_DELEGATE_H_ -#define _APP_DELEGATE_H_ - -#include "cocos2d.h" - -/** -@brief The cocos2d Application. - -The reason for implement as private inheritance is to hide some interface call by Director. -*/ -class AppDelegate : private cocos2d::Application -{ -public: - AppDelegate(); - virtual ~AppDelegate(); - - /** - @brief Implement Director and Scene init code here. - @return true Initialize success, app continue. - @return false Initialize failed, app terminate. - */ - virtual bool applicationDidFinishLaunching(); - - /** - @brief The function be called when the application enter background - @param the pointer of the application - */ - virtual void applicationDidEnterBackground(); - - /** - @brief The function be called when the application enter foreground - @param the pointer of the application - */ - virtual void applicationWillEnterForeground(); -}; - -#endif // _APP_DELEGATE_H_ - diff --git a/samples/Cpp/SimpleGame/Classes/GameOverScene.cpp b/samples/Cpp/SimpleGame/Classes/GameOverScene.cpp deleted file mode 100644 index a7b72e8b3c..0000000000 --- a/samples/Cpp/SimpleGame/Classes/GameOverScene.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2010 Ray Wenderlich - - 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 "GameOverScene.h" -#include "HelloWorldScene.h" - -using namespace cocos2d; - -bool GameOverScene::init() -{ - if( Scene::init() ) - { - this->_layer = GameOverLayer::create(); - this->_layer->retain(); - this->addChild(_layer); - - return true; - } - else - { - return false; - } -} - -GameOverScene::~GameOverScene() -{ - if (_layer) - { - _layer->release(); - _layer = NULL; - } -} - - -bool GameOverLayer::init() -{ - if ( LayerColor::initWithColor( Color4B(255,255,255,255) ) ) - { - auto winSize = Director::getInstance()->getWinSize(); - this->_label = LabelTTF::create("","Artial", 32); - _label->retain(); - _label->setColor( Color3B(0, 0, 0) ); - _label->setPosition( Point(winSize.width/2, winSize.height/2) ); - this->addChild(_label); - - this->runAction( Sequence::create( - DelayTime::create(3), - CallFunc::create( CC_CALLBACK_0(GameOverLayer::gameOverDone, this)), - NULL)); - - return true; - } - else - { - return false; - } -} - -void GameOverLayer::gameOverDone() -{ - Director::getInstance()->replaceScene( HelloWorld::scene() ); -} - -GameOverLayer::~GameOverLayer() -{ - if (_label) - { - _label->release(); - _label = NULL; - } -} diff --git a/samples/Cpp/SimpleGame/Classes/GameOverScene.h b/samples/Cpp/SimpleGame/Classes/GameOverScene.h deleted file mode 100644 index 1bbf1907e1..0000000000 --- a/samples/Cpp/SimpleGame/Classes/GameOverScene.h +++ /dev/null @@ -1,55 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2010 Ray Wenderlich - - 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 _GAME_OVER_SCENE_H_ -#define _GAME_OVER_SCENE_H_ - -#include "cocos2d.h" - -class GameOverLayer : public cocos2d::LayerColor -{ -public: - GameOverLayer():_label(NULL) {}; - virtual ~GameOverLayer(); - bool init(); - CREATE_FUNC(GameOverLayer); - - void gameOverDone(); - - CC_SYNTHESIZE_READONLY(cocos2d::LabelTTF*, _label, Label); -}; - -class GameOverScene : public cocos2d::Scene -{ -public: - GameOverScene():_layer(NULL) {}; - ~GameOverScene(); - bool init(); - CREATE_FUNC(GameOverScene); - - CC_SYNTHESIZE_READONLY(GameOverLayer*, _layer, Layer); -}; - -#endif // _GAME_OVER_SCENE_H_ diff --git a/samples/Cpp/SimpleGame/Classes/HelloWorldScene.cpp b/samples/Cpp/SimpleGame/Classes/HelloWorldScene.cpp deleted file mode 100644 index 85d2f97be9..0000000000 --- a/samples/Cpp/SimpleGame/Classes/HelloWorldScene.cpp +++ /dev/null @@ -1,316 +0,0 @@ -#include "HelloWorldScene.h" -#include "GameOverScene.h" -#include "SimpleAudioEngine.h" - -using namespace cocos2d; - -HelloWorld::~HelloWorld() -{ - if (_targets) - { - _targets->release(); - _targets = NULL; - } - - if (_projectiles) - { - _projectiles->release(); - _projectiles = NULL; - } - - // cpp don't need to call super dealloc - // virtual destructor will do this -} - -HelloWorld::HelloWorld() -:_targets(NULL) -,_projectiles(NULL) -,_projectilesDestroyed(0) -{ -} - -Scene* HelloWorld::scene() -{ - Scene * scene = NULL; - do - { - // 'scene' is an autorelease object - scene = Scene::create(); - CC_BREAK_IF(! scene); - - // 'layer' is an autorelease object - HelloWorld *layer = HelloWorld::create(); - CC_BREAK_IF(! layer); - - // add layer as a child to scene - scene->addChild(layer); - } while (0); - - // return the scene - return scene; -} - -// on "init" you need to initialize your instance -bool HelloWorld::init() -{ - bool bRet = false; - do - { - ////////////////////////////////////////////////////////////////////////// - // super init first - ////////////////////////////////////////////////////////////////////////// - - CC_BREAK_IF(! LayerColor::initWithColor( Color4B(255,255,255,255) ) ); - - ////////////////////////////////////////////////////////////////////////// - // add your codes below... - ////////////////////////////////////////////////////////////////////////// - - // 1. Add a menu item with "X" image, which is clicked to quit the program. - - // Create a "close" menu item with close icon, it's an auto release object. - auto closeItem = MenuItemImage::create( - "CloseNormal.png", - "CloseSelected.png", - CC_CALLBACK_1(HelloWorld::menuCloseCallback,this)); - CC_BREAK_IF(! closeItem); - - // Place the menu item bottom-right conner. - auto visibleSize = Director::getInstance()->getVisibleSize(); - auto origin = Director::getInstance()->getVisibleOrigin(); - - closeItem->setPosition(Point(origin.x + visibleSize.width - closeItem->getContentSize().width/2, - origin.y + closeItem->getContentSize().height/2)); - - // Create a menu with the "close" menu item, it's an auto release object. - auto menu = Menu::create(closeItem, NULL); - menu->setPosition(Point::ZERO); - CC_BREAK_IF(! menu); - - // Add the menu to HelloWorld layer as a child layer. - this->addChild(menu, 1); - - ///////////////////////////// - // 2. add your codes below... - auto player = Sprite::create("Player.png", Rect(0, 0, 27, 40) ); - - player->setPosition( Point(origin.x + player->getContentSize().width/2, - origin.y + visibleSize.height/2) ); - this->addChild(player); - - this->schedule( schedule_selector(HelloWorld::gameLogic), 1.0 ); - - auto dispatcher = Director::getInstance()->getEventDispatcher(); - auto listener = EventListenerTouchAllAtOnce::create(); - listener->onTouchesEnded = CC_CALLBACK_2(HelloWorld::onTouchesEnded, this); - dispatcher->addEventListenerWithSceneGraphPriority(listener, this); - - _targets = new Array(); - _targets->init(); - - _projectiles = new Array(); - _projectiles->init(); - - // use updateGame instead of update, otherwise it will conflit with SelectorProtocol::update - // see http://www.cocos2d-x.org/boards/6/topics/1478 - this->schedule( schedule_selector(HelloWorld::updateGame) ); - - CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("background-music-aac.wav", true); - - bRet = true; - } while (0); - - return bRet; -} - -void HelloWorld::menuCloseCallback(Object* sender) -{ - // "close" menu item clicked - Director::getInstance()->end(); -} - -// cpp with cocos2d-x -void HelloWorld::addTarget() -{ - Sprite *target = Sprite::create("Target.png", Rect(0,0,27,40) ); - - // Determine where to spawn the target along the Y axis - Size winSize = Director::getInstance()->getVisibleSize(); - float minY = target->getContentSize().height/2; - float maxY = winSize.height - target->getContentSize().height/2; - int rangeY = (int)(maxY - minY); - // srand( TimGetTicks() ); - int actualY = ( rand() % rangeY ) + (int)minY; - - // Create the target slightly off-screen along the right edge, - // and along a random position along the Y axis as calculated - target->setPosition( - Point(winSize.width + (target->getContentSize().width/2), - Director::getInstance()->getVisibleOrigin().y + actualY) ); - this->addChild(target); - - // Determine speed of the target - int minDuration = (int)2.0; - int maxDuration = (int)4.0; - int rangeDuration = maxDuration - minDuration; - // srand( TimGetTicks() ); - int actualDuration = ( rand() % rangeDuration ) + minDuration; - - // Create the actions - FiniteTimeAction* actionMove = MoveTo::create( (float)actualDuration, - Point(0 - target->getContentSize().width/2, actualY) ); - FiniteTimeAction* actionMoveDone = CallFuncN::create( CC_CALLBACK_1(HelloWorld::spriteMoveFinished, this)); - target->runAction( Sequence::create(actionMove, actionMoveDone, NULL) ); - - // Add to targets array - target->setTag(1); - _targets->addObject(target); -} - -void HelloWorld::spriteMoveFinished(Node* sender) -{ - Sprite *sprite = (Sprite *)sender; - this->removeChild(sprite, true); - - if (sprite->getTag() == 1) // target - { - _targets->removeObject(sprite); - - auto gameOverScene = GameOverScene::create(); - gameOverScene->getLayer()->getLabel()->setString("You Lose :["); - Director::getInstance()->replaceScene(gameOverScene); - - } - else if (sprite->getTag() == 2) // projectile - { - _projectiles->removeObject(sprite); - } -} - -void HelloWorld::gameLogic(float dt) -{ - this->addTarget(); -} - -// cpp with cocos2d-x -void HelloWorld::onTouchesEnded(const std::vector& touches, Event* event) -{ - // Choose one of the touches to work with - Touch* touch = touches[0]; - Point location = touch->getLocation(); - - log("++++++++after x:%f, y:%f", location.x, location.y); - - // Set up initial location of projectile - Size winSize = Director::getInstance()->getVisibleSize(); - auto origin = Director::getInstance()->getVisibleOrigin(); - Sprite *projectile = Sprite::create("Projectile.png", Rect(0, 0, 20, 20)); - projectile->setPosition( Point(origin.x+20, origin.y+winSize.height/2) ); - - // Determinie offset of location to projectile - float offX = location.x - projectile->getPosition().x; - float offY = location.y - projectile->getPosition().y; - - // Bail out if we are shooting down or backwards - if (offX <= 0) return; - - // Ok to add now - we've double checked position - this->addChild(projectile); - - // Determine where we wish to shoot the projectile to - float realX = origin.x+winSize.width + (projectile->getContentSize().width/2); - float ratio = offY / offX; - float realY = (realX * ratio) + projectile->getPosition().y; - Point realDest = Point(realX, realY); - - // Determine the length of how far we're shooting - float offRealX = realX - projectile->getPosition().x; - float offRealY = realY - projectile->getPosition().y; - float length = sqrtf((offRealX * offRealX) + (offRealY*offRealY)); - float velocity = 480/1; // 480pixels/1sec - float realMoveDuration = length/velocity; - - // Move projectile to actual endpoint - projectile->runAction( Sequence::create( - MoveTo::create(realMoveDuration, realDest), - CallFuncN::create(CC_CALLBACK_1(HelloWorld::spriteMoveFinished, this)), - NULL) ); - - // Add to projectiles array - projectile->setTag(2); - _projectiles->addObject(projectile); - - CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("pew-pew-lei.wav"); -} - -void HelloWorld::updateGame(float dt) -{ - Array *projectilesToDelete = new Array(); - projectilesToDelete->init(); - - Object* it = NULL; - Object* jt = NULL; - - // for (it = _projectiles->begin(); it != _projectiles->end(); it++) - CCARRAY_FOREACH(_projectiles, it) - { - auto projectile = dynamic_cast(it); - auto projectileRect = Rect( - projectile->getPosition().x - (projectile->getContentSize().width/2), - projectile->getPosition().y - (projectile->getContentSize().height/2), - projectile->getContentSize().width, - projectile->getContentSize().height); - - auto targetsToDelete = new Array(); - targetsToDelete->init(); - - // for (jt = _targets->begin(); jt != _targets->end(); jt++) - CCARRAY_FOREACH(_targets, jt) - { - auto target = dynamic_cast(jt); - auto targetRect = Rect( - target->getPosition().x - (target->getContentSize().width/2), - target->getPosition().y - (target->getContentSize().height/2), - target->getContentSize().width, - target->getContentSize().height); - - // if (Rect::RectIntersectsRect(projectileRect, targetRect)) - if (projectileRect.intersectsRect(targetRect)) - { - targetsToDelete->addObject(target); - } - } - - // for (jt = targetsToDelete->begin(); jt != targetsToDelete->end(); jt++) - CCARRAY_FOREACH(targetsToDelete, jt) - { - auto target = dynamic_cast(jt); - _targets->removeObject(target); - this->removeChild(target, true); - - _projectilesDestroyed++; - if (_projectilesDestroyed >= 5) - { - auto gameOverScene = GameOverScene::create(); - gameOverScene->getLayer()->getLabel()->setString("You Win!"); - Director::getInstance()->replaceScene(gameOverScene); - } - } - - if (targetsToDelete->count() > 0) - { - projectilesToDelete->addObject(projectile); - } - targetsToDelete->release(); - } - - // for (it = projectilesToDelete->begin(); it != projectilesToDelete->end(); it++) - CCARRAY_FOREACH(projectilesToDelete, it) - { - auto projectile = dynamic_cast(it); - _projectiles->removeObject(projectile); - this->removeChild(projectile, true); - } - projectilesToDelete->release(); -} - diff --git a/samples/Cpp/SimpleGame/Classes/HelloWorldScene.h b/samples/Cpp/SimpleGame/Classes/HelloWorldScene.h deleted file mode 100644 index ee65eb2f08..0000000000 --- a/samples/Cpp/SimpleGame/Classes/HelloWorldScene.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef __HELLOWORLD_SCENE_H__ -#define __HELLOWORLD_SCENE_H__ - -#include "cocos2d.h" - -//#include "SimpleAudioEngine.h" - -class HelloWorld : public cocos2d::LayerColor -{ -public: - HelloWorld(); - ~HelloWorld(); - - // Here's a difference. Method 'init' in cocos2d-x returns bool, - // instead of returning 'id' in cocos2d-iphone - virtual bool init(); - - // there's no 'id' in cpp, so we recommand to return the exactly class pointer - static cocos2d::Scene* scene(); - - // a selector callback - virtual void menuCloseCallback(cocos2d::Object* sender); - - // implement the "static node()" method manually - CREATE_FUNC(HelloWorld); - - void spriteMoveFinished(cocos2d::Node* sender); - - void gameLogic(float dt); - - void updateGame(float dt); - - void onTouchesEnded(const std::vector& touches, cocos2d::Event* event); - - -protected: - cocos2d::Array *_targets; - cocos2d::Array *_projectiles; - int _projectilesDestroyed; - - void addTarget(); - - -}; - -#endif // __HELLOWORLD_SCENE_H__ diff --git a/samples/Cpp/SimpleGame/Resources/.gitignore b/samples/Cpp/SimpleGame/Resources/.gitignore deleted file mode 100644 index 1d65afe366..0000000000 --- a/samples/Cpp/SimpleGame/Resources/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -#Do now ignore Marmalade icf files -!*.icf diff --git a/samples/Cpp/SimpleGame/Resources/app.config.txt b/samples/Cpp/SimpleGame/Resources/app.config.txt deleted file mode 100644 index b39bf0b1db..0000000000 --- a/samples/Cpp/SimpleGame/Resources/app.config.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This .config.txt file documents configuration settings for your -# application -# The syntax is similar to that in .icf files: -# -# [GroupName] -# Setting Documentation for setting -# -# e.g. -# [MyApplicationGroup] -# MySetting Description of what MySetting is for, its default values, etc diff --git a/samples/Cpp/SimpleGame/proj.android/.classpath b/samples/Cpp/SimpleGame/proj.android/.classpath deleted file mode 100644 index c06dfcb8e5..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/samples/Cpp/SimpleGame/proj.android/.project b/samples/Cpp/SimpleGame/proj.android/.project deleted file mode 100644 index bf3f3d0350..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/.project +++ /dev/null @@ -1,65 +0,0 @@ - - - SimpleGame - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - Classes - 2 - COCOS2DX/samples/Cpp/SimpleGame/Classes - - - cocos2dx - 2 - COCOS2DX/cocos2dx - - - cocosdenshion - 2 - COCOS2DX/CocosDenshion - - - extensions - 2 - COCOS2DX/extensions - - - diff --git a/samples/Cpp/SimpleGame/proj.android/.settings/org.eclipse.cdt.codan.core.prefs b/samples/Cpp/SimpleGame/proj.android/.settings/org.eclipse.cdt.codan.core.prefs deleted file mode 100644 index bad4196993..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/.settings/org.eclipse.cdt.codan.core.prefs +++ /dev/null @@ -1,68 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.cdt.codan.checkers.errnoreturn=-Warning -org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.checkers.errreturnvalue=-Error -org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.checkers.noreturn=-Error -org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=-Error -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},no_break_comment\=>"no break",last_case_param\=>true,empty_case_param\=>false} -org.eclipse.cdt.codan.internal.checkers.CatchByReference=-Warning -org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},unknown\=>false,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=-Error -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=-Warning -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},skip\=>true} -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidArguments=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.OverloadProblem=-Error -org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},paramNot\=>false} -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},else\=>false,afterelse\=>false} -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>("@(\#)","$Id")} -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -useParentScope=false diff --git a/samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml b/samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml deleted file mode 100644 index 52ef0f9c8c..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Cpp/SimpleGame/proj.android/README.md b/samples/Cpp/SimpleGame/proj.android/README.md deleted file mode 100644 index 312835611a..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/README.md +++ /dev/null @@ -1,87 +0,0 @@ -## Prerequisites: - -* Android NDK -* Android SDK **OR** Eclipse ADT Bundle -* Android AVD target installed - -## Building project - -There are two ways of building Android projects. - -1. Eclipse -2. Command Line - -### Import Project in Eclipse - -#### Features: - -1. Complete workflow from Eclipse, including: - * Build C++. - * Clean C++. - * Build and Run whole project. - * Logcat view. - * Debug Java code. - * Javascript editor. - * Project management. -2. True C++ editing, including: - * Code completion. - * Jump to definition. - * Refactoring tools etc. - * Quick open C++ files. - - -#### Setup Eclipse Environment (only once) - - -**NOTE:** This step needs to be done only once to setup the Eclipse environment for cocos2d-x projects. Skip this section if you've done this before. - -1. Download Eclipse ADT bundle from [Google ADT homepage](http://developer.android.com/sdk/index.html) - - **OR** - - Install Eclipse with Java. Add ADT and CDT plugins. - -2. Only for Windows - 1. Install [Cygwin](http://www.cygwin.com/) with make (select make package from the list during the install). - 2. Add `Cygwin\bin` directory to system PATH variable. - 3. Add this line `none /cygdrive cygdrive binary,noacl,posix=0,user 0 0` to `Cygwin\etc\fstab` file. - -3. Set up Variables: - 1. Path Variable `COCOS2DX`: - * Eclipse->Preferences->General->Workspace->**Linked Resources** - * Click **New** button to add a Path Variable `COCOS2DX` pointing to the root cocos2d-x directory. - ![Example](https://lh5.googleusercontent.com/-oPpk9kg3e5w/UUOYlq8n7aI/AAAAAAAAsdQ/zLA4eghBH9U/s400/cocos2d-x-eclipse-vars.png) - - 2. C/C++ Environment Variable `NDK_ROOT`: - * Eclipse->Preferences->C/C++->Build->**Environment**. - * Click **Add** button and add a new variable `NDK_ROOT` pointing to the root NDK directory. - ![Example](https://lh3.googleusercontent.com/-AVcY8IAT0_g/UUOYltoRobI/AAAAAAAAsdM/22D2J9u3sig/s400/cocos2d-x-eclipse-ndk.png) - * Only for Windows: Add new variables **CYGWIN** with value `nodosfilewarning` and **SHELLOPTS** with value `igncr` - -4. Import libcocos2dx library project: - 1. File->New->Project->Android Project From Existing Code. - 2. Click **Browse** button and open `cocos2d-x/cocos2dx/platform/android/java` directory. - 3. Click **Finish** to add project. - -#### Adding and running from Eclipse - -![Example](https://lh3.googleusercontent.com/-SLBOu6e3QbE/UUOcOXYaGqI/AAAAAAAAsdo/tYBY2SylOSM/s288/cocos2d-x-eclipse-project-from-code.png) ![Import](https://lh5.googleusercontent.com/-XzC9Pn65USc/UUOcOTAwizI/AAAAAAAAsdk/4b6YM-oim9Y/s400/cocos2d-x-eclipse-import-project.png) - -1. File->New->Project->Android Project From Existing Code -2. **Browse** to your project directory. eg: `cocos2d-x/cocos2dx/samples/Cpp/TestCpp/proj.android/` -3. Add the project -4. Click **Run** or **Debug** to compile C++ followed by Java and to run on connected device or emulator. - - -### Running project from Command Line - - $ cd cocos2d-x/samples/Cpp/TestCpp/proj.android/ - $ export NDK_ROOT=/path/to/ndk - $ ./build_native.sh - $ ant debug install - -If the last command results in sdk.dir missing error then do: - - $ android list target - $ android update project -p . -t (id from step 6) - $ android update project -p cocos2d-x/cocos2dx/platform/android/java/ -t (id from step 6) diff --git a/samples/Cpp/SimpleGame/proj.android/build.xml b/samples/Cpp/SimpleGame/proj.android/build.xml deleted file mode 100644 index e9678a9b14..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/build.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Cpp/SimpleGame/proj.android/jni/Android.mk b/samples/Cpp/SimpleGame/proj.android/jni/Android.mk deleted file mode 100644 index cdc6ac3234..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/jni/Android.mk +++ /dev/null @@ -1,21 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := game_shared - -LOCAL_MODULE_FILENAME := libgame - -LOCAL_SRC_FILES := hellocpp/main.cpp \ - ../../Classes/AppDelegate.cpp \ - ../../Classes/HelloWorldScene.cpp \ - ../../Classes/GameOverScene.cpp - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes - -LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static cocosdenshion_static - -include $(BUILD_SHARED_LIBRARY) - -$(call import-module,audio/android) -$(call import-module,2d) diff --git a/samples/Cpp/SimpleGame/proj.android/jni/Application.mk b/samples/Cpp/SimpleGame/proj.android/jni/Application.mk deleted file mode 100644 index 74af9626ab..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/jni/Application.mk +++ /dev/null @@ -1,5 +0,0 @@ -APP_STL := gnustl_static - -# add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] -# in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Cpp/SimpleGame/proj.android/jni/hellocpp/main.cpp b/samples/Cpp/SimpleGame/proj.android/jni/hellocpp/main.cpp deleted file mode 100644 index ab92fe0f5a..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/jni/hellocpp/main.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "AppDelegate.h" -#include "platform/android/jni/JniHelper.h" -#include -#include - -#include "HelloWorldScene.h" - -#define LOG_TAG "main" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) - -using namespace cocos2d; - -void cocos_android_app_init (struct android_app* app) { - LOGD("cocos_android_app_init"); - AppDelegate *pAppDelegate = new AppDelegate(); -} diff --git a/samples/Cpp/SimpleGame/proj.android/jni/list.sh b/samples/Cpp/SimpleGame/proj.android/jni/list.sh deleted file mode 100755 index b29f678cb8..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/jni/list.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash - -append_str=' \' - -list_alldir() -{ - for file in $1/* - do - if [ -f $file ]; then - echo $file$append_str | grep .cpp - fi - - if [ -d $file ]; then - list_alldir $file - fi - done -} - -if [ $# -gt 0 ]; then - list_alldir "$1" -else - list_alldir "." -fi diff --git a/samples/Cpp/SimpleGame/proj.android/ndkgdb.sh b/samples/Cpp/SimpleGame/proj.android/ndkgdb.sh deleted file mode 100755 index ed934f9bfb..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/ndkgdb.sh +++ /dev/null @@ -1,62 +0,0 @@ -APPNAME="SimpleGame" -APP_ANDROID_NAME="org.cocos2dx.simplegame" - -# read local.properties - -_LOCALPROPERTIES_FILE=$(dirname "$0")"/local.properties" -if [ -f "$_LOCALPROPERTIES_FILE" ] -then - [ -r "$_LOCALPROPERTIES_FILE" ] || die "Fatal Error: $_LOCALPROPERTIES_FILE exists but is unreadable" - - # strip out entries with a "." because Bash cannot process variables with a "." - _PROPERTIES=$(sed '/\./d' "$_LOCALPROPERTIES_FILE") - for line in $_PROPERTIES - do - declare "$line" - done -fi - -if [ -z "${SDK_ROOT+aaa}" ]; then -echo "SDK_ROOT not defined. Please define SDK_ROOT in your environment or in local.properties" -exit 1 -fi - -if [ -z "${NDK_ROOT+aaa}" ]; then -echo "NDK_ROOT not defined. Please define NDK_ROOT in your environment or in local.properties" -exit 1 -fi - -if [ -z "${COCOS2DX_ROOT+aaa}" ]; then -# ... if COCOS2DX_ROOT is not set -# ... find current working directory - DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory - COCOS2DX_ROOT="$DIR/../../../.." - APP_ROOT="$DIR/.." - APP_ANDROID_ROOT="$DIR" -else - APP_ROOT="$COCOS2DX_ROOT/samples/$APPNAME" - APP_ANDROID_ROOT="$COCOS2DX_ROOT/samples/$APPNAME/proj.android" -fi - -echo "NDK_ROOT = $NDK_ROOT" -echo "SDK_ROOT = $SDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" -echo "APP_ANDROID_NAME = $APP_ANDROID_NAME" - -echo -echo "Killing and restarting ${APP_ANDROID_NAME}" -echo - -set -x - -"${SDK_ROOT}"/platform-tools/adb shell am force-stop "${APP_ANDROID_NAME}" - -NDK_MODULE_PATH="${COCOS2DX_ROOT}":"${COCOS2DX_ROOT}"/cocos2dx/platform/third_party/android/prebuilt \ - "${NDK_ROOT}"/ndk-gdb \ - --adb="${SDK_ROOT}"/platform-tools/adb \ - --verbose \ - --start \ - --force diff --git a/samples/Cpp/SimpleGame/proj.android/project.properties b/samples/Cpp/SimpleGame/proj.android/project.properties deleted file mode 100644 index f7e62936d0..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/project.properties +++ /dev/null @@ -1,15 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system edit -# "ant.properties", and override values to adapt the script to your -# project structure. -# -# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): -#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt - -# Project target. -target=android-10 -android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Cpp/SimpleGame/proj.android/res/values/strings.xml b/samples/Cpp/SimpleGame/proj.android/res/values/strings.xml deleted file mode 100644 index f197c895b7..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/res/values/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - SimpleGame - diff --git a/samples/Cpp/SimpleGame/proj.android/run.sh b/samples/Cpp/SimpleGame/proj.android/run.sh deleted file mode 100755 index 6f21bffa98..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/run.sh +++ /dev/null @@ -1 +0,0 @@ -~/bin/android-sdk/platform-tools/adb shell am start org.cocos2dx.simplegame/android.app.NativeActivity diff --git a/samples/Cpp/SimpleGame/proj.android/src/org/cocos2dx/simplegame/Cocos2dxActivity.java b/samples/Cpp/SimpleGame/proj.android/src/org/cocos2dx/simplegame/Cocos2dxActivity.java deleted file mode 100644 index 09065bdd15..0000000000 --- a/samples/Cpp/SimpleGame/proj.android/src/org/cocos2dx/simplegame/Cocos2dxActivity.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.cocos2dx.simplegame; - -import android.app.NativeActivity; -import android.graphics.PixelFormat; -import android.os.Bundle; - -public class Cocos2dxActivity extends NativeActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - //For supports translucency - - //1.change "attribs" in cocos\2d\platform\android\nativeactivity.cpp - /*const EGLint attribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - //EGL_BLUE_SIZE, 5, -->delete - //EGL_GREEN_SIZE, 6, -->delete - //EGL_RED_SIZE, 5, -->delete - EGL_BUFFER_SIZE, 32, //-->new field - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - };*/ - - //2.Set the format of window - // getWindow().setFormat(PixelFormat.TRANSLUCENT); - - } -} diff --git a/samples/Cpp/SimpleGame/proj.ios/AppController.h b/samples/Cpp/SimpleGame/proj.ios/AppController.h deleted file mode 100644 index 3d51064ca0..0000000000 --- a/samples/Cpp/SimpleGame/proj.ios/AppController.h +++ /dev/null @@ -1,33 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010 cocos2d-x.org - - 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. - ****************************************************************************/ - -@class RootViewController; - -@interface AppController : NSObject { - UIWindow *window; - RootViewController *viewController; -} - -@end - diff --git a/samples/Cpp/SimpleGame/proj.ios/SimpleGame_Prefix.pch b/samples/Cpp/SimpleGame/proj.ios/SimpleGame_Prefix.pch deleted file mode 100644 index b8914281d2..0000000000 --- a/samples/Cpp/SimpleGame/proj.ios/SimpleGame_Prefix.pch +++ /dev/null @@ -1,8 +0,0 @@ -// -// Prefix header for all source files of the 'HelloWorld' target in the 'HelloWorld' project -// - -#ifdef __OBJC__ - #import - #import -#endif diff --git a/samples/Cpp/SimpleGame/proj.ios/main.m b/samples/Cpp/SimpleGame/proj.ios/main.m deleted file mode 100644 index bd577a036e..0000000000 --- a/samples/Cpp/SimpleGame/proj.ios/main.m +++ /dev/null @@ -1,17 +0,0 @@ -// -// main.m -// iphone -// -// Created by Walzer on 10-11-16. -// Copyright 2010 __MyCompanyName__. All rights reserved. -// - -#import - -int main(int argc, char *argv[]) { - - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - int retVal = UIApplicationMain(argc, argv, nil, @"AppController"); - [pool release]; - return retVal; -} diff --git a/samples/Cpp/SimpleGame/proj.linux/main.cpp b/samples/Cpp/SimpleGame/proj.linux/main.cpp deleted file mode 100644 index 33e1052ebd..0000000000 --- a/samples/Cpp/SimpleGame/proj.linux/main.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "../Classes/AppDelegate.h" -#include "cocos2d.h" - -#include -#include -#include -#include - -USING_NS_CC; - -int main(int argc, char **argv) -{ - // create the application instance - AppDelegate app; - EGLView eglView; - eglView.init("SimpleGame",900,640); - return Application::getInstance()->run(); -} diff --git a/samples/Cpp/SimpleGame/proj.mac/SampleGame_Prefix.pch b/samples/Cpp/SimpleGame/proj.mac/SampleGame_Prefix.pch deleted file mode 100644 index 46c36a7e99..0000000000 --- a/samples/Cpp/SimpleGame/proj.mac/SampleGame_Prefix.pch +++ /dev/null @@ -1,7 +0,0 @@ -// -// Prefix header for all source files of the 'Paralaxer' target in the 'Paralaxer' project -// - -#ifdef __OBJC__ - #import -#endif diff --git a/samples/Cpp/SimpleGame/proj.mac/en.lproj/MainMenu.xib b/samples/Cpp/SimpleGame/proj.mac/en.lproj/MainMenu.xib deleted file mode 100644 index 07f04dbab1..0000000000 --- a/samples/Cpp/SimpleGame/proj.mac/en.lproj/MainMenu.xib +++ /dev/null @@ -1,812 +0,0 @@ - - - - 1080 - 12D78 - 3084 - 1187.37 - 626.00 - - com.apple.InterfaceBuilder.CocoaPlugin - 3084 - - - YES - NSCustomObject - NSMenu - NSMenuItem - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - - - PluginDependencyRecalculationVersion - - - - YES - - NSApplication - - - FirstResponder - - - NSApplication - - - AMainMenu - - YES - - - SampleGame - - 1048576 - 2147483647 - - NSImage - NSMenuCheckmark - - - NSImage - NSMenuMixedState - - submenuAction: - - SampleGame - - YES - - - About SampleGame - - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Preferences… - , - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Services - - 1048576 - 2147483647 - - - submenuAction: - - Services - - YES - - _NSServicesMenu - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Hide HelloCpp - h - 1048576 - 2147483647 - - - - - - Hide Others - h - 1572864 - 2147483647 - - - - - - Show All - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Quit HelloCpp - q - 1048576 - 2147483647 - - - - - _NSAppleMenu - - - - - View - - 1048576 - 2147483647 - - - submenuAction: - - View - - YES - - - Toggle Fullscreen - f - 1048576 - 2147483647 - - - - - - - - - Window - - 1048576 - 2147483647 - - - submenuAction: - - Window - - YES - - - Minimize - m - 1048576 - 2147483647 - - - - - - Zoom - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Bring All to Front - - 1048576 - 2147483647 - - - - - _NSWindowsMenu - - - - - Help - - 2147483647 - - - submenuAction: - - Help - - YES - - - SampleGame Help - ? - 1048576 - 2147483647 - - - - - _NSHelpMenu - - - - _NSMainMenu - - - AppController - - - NSFontManager - - - - - YES - - - terminate: - - - - 449 - - - - orderFrontStandardAboutPanel: - - - - 142 - - - - delegate - - - - 495 - - - - performMiniaturize: - - - - 37 - - - - arrangeInFront: - - - - 39 - - - - performZoom: - - - - 240 - - - - hide: - - - - 367 - - - - hideOtherApplications: - - - - 368 - - - - unhideAllApplications: - - - - 370 - - - - showHelp: - - - - 493 - - - - toggleFullScreen: - - - - 537 - - - - - YES - - 0 - - YES - - - - - - -2 - - - File's Owner - - - -1 - - - First Responder - - - -3 - - - Application - - - 29 - - - YES - - - - - - - - - 19 - - - YES - - - - - - 56 - - - YES - - - - - - 57 - - - YES - - - - - - - - - - - - - - - - 58 - - - - - 134 - - - - - 150 - - - - - 136 - - - - - 144 - - - - - 129 - - - - - 143 - - - - - 236 - - - - - 131 - - - YES - - - - - - 149 - - - - - 145 - - - - - 130 - - - - - 24 - - - YES - - - - - - - - - 92 - - - - - 5 - - - - - 239 - - - - - 23 - - - - - 295 - - - YES - - - - - - 296 - - - YES - - - - - - 420 - - - - - 490 - - - YES - - - - - - 491 - - - YES - - - - - - 492 - - - - - 494 - - - - - 536 - - - - - - - YES - - YES - -1.IBPluginDependency - -2.IBPluginDependency - -3.IBPluginDependency - 129.IBPluginDependency - 130.IBPluginDependency - 131.IBPluginDependency - 134.IBPluginDependency - 136.IBPluginDependency - 143.IBPluginDependency - 144.IBPluginDependency - 145.IBPluginDependency - 149.IBPluginDependency - 150.IBPluginDependency - 19.IBPluginDependency - 23.IBPluginDependency - 236.IBPluginDependency - 239.IBPluginDependency - 24.IBPluginDependency - 29.IBPluginDependency - 295.IBPluginDependency - 296.IBPluginDependency - 420.IBPluginDependency - 490.IBPluginDependency - 491.IBPluginDependency - 492.IBPluginDependency - 494.IBPluginDependency - 5.IBPluginDependency - 536.IBPluginDependency - 56.IBPluginDependency - 57.IBPluginDependency - 58.IBPluginDependency - 92.IBPluginDependency - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - - - - YES - - - - - - YES - - - - - 541 - - - - YES - - AppController - NSObject - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - id - id - - - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - - exitFullScreen: - id - - - toggleFullScreen: - id - - - - - YES - - YES - glView - window - - - YES - EAGLView - NSWindow - - - - YES - - YES - glView - window - - - YES - - glView - EAGLView - - - window - NSWindow - - - - - IBProjectSource - ./Classes/AppController.h - - - - EAGLView - NSOpenGLView - - IBProjectSource - ./Classes/EAGLView.h - - - - - 0 - IBCocoaFramework - - com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 - - - YES - 3 - - YES - - YES - NSMenuCheckmark - NSMenuMixedState - - - YES - {11, 11} - {10, 3} - - - - diff --git a/samples/Cpp/SimpleGame/proj.mac/main.cpp b/samples/Cpp/SimpleGame/proj.mac/main.cpp deleted file mode 100644 index d9432ebfe8..0000000000 --- a/samples/Cpp/SimpleGame/proj.mac/main.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010 cocos2d-x.org - - 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 "AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -int main(int argc, char *argv[]) -{ - AppDelegate app; - EGLView eglView; - eglView.init("SimpleGame",900,640); - return Application::getInstance()->run(); -} - diff --git a/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj b/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj deleted file mode 100644 index cb3c74751e..0000000000 --- a/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj +++ /dev/null @@ -1,151 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {E0E282F4-8487-452C-BFAB-CB960EB4D22F} - SimpleGame - Win32Proj - - - - Application - Unicode - true - v100 - v110 - v110_xp - - - Application - Unicode - v100 - v110 - v110_xp - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.40219.1 - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - true - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - false - AllRules.ruleset - - - AllRules.ruleset - - - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - - Disabled - ..\Classes;$(EngineRoot)cocos\audio\include;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;_WINDOWS;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - - - Level3 - EditAndContinue - 4267;4251;4244;%(DisableSpecificWarnings) - - - $(OutDir)$(ProjectName).exe - $(OutDir);%(AdditionalLibraryDirectories) - true - Windows - MachineX86 - libcocos2d.lib;libchipmunk.lib;%(AdditionalDependencies) - - - - - - - - - MaxSpeed - true - ..\Classes;$(EngineRoot)cocos\audio\include;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - MultiThreadedDLL - true - - - Level3 - ProgramDatabase - 4267;4251;4244;%(DisableSpecificWarnings) - - - libcocos2d.lib;%(AdditionalDependencies) - $(OutDir)$(ProjectName).exe - $(OutDir);%(AdditionalLibraryDirectories) - true - Windows - true - true - MachineX86 - - - - - - - - - - - - - - - - - - - - - {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - false - - - {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - - - {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} - - - - - - \ No newline at end of file diff --git a/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.filters b/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.filters deleted file mode 100644 index cf39562aaa..0000000000 --- a/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.filters +++ /dev/null @@ -1,41 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - - - Classes - - - Classes - - - win32 - - - Classes - - - - - Classes - - - Classes - - - win32 - - - Classes - - - \ No newline at end of file diff --git a/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.user b/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.user deleted file mode 100644 index 32a6296820..0000000000 --- a/samples/Cpp/SimpleGame/proj.win32/SimpleGame.vcxproj.user +++ /dev/null @@ -1,11 +0,0 @@ - - - - $(ProjectDir)..\Resources - WindowsLocalDebugger - - - $(ProjectDir)..\Resources - WindowsLocalDebugger - - \ No newline at end of file diff --git a/samples/Cpp/SimpleGame/proj.win32/main.cpp b/samples/Cpp/SimpleGame/proj.win32/main.cpp deleted file mode 100644 index d819bb02e0..0000000000 --- a/samples/Cpp/SimpleGame/proj.win32/main.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "main.h" -#include "../Classes/AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -int APIENTRY _tWinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - UNREFERENCED_PARAMETER(hPrevInstance); - UNREFERENCED_PARAMETER(lpCmdLine); - - // create the application instance - AppDelegate app; - EGLView eglView; - eglView.init("SimpleGame",900,640); - return Application::getInstance()->run(); -} diff --git a/samples/Cpp/SimpleGame/proj.win32/main.h b/samples/Cpp/SimpleGame/proj.win32/main.h deleted file mode 100644 index e74708bdf2..0000000000 --- a/samples/Cpp/SimpleGame/proj.win32/main.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __MAIN_H__ -#define __MAIN_H__ - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -// Windows Header Files: -#include -#include - -// C RunTime Header Files -#include "CCStdC.h" - -#endif // __MAIN_H__ diff --git a/samples/Cpp/TestCpp/.cproject b/samples/Cpp/TestCpp/.cproject deleted file mode 100644 index fc4e7a2557..0000000000 --- a/samples/Cpp/TestCpp/.cproject +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Cpp/TestCpp/.externalToolBuilders/Javah_jni_builder.launch b/samples/Cpp/TestCpp/.externalToolBuilders/Javah_jni_builder.launch deleted file mode 100644 index 3506e4e944..0000000000 --- a/samples/Cpp/TestCpp/.externalToolBuilders/Javah_jni_builder.launch +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/samples/Cpp/TestCpp/Classes/AppDelegate.cpp b/samples/Cpp/TestCpp/Classes/AppDelegate.cpp deleted file mode 100644 index 285d9b17ae..0000000000 --- a/samples/Cpp/TestCpp/Classes/AppDelegate.cpp +++ /dev/null @@ -1,106 +0,0 @@ -#include "AppDelegate.h" - -#include "cocos2d.h" -#include "controller.h" -#include "SimpleAudioEngine.h" -#include "cocostudio/CocoStudio.h" -#include "extensions/cocos-ext.h" - -USING_NS_CC; -using namespace CocosDenshion; - -AppDelegate::AppDelegate() -{ -} - -AppDelegate::~AppDelegate() -{ -// SimpleAudioEngine::end(); - cocostudio::ArmatureDataManager::destroyInstance(); -} - -bool AppDelegate::applicationDidFinishLaunching() -{ - // As an example, load config file - // XXX: This should be loaded before the Director is initialized, - // XXX: but at this point, the director is already initialized - Configuration::getInstance()->loadConfigFile("configs/config-example.plist"); - - // initialize director - auto director = Director::getInstance(); - director->setOpenGLView(EGLView::getInstance()); - - director->setDisplayStats(true); - director->setAnimationInterval(1.0 / 60); - - auto screenSize = EGLView::getInstance()->getFrameSize(); - - auto designSize = Size(480, 320); - - auto pFileUtils = FileUtils::getInstance(); - std::vector searchPaths; - - if (screenSize.height > 320) - { - auto resourceSize = Size(960, 640); - searchPaths.push_back("hd"); - searchPaths.push_back("hd/scenetest"); - searchPaths.push_back("hd/scenetest/ArmatureComponentTest"); - searchPaths.push_back("hd/scenetest/AttributeComponentTest"); - searchPaths.push_back("hd/scenetest/BackgroundComponentTest"); - searchPaths.push_back("hd/scenetest/EffectComponentTest"); - searchPaths.push_back("hd/scenetest/LoadSceneEdtiorFileTest"); - searchPaths.push_back("hd/scenetest/ParticleComponentTest"); - searchPaths.push_back("hd/scenetest/SpriteComponentTest"); - searchPaths.push_back("hd/scenetest/TmxMapComponentTest"); - searchPaths.push_back("hd/scenetest/UIComponentTest"); - searchPaths.push_back("hd/scenetest/TriggerTest"); - director->setContentScaleFactor(resourceSize.height/designSize.height); - } - else - { - searchPaths.push_back("scenetest/ArmatureComponentTest"); - searchPaths.push_back("scenetest/AttributeComponentTest"); - searchPaths.push_back("scenetest/BackgroundComponentTest"); - searchPaths.push_back("scenetest/EffectComponentTest"); - searchPaths.push_back("scenetest/LoadSceneEdtiorFileTest"); - searchPaths.push_back("scenetest/ParticleComponentTest"); - searchPaths.push_back("scenetest/SpriteComponentTest"); - searchPaths.push_back("scenetest/TmxMapComponentTest"); - searchPaths.push_back("scenetest/UIComponentTest"); - searchPaths.push_back("scenetest/TriggerTest"); - } - - pFileUtils->setSearchPaths(searchPaths); - - EGLView::getInstance()->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); - - auto scene = Scene::create(); - auto layer = new TestController(); - layer->autorelease(); - - scene->addChild(layer); - director->runWithScene(scene); - - // Enable Remote Console - auto console = director->getConsole(); - console->listenOnTCP(5678); - - return true; -} - -// This function will be called when the app is inactive. When comes a phone call,it's be invoked too -void AppDelegate::applicationDidEnterBackground() -{ - Director::getInstance()->stopAnimation(); - SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); - SimpleAudioEngine::getInstance()->pauseAllEffects(); -} - -// this function will be called when the app is active again -void AppDelegate::applicationWillEnterForeground() -{ - Director::getInstance()->startAnimation(); - SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); - SimpleAudioEngine::getInstance()->resumeAllEffects(); -} diff --git a/samples/Cpp/TestCpp/Classes/AppDelegate.h b/samples/Cpp/TestCpp/Classes/AppDelegate.h deleted file mode 100644 index 18ee8aeb63..0000000000 --- a/samples/Cpp/TestCpp/Classes/AppDelegate.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef _APP_DELEGATE_H_ -#define _APP_DELEGATE_H_ - -#include "cocos2d.h" - -/** -@brief The cocos2d Application. - -The reason for implement as private inheritance is to hide some interface call by Director. -*/ -class AppDelegate : private cocos2d::Application -{ -public: - AppDelegate(); - virtual ~AppDelegate(); - - /** - @brief Implement Director and Scene init code here. - @return true Initialize success, app continue. - @return false Initialize failed, app terminate. - */ - virtual bool applicationDidFinishLaunching(); - - /** - @brief The function be called when the application enter background - @param the pointer of the application - */ - virtual void applicationDidEnterBackground(); - - /** - @brief The function be called when the application enter foreground - @param the pointer of the application - */ - virtual void applicationWillEnterForeground(); -}; - -#endif // _APP_DELEGATE_H_ - diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id deleted file mode 100644 index 8f885e907c..0000000000 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -689b357d7acda141d13a3dfc4cb52aabb274f6cd \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Resources/.gitignore b/samples/Cpp/TestCpp/Resources/.gitignore deleted file mode 100644 index 1d65afe366..0000000000 --- a/samples/Cpp/TestCpp/Resources/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -#Do now ignore Marmalade icf files -!*.icf diff --git a/samples/Cpp/TestCpp/Resources/background-music-aac.wav.REMOVED.git-id b/samples/Cpp/TestCpp/Resources/background-music-aac.wav.REMOVED.git-id deleted file mode 100644 index 584ed4de8a..0000000000 --- a/samples/Cpp/TestCpp/Resources/background-music-aac.wav.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -db5624cd760ef3e8dfad2f751d94fac652d6667f \ No newline at end of file diff --git a/samples/Cpp/TestCpp/proj.android/.classpath b/samples/Cpp/TestCpp/proj.android/.classpath deleted file mode 100644 index c06dfcb8e5..0000000000 --- a/samples/Cpp/TestCpp/proj.android/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/samples/Cpp/TestCpp/proj.android/.externalToolBuilders/Javah_jni_builder.launch b/samples/Cpp/TestCpp/proj.android/.externalToolBuilders/Javah_jni_builder.launch deleted file mode 100644 index 3506e4e944..0000000000 --- a/samples/Cpp/TestCpp/proj.android/.externalToolBuilders/Javah_jni_builder.launch +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/samples/Cpp/TestCpp/proj.android/.project b/samples/Cpp/TestCpp/proj.android/.project deleted file mode 100644 index dd5dee2a3b..0000000000 --- a/samples/Cpp/TestCpp/proj.android/.project +++ /dev/null @@ -1,65 +0,0 @@ - - - TestCpp - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - Classes - 2 - COCOS2DX/samples/Cpp/TestCpp/Classes - - - cocos2dx - 2 - COCOS2DX/cocos2dx - - - cocosdenshion - 2 - COCOS2DX/CocosDenshion - - - extensions - 2 - COCOS2DX/extensions - - - diff --git a/samples/Cpp/TestCpp/proj.android/.settings/org.eclipse.cdt.codan.core.prefs b/samples/Cpp/TestCpp/proj.android/.settings/org.eclipse.cdt.codan.core.prefs deleted file mode 100644 index bad4196993..0000000000 --- a/samples/Cpp/TestCpp/proj.android/.settings/org.eclipse.cdt.codan.core.prefs +++ /dev/null @@ -1,68 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.cdt.codan.checkers.errnoreturn=-Warning -org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.checkers.errreturnvalue=-Error -org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.checkers.noreturn=-Error -org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=-Error -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},no_break_comment\=>"no break",last_case_param\=>true,empty_case_param\=>false} -org.eclipse.cdt.codan.internal.checkers.CatchByReference=-Warning -org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},unknown\=>false,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=-Error -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=-Warning -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},skip\=>true} -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidArguments=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.OverloadProblem=-Error -org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},paramNot\=>false} -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},else\=>false,afterelse\=>false} -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>("@(\#)","$Id")} -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -useParentScope=false diff --git a/samples/Cpp/TestCpp/proj.android/README.md b/samples/Cpp/TestCpp/proj.android/README.md deleted file mode 100644 index 312835611a..0000000000 --- a/samples/Cpp/TestCpp/proj.android/README.md +++ /dev/null @@ -1,87 +0,0 @@ -## Prerequisites: - -* Android NDK -* Android SDK **OR** Eclipse ADT Bundle -* Android AVD target installed - -## Building project - -There are two ways of building Android projects. - -1. Eclipse -2. Command Line - -### Import Project in Eclipse - -#### Features: - -1. Complete workflow from Eclipse, including: - * Build C++. - * Clean C++. - * Build and Run whole project. - * Logcat view. - * Debug Java code. - * Javascript editor. - * Project management. -2. True C++ editing, including: - * Code completion. - * Jump to definition. - * Refactoring tools etc. - * Quick open C++ files. - - -#### Setup Eclipse Environment (only once) - - -**NOTE:** This step needs to be done only once to setup the Eclipse environment for cocos2d-x projects. Skip this section if you've done this before. - -1. Download Eclipse ADT bundle from [Google ADT homepage](http://developer.android.com/sdk/index.html) - - **OR** - - Install Eclipse with Java. Add ADT and CDT plugins. - -2. Only for Windows - 1. Install [Cygwin](http://www.cygwin.com/) with make (select make package from the list during the install). - 2. Add `Cygwin\bin` directory to system PATH variable. - 3. Add this line `none /cygdrive cygdrive binary,noacl,posix=0,user 0 0` to `Cygwin\etc\fstab` file. - -3. Set up Variables: - 1. Path Variable `COCOS2DX`: - * Eclipse->Preferences->General->Workspace->**Linked Resources** - * Click **New** button to add a Path Variable `COCOS2DX` pointing to the root cocos2d-x directory. - ![Example](https://lh5.googleusercontent.com/-oPpk9kg3e5w/UUOYlq8n7aI/AAAAAAAAsdQ/zLA4eghBH9U/s400/cocos2d-x-eclipse-vars.png) - - 2. C/C++ Environment Variable `NDK_ROOT`: - * Eclipse->Preferences->C/C++->Build->**Environment**. - * Click **Add** button and add a new variable `NDK_ROOT` pointing to the root NDK directory. - ![Example](https://lh3.googleusercontent.com/-AVcY8IAT0_g/UUOYltoRobI/AAAAAAAAsdM/22D2J9u3sig/s400/cocos2d-x-eclipse-ndk.png) - * Only for Windows: Add new variables **CYGWIN** with value `nodosfilewarning` and **SHELLOPTS** with value `igncr` - -4. Import libcocos2dx library project: - 1. File->New->Project->Android Project From Existing Code. - 2. Click **Browse** button and open `cocos2d-x/cocos2dx/platform/android/java` directory. - 3. Click **Finish** to add project. - -#### Adding and running from Eclipse - -![Example](https://lh3.googleusercontent.com/-SLBOu6e3QbE/UUOcOXYaGqI/AAAAAAAAsdo/tYBY2SylOSM/s288/cocos2d-x-eclipse-project-from-code.png) ![Import](https://lh5.googleusercontent.com/-XzC9Pn65USc/UUOcOTAwizI/AAAAAAAAsdk/4b6YM-oim9Y/s400/cocos2d-x-eclipse-import-project.png) - -1. File->New->Project->Android Project From Existing Code -2. **Browse** to your project directory. eg: `cocos2d-x/cocos2dx/samples/Cpp/TestCpp/proj.android/` -3. Add the project -4. Click **Run** or **Debug** to compile C++ followed by Java and to run on connected device or emulator. - - -### Running project from Command Line - - $ cd cocos2d-x/samples/Cpp/TestCpp/proj.android/ - $ export NDK_ROOT=/path/to/ndk - $ ./build_native.sh - $ ant debug install - -If the last command results in sdk.dir missing error then do: - - $ android list target - $ android update project -p . -t (id from step 6) - $ android update project -p cocos2d-x/cocos2dx/platform/android/java/ -t (id from step 6) diff --git a/samples/Cpp/TestCpp/proj.android/ant.properties b/samples/Cpp/TestCpp/proj.android/ant.properties deleted file mode 100644 index b0971e891e..0000000000 --- a/samples/Cpp/TestCpp/proj.android/ant.properties +++ /dev/null @@ -1,17 +0,0 @@ -# This file is used to override default values used by the Ant build system. -# -# This file must be checked into Version Control Systems, as it is -# integral to the build system of your project. - -# This file is only used by the Ant script. - -# You can use this to override default values such as -# 'source.dir' for the location of your java source folder and -# 'out.dir' for the location of your output folder. - -# You can also use it define how the release builds are signed by declaring -# the following properties: -# 'key.store' for the location of your keystore and -# 'key.alias' for the name of the key to use. -# The password will be asked during the build when you use the 'release' target. - diff --git a/samples/Cpp/TestCpp/proj.ios/Classes/RootViewController.h b/samples/Cpp/TestCpp/proj.ios/Classes/RootViewController.h deleted file mode 100644 index 1401055c5c..0000000000 --- a/samples/Cpp/TestCpp/proj.ios/Classes/RootViewController.h +++ /dev/null @@ -1,16 +0,0 @@ -// -// RootViewController.h -// test -// -// Created by Walzer on 11-4-28. -// Copyright 2011 __MyCompanyName__. All rights reserved. -// - -#import - - -@interface RootViewController : UIViewController { - -} -- (BOOL)prefersStatusBarHidden; -@end diff --git a/samples/Cpp/TestCpp/proj.ios/Classes/RootViewController.mm b/samples/Cpp/TestCpp/proj.ios/Classes/RootViewController.mm deleted file mode 100644 index 137ff450a6..0000000000 --- a/samples/Cpp/TestCpp/proj.ios/Classes/RootViewController.mm +++ /dev/null @@ -1,79 +0,0 @@ - // -// RootViewController.mm -// test -// -// Created by Walzer on 11-4-28. -// Copyright 2011 __MyCompanyName__. All rights reserved. -// - -#import "RootViewController.h" - - -@implementation RootViewController - -/* - // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { - if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { - // Custom initialization - } - return self; -} -*/ - -/* -// Implement loadView to create a view hierarchy programmatically, without using a nib. -- (void)loadView { -} -*/ - -/* -// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -- (void)viewDidLoad { - [super viewDidLoad]; -} - -*/ -// Override to allow orientations other than the default portrait orientation. -// This method is deprecated on ios6 -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { - return UIInterfaceOrientationIsLandscape( interfaceOrientation ); -} - -// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead -- (NSUInteger) supportedInterfaceOrientations{ -#ifdef __IPHONE_6_0 - return UIInterfaceOrientationMaskAllButUpsideDown; -#endif -} - -- (BOOL) shouldAutorotate { - return YES; -} - -//fix not hide status on ios7 -- (BOOL)prefersStatusBarHidden -{ - return YES; -} - -- (void)didReceiveMemoryWarning { - // Releases the view if it doesn't have a superview. - [super didReceiveMemoryWarning]; - - // Release any cached data, images, etc that aren't in use. -} - -- (void)viewDidUnload { - [super viewDidUnload]; - // Release any retained subviews of the main view. - // e.g. self.myOutlet = nil; -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end diff --git a/samples/Cpp/TestCpp/proj.ios/Classes/testsAppDelegate.h b/samples/Cpp/TestCpp/proj.ios/Classes/testsAppDelegate.h deleted file mode 100644 index aeed186767..0000000000 --- a/samples/Cpp/TestCpp/proj.ios/Classes/testsAppDelegate.h +++ /dev/null @@ -1,19 +0,0 @@ -// -// iphoneAppDelegate.h -// iphone -// -// Created by Walzer on 10-11-16. -// Copyright 2010 __MyCompanyName__. All rights reserved. -// - -#import - -@class RootViewController; - -@interface AppController : NSObject { - UIWindow *window; - RootViewController *viewController; -} - -@end - diff --git a/samples/Cpp/TestCpp/proj.ios/Classes/testsAppDelegate.mm b/samples/Cpp/TestCpp/proj.ios/Classes/testsAppDelegate.mm deleted file mode 100644 index 55b5156c7f..0000000000 --- a/samples/Cpp/TestCpp/proj.ios/Classes/testsAppDelegate.mm +++ /dev/null @@ -1,122 +0,0 @@ -// -// iphoneAppDelegate.m -// iphone -// -// Created by Walzer on 10-11-16. -// Copyright 2010 __MyCompanyName__. All rights reserved. -// - -#import "testsAppDelegate.h" - -#import "EAGLView.h" -#import "cocos2d.h" -#import "AppDelegate.h" -#import "RootViewController.h" - -@implementation AppController - -#pragma mark - -#pragma mark Application lifecycle - -// cocos2d application instance -static AppDelegate s_sharedApplication; - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - - // Override point for customization after application launch. - - // Add the view controller's view to the window and display. - window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; - - // Init the CCEAGLView - CCEAGLView *__glView = [CCEAGLView viewWithFrame: [window bounds] - pixelFormat: kEAGLColorFormatRGB565 - depthFormat: GL_DEPTH24_STENCIL8_OES - preserveBackbuffer: NO - sharegroup: nil - multiSampling: NO - numberOfSamples: 0]; - [__glView setMultipleTouchEnabled:YES]; - - // Use RootViewController manage CCEAGLView - viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; - viewController.wantsFullScreenLayout = YES; - viewController.view = __glView; - - // Set RootViewController to window - if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) - { - // warning: addSubView doesn't work on iOS6 - [window addSubview: viewController.view]; - } - else - { - // use this method on ios6 - [window setRootViewController:viewController]; - } - - [window makeKeyAndVisible]; - - [[UIApplication sharedApplication] setStatusBarHidden:true]; - - cocos2d::Application::getInstance()->run(); - - return YES; -} - - -- (void)applicationWillResignActive:(UIApplication *)application { - /* - Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. - */ - cocos2d::Director::getInstance()->pause(); -} - -- (void)applicationDidBecomeActive:(UIApplication *)application { - /* - Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - */ - cocos2d::Director::getInstance()->resume(); -} - -- (void)applicationDidEnterBackground:(UIApplication *)application { - /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - If your application supports background execution, called instead of applicationWillTerminate: when the user quits. - */ - cocos2d::Application::getInstance()->applicationDidEnterBackground(); -} - -- (void)applicationWillEnterForeground:(UIApplication *)application { - /* - Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. - */ - cocos2d::Application::getInstance()->applicationWillEnterForeground(); -} - -- (void)applicationWillTerminate:(UIApplication *)application { - /* - Called when the application is about to terminate. - See also applicationDidEnterBackground:. - */ -} - - -#pragma mark - -#pragma mark Memory management - -- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { - /* - Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. - */ -} - - -- (void)dealloc { - [window release]; - [super dealloc]; -} - - -@end diff --git a/samples/Cpp/TestCpp/proj.linux/main.cpp b/samples/Cpp/TestCpp/proj.linux/main.cpp deleted file mode 100644 index fe87d9a1cd..0000000000 --- a/samples/Cpp/TestCpp/proj.linux/main.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "../Classes/AppDelegate.h" -#include "cocos2d.h" -#include "CCEGLView.h" - -#include -#include -#include -#include - -USING_NS_CC; - -int main(int argc, char **argv) -{ - // create the application instance - AppDelegate app; - EGLView eglView; - eglView.init("TestCPP",900,640); - return Application::getInstance()->run(); -} diff --git a/samples/Cpp/TestCpp/proj.win32/main.h b/samples/Cpp/TestCpp/proj.win32/main.h deleted file mode 100644 index e74708bdf2..0000000000 --- a/samples/Cpp/TestCpp/proj.win32/main.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __MAIN_H__ -#define __MAIN_H__ - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -// Windows Header Files: -#include -#include - -// C RunTime Header Files -#include "CCStdC.h" - -#endif // __MAIN_H__ diff --git a/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp b/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp deleted file mode 100644 index f14e6df017..0000000000 --- a/samples/Javascript/CocosDragonJS/Classes/AppDelegate.cpp +++ /dev/null @@ -1,182 +0,0 @@ -#include "AppDelegate.h" - -#include -#include - -#include "cocos2d.h" -#include "SimpleAudioEngine.h" -#include "ScriptingCore.h" -#include "jsb_cocos2dx_auto.hpp" -#include "jsb_cocos2dx_extension_auto.hpp" -#include "jsb_cocos2dx_builder_auto.hpp" -#include "extension/jsb_cocos2dx_extension_manual.h" -#include "cocos2d_specifics.hpp" -#include "cocosbuilder/js_bindings_ccbreader.h" -#include "localstorage/js_bindings_system_registration.h" -#include "chipmunk/js_bindings_chipmunk_registration.h" -#include "jsb_opengl_registration.h" - -USING_NS_CC; -using namespace CocosDenshion; -using namespace std; - -AppDelegate::AppDelegate() -{ -} - -AppDelegate::~AppDelegate() -{ - ScriptEngineManager::destroyInstance(); -} - -bool AppDelegate::applicationDidFinishLaunching() -{ - // initialize director - auto pDirector = Director::getInstance(); - pDirector->setOpenGLView(EGLView::getInstance()); - pDirector->setProjection(Director::Projection::_2D); - - - FileUtils::getInstance()->addSearchPath("script"); - - auto screenSize = EGLView::getInstance()->getFrameSize(); - - auto designSize = Size(320, 480); - auto resourceSize = Size(320, 480); - - std::vector resDirOrders; - - Platform platform = Application::getInstance()->getTargetPlatform(); - if (platform == Application::Platform::OS_IPHONE || platform == Application::Platform::OS_IPAD || platform == Application::Platform::OS_MAC) - { - std::vector searchPaths = FileUtils::getInstance()->getSearchPaths(); - searchPaths.insert(searchPaths.begin(), "Published files iOS"); - FileUtils::getInstance()->setSearchPaths(searchPaths); - if (screenSize.height > 1024) - { - resourceSize = Size(1536, 2048); - resDirOrders.push_back("resources-ipadhd"); - resDirOrders.push_back("resources-ipad"); - resDirOrders.push_back("resources-iphonehd"); - } - else if (screenSize.height > 960) - { - resourceSize = Size(768, 1024); - resDirOrders.push_back("resources-ipad"); - resDirOrders.push_back("resources-iphonehd"); - } - else if (screenSize.height > 480) - { - resourceSize = Size(640, 960); - resDirOrders.push_back("resources-iphonehd"); - resDirOrders.push_back("resources-iphone"); - } - else - { - resourceSize = Size(320, 480); - resDirOrders.push_back("resources-iphone"); - } - - } - else if (platform == Application::Platform::OS_ANDROID || platform == Application::Platform::OS_WINDOWS) - { - if (screenSize.height > 960) - { - resourceSize = Size(1280, 1920); - resDirOrders.push_back("resources-xlarge"); - resDirOrders.push_back("resources-large"); - resDirOrders.push_back("resources-medium"); - resDirOrders.push_back("resources-small"); - } - else if (screenSize.height > 720) - { - resourceSize = Size(640, 960); - resDirOrders.push_back("resources-large"); - resDirOrders.push_back("resources-medium"); - resDirOrders.push_back("resources-small"); - } - else if (screenSize.height > 480) - { - resourceSize = Size(480, 720); - resDirOrders.push_back("resources-medium"); - resDirOrders.push_back("resources-small"); - } - else - { - resourceSize = Size(320, 480); - resDirOrders.push_back("resources-small"); - } - } - - FileUtils::getInstance()->setSearchResolutionsOrder(resDirOrders); - - pDirector->setContentScaleFactor(resourceSize.width/designSize.width); - - EGLView::getInstance()->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); - - // turn on display FPS - pDirector->setDisplayStats(true); - - // set FPS. the default value is 1.0/60 if you don't call this - pDirector->setAnimationInterval(1.0 / 60); - - ScriptingCore* sc = ScriptingCore::getInstance(); - sc->addRegisterCallback(register_all_cocos2dx); - sc->addRegisterCallback(register_all_cocos2dx_extension); - sc->addRegisterCallback(register_cocos2dx_js_extensions); - sc->addRegisterCallback(register_all_cocos2dx_extension_manual); - sc->addRegisterCallback(register_all_cocos2dx_builder); - sc->addRegisterCallback(register_CCBuilderReader); - sc->addRegisterCallback(jsb_register_system); - sc->addRegisterCallback(JSB_register_opengl); - sc->addRegisterCallback(jsb_register_chipmunk); - - sc->start(); - -#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) - sc->enableDebugger(); -#endif - - js_log("RUNNING Main"); - auto pEngine = ScriptingCore::getInstance(); - ScriptEngineManager::getInstance()->setScriptEngine(pEngine); - ScriptingCore::getInstance()->runScript("main.js"); - - return true; -} - -void handle_signal(int signal) { - static int internal_state = 0; - ScriptingCore* sc = ScriptingCore::getInstance(); - // should start everything back - auto director = Director::getInstance(); - if (director->getRunningScene()) { - director->popToRootScene(); - } else { - PoolManager::sharedPoolManager()->finalize(); - if (internal_state == 0) { - //sc->dumpRoot(NULL, 0, NULL); - sc->start(); - internal_state = 1; - } else { - sc->runScript("hello.js"); - internal_state = 0; - } - } -} - -// This function will be called when the app is inactive. When comes a phone call,it's be invoked too -void AppDelegate::applicationDidEnterBackground() -{ - Director::getInstance()->stopAnimation(); - SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); - SimpleAudioEngine::getInstance()->pauseAllEffects(); -} - -// this function will be called when the app is active again -void AppDelegate::applicationWillEnterForeground() -{ - Director::getInstance()->startAnimation(); - SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); - SimpleAudioEngine::getInstance()->resumeAllEffects(); -} diff --git a/samples/Javascript/CocosDragonJS/proj.android/.project b/samples/Javascript/CocosDragonJS/proj.android/.project deleted file mode 100644 index 0a52fa2ab9..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/.project +++ /dev/null @@ -1,70 +0,0 @@ - - - CocosDragonJS - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - Classes - 2 - COCOS2DX/samples/Javascript/CocosDragonJS/Classes - - - cocos2dx - 2 - COCOS2DX/cocos2dx - - - cocosdenshion - 2 - COCOS2DX/CocosDenshion - - - extensions - 2 - COCOS2DX/extensions - - - scripting - 2 - COCOS2DX/scripting - - - diff --git a/samples/Javascript/CocosDragonJS/proj.android/.settings/org.eclipse.cdt.codan.core.prefs b/samples/Javascript/CocosDragonJS/proj.android/.settings/org.eclipse.cdt.codan.core.prefs deleted file mode 100644 index bad4196993..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/.settings/org.eclipse.cdt.codan.core.prefs +++ /dev/null @@ -1,68 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.cdt.codan.checkers.errnoreturn=-Warning -org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.checkers.errreturnvalue=-Error -org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.checkers.noreturn=-Error -org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=-Error -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},no_break_comment\=>"no break",last_case_param\=>true,empty_case_param\=>false} -org.eclipse.cdt.codan.internal.checkers.CatchByReference=-Warning -org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},unknown\=>false,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=-Error -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=-Warning -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},skip\=>true} -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidArguments=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.OverloadProblem=-Error -org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},paramNot\=>false} -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},else\=>false,afterelse\=>false} -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>("@(\#)","$Id")} -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -useParentScope=false diff --git a/samples/Javascript/CocosDragonJS/proj.android/AndroidManifest.xml b/samples/Javascript/CocosDragonJS/proj.android/AndroidManifest.xml deleted file mode 100644 index fb10a9db77..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/AndroidManifest.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Javascript/CocosDragonJS/proj.android/README.md b/samples/Javascript/CocosDragonJS/proj.android/README.md deleted file mode 100644 index 312835611a..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/README.md +++ /dev/null @@ -1,87 +0,0 @@ -## Prerequisites: - -* Android NDK -* Android SDK **OR** Eclipse ADT Bundle -* Android AVD target installed - -## Building project - -There are two ways of building Android projects. - -1. Eclipse -2. Command Line - -### Import Project in Eclipse - -#### Features: - -1. Complete workflow from Eclipse, including: - * Build C++. - * Clean C++. - * Build and Run whole project. - * Logcat view. - * Debug Java code. - * Javascript editor. - * Project management. -2. True C++ editing, including: - * Code completion. - * Jump to definition. - * Refactoring tools etc. - * Quick open C++ files. - - -#### Setup Eclipse Environment (only once) - - -**NOTE:** This step needs to be done only once to setup the Eclipse environment for cocos2d-x projects. Skip this section if you've done this before. - -1. Download Eclipse ADT bundle from [Google ADT homepage](http://developer.android.com/sdk/index.html) - - **OR** - - Install Eclipse with Java. Add ADT and CDT plugins. - -2. Only for Windows - 1. Install [Cygwin](http://www.cygwin.com/) with make (select make package from the list during the install). - 2. Add `Cygwin\bin` directory to system PATH variable. - 3. Add this line `none /cygdrive cygdrive binary,noacl,posix=0,user 0 0` to `Cygwin\etc\fstab` file. - -3. Set up Variables: - 1. Path Variable `COCOS2DX`: - * Eclipse->Preferences->General->Workspace->**Linked Resources** - * Click **New** button to add a Path Variable `COCOS2DX` pointing to the root cocos2d-x directory. - ![Example](https://lh5.googleusercontent.com/-oPpk9kg3e5w/UUOYlq8n7aI/AAAAAAAAsdQ/zLA4eghBH9U/s400/cocos2d-x-eclipse-vars.png) - - 2. C/C++ Environment Variable `NDK_ROOT`: - * Eclipse->Preferences->C/C++->Build->**Environment**. - * Click **Add** button and add a new variable `NDK_ROOT` pointing to the root NDK directory. - ![Example](https://lh3.googleusercontent.com/-AVcY8IAT0_g/UUOYltoRobI/AAAAAAAAsdM/22D2J9u3sig/s400/cocos2d-x-eclipse-ndk.png) - * Only for Windows: Add new variables **CYGWIN** with value `nodosfilewarning` and **SHELLOPTS** with value `igncr` - -4. Import libcocos2dx library project: - 1. File->New->Project->Android Project From Existing Code. - 2. Click **Browse** button and open `cocos2d-x/cocos2dx/platform/android/java` directory. - 3. Click **Finish** to add project. - -#### Adding and running from Eclipse - -![Example](https://lh3.googleusercontent.com/-SLBOu6e3QbE/UUOcOXYaGqI/AAAAAAAAsdo/tYBY2SylOSM/s288/cocos2d-x-eclipse-project-from-code.png) ![Import](https://lh5.googleusercontent.com/-XzC9Pn65USc/UUOcOTAwizI/AAAAAAAAsdk/4b6YM-oim9Y/s400/cocos2d-x-eclipse-import-project.png) - -1. File->New->Project->Android Project From Existing Code -2. **Browse** to your project directory. eg: `cocos2d-x/cocos2dx/samples/Cpp/TestCpp/proj.android/` -3. Add the project -4. Click **Run** or **Debug** to compile C++ followed by Java and to run on connected device or emulator. - - -### Running project from Command Line - - $ cd cocos2d-x/samples/Cpp/TestCpp/proj.android/ - $ export NDK_ROOT=/path/to/ndk - $ ./build_native.sh - $ ant debug install - -If the last command results in sdk.dir missing error then do: - - $ android list target - $ android update project -p . -t (id from step 6) - $ android update project -p cocos2d-x/cocos2dx/platform/android/java/ -t (id from step 6) diff --git a/samples/Javascript/CocosDragonJS/proj.android/build.xml b/samples/Javascript/CocosDragonJS/proj.android/build.xml deleted file mode 100644 index b5b34f9013..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/build.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Javascript/CocosDragonJS/proj.android/jni/Android.mk b/samples/Javascript/CocosDragonJS/proj.android/jni/Android.mk deleted file mode 100644 index 1e65b8e7a5..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/jni/Android.mk +++ /dev/null @@ -1,31 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := cocosdragonjs_shared - -LOCAL_MODULE_FILENAME := libcocosdragonjs - -LOCAL_SRC_FILES := cocosdragonjs/main.cpp \ - ../../Classes/AppDelegate.cpp - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes - -LOCAL_WHOLE_STATIC_LIBRARIES := cocos_jsb_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_chipmunk_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_extension_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_localstorage_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_network_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_builder_static - -LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT - -include $(BUILD_SHARED_LIBRARY) - -$(call import-module,scripting/javascript/bindings) -$(call import-module,scripting/javascript/bindings/chipmunk) -$(call import-module,scripting/javascript/bindings/extension) -$(call import-module,scripting/javascript/bindings/localstorage) -$(call import-module,scripting/javascript/bindings/network) -$(call import-module,scripting/javascript/bindings/cocosbuilder) - diff --git a/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk b/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk deleted file mode 100644 index 3666985a1f..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/jni/Application.mk +++ /dev/null @@ -1,6 +0,0 @@ -APP_STL := gnustl_static - -# add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] -# in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char - diff --git a/samples/Javascript/CocosDragonJS/proj.android/ndkgdb.sh b/samples/Javascript/CocosDragonJS/proj.android/ndkgdb.sh deleted file mode 100755 index 779acc425f..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/ndkgdb.sh +++ /dev/null @@ -1,47 +0,0 @@ -APPNAME="CocosDragonJS" -APP_ANDROID_NAME="org.cocos2dx.cocosdragonjs" - -if [ -z "${SDK_ROOT+aaa}" ]; then -# ... if SDK_ROOT is not set, use "$HOME/bin/android-sdk" - SDK_ROOT="$HOME/bin/android-sdk" -fi - -if [ -z "${NDK_ROOT+aaa}" ]; then -# ... if NDK_ROOT is not set, use "$HOME/bin/android-ndk" - NDK_ROOT="$HOME/bin/android-ndk" -fi - -if [ -z "${COCOS2DX_ROOT+aaa}" ]; then -# ... if COCOS2DX_ROOT is not set -# ... find current working directory - DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory - COCOS2DX_ROOT="$DIR/../../.." - APP_ROOT="$DIR/.." - APP_ANDROID_ROOT="$DIR" -else - APP_ROOT="$COCOS2DX_ROOT/samples/$APPNAME" - APP_ANDROID_ROOT="$COCOS2DX_ROOT/samples/$APPNAME/proj.android" -fi - -echo "NDK_ROOT = $NDK_ROOT" -echo "SDK_ROOT = $SDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" -echo "APP_ANDROID_NAME = $APP_ANDROID_NAME" - -echo -echo "Killing and restarting ${APP_ANDROID_NAME}" -echo - -set -x - -"${SDK_ROOT}"/platform-tools/adb shell am force-stop "${APP_ANDROID_NAME}" - -NDK_MODULE_PATH="${COCOS2DX_ROOT}":"${COCOS2DX_ROOT}"/cocos2dx/platform/third_party/android/prebuilt \ - "${NDK_ROOT}"/ndk-gdb \ - --adb="${SDK_ROOT}"/platform-tools/adb \ - --verbose \ - --start \ - --force diff --git a/samples/Javascript/CocosDragonJS/proj.android/proguard-project.txt b/samples/Javascript/CocosDragonJS/proj.android/proguard-project.txt deleted file mode 100644 index f2fe1559a2..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/proguard-project.txt +++ /dev/null @@ -1,20 +0,0 @@ -# To enable ProGuard in your project, edit project.properties -# to define the proguard.config property as described in that file. -# -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in ${sdk.dir}/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the ProGuard -# include property in project.properties. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/samples/Javascript/CocosDragonJS/proj.android/res/values/strings.xml b/samples/Javascript/CocosDragonJS/proj.android/res/values/strings.xml deleted file mode 100644 index 1cc07c9cad..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/res/values/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - CocosDragonJS - diff --git a/samples/Javascript/CocosDragonJS/proj.android/src/org/cocos2dx/cocosdragonjs/Cocos2dxActivity.java b/samples/Javascript/CocosDragonJS/proj.android/src/org/cocos2dx/cocosdragonjs/Cocos2dxActivity.java deleted file mode 100644 index bde3e3a5a0..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.android/src/org/cocos2dx/cocosdragonjs/Cocos2dxActivity.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.cocos2dx.cocosdragonjs; - -import android.app.NativeActivity; -import android.graphics.PixelFormat; -import android.os.Bundle; - -public class Cocos2dxActivity extends NativeActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - //For supports translucency - - //1.change "attribs" in cocos\2d\platform\android\nativeactivity.cpp - /*const EGLint attribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - //EGL_BLUE_SIZE, 5, -->delete - //EGL_GREEN_SIZE, 6, -->delete - //EGL_RED_SIZE, 5, -->delete - EGL_BUFFER_SIZE, 32, //-->new field - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - };*/ - - //2.Set the format of window - // getWindow().setFormat(PixelFormat.TRANSLUCENT); - - } -} diff --git a/samples/Javascript/CocosDragonJS/proj.ios/AppController.h b/samples/Javascript/CocosDragonJS/proj.ios/AppController.h deleted file mode 100644 index 10287bd13f..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.ios/AppController.h +++ /dev/null @@ -1,17 +0,0 @@ -// -// testjsAppController.h -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -@class RootViewController; - -@interface AppController : NSObject { - UIWindow *window; - RootViewController *viewController; -} - -@end - diff --git a/samples/Javascript/CocosDragonJS/proj.ios/AppController.mm b/samples/Javascript/CocosDragonJS/proj.ios/AppController.mm deleted file mode 100644 index ca23f1b7f8..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.ios/AppController.mm +++ /dev/null @@ -1,119 +0,0 @@ -// -// testjsAppController.mm -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// -#import -#import "AppController.h" -#import "cocos2d.h" -#import "EAGLView.h" -#import "AppDelegate.h" - -#import "RootViewController.h" - -@implementation AppController - -#pragma mark - -#pragma mark Application lifecycle - -// cocos2d application instance -static AppDelegate s_sharedApplication; - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - - // Override point for customization after application launch. - - // Add the view controller's view to the window and display. - window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; - CCEAGLView *__glView = [CCEAGLView viewWithFrame: [window bounds] - pixelFormat: kEAGLColorFormatRGBA8 - depthFormat: GL_DEPTH_COMPONENT16 //_OES - preserveBackbuffer: NO - sharegroup: nil - multiSampling: NO - numberOfSamples: 0 ]; - - // Use RootViewController manage CCEAGLView - viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; - viewController.wantsFullScreenLayout = YES; - viewController.view = __glView; - - // Set RootViewController to window - if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) - { - // warning: addSubView doesn't work on iOS6 - [window addSubview: viewController.view]; - } - else - { - // use this method on ios6 - [window setRootViewController:viewController]; - } - - [window makeKeyAndVisible]; - - [[UIApplication sharedApplication] setStatusBarHidden: YES]; - - cocos2d::Application::getInstance()->run(); - return YES; -} - - -- (void)applicationWillResignActive:(UIApplication *)application { - /* - Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. - */ - cocos2d::Director::getInstance()->pause(); -} - -- (void)applicationDidBecomeActive:(UIApplication *)application { - /* - Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - */ - cocos2d::Director::getInstance()->resume(); -} - -- (void)applicationDidEnterBackground:(UIApplication *)application { - /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - If your application supports background execution, called instead of applicationWillTerminate: when the user quits. - */ - cocos2d::Application::getInstance()->applicationDidEnterBackground(); -} - -- (void)applicationWillEnterForeground:(UIApplication *)application { - /* - Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. - */ - cocos2d::Application::getInstance()->applicationWillEnterForeground(); -} - -- (void)applicationWillTerminate:(UIApplication *)application { - /* - Called when the application is about to terminate. - See also applicationDidEnterBackground:. - */ -} - - -#pragma mark - -#pragma mark Memory management - -- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { - /* - Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. - */ - cocos2d::Director::getInstance()->purgeCachedData(); -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end - diff --git a/samples/Javascript/CocosDragonJS/proj.ios/Default-568h@2x.png.REMOVED.git-id b/samples/Javascript/CocosDragonJS/proj.ios/Default-568h@2x.png.REMOVED.git-id deleted file mode 100644 index 8f5838f3a8..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.ios/Default-568h@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -66c6d1cead373b45218424f6a82f370897e443e4 \ No newline at end of file diff --git a/samples/Javascript/CocosDragonJS/proj.ios/Default@2x.png.REMOVED.git-id b/samples/Javascript/CocosDragonJS/proj.ios/Default@2x.png.REMOVED.git-id deleted file mode 100644 index 8843505b20..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.ios/Default@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -84689888a14a2123d2b39f7f2f61be8c15207479 \ No newline at end of file diff --git a/samples/Javascript/CocosDragonJS/proj.ios/RootViewController.h b/samples/Javascript/CocosDragonJS/proj.ios/RootViewController.h deleted file mode 100644 index 11dfc4bf88..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.ios/RootViewController.h +++ /dev/null @@ -1,33 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2010 Ricardo Quesada - - 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. - ****************************************************************************/ - -#import - - -@interface RootViewController : UIViewController { - -} -- (BOOL)prefersStatusBarHidden; -@end diff --git a/samples/Javascript/CocosDragonJS/proj.mac/Icon.icns.REMOVED.git-id b/samples/Javascript/CocosDragonJS/proj.mac/Icon.icns.REMOVED.git-id deleted file mode 100644 index 9874ec6979..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.mac/Icon.icns.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Javascript/CocosDragonJS/proj.mac/en.lproj/InfoPlist.strings b/samples/Javascript/CocosDragonJS/proj.mac/en.lproj/InfoPlist.strings deleted file mode 100644 index 477b28ff8f..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.mac/en.lproj/InfoPlist.strings +++ /dev/null @@ -1,2 +0,0 @@ -/* Localized versions of Info.plist keys */ - diff --git a/samples/Javascript/CocosDragonJS/proj.mac/main.cpp b/samples/Javascript/CocosDragonJS/proj.mac/main.cpp deleted file mode 100644 index f363879238..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.mac/main.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010 cocos2d-x.org - - 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 "AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -int main(int argc, char *argv[]) -{ - AppDelegate app; - EGLView eglView; - eglView.init("CocosDragonJS", 480, 720); - return Application::getInstance()->run(); -} diff --git a/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj b/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj deleted file mode 100644 index 2e7cc9a5d5..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj +++ /dev/null @@ -1,228 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {68ED0B4E-2BCA-45D2-9648-CEABEBD3B9D7} - CocosDragonJS - - - - Application - Unicode - v100 - v110 - v110_xp - - - Application - Unicode - v100 - v110 - v110_xp - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.40219.1 - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - false - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - false - AllRules.ruleset - - - AllRules.ruleset - - - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - - _DEBUG;%(PreprocessorDefinitions) - false - Win32 - true - $(IntDir)testjs.tlb - testjs.h - - - testjs_i.c - testjs_p.c - - - Disabled - $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;_DEBUG;DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - - - Level3 - EditAndContinue - 4267;4251;4244;%(DisableSpecificWarnings) - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - - - - libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) - $(OutDir);%(AdditionalLibraryDirectories) - true - Windows - MachineX86 - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -if exist "$(OutDir)\CocosDragonJSRes" rd /s /q "$(OutDir)\CocosDragonJSRes" -mkdir "$(OutDir)\CocosDragonJSRes" -xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\CocosDragonJSRes" /e /Y -xcopy "$(ProjectDir)..\..\Shared\games\CocosDragonJS\Published files Android" "$(OutDir)\CocosDragonJSRes\" /e /Y - - - Copy js and resource files. - - - - - NDEBUG;%(PreprocessorDefinitions) - false - Win32 - true - $(IntDir)testjs.tlb - testjs.h - - - testjs_i.c - testjs_p.c - - - $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;NDEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;CC_ENABLE_CHIPMUNK_INTEGRATION=1;COCOS2D_JAVASCRIPT=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - MultiThreadedDLL - - - Level3 - - - 4267;4251;4244;%(DisableSpecificWarnings) - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - - - - libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) - $(OutDir);%(AdditionalLibraryDirectories) - Windows - MachineX86 - true - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -if exist "$(OutDir)\CocosDragonJSRes" rd /s /q "$(OutDir)\CocosDragonJSRes" -mkdir "$(OutDir)\CocosDragonJSRes" -xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\CocosDragonJSRes" /e /Y -xcopy "$(ProjectDir)..\..\Shared\games\CocosDragonJS\Published files Android" "$(OutDir)\CocosDragonJSRes\" /e /Y - Copy js and resource files. - - - - - - - - - - - - - - - - - - - - {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - - - {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - - - {811c0dab-7b96-4bd3-a154-b7572b58e4ab} - - - {21070e58-eec6-4e16-8b4f-6d083df55790} - - - {f9da0fc1-651b-457b-962e-a4d61cebf5fd} - - - {625f7391-9a91-48a1-8cfc-79508c822637} - - - {68f5f371-bd7b-4c30-ae5b-0b08f22e0cde} - - - {39379840-825a-45a0-b363-c09ffef864bd} - - - {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} - - - {21b2c324-891f-48ea-ad1a-5ae13de12e28} - - - {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} - - - - - - \ No newline at end of file diff --git a/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj.filters b/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj.filters deleted file mode 100644 index 56df37ce6f..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj.filters +++ /dev/null @@ -1,44 +0,0 @@ - - - - - {ca9c9e15-d942-43a1-aa7a-5f0b74ca1afd} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;jpg;jpeg;jpe;png;manifest - - - {ccb2323b-1cfa-41ea-bcf4-ba5f07309396} - - - {e93a77e1-af1e-4400-87d3-504b62ebdbb0} - - - - - win32 - - - Classes - - - - - win32 - - - win32 - - - Classes - - - - - resource - - - - - resource - - - \ No newline at end of file diff --git a/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj.user b/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj.user deleted file mode 100644 index 9d1dc0a360..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.win32/CocosDragonJS.vcxproj.user +++ /dev/null @@ -1,11 +0,0 @@ - - - - $(OutDir)\CocosDragonJSRes - WindowsLocalDebugger - - - $(OutDir)\CocosDragonJSRes - WindowsLocalDebugger - - \ No newline at end of file diff --git a/samples/Javascript/CocosDragonJS/proj.win32/main.cpp b/samples/Javascript/CocosDragonJS/proj.win32/main.cpp deleted file mode 100644 index 32adc1cd52..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.win32/main.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "main.h" -#include "AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -// uncomment below line, open debug console -// #define USE_WIN32_CONSOLE - -int APIENTRY _tWinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - UNREFERENCED_PARAMETER(hPrevInstance); - UNREFERENCED_PARAMETER(lpCmdLine); - -#ifdef USE_WIN32_CONSOLE - AllocConsole(); - freopen("CONIN$", "r", stdin); - freopen("CONOUT$", "w", stdout); - freopen("CONOUT$", "w", stderr); -#endif - - // create the application instance - AppDelegate app; - EGLView eglView; - eglView.init("CocosDragonJS", 480, 720); - - int ret = Application::getInstance()->run(); - -#ifdef USE_WIN32_CONSOLE - FreeConsole(); -#endif - - return ret; -} diff --git a/samples/Javascript/CocosDragonJS/proj.win32/main.h b/samples/Javascript/CocosDragonJS/proj.win32/main.h deleted file mode 100644 index e29aeedb3a..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.win32/main.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef __MAIN_H__ -#define __MAIN_H__ - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -// Windows Header Files: -#include - -// C RunTime Header Files -#include "CCStdC.h" - -#endif // __WINMAIN_H__ diff --git a/samples/Javascript/CocosDragonJS/proj.win32/resource.h b/samples/Javascript/CocosDragonJS/proj.win32/resource.h deleted file mode 100644 index a4cfa38af8..0000000000 --- a/samples/Javascript/CocosDragonJS/proj.win32/resource.h +++ /dev/null @@ -1,20 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by testjs.RC -// - -#define IDS_PROJNAME 100 -#define IDR_TESTJS 100 - -#define ID_FILE_NEW_WINDOW 32771 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 201 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 32775 -#endif -#endif diff --git a/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp b/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp deleted file mode 100644 index 63f1c31aed..0000000000 --- a/samples/Javascript/CrystalCraze/Classes/AppDelegate.cpp +++ /dev/null @@ -1,163 +0,0 @@ -#include "AppDelegate.h" - -#include "cocos2d.h" -#include "SimpleAudioEngine.h" -#include "ScriptingCore.h" -#include "jsb_cocos2dx_auto.hpp" -#include "jsb_cocos2dx_extension_auto.hpp" -#include "jsb_cocos2dx_builder_auto.hpp" -#include "extension/jsb_cocos2dx_extension_manual.h" -#include "cocos2d_specifics.hpp" -#include "cocosbuilder/js_bindings_ccbreader.h" -#include "localstorage/js_bindings_system_registration.h" -#include "chipmunk/js_bindings_chipmunk_registration.h" -#include "jsb_opengl_registration.h" - -USING_NS_CC; -using namespace CocosDenshion; - -AppDelegate::AppDelegate() -{ -} - -AppDelegate::~AppDelegate() -{ - ScriptEngineManager::destroyInstance(); -} - -bool AppDelegate::applicationDidFinishLaunching() -{ - // initialize director - auto pDirector = Director::getInstance(); - pDirector->setOpenGLView(EGLView::getInstance()); - pDirector->setProjection(Director::Projection::_2D); - - FileUtils::getInstance()->addSearchPath("script"); - - auto screenSize = EGLView::getInstance()->getFrameSize(); - - auto designSize = Size(320, 480); - auto resourceSize = Size(320, 480); - - std::vector searchPaths = FileUtils::getInstance()->getSearchPaths(); - std::vector resDirOrders; - - Application::Platform platform = Application::getInstance()->getTargetPlatform(); - if (platform == Application::Platform::OS_IPHONE || platform == Application::Platform::OS_IPAD || platform == Application::Platform::OS_MAC) - { - searchPaths.push_back("Published-iOS"); // Resources/Published-iOS - FileUtils::getInstance()->setSearchPaths(searchPaths); - - if (screenSize.height > 480) - { - resourceSize = Size(640, 960); - resDirOrders.push_back("resources-iphonehd"); - } - else - { - resDirOrders.push_back("resources-iphone"); - } - - FileUtils::getInstance()->setSearchResolutionsOrder(resDirOrders); - } - else if (platform == Application::Platform::OS_ANDROID || platform == Application::Platform::OS_WINDOWS) - { - // Comments it since opengles2.0 only supports texture size within 2048x2048. -// if (screenSize.height > 1024) -// { -// resourceSize = Size(1280, 1920); -// resDirOrders.push_back("resources-xlarge"); -// resDirOrders.push_back(""); -// } -// else - if (screenSize.height > 960) - { - resourceSize = Size(640, 960); - resDirOrders.push_back("resources-large"); - resDirOrders.push_back("resources-medium"); - resDirOrders.push_back("resources-small"); - } - else if (screenSize.height > 480) - { - resourceSize = Size(480, 720); - resDirOrders.push_back("resources-medium"); - resDirOrders.push_back("resources-small"); - } - else - { - resourceSize = Size(320, 568); - resDirOrders.push_back("resources-small"); - } - - FileUtils::getInstance()->setSearchResolutionsOrder(resDirOrders); - } - pDirector->setContentScaleFactor(resourceSize.width/designSize.width); - - EGLView::getInstance()->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::SHOW_ALL); - - // turn on display FPS - pDirector->setDisplayStats(true); - - // set FPS. the default value is 1.0/60 if you don't call this - pDirector->setAnimationInterval(1.0 / 60); - - 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_all_cocos2dx_builder); - 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(); -#endif - - js_log("RUNNING Main"); - auto pEngine = ScriptingCore::getInstance(); - ScriptEngineManager::getInstance()->setScriptEngine(pEngine); - ScriptingCore::getInstance()->runScript("main.js"); - - return true; -} - -void handle_signal(int signal) { - static int internal_state = 0; - ScriptingCore* sc = ScriptingCore::getInstance(); - // should start everything back - auto director = Director::getInstance(); - if (director->getRunningScene()) { - director->popToRootScene(); - } else { - PoolManager::sharedPoolManager()->finalize(); - if (internal_state == 0) { - //sc->dumpRoot(NULL, 0, NULL); - sc->start(); - internal_state = 1; - } else { - sc->runScript("hello.js"); - internal_state = 0; - } - } -} - -// This function will be called when the app is inactive. When comes a phone call,it's be invoked too -void AppDelegate::applicationDidEnterBackground() -{ - Director::getInstance()->stopAnimation(); - SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); - SimpleAudioEngine::getInstance()->pauseAllEffects(); -} - -// this function will be called when the app is active again -void AppDelegate::applicationWillEnterForeground() -{ - Director::getInstance()->startAnimation(); - SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); - SimpleAudioEngine::getInstance()->resumeAllEffects(); -} diff --git a/samples/Javascript/CrystalCraze/Classes/AppDelegate.h b/samples/Javascript/CrystalCraze/Classes/AppDelegate.h deleted file mode 100644 index df8f12f70f..0000000000 --- a/samples/Javascript/CrystalCraze/Classes/AppDelegate.h +++ /dev/null @@ -1,45 +0,0 @@ -// -// GCTestAppDelegate.h -// GCTest -// -// Created by Rohan Kuruvilla on 06/08/2012. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -#ifndef _APP_DELEGATE_H_ -#define _APP_DELEGATE_H_ - -#include "CCApplication.h" -/** - @brief The cocos2d Application. - - The reason for implement as private inheritance is to hide some interface call by Director. - */ -class AppDelegate : private cocos2d::Application -{ -public: - AppDelegate(); - virtual ~AppDelegate(); - - /** - @brief Implement Director and Scene init code here. - @return true Initialize success, app continue. - @return false Initialize failed, app terminate. - */ - virtual bool applicationDidFinishLaunching(); - - /** - @brief The function be called when the application enter background - @param the pointer of the application - */ - virtual void applicationDidEnterBackground(); - - /** - @brief The function be called when the application enter foreground - @param the pointer of the application - */ - virtual void applicationWillEnterForeground(); -}; - -#endif // _APP_DELEGATE_H_ - diff --git a/samples/Javascript/CrystalCraze/proj.android/.classpath b/samples/Javascript/CrystalCraze/proj.android/.classpath deleted file mode 100644 index 0b08408342..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/samples/Javascript/CrystalCraze/proj.android/.project b/samples/Javascript/CrystalCraze/proj.android/.project deleted file mode 100644 index 48f68239f6..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/.project +++ /dev/null @@ -1,70 +0,0 @@ - - - CrystalCraze - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - Classes - 2 - COCOS2DX/samples/Javascript/CrystalCraze/Classes - - - cocos2dx - 2 - COCOS2DX/cocos2dx - - - cocosdenshion - 2 - COCOS2DX/CocosDenshion - - - extensions - 2 - COCOS2DX/extensions - - - scripting - 2 - COCOS2DX/scripting - - - diff --git a/samples/Javascript/CrystalCraze/proj.android/.settings/org.eclipse.cdt.codan.core.prefs b/samples/Javascript/CrystalCraze/proj.android/.settings/org.eclipse.cdt.codan.core.prefs deleted file mode 100644 index bad4196993..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/.settings/org.eclipse.cdt.codan.core.prefs +++ /dev/null @@ -1,68 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.cdt.codan.checkers.errnoreturn=-Warning -org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.checkers.errreturnvalue=-Error -org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.checkers.noreturn=-Error -org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=-Error -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},no_break_comment\=>"no break",last_case_param\=>true,empty_case_param\=>false} -org.eclipse.cdt.codan.internal.checkers.CatchByReference=-Warning -org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},unknown\=>false,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=-Error -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=-Warning -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},skip\=>true} -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidArguments=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.OverloadProblem=-Error -org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},paramNot\=>false} -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},else\=>false,afterelse\=>false} -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>("@(\#)","$Id")} -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -useParentScope=false diff --git a/samples/Javascript/CrystalCraze/proj.android/AndroidManifest.xml b/samples/Javascript/CrystalCraze/proj.android/AndroidManifest.xml deleted file mode 100644 index 3917dd65f4..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/AndroidManifest.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Javascript/CrystalCraze/proj.android/README.md b/samples/Javascript/CrystalCraze/proj.android/README.md deleted file mode 100644 index 312835611a..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/README.md +++ /dev/null @@ -1,87 +0,0 @@ -## Prerequisites: - -* Android NDK -* Android SDK **OR** Eclipse ADT Bundle -* Android AVD target installed - -## Building project - -There are two ways of building Android projects. - -1. Eclipse -2. Command Line - -### Import Project in Eclipse - -#### Features: - -1. Complete workflow from Eclipse, including: - * Build C++. - * Clean C++. - * Build and Run whole project. - * Logcat view. - * Debug Java code. - * Javascript editor. - * Project management. -2. True C++ editing, including: - * Code completion. - * Jump to definition. - * Refactoring tools etc. - * Quick open C++ files. - - -#### Setup Eclipse Environment (only once) - - -**NOTE:** This step needs to be done only once to setup the Eclipse environment for cocos2d-x projects. Skip this section if you've done this before. - -1. Download Eclipse ADT bundle from [Google ADT homepage](http://developer.android.com/sdk/index.html) - - **OR** - - Install Eclipse with Java. Add ADT and CDT plugins. - -2. Only for Windows - 1. Install [Cygwin](http://www.cygwin.com/) with make (select make package from the list during the install). - 2. Add `Cygwin\bin` directory to system PATH variable. - 3. Add this line `none /cygdrive cygdrive binary,noacl,posix=0,user 0 0` to `Cygwin\etc\fstab` file. - -3. Set up Variables: - 1. Path Variable `COCOS2DX`: - * Eclipse->Preferences->General->Workspace->**Linked Resources** - * Click **New** button to add a Path Variable `COCOS2DX` pointing to the root cocos2d-x directory. - ![Example](https://lh5.googleusercontent.com/-oPpk9kg3e5w/UUOYlq8n7aI/AAAAAAAAsdQ/zLA4eghBH9U/s400/cocos2d-x-eclipse-vars.png) - - 2. C/C++ Environment Variable `NDK_ROOT`: - * Eclipse->Preferences->C/C++->Build->**Environment**. - * Click **Add** button and add a new variable `NDK_ROOT` pointing to the root NDK directory. - ![Example](https://lh3.googleusercontent.com/-AVcY8IAT0_g/UUOYltoRobI/AAAAAAAAsdM/22D2J9u3sig/s400/cocos2d-x-eclipse-ndk.png) - * Only for Windows: Add new variables **CYGWIN** with value `nodosfilewarning` and **SHELLOPTS** with value `igncr` - -4. Import libcocos2dx library project: - 1. File->New->Project->Android Project From Existing Code. - 2. Click **Browse** button and open `cocos2d-x/cocos2dx/platform/android/java` directory. - 3. Click **Finish** to add project. - -#### Adding and running from Eclipse - -![Example](https://lh3.googleusercontent.com/-SLBOu6e3QbE/UUOcOXYaGqI/AAAAAAAAsdo/tYBY2SylOSM/s288/cocos2d-x-eclipse-project-from-code.png) ![Import](https://lh5.googleusercontent.com/-XzC9Pn65USc/UUOcOTAwizI/AAAAAAAAsdk/4b6YM-oim9Y/s400/cocos2d-x-eclipse-import-project.png) - -1. File->New->Project->Android Project From Existing Code -2. **Browse** to your project directory. eg: `cocos2d-x/cocos2dx/samples/Cpp/TestCpp/proj.android/` -3. Add the project -4. Click **Run** or **Debug** to compile C++ followed by Java and to run on connected device or emulator. - - -### Running project from Command Line - - $ cd cocos2d-x/samples/Cpp/TestCpp/proj.android/ - $ export NDK_ROOT=/path/to/ndk - $ ./build_native.sh - $ ant debug install - -If the last command results in sdk.dir missing error then do: - - $ android list target - $ android update project -p . -t (id from step 6) - $ android update project -p cocos2d-x/cocos2dx/platform/android/java/ -t (id from step 6) diff --git a/samples/Javascript/CrystalCraze/proj.android/ant.properties b/samples/Javascript/CrystalCraze/proj.android/ant.properties deleted file mode 100644 index f8af38bfb4..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/ant.properties +++ /dev/null @@ -1 +0,0 @@ -aapt.ignore.assets="!*.pvr.gz:!*.gz:!.svn:!.git:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*.scc:*~" diff --git a/samples/Javascript/CrystalCraze/proj.android/build.xml b/samples/Javascript/CrystalCraze/proj.android/build.xml deleted file mode 100644 index 1bb22c3efd..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/build.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Javascript/CrystalCraze/proj.android/jni/Android.mk b/samples/Javascript/CrystalCraze/proj.android/jni/Android.mk deleted file mode 100644 index 9c8854568c..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/jni/Android.mk +++ /dev/null @@ -1,30 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := crystalcraze_shared - -LOCAL_MODULE_FILENAME := libcrystalcraze - -LOCAL_SRC_FILES := crystalcraze/main.cpp \ - ../../Classes/AppDelegate.cpp - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes - -LOCAL_WHOLE_STATIC_LIBRARIES := cocos_jsb_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_chipmunk_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_extension_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_localstorage_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_network_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_builder_static - -LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT - -include $(BUILD_SHARED_LIBRARY) - -$(call import-module,scripting/javascript/bindings) -$(call import-module,scripting/javascript/bindings/chipmunk) -$(call import-module,scripting/javascript/bindings/extension) -$(call import-module,scripting/javascript/bindings/localstorage) -$(call import-module,scripting/javascript/bindings/network) -$(call import-module,scripting/javascript/bindings/cocosbuilder) diff --git a/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk b/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk deleted file mode 100644 index 3666985a1f..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/jni/Application.mk +++ /dev/null @@ -1,6 +0,0 @@ -APP_STL := gnustl_static - -# add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] -# in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char - diff --git a/samples/Javascript/CrystalCraze/proj.android/jni/crystalcraze/main.cpp b/samples/Javascript/CrystalCraze/proj.android/jni/crystalcraze/main.cpp deleted file mode 100644 index 9793beefb1..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/jni/crystalcraze/main.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "AppDelegate.h" -#include "cocos2d.h" -#include "platform/android/jni/JniHelper.h" -#include "CCEventType.h" -#include -#include - -#define LOG_TAG "main" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) - -using namespace cocos2d; - -void cocos_android_app_init (struct android_app* app) { - LOGD("cocos_android_app_init"); - AppDelegate *pAppDelegate = new AppDelegate(); -} diff --git a/samples/Javascript/CrystalCraze/proj.android/ndkgdb.sh b/samples/Javascript/CrystalCraze/proj.android/ndkgdb.sh deleted file mode 100755 index b62f46024e..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/ndkgdb.sh +++ /dev/null @@ -1,47 +0,0 @@ -APPNAME="CrystalCraze" -APP_ANDROID_NAME="org.cocos2dx.cocosdragonjs" - -if [ -z "${SDK_ROOT+aaa}" ]; then -# ... if SDK_ROOT is not set, use "$HOME/bin/android-sdk" - SDK_ROOT="$HOME/bin/android-sdk" -fi - -if [ -z "${NDK_ROOT+aaa}" ]; then -# ... if NDK_ROOT is not set, use "$HOME/bin/android-ndk" - NDK_ROOT="$HOME/bin/android-ndk" -fi - -if [ -z "${COCOS2DX_ROOT+aaa}" ]; then -# ... if COCOS2DX_ROOT is not set -# ... find current working directory - DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory - COCOS2DX_ROOT="$DIR/../../.." - APP_ROOT="$DIR/.." - APP_ANDROID_ROOT="$DIR" -else - APP_ROOT="$COCOS2DX_ROOT/samples/$APPNAME" - APP_ANDROID_ROOT="$COCOS2DX_ROOT/samples/$APPNAME/proj.android" -fi - -echo "NDK_ROOT = $NDK_ROOT" -echo "SDK_ROOT = $SDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" -echo "APP_ANDROID_NAME = $APP_ANDROID_NAME" - -echo -echo "Killing and restarting ${APP_ANDROID_NAME}" -echo - -set -x - -"${SDK_ROOT}"/platform-tools/adb shell am force-stop "${APP_ANDROID_NAME}" - -NDK_MODULE_PATH="${COCOS2DX_ROOT}":"${COCOS2DX_ROOT}"/cocos2dx/platform/third_party/android/prebuilt \ - "${NDK_ROOT}"/ndk-gdb \ - --adb="${SDK_ROOT}"/platform-tools/adb \ - --verbose \ - --start \ - --force diff --git a/samples/Javascript/CrystalCraze/proj.android/proguard-project.txt b/samples/Javascript/CrystalCraze/proj.android/proguard-project.txt deleted file mode 100644 index f2fe1559a2..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/proguard-project.txt +++ /dev/null @@ -1,20 +0,0 @@ -# To enable ProGuard in your project, edit project.properties -# to define the proguard.config property as described in that file. -# -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in ${sdk.dir}/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the ProGuard -# include property in project.properties. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/samples/Javascript/CrystalCraze/proj.android/project.properties b/samples/Javascript/CrystalCraze/proj.android/project.properties deleted file mode 100644 index 0a6dc6664d..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/project.properties +++ /dev/null @@ -1,13 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "ant.properties", and override values to adapt the script to your -# project structure. - -# Project target. -target=android-10 - -android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Javascript/CrystalCraze/proj.android/res/values/strings.xml b/samples/Javascript/CrystalCraze/proj.android/res/values/strings.xml deleted file mode 100644 index 3e26a6a118..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/res/values/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - CrystalCraze - diff --git a/samples/Javascript/CrystalCraze/proj.android/src/org/cocos2dx/crystalcraze/Cocos2dxActivity.java b/samples/Javascript/CrystalCraze/proj.android/src/org/cocos2dx/crystalcraze/Cocos2dxActivity.java deleted file mode 100644 index f4dfa7e83b..0000000000 --- a/samples/Javascript/CrystalCraze/proj.android/src/org/cocos2dx/crystalcraze/Cocos2dxActivity.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.cocos2dx.crystalcraze; - -import android.app.NativeActivity; -import android.graphics.PixelFormat; -import android.os.Bundle; - -public class Cocos2dxActivity extends NativeActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - //For supports translucency - - //1.change "attribs" in cocos\2d\platform\android\nativeactivity.cpp - /*const EGLint attribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - //EGL_BLUE_SIZE, 5, -->delete - //EGL_GREEN_SIZE, 6, -->delete - //EGL_RED_SIZE, 5, -->delete - EGL_BUFFER_SIZE, 32, //-->new field - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - };*/ - - //2.Set the format of window - // getWindow().setFormat(PixelFormat.TRANSLUCENT); - - } -} diff --git a/samples/Javascript/CrystalCraze/proj.ios/AppController.h b/samples/Javascript/CrystalCraze/proj.ios/AppController.h deleted file mode 100644 index 10287bd13f..0000000000 --- a/samples/Javascript/CrystalCraze/proj.ios/AppController.h +++ /dev/null @@ -1,17 +0,0 @@ -// -// testjsAppController.h -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -@class RootViewController; - -@interface AppController : NSObject { - UIWindow *window; - RootViewController *viewController; -} - -@end - diff --git a/samples/Javascript/CrystalCraze/proj.ios/AppController.mm b/samples/Javascript/CrystalCraze/proj.ios/AppController.mm deleted file mode 100644 index ca23f1b7f8..0000000000 --- a/samples/Javascript/CrystalCraze/proj.ios/AppController.mm +++ /dev/null @@ -1,119 +0,0 @@ -// -// testjsAppController.mm -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// -#import -#import "AppController.h" -#import "cocos2d.h" -#import "EAGLView.h" -#import "AppDelegate.h" - -#import "RootViewController.h" - -@implementation AppController - -#pragma mark - -#pragma mark Application lifecycle - -// cocos2d application instance -static AppDelegate s_sharedApplication; - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - - // Override point for customization after application launch. - - // Add the view controller's view to the window and display. - window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; - CCEAGLView *__glView = [CCEAGLView viewWithFrame: [window bounds] - pixelFormat: kEAGLColorFormatRGBA8 - depthFormat: GL_DEPTH_COMPONENT16 //_OES - preserveBackbuffer: NO - sharegroup: nil - multiSampling: NO - numberOfSamples: 0 ]; - - // Use RootViewController manage CCEAGLView - viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; - viewController.wantsFullScreenLayout = YES; - viewController.view = __glView; - - // Set RootViewController to window - if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) - { - // warning: addSubView doesn't work on iOS6 - [window addSubview: viewController.view]; - } - else - { - // use this method on ios6 - [window setRootViewController:viewController]; - } - - [window makeKeyAndVisible]; - - [[UIApplication sharedApplication] setStatusBarHidden: YES]; - - cocos2d::Application::getInstance()->run(); - return YES; -} - - -- (void)applicationWillResignActive:(UIApplication *)application { - /* - Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. - */ - cocos2d::Director::getInstance()->pause(); -} - -- (void)applicationDidBecomeActive:(UIApplication *)application { - /* - Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - */ - cocos2d::Director::getInstance()->resume(); -} - -- (void)applicationDidEnterBackground:(UIApplication *)application { - /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - If your application supports background execution, called instead of applicationWillTerminate: when the user quits. - */ - cocos2d::Application::getInstance()->applicationDidEnterBackground(); -} - -- (void)applicationWillEnterForeground:(UIApplication *)application { - /* - Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. - */ - cocos2d::Application::getInstance()->applicationWillEnterForeground(); -} - -- (void)applicationWillTerminate:(UIApplication *)application { - /* - Called when the application is about to terminate. - See also applicationDidEnterBackground:. - */ -} - - -#pragma mark - -#pragma mark Memory management - -- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { - /* - Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. - */ - cocos2d::Director::getInstance()->purgeCachedData(); -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end - diff --git a/samples/Javascript/CrystalCraze/proj.ios/Default-568h@2x.png.REMOVED.git-id b/samples/Javascript/CrystalCraze/proj.ios/Default-568h@2x.png.REMOVED.git-id deleted file mode 100644 index 8f5838f3a8..0000000000 --- a/samples/Javascript/CrystalCraze/proj.ios/Default-568h@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -66c6d1cead373b45218424f6a82f370897e443e4 \ No newline at end of file diff --git a/samples/Javascript/CrystalCraze/proj.ios/Default@2x.png.REMOVED.git-id b/samples/Javascript/CrystalCraze/proj.ios/Default@2x.png.REMOVED.git-id deleted file mode 100644 index 8843505b20..0000000000 --- a/samples/Javascript/CrystalCraze/proj.ios/Default@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -84689888a14a2123d2b39f7f2f61be8c15207479 \ No newline at end of file diff --git a/samples/Javascript/CrystalCraze/proj.ios/Prefix.pch b/samples/Javascript/CrystalCraze/proj.ios/Prefix.pch deleted file mode 100644 index b056d8694a..0000000000 --- a/samples/Javascript/CrystalCraze/proj.ios/Prefix.pch +++ /dev/null @@ -1,8 +0,0 @@ -// -// Prefix header for all source files of the 'testjs' target in the 'testjs' project -// - -#ifdef __OBJC__ - #import - #import -#endif diff --git a/samples/Javascript/CrystalCraze/proj.ios/RootViewController.mm b/samples/Javascript/CrystalCraze/proj.ios/RootViewController.mm deleted file mode 100644 index 8438d7a420..0000000000 --- a/samples/Javascript/CrystalCraze/proj.ios/RootViewController.mm +++ /dev/null @@ -1,79 +0,0 @@ -// -// testjsAppController.h -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -#import "RootViewController.h" - - -@implementation RootViewController - -/* - // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { - if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { - // Custom initialization - } - return self; -} -*/ - -/* -// Implement loadView to create a view hierarchy programmatically, without using a nib. -- (void)loadView { -} -*/ - -/* -// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -- (void)viewDidLoad { - [super viewDidLoad]; -} - -*/ -// Override to allow orientations other than the default portrait orientation. -// This method is deprecated on ios6 -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { - return UIInterfaceOrientationIsLandscape( interfaceOrientation ); -} - -// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead -- (NSUInteger) supportedInterfaceOrientations{ -#ifdef __IPHONE_6_0 - return UIInterfaceOrientationMaskAllButUpsideDown; -#endif -} - -- (BOOL) shouldAutorotate { - return YES; -} - -//fix not hide status on ios7 -- (BOOL)prefersStatusBarHidden -{ - return YES; -} - -- (void)didReceiveMemoryWarning { - // Releases the view if it doesn't have a superview. - [super didReceiveMemoryWarning]; - - // Release any cached data, images, etc that aren't in use. -} - -- (void)viewDidUnload { - [super viewDidUnload]; - // Release any retained subviews of the main view. - // e.g. self.myOutlet = nil; -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end diff --git a/samples/Javascript/CrystalCraze/proj.ios/main.m b/samples/Javascript/CrystalCraze/proj.ios/main.m deleted file mode 100644 index e3dedca28b..0000000000 --- a/samples/Javascript/CrystalCraze/proj.ios/main.m +++ /dev/null @@ -1,17 +0,0 @@ -// -// main.m -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -#import - -int main(int argc, char *argv[]) { - - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - int retVal = UIApplicationMain(argc, argv, nil, @"AppController"); - [pool release]; - return retVal; -} diff --git a/samples/Javascript/CrystalCraze/proj.mac/Icon.icns.REMOVED.git-id b/samples/Javascript/CrystalCraze/proj.mac/Icon.icns.REMOVED.git-id deleted file mode 100644 index 9874ec6979..0000000000 --- a/samples/Javascript/CrystalCraze/proj.mac/Icon.icns.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Javascript/CrystalCraze/proj.mac/en.lproj/InfoPlist.strings b/samples/Javascript/CrystalCraze/proj.mac/en.lproj/InfoPlist.strings deleted file mode 100644 index 477b28ff8f..0000000000 --- a/samples/Javascript/CrystalCraze/proj.mac/en.lproj/InfoPlist.strings +++ /dev/null @@ -1,2 +0,0 @@ -/* Localized versions of Info.plist keys */ - diff --git a/samples/Javascript/CrystalCraze/proj.mac/en.lproj/MainMenu.xib b/samples/Javascript/CrystalCraze/proj.mac/en.lproj/MainMenu.xib deleted file mode 100644 index 3dacdedbd0..0000000000 --- a/samples/Javascript/CrystalCraze/proj.mac/en.lproj/MainMenu.xib +++ /dev/null @@ -1,812 +0,0 @@ - - - - 1060 - 10K549 - 1938 - 1038.36 - 461.00 - - com.apple.InterfaceBuilder.CocoaPlugin - 1938 - - - YES - NSMenuItem - NSCustomObject - NSMenu - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - - - PluginDependencyRecalculationVersion - - - - YES - - NSApplication - - - FirstResponder - - - NSApplication - - - AMainMenu - - YES - - - TestCpp - - 1048576 - 2147483647 - - NSImage - NSMenuCheckmark - - - NSImage - NSMenuMixedState - - submenuAction: - - TestCpp - - YES - - - About TestCpp - - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Preferences… - , - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Services - - 1048576 - 2147483647 - - - submenuAction: - - Services - - YES - - _NSServicesMenu - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Hide TestCpp - h - 1048576 - 2147483647 - - - - - - Hide Others - h - 1572864 - 2147483647 - - - - - - Show All - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Quit TestCpp - q - 1048576 - 2147483647 - - - - - _NSAppleMenu - - - - - View - - 1048576 - 2147483647 - - - submenuAction: - - View - - YES - - - Toggle Fullscreen - f - 1048576 - 2147483647 - - - - - - - - - Window - - 1048576 - 2147483647 - - - submenuAction: - - Window - - YES - - - Minimize - m - 1048576 - 2147483647 - - - - - - Zoom - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Bring All to Front - - 1048576 - 2147483647 - - - - - _NSWindowsMenu - - - - - Help - - 2147483647 - - - submenuAction: - - Help - - YES - - - TestCpp Help - ? - 1048576 - 2147483647 - - - - - _NSHelpMenu - - - - _NSMainMenu - - - AppController - - - NSFontManager - - - - - YES - - - terminate: - - - - 449 - - - - orderFrontStandardAboutPanel: - - - - 142 - - - - delegate - - - - 495 - - - - performMiniaturize: - - - - 37 - - - - arrangeInFront: - - - - 39 - - - - performZoom: - - - - 240 - - - - hide: - - - - 367 - - - - hideOtherApplications: - - - - 368 - - - - unhideAllApplications: - - - - 370 - - - - showHelp: - - - - 493 - - - - toggleFullScreen: - - - - 537 - - - - - YES - - 0 - - YES - - - - - - -2 - - - File's Owner - - - -1 - - - First Responder - - - -3 - - - Application - - - 29 - - - YES - - - - - - - - - 19 - - - YES - - - - - - 56 - - - YES - - - - - - 57 - - - YES - - - - - - - - - - - - - - - - 58 - - - - - 134 - - - - - 150 - - - - - 136 - - - - - 144 - - - - - 129 - - - - - 143 - - - - - 236 - - - - - 131 - - - YES - - - - - - 149 - - - - - 145 - - - - - 130 - - - - - 24 - - - YES - - - - - - - - - 92 - - - - - 5 - - - - - 239 - - - - - 23 - - - - - 295 - - - YES - - - - - - 296 - - - YES - - - - - - 420 - - - - - 490 - - - YES - - - - - - 491 - - - YES - - - - - - 492 - - - - - 494 - - - - - 536 - - - - - - - YES - - YES - -1.IBPluginDependency - -2.IBPluginDependency - -3.IBPluginDependency - 129.IBPluginDependency - 130.IBPluginDependency - 131.IBPluginDependency - 134.IBPluginDependency - 136.IBPluginDependency - 143.IBPluginDependency - 144.IBPluginDependency - 145.IBPluginDependency - 149.IBPluginDependency - 150.IBPluginDependency - 19.IBPluginDependency - 23.IBPluginDependency - 236.IBPluginDependency - 239.IBPluginDependency - 24.IBPluginDependency - 29.IBPluginDependency - 295.IBPluginDependency - 296.IBPluginDependency - 420.IBPluginDependency - 490.IBPluginDependency - 491.IBPluginDependency - 492.IBPluginDependency - 494.IBPluginDependency - 5.IBPluginDependency - 536.IBPluginDependency - 56.IBPluginDependency - 57.IBPluginDependency - 58.IBPluginDependency - 92.IBPluginDependency - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - - - - YES - - - - - - YES - - - - - 541 - - - - YES - - AppController - NSObject - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - id - id - - - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - - exitFullScreen: - id - - - toggleFullScreen: - id - - - - - YES - - YES - glView - window - - - YES - EAGLView - NSWindow - - - - YES - - YES - glView - window - - - YES - - glView - EAGLView - - - window - NSWindow - - - - - IBProjectSource - ./Classes/AppController.h - - - - EAGLView - NSOpenGLView - - IBProjectSource - ./Classes/EAGLView.h - - - - - 0 - IBCocoaFramework - - com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 - - - YES - 3 - - YES - - YES - NSMenuCheckmark - NSMenuMixedState - - - YES - {9, 8} - {7, 2} - - - - diff --git a/samples/Javascript/CrystalCraze/proj.mac/main.cpp b/samples/Javascript/CrystalCraze/proj.mac/main.cpp deleted file mode 100644 index ab9957f29e..0000000000 --- a/samples/Javascript/CrystalCraze/proj.mac/main.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010 cocos2d-x.org - - 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 "AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -int main(int argc, char *argv[]) -{ - AppDelegate app; - EGLView eglView; - eglView.init("CrystalCraze", 480, 720); - return Application::getInstance()->run(); -} diff --git a/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj b/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj deleted file mode 100644 index 36fd882002..0000000000 --- a/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj +++ /dev/null @@ -1,234 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {9A17D9A4-4B11-4E32-94F6-895FF4909EC5} - CrystalCraze - - - - Application - Unicode - v100 - v110 - v110_xp - - - Application - Unicode - v100 - v110 - v110_xp - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.40219.1 - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - false - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - false - AllRules.ruleset - - - AllRules.ruleset - - - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - - _DEBUG;%(PreprocessorDefinitions) - false - Win32 - true - $(IntDir)testjs.tlb - testjs.h - - - testjs_i.c - testjs_p.c - - - Disabled - $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;_DEBUG;DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - - - Level3 - EditAndContinue - 4267;4251;4244;%(DisableSpecificWarnings) - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - - - - libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) - $(OutDir);%(AdditionalLibraryDirectories) - true - Windows - MachineX86 - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -if exist "$(OutDir)\CrystalCrazeRes" rd /s /q "$(OutDir)\CrystalCrazeRes" -mkdir "$(OutDir)\CrystalCrazeRes" -xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\CrystalCrazeRes" /e /Y -xcopy "$(ProjectDir)..\..\Shared\games\CrystalCraze\Published-Android" "$(OutDir)\CrystalCrazeRes\" /e /Y - - - Copy js and resource files. - - - - - NDEBUG;%(PreprocessorDefinitions) - false - Win32 - true - $(IntDir)testjs.tlb - testjs.h - - - testjs_i.c - testjs_p.c - - - $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;NDEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;CC_ENABLE_CHIPMUNK_INTEGRATION=1;COCOS2D_JAVASCRIPT=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - MultiThreadedDLL - - - Level3 - - - 4267;4251;4244;%(DisableSpecificWarnings) - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - - - - libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) - $(OutDir);%(AdditionalLibraryDirectories) - Windows - MachineX86 - true - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -if exist "$(OutDir)\CrystalCrazeRes" rd /s /q "$(OutDir)\CrystalCrazeRes" -mkdir "$(OutDir)\CrystalCrazeRes" -xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\CrystalCrazeRes" /e /Y -xcopy "$(ProjectDir)..\..\Shared\games\CrystalCraze\Published-Android" "$(OutDir)\CrystalCrazeRes\" /e /Y - Copy js and resource files. - - - - - - - - - - - - - - - - - - - - {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - - - {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - - - {811c0dab-7b96-4bd3-a154-b7572b58e4ab} - - - {b57cf53f-2e49-4031-9822-047cc0e6bde2} - - - {df2638c0-8128-4847-867c-6eafe3dee7b5} - - - {21070e58-eec6-4e16-8b4f-6d083df55790} - - - {f9da0fc1-651b-457b-962e-a4d61cebf5fd} - - - {625f7391-9a91-48a1-8cfc-79508c822637} - - - {68f5f371-bd7b-4c30-ae5b-0b08f22e0cde} - - - {39379840-825a-45a0-b363-c09ffef864bd} - - - {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} - - - {21b2c324-891f-48ea-ad1a-5ae13de12e28} - - - {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} - - - - - - \ No newline at end of file diff --git a/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj.filters b/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj.filters deleted file mode 100644 index 56df37ce6f..0000000000 --- a/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj.filters +++ /dev/null @@ -1,44 +0,0 @@ - - - - - {ca9c9e15-d942-43a1-aa7a-5f0b74ca1afd} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;jpg;jpeg;jpe;png;manifest - - - {ccb2323b-1cfa-41ea-bcf4-ba5f07309396} - - - {e93a77e1-af1e-4400-87d3-504b62ebdbb0} - - - - - win32 - - - Classes - - - - - win32 - - - win32 - - - Classes - - - - - resource - - - - - resource - - - \ No newline at end of file diff --git a/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj.user b/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj.user deleted file mode 100644 index 17116bfa9e..0000000000 --- a/samples/Javascript/CrystalCraze/proj.win32/CrystalCraze.vcxproj.user +++ /dev/null @@ -1,11 +0,0 @@ - - - - $(OutDir)\CrystalCrazeRes - WindowsLocalDebugger - - - $(OutDir)\CrystalCrazeRes - WindowsLocalDebugger - - \ No newline at end of file diff --git a/samples/Javascript/CrystalCraze/proj.win32/main.cpp b/samples/Javascript/CrystalCraze/proj.win32/main.cpp deleted file mode 100644 index 6064ff7dd8..0000000000 --- a/samples/Javascript/CrystalCraze/proj.win32/main.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "main.h" -#include "AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -// uncomment below line, open debug console -// #define USE_WIN32_CONSOLE - -int APIENTRY _tWinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - UNREFERENCED_PARAMETER(hPrevInstance); - UNREFERENCED_PARAMETER(lpCmdLine); - -#ifdef USE_WIN32_CONSOLE - AllocConsole(); - freopen("CONIN$", "r", stdin); - freopen("CONOUT$", "w", stdout); - freopen("CONOUT$", "w", stderr); -#endif - - // create the application instance - AppDelegate app; - EGLView eglView; - eglView.init("CrystalCraze", 480, 720); - - int ret = Application::getInstance()->run(); - -#ifdef USE_WIN32_CONSOLE - FreeConsole(); -#endif - - return ret; -} diff --git a/samples/Javascript/CrystalCraze/proj.win32/main.h b/samples/Javascript/CrystalCraze/proj.win32/main.h deleted file mode 100644 index e29aeedb3a..0000000000 --- a/samples/Javascript/CrystalCraze/proj.win32/main.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef __MAIN_H__ -#define __MAIN_H__ - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -// Windows Header Files: -#include - -// C RunTime Header Files -#include "CCStdC.h" - -#endif // __WINMAIN_H__ diff --git a/samples/Javascript/CrystalCraze/proj.win32/res/testjs.ico b/samples/Javascript/CrystalCraze/proj.win32/res/testjs.ico deleted file mode 100644 index feaf932a74..0000000000 Binary files a/samples/Javascript/CrystalCraze/proj.win32/res/testjs.ico and /dev/null differ diff --git a/samples/Javascript/CrystalCraze/proj.win32/resource.h b/samples/Javascript/CrystalCraze/proj.win32/resource.h deleted file mode 100644 index a4cfa38af8..0000000000 --- a/samples/Javascript/CrystalCraze/proj.win32/resource.h +++ /dev/null @@ -1,20 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by testjs.RC -// - -#define IDS_PROJNAME 100 -#define IDR_TESTJS 100 - -#define ID_FILE_NEW_WINDOW 32771 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 201 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 32775 -#endif -#endif diff --git a/samples/Javascript/CrystalCraze/proj.win32/testjs.rc b/samples/Javascript/CrystalCraze/proj.win32/testjs.rc deleted file mode 100644 index 99e7360397..0000000000 --- a/samples/Javascript/CrystalCraze/proj.win32/testjs.rc +++ /dev/null @@ -1,86 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#define APSTUDIO_HIDDEN_SYMBOLS -#include "windows.h" -#undef APSTUDIO_HIDDEN_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -#endif // APSTUDIO_INVOKED - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDR_MAINFRAME ICON "res\\testjs.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "CompanyName", "\0" - VALUE "FileDescription", "testjs Module\0" - VALUE "FileVersion", "1, 0, 0, 1\0" - VALUE "InternalName", "testjs\0" - VALUE "LegalCopyright", "Copyright \0" - VALUE "OriginalFilename", "testjs.exe\0" - VALUE "ProductName", "testjs Module\0" - VALUE "ProductVersion", "1, 0, 0, 1\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 0x04B0 - END -END - -///////////////////////////////////////////////////////////////////////////// -#endif // !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) diff --git a/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp b/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp deleted file mode 100644 index c1406c1586..0000000000 --- a/samples/Javascript/MoonWarriors/Classes/AppDelegate.cpp +++ /dev/null @@ -1,105 +0,0 @@ -#include "AppDelegate.h" - -#include "cocos2d.h" -#include "SimpleAudioEngine.h" -#include "ScriptingCore.h" -#include "jsb_cocos2dx_auto.hpp" -#include "jsb_cocos2dx_extension_auto.hpp" -#include "jsb_cocos2dx_builder_auto.hpp" -#include "extension/jsb_cocos2dx_extension_manual.h" -#include "cocos2d_specifics.hpp" -#include "cocosbuilder/js_bindings_ccbreader.h" -#include "localstorage/js_bindings_system_registration.h" -#include "chipmunk/js_bindings_chipmunk_registration.h" -#include "jsb_opengl_registration.h" - -USING_NS_CC; -using namespace CocosDenshion; - -AppDelegate::AppDelegate() -{ -} - -AppDelegate::~AppDelegate() -{ - ScriptEngineManager::destroyInstance(); -} - -bool AppDelegate::applicationDidFinishLaunching() -{ - // initialize director - auto pDirector = Director::getInstance(); - pDirector->setOpenGLView(EGLView::getInstance()); - pDirector->setProjection(Director::Projection::_2D); - - // Set the design resolution - EGLView::getInstance()->setDesignResolutionSize(320, 480, ResolutionPolicy::SHOW_ALL); - - // turn on display FPS - pDirector->setDisplayStats(true); - - // set FPS. the default value is 1.0/60 if you don't call this - pDirector->setAnimationInterval(1.0 / 60); - - FileUtils::getInstance()->addSearchPath("script"); - - 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_all_cocos2dx_builder); - 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(); -#endif - - auto pEngine = ScriptingCore::getInstance(); - ScriptEngineManager::getInstance()->setScriptEngine(pEngine); - - ScriptingCore::getInstance()->runScript("MoonWarriors-jsb.js"); - - return true; -} - -void handle_signal(int signal) { - static int internal_state = 0; - ScriptingCore* sc = ScriptingCore::getInstance(); - // should start everything back - auto director = Director::getInstance(); - if (director->getRunningScene()) { - director->popToRootScene(); - } else { - PoolManager::sharedPoolManager()->finalize(); - if (internal_state == 0) { - //sc->dumpRoot(NULL, 0, NULL); - sc->start(); - internal_state = 1; - } else { - sc->runScript("hello.js"); - internal_state = 0; - } - } -} - -// This function will be called when the app is inactive. When comes a phone call,it's be invoked too -void AppDelegate::applicationDidEnterBackground() -{ - Director::getInstance()->stopAnimation(); - SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); - SimpleAudioEngine::getInstance()->pauseAllEffects(); -} - -// this function will be called when the app is active again -void AppDelegate::applicationWillEnterForeground() -{ - Director::getInstance()->startAnimation(); - SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); - SimpleAudioEngine::getInstance()->resumeAllEffects(); -} diff --git a/samples/Javascript/MoonWarriors/Classes/AppDelegate.h b/samples/Javascript/MoonWarriors/Classes/AppDelegate.h deleted file mode 100644 index df8f12f70f..0000000000 --- a/samples/Javascript/MoonWarriors/Classes/AppDelegate.h +++ /dev/null @@ -1,45 +0,0 @@ -// -// GCTestAppDelegate.h -// GCTest -// -// Created by Rohan Kuruvilla on 06/08/2012. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -#ifndef _APP_DELEGATE_H_ -#define _APP_DELEGATE_H_ - -#include "CCApplication.h" -/** - @brief The cocos2d Application. - - The reason for implement as private inheritance is to hide some interface call by Director. - */ -class AppDelegate : private cocos2d::Application -{ -public: - AppDelegate(); - virtual ~AppDelegate(); - - /** - @brief Implement Director and Scene init code here. - @return true Initialize success, app continue. - @return false Initialize failed, app terminate. - */ - virtual bool applicationDidFinishLaunching(); - - /** - @brief The function be called when the application enter background - @param the pointer of the application - */ - virtual void applicationDidEnterBackground(); - - /** - @brief The function be called when the application enter foreground - @param the pointer of the application - */ - virtual void applicationWillEnterForeground(); -}; - -#endif // _APP_DELEGATE_H_ - diff --git a/samples/Javascript/MoonWarriors/proj.android/.classpath b/samples/Javascript/MoonWarriors/proj.android/.classpath deleted file mode 100644 index 0b08408342..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/samples/Javascript/MoonWarriors/proj.android/.project b/samples/Javascript/MoonWarriors/proj.android/.project deleted file mode 100644 index 4bdf70520e..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/.project +++ /dev/null @@ -1,70 +0,0 @@ - - - MoonWarriors - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - Classes - 2 - COCOS2DX/samples/Javascript/MoonWarriors/Classes - - - cocos2dx - 2 - COCOS2DX/cocos2dx - - - cocosdenshion - 2 - COCOS2DX/CocosDenshion - - - extensions - 2 - COCOS2DX/extensions - - - scripting - 2 - COCOS2DX/scripting - - - diff --git a/samples/Javascript/MoonWarriors/proj.android/.settings/org.eclipse.cdt.codan.core.prefs b/samples/Javascript/MoonWarriors/proj.android/.settings/org.eclipse.cdt.codan.core.prefs deleted file mode 100644 index bad4196993..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/.settings/org.eclipse.cdt.codan.core.prefs +++ /dev/null @@ -1,68 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.cdt.codan.checkers.errnoreturn=-Warning -org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.checkers.errreturnvalue=-Error -org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.checkers.noreturn=-Error -org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=-Error -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},no_break_comment\=>"no break",last_case_param\=>true,empty_case_param\=>false} -org.eclipse.cdt.codan.internal.checkers.CatchByReference=-Warning -org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},unknown\=>false,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=-Error -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=-Warning -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},skip\=>true} -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidArguments=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.OverloadProblem=-Error -org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},paramNot\=>false} -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},else\=>false,afterelse\=>false} -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>("@(\#)","$Id")} -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -useParentScope=false diff --git a/samples/Javascript/MoonWarriors/proj.android/AndroidManifest.xml b/samples/Javascript/MoonWarriors/proj.android/AndroidManifest.xml deleted file mode 100644 index 59eba07645..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/AndroidManifest.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Javascript/MoonWarriors/proj.android/README.md b/samples/Javascript/MoonWarriors/proj.android/README.md deleted file mode 100644 index 312835611a..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/README.md +++ /dev/null @@ -1,87 +0,0 @@ -## Prerequisites: - -* Android NDK -* Android SDK **OR** Eclipse ADT Bundle -* Android AVD target installed - -## Building project - -There are two ways of building Android projects. - -1. Eclipse -2. Command Line - -### Import Project in Eclipse - -#### Features: - -1. Complete workflow from Eclipse, including: - * Build C++. - * Clean C++. - * Build and Run whole project. - * Logcat view. - * Debug Java code. - * Javascript editor. - * Project management. -2. True C++ editing, including: - * Code completion. - * Jump to definition. - * Refactoring tools etc. - * Quick open C++ files. - - -#### Setup Eclipse Environment (only once) - - -**NOTE:** This step needs to be done only once to setup the Eclipse environment for cocos2d-x projects. Skip this section if you've done this before. - -1. Download Eclipse ADT bundle from [Google ADT homepage](http://developer.android.com/sdk/index.html) - - **OR** - - Install Eclipse with Java. Add ADT and CDT plugins. - -2. Only for Windows - 1. Install [Cygwin](http://www.cygwin.com/) with make (select make package from the list during the install). - 2. Add `Cygwin\bin` directory to system PATH variable. - 3. Add this line `none /cygdrive cygdrive binary,noacl,posix=0,user 0 0` to `Cygwin\etc\fstab` file. - -3. Set up Variables: - 1. Path Variable `COCOS2DX`: - * Eclipse->Preferences->General->Workspace->**Linked Resources** - * Click **New** button to add a Path Variable `COCOS2DX` pointing to the root cocos2d-x directory. - ![Example](https://lh5.googleusercontent.com/-oPpk9kg3e5w/UUOYlq8n7aI/AAAAAAAAsdQ/zLA4eghBH9U/s400/cocos2d-x-eclipse-vars.png) - - 2. C/C++ Environment Variable `NDK_ROOT`: - * Eclipse->Preferences->C/C++->Build->**Environment**. - * Click **Add** button and add a new variable `NDK_ROOT` pointing to the root NDK directory. - ![Example](https://lh3.googleusercontent.com/-AVcY8IAT0_g/UUOYltoRobI/AAAAAAAAsdM/22D2J9u3sig/s400/cocos2d-x-eclipse-ndk.png) - * Only for Windows: Add new variables **CYGWIN** with value `nodosfilewarning` and **SHELLOPTS** with value `igncr` - -4. Import libcocos2dx library project: - 1. File->New->Project->Android Project From Existing Code. - 2. Click **Browse** button and open `cocos2d-x/cocos2dx/platform/android/java` directory. - 3. Click **Finish** to add project. - -#### Adding and running from Eclipse - -![Example](https://lh3.googleusercontent.com/-SLBOu6e3QbE/UUOcOXYaGqI/AAAAAAAAsdo/tYBY2SylOSM/s288/cocos2d-x-eclipse-project-from-code.png) ![Import](https://lh5.googleusercontent.com/-XzC9Pn65USc/UUOcOTAwizI/AAAAAAAAsdk/4b6YM-oim9Y/s400/cocos2d-x-eclipse-import-project.png) - -1. File->New->Project->Android Project From Existing Code -2. **Browse** to your project directory. eg: `cocos2d-x/cocos2dx/samples/Cpp/TestCpp/proj.android/` -3. Add the project -4. Click **Run** or **Debug** to compile C++ followed by Java and to run on connected device or emulator. - - -### Running project from Command Line - - $ cd cocos2d-x/samples/Cpp/TestCpp/proj.android/ - $ export NDK_ROOT=/path/to/ndk - $ ./build_native.sh - $ ant debug install - -If the last command results in sdk.dir missing error then do: - - $ android list target - $ android update project -p . -t (id from step 6) - $ android update project -p cocos2d-x/cocos2dx/platform/android/java/ -t (id from step 6) diff --git a/samples/Javascript/MoonWarriors/proj.android/ant.properties b/samples/Javascript/MoonWarriors/proj.android/ant.properties deleted file mode 100644 index f8af38bfb4..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/ant.properties +++ /dev/null @@ -1 +0,0 @@ -aapt.ignore.assets="!*.pvr.gz:!*.gz:!.svn:!.git:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*.scc:*~" diff --git a/samples/Javascript/MoonWarriors/proj.android/build.xml b/samples/Javascript/MoonWarriors/proj.android/build.xml deleted file mode 100644 index ae419c802d..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/build.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Javascript/MoonWarriors/proj.android/jni/Android.mk b/samples/Javascript/MoonWarriors/proj.android/jni/Android.mk deleted file mode 100644 index 93726f5b70..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/jni/Android.mk +++ /dev/null @@ -1,30 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := moonwarriors_shared - -LOCAL_MODULE_FILENAME := libmoonwarriors - -LOCAL_SRC_FILES := moonwarriors/main.cpp \ - ../../Classes/AppDelegate.cpp - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes - -LOCAL_WHOLE_STATIC_LIBRARIES := cocos_jsb_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_chipmunk_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_extension_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_localstorage_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_network_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_builder_static - -LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT - -include $(BUILD_SHARED_LIBRARY) - -$(call import-module,scripting/javascript/bindings) -$(call import-module,scripting/javascript/bindings/chipmunk) -$(call import-module,scripting/javascript/bindings/extension) -$(call import-module,scripting/javascript/bindings/localstorage) -$(call import-module,scripting/javascript/bindings/network) -$(call import-module,scripting/javascript/bindings/cocosbuilder) diff --git a/samples/Javascript/MoonWarriors/proj.android/jni/moonwarriors/main.cpp b/samples/Javascript/MoonWarriors/proj.android/jni/moonwarriors/main.cpp deleted file mode 100644 index 9793beefb1..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/jni/moonwarriors/main.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "AppDelegate.h" -#include "cocos2d.h" -#include "platform/android/jni/JniHelper.h" -#include "CCEventType.h" -#include -#include - -#define LOG_TAG "main" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) - -using namespace cocos2d; - -void cocos_android_app_init (struct android_app* app) { - LOGD("cocos_android_app_init"); - AppDelegate *pAppDelegate = new AppDelegate(); -} diff --git a/samples/Javascript/MoonWarriors/proj.android/proguard-project.txt b/samples/Javascript/MoonWarriors/proj.android/proguard-project.txt deleted file mode 100644 index f2fe1559a2..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/proguard-project.txt +++ /dev/null @@ -1,20 +0,0 @@ -# To enable ProGuard in your project, edit project.properties -# to define the proguard.config property as described in that file. -# -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in ${sdk.dir}/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the ProGuard -# include property in project.properties. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/samples/Javascript/MoonWarriors/proj.android/project.properties b/samples/Javascript/MoonWarriors/proj.android/project.properties deleted file mode 100644 index 0a6dc6664d..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/project.properties +++ /dev/null @@ -1,13 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "ant.properties", and override values to adapt the script to your -# project structure. - -# Project target. -target=android-10 - -android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Javascript/MoonWarriors/proj.android/res/values/strings.xml b/samples/Javascript/MoonWarriors/proj.android/res/values/strings.xml deleted file mode 100644 index 707408a4d7..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/res/values/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - MoonWarriors - diff --git a/samples/Javascript/MoonWarriors/proj.android/src/org/cocos2dx/moonwarriors/Cocos2dxActivity.java b/samples/Javascript/MoonWarriors/proj.android/src/org/cocos2dx/moonwarriors/Cocos2dxActivity.java deleted file mode 100644 index c979c4d044..0000000000 --- a/samples/Javascript/MoonWarriors/proj.android/src/org/cocos2dx/moonwarriors/Cocos2dxActivity.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.cocos2dx.moonwarriors; - -import android.app.NativeActivity; -import android.graphics.PixelFormat; -import android.os.Bundle; - -public class Cocos2dxActivity extends NativeActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - //For supports translucency - - //1.change "attribs" in cocos\2d\platform\android\nativeactivity.cpp - /*const EGLint attribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - //EGL_BLUE_SIZE, 5, -->delete - //EGL_GREEN_SIZE, 6, -->delete - //EGL_RED_SIZE, 5, -->delete - EGL_BUFFER_SIZE, 32, //-->new field - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - };*/ - - //2.Set the format of window - // getWindow().setFormat(PixelFormat.TRANSLUCENT); - - } -} diff --git a/samples/Javascript/MoonWarriors/proj.ios/AppController.h b/samples/Javascript/MoonWarriors/proj.ios/AppController.h deleted file mode 100644 index 10287bd13f..0000000000 --- a/samples/Javascript/MoonWarriors/proj.ios/AppController.h +++ /dev/null @@ -1,17 +0,0 @@ -// -// testjsAppController.h -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -@class RootViewController; - -@interface AppController : NSObject { - UIWindow *window; - RootViewController *viewController; -} - -@end - diff --git a/samples/Javascript/MoonWarriors/proj.ios/AppController.mm b/samples/Javascript/MoonWarriors/proj.ios/AppController.mm deleted file mode 100644 index ca23f1b7f8..0000000000 --- a/samples/Javascript/MoonWarriors/proj.ios/AppController.mm +++ /dev/null @@ -1,119 +0,0 @@ -// -// testjsAppController.mm -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// -#import -#import "AppController.h" -#import "cocos2d.h" -#import "EAGLView.h" -#import "AppDelegate.h" - -#import "RootViewController.h" - -@implementation AppController - -#pragma mark - -#pragma mark Application lifecycle - -// cocos2d application instance -static AppDelegate s_sharedApplication; - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - - // Override point for customization after application launch. - - // Add the view controller's view to the window and display. - window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; - CCEAGLView *__glView = [CCEAGLView viewWithFrame: [window bounds] - pixelFormat: kEAGLColorFormatRGBA8 - depthFormat: GL_DEPTH_COMPONENT16 //_OES - preserveBackbuffer: NO - sharegroup: nil - multiSampling: NO - numberOfSamples: 0 ]; - - // Use RootViewController manage CCEAGLView - viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; - viewController.wantsFullScreenLayout = YES; - viewController.view = __glView; - - // Set RootViewController to window - if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) - { - // warning: addSubView doesn't work on iOS6 - [window addSubview: viewController.view]; - } - else - { - // use this method on ios6 - [window setRootViewController:viewController]; - } - - [window makeKeyAndVisible]; - - [[UIApplication sharedApplication] setStatusBarHidden: YES]; - - cocos2d::Application::getInstance()->run(); - return YES; -} - - -- (void)applicationWillResignActive:(UIApplication *)application { - /* - Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. - */ - cocos2d::Director::getInstance()->pause(); -} - -- (void)applicationDidBecomeActive:(UIApplication *)application { - /* - Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - */ - cocos2d::Director::getInstance()->resume(); -} - -- (void)applicationDidEnterBackground:(UIApplication *)application { - /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - If your application supports background execution, called instead of applicationWillTerminate: when the user quits. - */ - cocos2d::Application::getInstance()->applicationDidEnterBackground(); -} - -- (void)applicationWillEnterForeground:(UIApplication *)application { - /* - Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. - */ - cocos2d::Application::getInstance()->applicationWillEnterForeground(); -} - -- (void)applicationWillTerminate:(UIApplication *)application { - /* - Called when the application is about to terminate. - See also applicationDidEnterBackground:. - */ -} - - -#pragma mark - -#pragma mark Memory management - -- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { - /* - Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. - */ - cocos2d::Director::getInstance()->purgeCachedData(); -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end - diff --git a/samples/Javascript/MoonWarriors/proj.ios/Default-568h@2x.png.REMOVED.git-id b/samples/Javascript/MoonWarriors/proj.ios/Default-568h@2x.png.REMOVED.git-id deleted file mode 100644 index 8f5838f3a8..0000000000 --- a/samples/Javascript/MoonWarriors/proj.ios/Default-568h@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -66c6d1cead373b45218424f6a82f370897e443e4 \ No newline at end of file diff --git a/samples/Javascript/MoonWarriors/proj.ios/Default@2x.png.REMOVED.git-id b/samples/Javascript/MoonWarriors/proj.ios/Default@2x.png.REMOVED.git-id deleted file mode 100644 index 8843505b20..0000000000 --- a/samples/Javascript/MoonWarriors/proj.ios/Default@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -84689888a14a2123d2b39f7f2f61be8c15207479 \ No newline at end of file diff --git a/samples/Javascript/MoonWarriors/proj.ios/Prefix.pch b/samples/Javascript/MoonWarriors/proj.ios/Prefix.pch deleted file mode 100644 index b056d8694a..0000000000 --- a/samples/Javascript/MoonWarriors/proj.ios/Prefix.pch +++ /dev/null @@ -1,8 +0,0 @@ -// -// Prefix header for all source files of the 'testjs' target in the 'testjs' project -// - -#ifdef __OBJC__ - #import - #import -#endif diff --git a/samples/Javascript/MoonWarriors/proj.ios/RootViewController.h b/samples/Javascript/MoonWarriors/proj.ios/RootViewController.h deleted file mode 100644 index 11dfc4bf88..0000000000 --- a/samples/Javascript/MoonWarriors/proj.ios/RootViewController.h +++ /dev/null @@ -1,33 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2010 Ricardo Quesada - - 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. - ****************************************************************************/ - -#import - - -@interface RootViewController : UIViewController { - -} -- (BOOL)prefersStatusBarHidden; -@end diff --git a/samples/Javascript/MoonWarriors/proj.ios/RootViewController.mm b/samples/Javascript/MoonWarriors/proj.ios/RootViewController.mm deleted file mode 100644 index 3a37088ebd..0000000000 --- a/samples/Javascript/MoonWarriors/proj.ios/RootViewController.mm +++ /dev/null @@ -1,79 +0,0 @@ -// -// testjsAppController.h -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -#import "RootViewController.h" - - -@implementation RootViewController - -/* - // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { - if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { - // Custom initialization - } - return self; -} -*/ - -/* -// Implement loadView to create a view hierarchy programmatically, without using a nib. -- (void)loadView { -} -*/ - -/* -// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -- (void)viewDidLoad { - [super viewDidLoad]; -} - -*/ -// Override to allow orientations other than the default portrait orientation. -// This method is deprecated on ios6 -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { - return UIInterfaceOrientationIsPortrait(interfaceOrientation); -} - -// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead -- (NSUInteger) supportedInterfaceOrientations{ -#ifdef __IPHONE_6_0 - return UIInterfaceOrientationMaskAllButUpsideDown; -#endif -} - -- (BOOL) shouldAutorotate { - return YES; -} - -//fix not hide status on ios7 -- (BOOL)prefersStatusBarHidden -{ - return YES; -} - -- (void)didReceiveMemoryWarning { - // Releases the view if it doesn't have a superview. - [super didReceiveMemoryWarning]; - - // Release any cached data, images, etc that aren't in use. -} - -- (void)viewDidUnload { - [super viewDidUnload]; - // Release any retained subviews of the main view. - // e.g. self.myOutlet = nil; -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end diff --git a/samples/Javascript/MoonWarriors/proj.ios/main.m b/samples/Javascript/MoonWarriors/proj.ios/main.m deleted file mode 100644 index e3dedca28b..0000000000 --- a/samples/Javascript/MoonWarriors/proj.ios/main.m +++ /dev/null @@ -1,17 +0,0 @@ -// -// main.m -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -#import - -int main(int argc, char *argv[]) { - - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - int retVal = UIApplicationMain(argc, argv, nil, @"AppController"); - [pool release]; - return retVal; -} diff --git a/samples/Javascript/MoonWarriors/proj.mac/Icon.icns.REMOVED.git-id b/samples/Javascript/MoonWarriors/proj.mac/Icon.icns.REMOVED.git-id deleted file mode 100644 index 9874ec6979..0000000000 --- a/samples/Javascript/MoonWarriors/proj.mac/Icon.icns.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Javascript/MoonWarriors/proj.mac/en.lproj/InfoPlist.strings b/samples/Javascript/MoonWarriors/proj.mac/en.lproj/InfoPlist.strings deleted file mode 100644 index 477b28ff8f..0000000000 --- a/samples/Javascript/MoonWarriors/proj.mac/en.lproj/InfoPlist.strings +++ /dev/null @@ -1,2 +0,0 @@ -/* Localized versions of Info.plist keys */ - diff --git a/samples/Javascript/MoonWarriors/proj.mac/en.lproj/MainMenu.xib b/samples/Javascript/MoonWarriors/proj.mac/en.lproj/MainMenu.xib deleted file mode 100644 index 3dacdedbd0..0000000000 --- a/samples/Javascript/MoonWarriors/proj.mac/en.lproj/MainMenu.xib +++ /dev/null @@ -1,812 +0,0 @@ - - - - 1060 - 10K549 - 1938 - 1038.36 - 461.00 - - com.apple.InterfaceBuilder.CocoaPlugin - 1938 - - - YES - NSMenuItem - NSCustomObject - NSMenu - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - - - PluginDependencyRecalculationVersion - - - - YES - - NSApplication - - - FirstResponder - - - NSApplication - - - AMainMenu - - YES - - - TestCpp - - 1048576 - 2147483647 - - NSImage - NSMenuCheckmark - - - NSImage - NSMenuMixedState - - submenuAction: - - TestCpp - - YES - - - About TestCpp - - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Preferences… - , - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Services - - 1048576 - 2147483647 - - - submenuAction: - - Services - - YES - - _NSServicesMenu - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Hide TestCpp - h - 1048576 - 2147483647 - - - - - - Hide Others - h - 1572864 - 2147483647 - - - - - - Show All - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Quit TestCpp - q - 1048576 - 2147483647 - - - - - _NSAppleMenu - - - - - View - - 1048576 - 2147483647 - - - submenuAction: - - View - - YES - - - Toggle Fullscreen - f - 1048576 - 2147483647 - - - - - - - - - Window - - 1048576 - 2147483647 - - - submenuAction: - - Window - - YES - - - Minimize - m - 1048576 - 2147483647 - - - - - - Zoom - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Bring All to Front - - 1048576 - 2147483647 - - - - - _NSWindowsMenu - - - - - Help - - 2147483647 - - - submenuAction: - - Help - - YES - - - TestCpp Help - ? - 1048576 - 2147483647 - - - - - _NSHelpMenu - - - - _NSMainMenu - - - AppController - - - NSFontManager - - - - - YES - - - terminate: - - - - 449 - - - - orderFrontStandardAboutPanel: - - - - 142 - - - - delegate - - - - 495 - - - - performMiniaturize: - - - - 37 - - - - arrangeInFront: - - - - 39 - - - - performZoom: - - - - 240 - - - - hide: - - - - 367 - - - - hideOtherApplications: - - - - 368 - - - - unhideAllApplications: - - - - 370 - - - - showHelp: - - - - 493 - - - - toggleFullScreen: - - - - 537 - - - - - YES - - 0 - - YES - - - - - - -2 - - - File's Owner - - - -1 - - - First Responder - - - -3 - - - Application - - - 29 - - - YES - - - - - - - - - 19 - - - YES - - - - - - 56 - - - YES - - - - - - 57 - - - YES - - - - - - - - - - - - - - - - 58 - - - - - 134 - - - - - 150 - - - - - 136 - - - - - 144 - - - - - 129 - - - - - 143 - - - - - 236 - - - - - 131 - - - YES - - - - - - 149 - - - - - 145 - - - - - 130 - - - - - 24 - - - YES - - - - - - - - - 92 - - - - - 5 - - - - - 239 - - - - - 23 - - - - - 295 - - - YES - - - - - - 296 - - - YES - - - - - - 420 - - - - - 490 - - - YES - - - - - - 491 - - - YES - - - - - - 492 - - - - - 494 - - - - - 536 - - - - - - - YES - - YES - -1.IBPluginDependency - -2.IBPluginDependency - -3.IBPluginDependency - 129.IBPluginDependency - 130.IBPluginDependency - 131.IBPluginDependency - 134.IBPluginDependency - 136.IBPluginDependency - 143.IBPluginDependency - 144.IBPluginDependency - 145.IBPluginDependency - 149.IBPluginDependency - 150.IBPluginDependency - 19.IBPluginDependency - 23.IBPluginDependency - 236.IBPluginDependency - 239.IBPluginDependency - 24.IBPluginDependency - 29.IBPluginDependency - 295.IBPluginDependency - 296.IBPluginDependency - 420.IBPluginDependency - 490.IBPluginDependency - 491.IBPluginDependency - 492.IBPluginDependency - 494.IBPluginDependency - 5.IBPluginDependency - 536.IBPluginDependency - 56.IBPluginDependency - 57.IBPluginDependency - 58.IBPluginDependency - 92.IBPluginDependency - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - - - - YES - - - - - - YES - - - - - 541 - - - - YES - - AppController - NSObject - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - id - id - - - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - - exitFullScreen: - id - - - toggleFullScreen: - id - - - - - YES - - YES - glView - window - - - YES - EAGLView - NSWindow - - - - YES - - YES - glView - window - - - YES - - glView - EAGLView - - - window - NSWindow - - - - - IBProjectSource - ./Classes/AppController.h - - - - EAGLView - NSOpenGLView - - IBProjectSource - ./Classes/EAGLView.h - - - - - 0 - IBCocoaFramework - - com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 - - - YES - 3 - - YES - - YES - NSMenuCheckmark - NSMenuMixedState - - - YES - {9, 8} - {7, 2} - - - - diff --git a/samples/Javascript/MoonWarriors/proj.mac/main.cpp b/samples/Javascript/MoonWarriors/proj.mac/main.cpp deleted file mode 100644 index f572fb10f2..0000000000 --- a/samples/Javascript/MoonWarriors/proj.mac/main.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010 cocos2d-x.org - - 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 "AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -int main(int argc, char *argv[]) -{ - AppDelegate app; - EGLView eglView; - eglView.init("MoonWarriors", 480, 720); - return Application::getInstance()->run(); -} - diff --git a/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj b/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj deleted file mode 100644 index d0dfa15e88..0000000000 --- a/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj +++ /dev/null @@ -1,235 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {1DB7C0FC-46FF-4A1B-82E0-C6244EEEC4C2} - MoonWarriors - - - - Application - Unicode - v100 - v110 - v110_xp - - - Application - Unicode - v100 - v110 - v110_xp - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.40219.1 - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - false - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - false - AllRules.ruleset - - - AllRules.ruleset - - - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - - _DEBUG;%(PreprocessorDefinitions) - false - Win32 - true - $(IntDir)testjs.tlb - testjs.h - - - testjs_i.c - testjs_p.c - - - Disabled - .;..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;_DEBUG;DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - - - Level3 - EditAndContinue - 4267;4251;4244;%(DisableSpecificWarnings) - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - - - - libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) - $(OutDir);%(AdditionalLibraryDirectories) - true - Windows - MachineX86 - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -if exist "$(OutDir)\MoonWarriorsRes" rd /s /q "$(OutDir)\MoonWarriorsRes" -mkdir "$(OutDir)\MoonWarriorsRes" -xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\MoonWarriorsRes" /e /Y -xcopy "$(ProjectDir)..\..\Shared\games\MoonWarriors" "$(OutDir)\MoonWarriorsRes\" /e /Y - Copy js and resource files. - - - - - NDEBUG;%(PreprocessorDefinitions) - false - Win32 - true - $(IntDir)testjs.tlb - testjs.h - - - testjs_i.c - testjs_p.c - - - .;..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;NDEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - MultiThreadedDLL - - - Level3 - - - 4267;4251;4244;%(DisableSpecificWarnings) - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - - - - libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) - $(OutDir);%(AdditionalLibraryDirectories) - Windows - MachineX86 - true - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -if exist "$(OutDir)\MoonWarriorsRes" rd /s /q "$(OutDir)\MoonWarriorsRes" -mkdir "$(OutDir)\MoonWarriorsRes" -xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\MoonWarriorsRes" /e /Y -xcopy "$(ProjectDir)..\..\Shared\games\MoonWarriors" "$(OutDir)\MoonWarriorsRes\" /e /Y - Copy js and resource files. - - - - - - - - - - - - - - - - - - - - {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - - - {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - - - {811c0dab-7b96-4bd3-a154-b7572b58e4ab} - - - {b57cf53f-2e49-4031-9822-047cc0e6bde2} - - - {7e06e92c-537a-442b-9e4a-4761c84f8a1a} - - - {df2638c0-8128-4847-867c-6eafe3dee7b5} - - - {21070e58-eec6-4e16-8b4f-6d083df55790} - - - {f9da0fc1-651b-457b-962e-a4d61cebf5fd} - - - {625f7391-9a91-48a1-8cfc-79508c822637} - - - {68f5f371-bd7b-4c30-ae5b-0b08f22e0cde} - - - {39379840-825a-45a0-b363-c09ffef864bd} - - - {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} - - - {21b2c324-891f-48ea-ad1a-5ae13de12e28} - - - {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} - - - - - - \ No newline at end of file diff --git a/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj.filters b/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj.filters deleted file mode 100644 index 56df37ce6f..0000000000 --- a/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj.filters +++ /dev/null @@ -1,44 +0,0 @@ - - - - - {ca9c9e15-d942-43a1-aa7a-5f0b74ca1afd} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;jpg;jpeg;jpe;png;manifest - - - {ccb2323b-1cfa-41ea-bcf4-ba5f07309396} - - - {e93a77e1-af1e-4400-87d3-504b62ebdbb0} - - - - - win32 - - - Classes - - - - - win32 - - - win32 - - - Classes - - - - - resource - - - - - resource - - - \ No newline at end of file diff --git a/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj.user b/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj.user deleted file mode 100644 index 475efbea21..0000000000 --- a/samples/Javascript/MoonWarriors/proj.win32/MoonWarriors.vcxproj.user +++ /dev/null @@ -1,11 +0,0 @@ - - - - $(OutDir)\MoonWarriorsRes - WindowsLocalDebugger - - - $(OutDir)\MoonWarriorsRes - WindowsLocalDebugger - - \ No newline at end of file diff --git a/samples/Javascript/MoonWarriors/proj.win32/main.h b/samples/Javascript/MoonWarriors/proj.win32/main.h deleted file mode 100644 index e29aeedb3a..0000000000 --- a/samples/Javascript/MoonWarriors/proj.win32/main.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef __MAIN_H__ -#define __MAIN_H__ - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -// Windows Header Files: -#include - -// C RunTime Header Files -#include "CCStdC.h" - -#endif // __WINMAIN_H__ diff --git a/samples/Javascript/MoonWarriors/proj.win32/res/testjs.ico b/samples/Javascript/MoonWarriors/proj.win32/res/testjs.ico deleted file mode 100644 index feaf932a74..0000000000 Binary files a/samples/Javascript/MoonWarriors/proj.win32/res/testjs.ico and /dev/null differ diff --git a/samples/Javascript/MoonWarriors/proj.win32/resource.h b/samples/Javascript/MoonWarriors/proj.win32/resource.h deleted file mode 100644 index a4cfa38af8..0000000000 --- a/samples/Javascript/MoonWarriors/proj.win32/resource.h +++ /dev/null @@ -1,20 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by testjs.RC -// - -#define IDS_PROJNAME 100 -#define IDR_TESTJS 100 - -#define ID_FILE_NEW_WINDOW 32771 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 201 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 32775 -#endif -#endif diff --git a/samples/Javascript/MoonWarriors/proj.win32/testjs.rc b/samples/Javascript/MoonWarriors/proj.win32/testjs.rc deleted file mode 100644 index 99e7360397..0000000000 --- a/samples/Javascript/MoonWarriors/proj.win32/testjs.rc +++ /dev/null @@ -1,86 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#define APSTUDIO_HIDDEN_SYMBOLS -#include "windows.h" -#undef APSTUDIO_HIDDEN_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -#endif // APSTUDIO_INVOKED - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDR_MAINFRAME ICON "res\\testjs.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "CompanyName", "\0" - VALUE "FileDescription", "testjs Module\0" - VALUE "FileVersion", "1, 0, 0, 1\0" - VALUE "InternalName", "testjs\0" - VALUE "LegalCopyright", "Copyright \0" - VALUE "OriginalFilename", "testjs.exe\0" - VALUE "ProductName", "testjs Module\0" - VALUE "ProductVersion", "1, 0, 0, 1\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 0x04B0 - END -END - -///////////////////////////////////////////////////////////////////////////// -#endif // !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) diff --git a/samples/Javascript/Shared b/samples/Javascript/Shared deleted file mode 160000 index 301c8e9f6b..0000000000 --- a/samples/Javascript/Shared +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 301c8e9f6ba2f9d9d6012f6581cb40eddcc3840a diff --git a/samples/Javascript/TestJavascript/Classes/AppDelegate.h b/samples/Javascript/TestJavascript/Classes/AppDelegate.h deleted file mode 100644 index df8f12f70f..0000000000 --- a/samples/Javascript/TestJavascript/Classes/AppDelegate.h +++ /dev/null @@ -1,45 +0,0 @@ -// -// GCTestAppDelegate.h -// GCTest -// -// Created by Rohan Kuruvilla on 06/08/2012. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -#ifndef _APP_DELEGATE_H_ -#define _APP_DELEGATE_H_ - -#include "CCApplication.h" -/** - @brief The cocos2d Application. - - The reason for implement as private inheritance is to hide some interface call by Director. - */ -class AppDelegate : private cocos2d::Application -{ -public: - AppDelegate(); - virtual ~AppDelegate(); - - /** - @brief Implement Director and Scene init code here. - @return true Initialize success, app continue. - @return false Initialize failed, app terminate. - */ - virtual bool applicationDidFinishLaunching(); - - /** - @brief The function be called when the application enter background - @param the pointer of the application - */ - virtual void applicationDidEnterBackground(); - - /** - @brief The function be called when the application enter foreground - @param the pointer of the application - */ - virtual void applicationWillEnterForeground(); -}; - -#endif // _APP_DELEGATE_H_ - diff --git a/samples/Javascript/TestJavascript/proj.android/.classpath b/samples/Javascript/TestJavascript/proj.android/.classpath deleted file mode 100644 index 0b08408342..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/samples/Javascript/TestJavascript/proj.android/.project b/samples/Javascript/TestJavascript/proj.android/.project deleted file mode 100644 index 48030971da..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/.project +++ /dev/null @@ -1,76 +0,0 @@ - - - TestJavascript - - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - org.eclipse.wst.jsdt.core.jsNature - - - - Classes - 2 - COCOS2DX/samples/Javascript/TestJavascript/Classes - - - cocos2dx - 2 - COCOS2DX/cocos2dx - - - cocosdenshion - 2 - COCOS2DX/CocosDenshion - - - extensions - 2 - COCOS2DX/extensions - - - scripting - 2 - COCOS2DX/scripting - - - diff --git a/samples/Javascript/TestJavascript/proj.android/.settings/.jsdtscope b/samples/Javascript/TestJavascript/proj.android/.settings/.jsdtscope deleted file mode 100644 index bbf7a521cc..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/.settings/.jsdtscope +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/samples/Javascript/TestJavascript/proj.android/.settings/org.eclipse.cdt.codan.core.prefs b/samples/Javascript/TestJavascript/proj.android/.settings/org.eclipse.cdt.codan.core.prefs deleted file mode 100644 index bad4196993..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/.settings/org.eclipse.cdt.codan.core.prefs +++ /dev/null @@ -1,68 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.cdt.codan.checkers.errnoreturn=-Warning -org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.checkers.errreturnvalue=-Error -org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.checkers.noreturn=-Error -org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=-Error -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},no_break_comment\=>"no break",last_case_param\=>true,empty_case_param\=>false} -org.eclipse.cdt.codan.internal.checkers.CatchByReference=-Warning -org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},unknown\=>false,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=-Error -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=-Warning -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},skip\=>true} -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidArguments=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.OverloadProblem=-Error -org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},paramNot\=>false} -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},else\=>false,afterelse\=>false} -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>("@(\#)","$Id")} -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -useParentScope=false diff --git a/samples/Javascript/TestJavascript/proj.android/.settings/org.eclipse.wst.jsdt.ui.prefs b/samples/Javascript/TestJavascript/proj.android/.settings/org.eclipse.wst.jsdt.ui.prefs deleted file mode 100644 index 6bf5ec1a0a..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/.settings/org.eclipse.wst.jsdt.ui.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.jsdt.ui.text.custom_code_templates= diff --git a/samples/Javascript/TestJavascript/proj.android/.settings/org.eclipse.wst.jsdt.ui.superType.container b/samples/Javascript/TestJavascript/proj.android/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/samples/Javascript/TestJavascript/proj.android/.settings/org.eclipse.wst.jsdt.ui.superType.name b/samples/Javascript/TestJavascript/proj.android/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/samples/Javascript/TestJavascript/proj.android/README.md b/samples/Javascript/TestJavascript/proj.android/README.md deleted file mode 100644 index 312835611a..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/README.md +++ /dev/null @@ -1,87 +0,0 @@ -## Prerequisites: - -* Android NDK -* Android SDK **OR** Eclipse ADT Bundle -* Android AVD target installed - -## Building project - -There are two ways of building Android projects. - -1. Eclipse -2. Command Line - -### Import Project in Eclipse - -#### Features: - -1. Complete workflow from Eclipse, including: - * Build C++. - * Clean C++. - * Build and Run whole project. - * Logcat view. - * Debug Java code. - * Javascript editor. - * Project management. -2. True C++ editing, including: - * Code completion. - * Jump to definition. - * Refactoring tools etc. - * Quick open C++ files. - - -#### Setup Eclipse Environment (only once) - - -**NOTE:** This step needs to be done only once to setup the Eclipse environment for cocos2d-x projects. Skip this section if you've done this before. - -1. Download Eclipse ADT bundle from [Google ADT homepage](http://developer.android.com/sdk/index.html) - - **OR** - - Install Eclipse with Java. Add ADT and CDT plugins. - -2. Only for Windows - 1. Install [Cygwin](http://www.cygwin.com/) with make (select make package from the list during the install). - 2. Add `Cygwin\bin` directory to system PATH variable. - 3. Add this line `none /cygdrive cygdrive binary,noacl,posix=0,user 0 0` to `Cygwin\etc\fstab` file. - -3. Set up Variables: - 1. Path Variable `COCOS2DX`: - * Eclipse->Preferences->General->Workspace->**Linked Resources** - * Click **New** button to add a Path Variable `COCOS2DX` pointing to the root cocos2d-x directory. - ![Example](https://lh5.googleusercontent.com/-oPpk9kg3e5w/UUOYlq8n7aI/AAAAAAAAsdQ/zLA4eghBH9U/s400/cocos2d-x-eclipse-vars.png) - - 2. C/C++ Environment Variable `NDK_ROOT`: - * Eclipse->Preferences->C/C++->Build->**Environment**. - * Click **Add** button and add a new variable `NDK_ROOT` pointing to the root NDK directory. - ![Example](https://lh3.googleusercontent.com/-AVcY8IAT0_g/UUOYltoRobI/AAAAAAAAsdM/22D2J9u3sig/s400/cocos2d-x-eclipse-ndk.png) - * Only for Windows: Add new variables **CYGWIN** with value `nodosfilewarning` and **SHELLOPTS** with value `igncr` - -4. Import libcocos2dx library project: - 1. File->New->Project->Android Project From Existing Code. - 2. Click **Browse** button and open `cocos2d-x/cocos2dx/platform/android/java` directory. - 3. Click **Finish** to add project. - -#### Adding and running from Eclipse - -![Example](https://lh3.googleusercontent.com/-SLBOu6e3QbE/UUOcOXYaGqI/AAAAAAAAsdo/tYBY2SylOSM/s288/cocos2d-x-eclipse-project-from-code.png) ![Import](https://lh5.googleusercontent.com/-XzC9Pn65USc/UUOcOTAwizI/AAAAAAAAsdk/4b6YM-oim9Y/s400/cocos2d-x-eclipse-import-project.png) - -1. File->New->Project->Android Project From Existing Code -2. **Browse** to your project directory. eg: `cocos2d-x/cocos2dx/samples/Cpp/TestCpp/proj.android/` -3. Add the project -4. Click **Run** or **Debug** to compile C++ followed by Java and to run on connected device or emulator. - - -### Running project from Command Line - - $ cd cocos2d-x/samples/Cpp/TestCpp/proj.android/ - $ export NDK_ROOT=/path/to/ndk - $ ./build_native.sh - $ ant debug install - -If the last command results in sdk.dir missing error then do: - - $ android list target - $ android update project -p . -t (id from step 6) - $ android update project -p cocos2d-x/cocos2dx/platform/android/java/ -t (id from step 6) diff --git a/samples/Javascript/TestJavascript/proj.android/ant.properties b/samples/Javascript/TestJavascript/proj.android/ant.properties deleted file mode 100644 index f8af38bfb4..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/ant.properties +++ /dev/null @@ -1 +0,0 @@ -aapt.ignore.assets="!*.pvr.gz:!*.gz:!.svn:!.git:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*.scc:*~" diff --git a/samples/Javascript/TestJavascript/proj.android/jni/Application.mk b/samples/Javascript/TestJavascript/proj.android/jni/Application.mk deleted file mode 100644 index 47d8add103..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/jni/Application.mk +++ /dev/null @@ -1,5 +0,0 @@ -APP_STL := gnustl_static - -# add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] -# in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/TestJavascript/proj.android/jni/testjavascript/main.cpp b/samples/Javascript/TestJavascript/proj.android/jni/testjavascript/main.cpp deleted file mode 100644 index 9793beefb1..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/jni/testjavascript/main.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "AppDelegate.h" -#include "cocos2d.h" -#include "platform/android/jni/JniHelper.h" -#include "CCEventType.h" -#include -#include - -#define LOG_TAG "main" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) - -using namespace cocos2d; - -void cocos_android_app_init (struct android_app* app) { - LOGD("cocos_android_app_init"); - AppDelegate *pAppDelegate = new AppDelegate(); -} diff --git a/samples/Javascript/TestJavascript/proj.android/proguard-project.txt b/samples/Javascript/TestJavascript/proj.android/proguard-project.txt deleted file mode 100644 index f2fe1559a2..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/proguard-project.txt +++ /dev/null @@ -1,20 +0,0 @@ -# To enable ProGuard in your project, edit project.properties -# to define the proguard.config property as described in that file. -# -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in ${sdk.dir}/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the ProGuard -# include property in project.properties. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/samples/Javascript/TestJavascript/proj.android/project.properties b/samples/Javascript/TestJavascript/proj.android/project.properties deleted file mode 100644 index 0a6dc6664d..0000000000 --- a/samples/Javascript/TestJavascript/proj.android/project.properties +++ /dev/null @@ -1,13 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "ant.properties", and override values to adapt the script to your -# project structure. - -# Project target. -target=android-10 - -android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Javascript/TestJavascript/proj.ios/AppController.h b/samples/Javascript/TestJavascript/proj.ios/AppController.h deleted file mode 100644 index 10287bd13f..0000000000 --- a/samples/Javascript/TestJavascript/proj.ios/AppController.h +++ /dev/null @@ -1,17 +0,0 @@ -// -// testjsAppController.h -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -@class RootViewController; - -@interface AppController : NSObject { - UIWindow *window; - RootViewController *viewController; -} - -@end - diff --git a/samples/Javascript/TestJavascript/proj.ios/AppController.mm b/samples/Javascript/TestJavascript/proj.ios/AppController.mm deleted file mode 100644 index 5cd84017c9..0000000000 --- a/samples/Javascript/TestJavascript/proj.ios/AppController.mm +++ /dev/null @@ -1,121 +0,0 @@ -// -// testjsAppController.mm -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// -#import -#import "AppController.h" -#import "cocos2d.h" -#import "EAGLView.h" -#import "AppDelegate.h" - -#import "RootViewController.h" - -@implementation AppController - -#pragma mark - -#pragma mark Application lifecycle - -// cocos2d application instance -static AppDelegate s_sharedApplication; - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - - // Override point for customization after application launch. - - // Add the view controller's view to the window and display. - window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; - CCEAGLView *__glView = [CCEAGLView viewWithFrame: [window bounds] - pixelFormat: kEAGLColorFormatRGBA8 - depthFormat: GL_DEPTH24_STENCIL8_OES - preserveBackbuffer: NO - sharegroup: nil - multiSampling: NO - numberOfSamples: 0 ]; - - [__glView setMultipleTouchEnabled:YES]; - - // Use RootViewController manage CCEAGLView - viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; - viewController.wantsFullScreenLayout = YES; - viewController.view = __glView; - - // Set RootViewController to window - if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) - { - // warning: addSubView doesn't work on iOS6 - [window addSubview: viewController.view]; - } - else - { - // use this method on ios6 - [window setRootViewController:viewController]; - } - - [window makeKeyAndVisible]; - - [[UIApplication sharedApplication] setStatusBarHidden: YES]; - - cocos2d::Application::getInstance()->run(); - return YES; -} - - -- (void)applicationWillResignActive:(UIApplication *)application { - /* - Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. - */ - cocos2d::Director::getInstance()->pause(); -} - -- (void)applicationDidBecomeActive:(UIApplication *)application { - /* - Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - */ - cocos2d::Director::getInstance()->resume(); -} - -- (void)applicationDidEnterBackground:(UIApplication *)application { - /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - If your application supports background execution, called instead of applicationWillTerminate: when the user quits. - */ - cocos2d::Application::getInstance()->applicationDidEnterBackground(); -} - -- (void)applicationWillEnterForeground:(UIApplication *)application { - /* - Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. - */ - cocos2d::Application::getInstance()->applicationWillEnterForeground(); -} - -- (void)applicationWillTerminate:(UIApplication *)application { - /* - Called when the application is about to terminate. - See also applicationDidEnterBackground:. - */ -} - - -#pragma mark - -#pragma mark Memory management - -- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { - /* - Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. - */ - cocos2d::Director::getInstance()->purgeCachedData(); -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end - diff --git a/samples/Javascript/TestJavascript/proj.ios/Default-568h@2x.png.REMOVED.git-id b/samples/Javascript/TestJavascript/proj.ios/Default-568h@2x.png.REMOVED.git-id deleted file mode 100644 index 8f5838f3a8..0000000000 --- a/samples/Javascript/TestJavascript/proj.ios/Default-568h@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -66c6d1cead373b45218424f6a82f370897e443e4 \ No newline at end of file diff --git a/samples/Javascript/TestJavascript/proj.ios/Default@2x.png.REMOVED.git-id b/samples/Javascript/TestJavascript/proj.ios/Default@2x.png.REMOVED.git-id deleted file mode 100644 index 8843505b20..0000000000 --- a/samples/Javascript/TestJavascript/proj.ios/Default@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -84689888a14a2123d2b39f7f2f61be8c15207479 \ No newline at end of file diff --git a/samples/Javascript/TestJavascript/proj.ios/Prefix.pch b/samples/Javascript/TestJavascript/proj.ios/Prefix.pch deleted file mode 100644 index b056d8694a..0000000000 --- a/samples/Javascript/TestJavascript/proj.ios/Prefix.pch +++ /dev/null @@ -1,8 +0,0 @@ -// -// Prefix header for all source files of the 'testjs' target in the 'testjs' project -// - -#ifdef __OBJC__ - #import - #import -#endif diff --git a/samples/Javascript/TestJavascript/proj.ios/RootViewController.h b/samples/Javascript/TestJavascript/proj.ios/RootViewController.h deleted file mode 100644 index 11dfc4bf88..0000000000 --- a/samples/Javascript/TestJavascript/proj.ios/RootViewController.h +++ /dev/null @@ -1,33 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2010 Ricardo Quesada - - 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. - ****************************************************************************/ - -#import - - -@interface RootViewController : UIViewController { - -} -- (BOOL)prefersStatusBarHidden; -@end diff --git a/samples/Javascript/TestJavascript/proj.ios/RootViewController.mm b/samples/Javascript/TestJavascript/proj.ios/RootViewController.mm deleted file mode 100644 index 8438d7a420..0000000000 --- a/samples/Javascript/TestJavascript/proj.ios/RootViewController.mm +++ /dev/null @@ -1,79 +0,0 @@ -// -// testjsAppController.h -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -#import "RootViewController.h" - - -@implementation RootViewController - -/* - // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { - if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { - // Custom initialization - } - return self; -} -*/ - -/* -// Implement loadView to create a view hierarchy programmatically, without using a nib. -- (void)loadView { -} -*/ - -/* -// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -- (void)viewDidLoad { - [super viewDidLoad]; -} - -*/ -// Override to allow orientations other than the default portrait orientation. -// This method is deprecated on ios6 -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { - return UIInterfaceOrientationIsLandscape( interfaceOrientation ); -} - -// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead -- (NSUInteger) supportedInterfaceOrientations{ -#ifdef __IPHONE_6_0 - return UIInterfaceOrientationMaskAllButUpsideDown; -#endif -} - -- (BOOL) shouldAutorotate { - return YES; -} - -//fix not hide status on ios7 -- (BOOL)prefersStatusBarHidden -{ - return YES; -} - -- (void)didReceiveMemoryWarning { - // Releases the view if it doesn't have a superview. - [super didReceiveMemoryWarning]; - - // Release any cached data, images, etc that aren't in use. -} - -- (void)viewDidUnload { - [super viewDidUnload]; - // Release any retained subviews of the main view. - // e.g. self.myOutlet = nil; -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end diff --git a/samples/Javascript/TestJavascript/proj.ios/main.m b/samples/Javascript/TestJavascript/proj.ios/main.m deleted file mode 100644 index e3dedca28b..0000000000 --- a/samples/Javascript/TestJavascript/proj.ios/main.m +++ /dev/null @@ -1,17 +0,0 @@ -// -// main.m -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -#import - -int main(int argc, char *argv[]) { - - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - int retVal = UIApplicationMain(argc, argv, nil, @"AppController"); - [pool release]; - return retVal; -} diff --git a/samples/Javascript/TestJavascript/proj.mac/Icon.icns.REMOVED.git-id b/samples/Javascript/TestJavascript/proj.mac/Icon.icns.REMOVED.git-id deleted file mode 100644 index 9874ec6979..0000000000 --- a/samples/Javascript/TestJavascript/proj.mac/Icon.icns.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Javascript/TestJavascript/proj.mac/en.lproj/InfoPlist.strings b/samples/Javascript/TestJavascript/proj.mac/en.lproj/InfoPlist.strings deleted file mode 100644 index 477b28ff8f..0000000000 --- a/samples/Javascript/TestJavascript/proj.mac/en.lproj/InfoPlist.strings +++ /dev/null @@ -1,2 +0,0 @@ -/* Localized versions of Info.plist keys */ - diff --git a/samples/Javascript/TestJavascript/proj.mac/en.lproj/MainMenu.xib b/samples/Javascript/TestJavascript/proj.mac/en.lproj/MainMenu.xib deleted file mode 100644 index 3dacdedbd0..0000000000 --- a/samples/Javascript/TestJavascript/proj.mac/en.lproj/MainMenu.xib +++ /dev/null @@ -1,812 +0,0 @@ - - - - 1060 - 10K549 - 1938 - 1038.36 - 461.00 - - com.apple.InterfaceBuilder.CocoaPlugin - 1938 - - - YES - NSMenuItem - NSCustomObject - NSMenu - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - - - PluginDependencyRecalculationVersion - - - - YES - - NSApplication - - - FirstResponder - - - NSApplication - - - AMainMenu - - YES - - - TestCpp - - 1048576 - 2147483647 - - NSImage - NSMenuCheckmark - - - NSImage - NSMenuMixedState - - submenuAction: - - TestCpp - - YES - - - About TestCpp - - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Preferences… - , - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Services - - 1048576 - 2147483647 - - - submenuAction: - - Services - - YES - - _NSServicesMenu - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Hide TestCpp - h - 1048576 - 2147483647 - - - - - - Hide Others - h - 1572864 - 2147483647 - - - - - - Show All - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Quit TestCpp - q - 1048576 - 2147483647 - - - - - _NSAppleMenu - - - - - View - - 1048576 - 2147483647 - - - submenuAction: - - View - - YES - - - Toggle Fullscreen - f - 1048576 - 2147483647 - - - - - - - - - Window - - 1048576 - 2147483647 - - - submenuAction: - - Window - - YES - - - Minimize - m - 1048576 - 2147483647 - - - - - - Zoom - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Bring All to Front - - 1048576 - 2147483647 - - - - - _NSWindowsMenu - - - - - Help - - 2147483647 - - - submenuAction: - - Help - - YES - - - TestCpp Help - ? - 1048576 - 2147483647 - - - - - _NSHelpMenu - - - - _NSMainMenu - - - AppController - - - NSFontManager - - - - - YES - - - terminate: - - - - 449 - - - - orderFrontStandardAboutPanel: - - - - 142 - - - - delegate - - - - 495 - - - - performMiniaturize: - - - - 37 - - - - arrangeInFront: - - - - 39 - - - - performZoom: - - - - 240 - - - - hide: - - - - 367 - - - - hideOtherApplications: - - - - 368 - - - - unhideAllApplications: - - - - 370 - - - - showHelp: - - - - 493 - - - - toggleFullScreen: - - - - 537 - - - - - YES - - 0 - - YES - - - - - - -2 - - - File's Owner - - - -1 - - - First Responder - - - -3 - - - Application - - - 29 - - - YES - - - - - - - - - 19 - - - YES - - - - - - 56 - - - YES - - - - - - 57 - - - YES - - - - - - - - - - - - - - - - 58 - - - - - 134 - - - - - 150 - - - - - 136 - - - - - 144 - - - - - 129 - - - - - 143 - - - - - 236 - - - - - 131 - - - YES - - - - - - 149 - - - - - 145 - - - - - 130 - - - - - 24 - - - YES - - - - - - - - - 92 - - - - - 5 - - - - - 239 - - - - - 23 - - - - - 295 - - - YES - - - - - - 296 - - - YES - - - - - - 420 - - - - - 490 - - - YES - - - - - - 491 - - - YES - - - - - - 492 - - - - - 494 - - - - - 536 - - - - - - - YES - - YES - -1.IBPluginDependency - -2.IBPluginDependency - -3.IBPluginDependency - 129.IBPluginDependency - 130.IBPluginDependency - 131.IBPluginDependency - 134.IBPluginDependency - 136.IBPluginDependency - 143.IBPluginDependency - 144.IBPluginDependency - 145.IBPluginDependency - 149.IBPluginDependency - 150.IBPluginDependency - 19.IBPluginDependency - 23.IBPluginDependency - 236.IBPluginDependency - 239.IBPluginDependency - 24.IBPluginDependency - 29.IBPluginDependency - 295.IBPluginDependency - 296.IBPluginDependency - 420.IBPluginDependency - 490.IBPluginDependency - 491.IBPluginDependency - 492.IBPluginDependency - 494.IBPluginDependency - 5.IBPluginDependency - 536.IBPluginDependency - 56.IBPluginDependency - 57.IBPluginDependency - 58.IBPluginDependency - 92.IBPluginDependency - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - - - - YES - - - - - - YES - - - - - 541 - - - - YES - - AppController - NSObject - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - id - id - - - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - - exitFullScreen: - id - - - toggleFullScreen: - id - - - - - YES - - YES - glView - window - - - YES - EAGLView - NSWindow - - - - YES - - YES - glView - window - - - YES - - glView - EAGLView - - - window - NSWindow - - - - - IBProjectSource - ./Classes/AppController.h - - - - EAGLView - NSOpenGLView - - IBProjectSource - ./Classes/EAGLView.h - - - - - 0 - IBCocoaFramework - - com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 - - - YES - 3 - - YES - - YES - NSMenuCheckmark - NSMenuMixedState - - - YES - {9, 8} - {7, 2} - - - - diff --git a/samples/Javascript/TestJavascript/proj.mac/main.cpp b/samples/Javascript/TestJavascript/proj.mac/main.cpp deleted file mode 100644 index 01efc8b89b..0000000000 --- a/samples/Javascript/TestJavascript/proj.mac/main.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010 cocos2d-x.org - - 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 "AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -int main(int argc, char *argv[]) -{ - AppDelegate app; - EGLView eglView; - eglView.init("TestJavascript",900,640); - return Application::getInstance()->run(); -} - diff --git a/samples/Javascript/TestJavascript/proj.win32/main.cpp b/samples/Javascript/TestJavascript/proj.win32/main.cpp deleted file mode 100644 index 0f4c16d7c8..0000000000 --- a/samples/Javascript/TestJavascript/proj.win32/main.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "main.h" -#include "AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -// uncomment below line, open debug console -// #define USE_WIN32_CONSOLE - -int APIENTRY _tWinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - UNREFERENCED_PARAMETER(hPrevInstance); - UNREFERENCED_PARAMETER(lpCmdLine); - -#ifdef USE_WIN32_CONSOLE - AllocConsole(); - freopen("CONIN$", "r", stdin); - freopen("CONOUT$", "w", stdout); - freopen("CONOUT$", "w", stderr); -#endif - - // create the application instance - AppDelegate app; - EGLView eglView; - eglView.init("TestJavascript",900,640); - - int ret = Application::getInstance()->run(); - -#ifdef USE_WIN32_CONSOLE - FreeConsole(); -#endif - - return ret; -} diff --git a/samples/Javascript/TestJavascript/proj.win32/main.h b/samples/Javascript/TestJavascript/proj.win32/main.h deleted file mode 100644 index e29aeedb3a..0000000000 --- a/samples/Javascript/TestJavascript/proj.win32/main.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef __MAIN_H__ -#define __MAIN_H__ - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -// Windows Header Files: -#include - -// C RunTime Header Files -#include "CCStdC.h" - -#endif // __WINMAIN_H__ diff --git a/samples/Javascript/TestJavascript/proj.win32/res/testjs.ico b/samples/Javascript/TestJavascript/proj.win32/res/testjs.ico deleted file mode 100644 index feaf932a74..0000000000 Binary files a/samples/Javascript/TestJavascript/proj.win32/res/testjs.ico and /dev/null differ diff --git a/samples/Javascript/TestJavascript/proj.win32/resource.h b/samples/Javascript/TestJavascript/proj.win32/resource.h deleted file mode 100644 index a4cfa38af8..0000000000 --- a/samples/Javascript/TestJavascript/proj.win32/resource.h +++ /dev/null @@ -1,20 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by testjs.RC -// - -#define IDS_PROJNAME 100 -#define IDR_TESTJS 100 - -#define ID_FILE_NEW_WINDOW 32771 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 201 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 32775 -#endif -#endif diff --git a/samples/Javascript/TestJavascript/proj.win32/testjs.rc b/samples/Javascript/TestJavascript/proj.win32/testjs.rc deleted file mode 100644 index 99e7360397..0000000000 --- a/samples/Javascript/TestJavascript/proj.win32/testjs.rc +++ /dev/null @@ -1,86 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#define APSTUDIO_HIDDEN_SYMBOLS -#include "windows.h" -#undef APSTUDIO_HIDDEN_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -#endif // APSTUDIO_INVOKED - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDR_MAINFRAME ICON "res\\testjs.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "CompanyName", "\0" - VALUE "FileDescription", "testjs Module\0" - VALUE "FileVersion", "1, 0, 0, 1\0" - VALUE "InternalName", "testjs\0" - VALUE "LegalCopyright", "Copyright \0" - VALUE "OriginalFilename", "testjs.exe\0" - VALUE "ProductName", "testjs Module\0" - VALUE "ProductVersion", "1, 0, 0, 1\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 0x04B0 - END -END - -///////////////////////////////////////////////////////////////////////////// -#endif // !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) diff --git a/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp b/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp deleted file mode 100644 index 663cd87769..0000000000 --- a/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.cpp +++ /dev/null @@ -1,102 +0,0 @@ -#include "AppDelegate.h" - -#include "cocos2d.h" -#include "SimpleAudioEngine.h" -#include "ScriptingCore.h" -#include "jsb_cocos2dx_auto.hpp" -#include "jsb_cocos2dx_extension_auto.hpp" -#include "jsb_cocos2dx_builder_auto.hpp" -#include "extension/jsb_cocos2dx_extension_manual.h" -#include "cocos2d_specifics.hpp" -#include "chipmunk/js_bindings_chipmunk_registration.h" -#include "cocosbuilder/js_bindings_ccbreader.h" -#include "localstorage/js_bindings_system_registration.h" -#include "jsb_opengl_registration.h" - -USING_NS_CC; -using namespace CocosDenshion; - -AppDelegate::AppDelegate() -{ -} - -AppDelegate::~AppDelegate() -{ - ScriptEngineManager::destroyInstance(); -} - -bool AppDelegate::applicationDidFinishLaunching() -{ - // initialize director - auto pDirector = Director::getInstance(); - pDirector->setOpenGLView(EGLView::getInstance()); - - // turn on display FPS - pDirector->setDisplayStats(true); - - // set FPS. the default value is 1.0/60 if you don't call this - pDirector->setAnimationInterval(1.0 / 60); - - EGLView::getInstance()->setDesignResolutionSize(480, 320, ResolutionPolicy::FIXED_HEIGHT); - - FileUtils::getInstance()->addSearchPath("script"); - - ScriptingCore* sc = ScriptingCore::getInstance(); - sc->addRegisterCallback(register_all_cocos2dx); - sc->addRegisterCallback(register_all_cocos2dx_extension); - sc->addRegisterCallback(register_all_cocos2dx_extension_manual); - sc->addRegisterCallback(register_cocos2dx_js_extensions); - sc->addRegisterCallback(jsb_register_chipmunk); - sc->addRegisterCallback(register_all_cocos2dx_builder); - 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(); -#endif - - auto pEngine = ScriptingCore::getInstance(); - ScriptEngineManager::getInstance()->setScriptEngine(pEngine); - ScriptingCore::getInstance()->runScript("boot-jsb.js"); - - return true; -} - -void handle_signal(int signal) { - static int internal_state = 0; - ScriptingCore* sc = ScriptingCore::getInstance(); - // should start everything back - auto director = Director::getInstance(); - if (director->getRunningScene()) { - director->popToRootScene(); - } else { - PoolManager::sharedPoolManager()->finalize(); - if (internal_state == 0) { - //sc->dumpRoot(NULL, 0, NULL); - sc->start(); - internal_state = 1; - } else { - sc->runScript("hello.js"); - internal_state = 0; - } - } -} - -// This function will be called when the app is inactive. When comes a phone call,it's be invoked too -void AppDelegate::applicationDidEnterBackground() -{ - Director::getInstance()->stopAnimation(); - SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); - SimpleAudioEngine::getInstance()->pauseAllEffects(); -} - -// this function will be called when the app is active again -void AppDelegate::applicationWillEnterForeground() -{ - Director::getInstance()->startAnimation(); - SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); - SimpleAudioEngine::getInstance()->resumeAllEffects(); -} diff --git a/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.h b/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.h deleted file mode 100644 index df8f12f70f..0000000000 --- a/samples/Javascript/WatermelonWithMe/Classes/AppDelegate.h +++ /dev/null @@ -1,45 +0,0 @@ -// -// GCTestAppDelegate.h -// GCTest -// -// Created by Rohan Kuruvilla on 06/08/2012. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -#ifndef _APP_DELEGATE_H_ -#define _APP_DELEGATE_H_ - -#include "CCApplication.h" -/** - @brief The cocos2d Application. - - The reason for implement as private inheritance is to hide some interface call by Director. - */ -class AppDelegate : private cocos2d::Application -{ -public: - AppDelegate(); - virtual ~AppDelegate(); - - /** - @brief Implement Director and Scene init code here. - @return true Initialize success, app continue. - @return false Initialize failed, app terminate. - */ - virtual bool applicationDidFinishLaunching(); - - /** - @brief The function be called when the application enter background - @param the pointer of the application - */ - virtual void applicationDidEnterBackground(); - - /** - @brief The function be called when the application enter foreground - @param the pointer of the application - */ - virtual void applicationWillEnterForeground(); -}; - -#endif // _APP_DELEGATE_H_ - diff --git a/samples/Javascript/WatermelonWithMe/proj.android/.classpath b/samples/Javascript/WatermelonWithMe/proj.android/.classpath deleted file mode 100644 index 0b08408342..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/samples/Javascript/WatermelonWithMe/proj.android/.project b/samples/Javascript/WatermelonWithMe/proj.android/.project deleted file mode 100644 index 1a3080f5bb..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/.project +++ /dev/null @@ -1,70 +0,0 @@ - - - WatermelonWithMe - - - - - - com.android.ide.eclipse.adt.ResourceManagerBuilder - - - - - com.android.ide.eclipse.adt.PreCompilerBuilder - - - - - org.eclipse.jdt.core.javabuilder - - - - - com.android.ide.eclipse.adt.ApkBuilder - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - com.android.ide.eclipse.adt.AndroidNature - org.eclipse.jdt.core.javanature - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - - Classes - 2 - COCOS2DX/samples/Javascript/WatermelonWithMe/Classes - - - cocos2dx - 2 - COCOS2DX/cocos2dx - - - cocosdenshion - 2 - COCOS2DX/CocosDenshion - - - extensions - 2 - COCOS2DX/extensions - - - scripting - 2 - COCOS2DX/scripting - - - diff --git a/samples/Javascript/WatermelonWithMe/proj.android/.settings/org.eclipse.cdt.codan.core.prefs b/samples/Javascript/WatermelonWithMe/proj.android/.settings/org.eclipse.cdt.codan.core.prefs deleted file mode 100644 index bad4196993..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/.settings/org.eclipse.cdt.codan.core.prefs +++ /dev/null @@ -1,68 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.cdt.codan.checkers.errnoreturn=-Warning -org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.checkers.errreturnvalue=-Error -org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.checkers.noreturn=-Error -org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=-Error -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},no_break_comment\=>"no break",last_case_param\=>true,empty_case_param\=>false} -org.eclipse.cdt.codan.internal.checkers.CatchByReference=-Warning -org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},unknown\=>false,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=-Error -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=-Warning -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},skip\=>true} -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidArguments=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.OverloadProblem=-Error -org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},paramNot\=>false} -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},else\=>false,afterelse\=>false} -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>("@(\#)","$Id")} -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -useParentScope=false diff --git a/samples/Javascript/WatermelonWithMe/proj.android/AndroidManifest.xml b/samples/Javascript/WatermelonWithMe/proj.android/AndroidManifest.xml deleted file mode 100644 index 2f6da28f49..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/AndroidManifest.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Javascript/WatermelonWithMe/proj.android/README.md b/samples/Javascript/WatermelonWithMe/proj.android/README.md deleted file mode 100644 index 312835611a..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/README.md +++ /dev/null @@ -1,87 +0,0 @@ -## Prerequisites: - -* Android NDK -* Android SDK **OR** Eclipse ADT Bundle -* Android AVD target installed - -## Building project - -There are two ways of building Android projects. - -1. Eclipse -2. Command Line - -### Import Project in Eclipse - -#### Features: - -1. Complete workflow from Eclipse, including: - * Build C++. - * Clean C++. - * Build and Run whole project. - * Logcat view. - * Debug Java code. - * Javascript editor. - * Project management. -2. True C++ editing, including: - * Code completion. - * Jump to definition. - * Refactoring tools etc. - * Quick open C++ files. - - -#### Setup Eclipse Environment (only once) - - -**NOTE:** This step needs to be done only once to setup the Eclipse environment for cocos2d-x projects. Skip this section if you've done this before. - -1. Download Eclipse ADT bundle from [Google ADT homepage](http://developer.android.com/sdk/index.html) - - **OR** - - Install Eclipse with Java. Add ADT and CDT plugins. - -2. Only for Windows - 1. Install [Cygwin](http://www.cygwin.com/) with make (select make package from the list during the install). - 2. Add `Cygwin\bin` directory to system PATH variable. - 3. Add this line `none /cygdrive cygdrive binary,noacl,posix=0,user 0 0` to `Cygwin\etc\fstab` file. - -3. Set up Variables: - 1. Path Variable `COCOS2DX`: - * Eclipse->Preferences->General->Workspace->**Linked Resources** - * Click **New** button to add a Path Variable `COCOS2DX` pointing to the root cocos2d-x directory. - ![Example](https://lh5.googleusercontent.com/-oPpk9kg3e5w/UUOYlq8n7aI/AAAAAAAAsdQ/zLA4eghBH9U/s400/cocos2d-x-eclipse-vars.png) - - 2. C/C++ Environment Variable `NDK_ROOT`: - * Eclipse->Preferences->C/C++->Build->**Environment**. - * Click **Add** button and add a new variable `NDK_ROOT` pointing to the root NDK directory. - ![Example](https://lh3.googleusercontent.com/-AVcY8IAT0_g/UUOYltoRobI/AAAAAAAAsdM/22D2J9u3sig/s400/cocos2d-x-eclipse-ndk.png) - * Only for Windows: Add new variables **CYGWIN** with value `nodosfilewarning` and **SHELLOPTS** with value `igncr` - -4. Import libcocos2dx library project: - 1. File->New->Project->Android Project From Existing Code. - 2. Click **Browse** button and open `cocos2d-x/cocos2dx/platform/android/java` directory. - 3. Click **Finish** to add project. - -#### Adding and running from Eclipse - -![Example](https://lh3.googleusercontent.com/-SLBOu6e3QbE/UUOcOXYaGqI/AAAAAAAAsdo/tYBY2SylOSM/s288/cocos2d-x-eclipse-project-from-code.png) ![Import](https://lh5.googleusercontent.com/-XzC9Pn65USc/UUOcOTAwizI/AAAAAAAAsdk/4b6YM-oim9Y/s400/cocos2d-x-eclipse-import-project.png) - -1. File->New->Project->Android Project From Existing Code -2. **Browse** to your project directory. eg: `cocos2d-x/cocos2dx/samples/Cpp/TestCpp/proj.android/` -3. Add the project -4. Click **Run** or **Debug** to compile C++ followed by Java and to run on connected device or emulator. - - -### Running project from Command Line - - $ cd cocos2d-x/samples/Cpp/TestCpp/proj.android/ - $ export NDK_ROOT=/path/to/ndk - $ ./build_native.sh - $ ant debug install - -If the last command results in sdk.dir missing error then do: - - $ android list target - $ android update project -p . -t (id from step 6) - $ android update project -p cocos2d-x/cocos2dx/platform/android/java/ -t (id from step 6) diff --git a/samples/Javascript/WatermelonWithMe/proj.android/ant.properties b/samples/Javascript/WatermelonWithMe/proj.android/ant.properties deleted file mode 100644 index f8af38bfb4..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/ant.properties +++ /dev/null @@ -1 +0,0 @@ -aapt.ignore.assets="!*.pvr.gz:!*.gz:!.svn:!.git:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*.scc:*~" diff --git a/samples/Javascript/WatermelonWithMe/proj.android/build.xml b/samples/Javascript/WatermelonWithMe/proj.android/build.xml deleted file mode 100644 index f3fd9b9293..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/build.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Javascript/WatermelonWithMe/proj.android/jni/Android.mk b/samples/Javascript/WatermelonWithMe/proj.android/jni/Android.mk deleted file mode 100644 index 2d7b4097ab..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/jni/Android.mk +++ /dev/null @@ -1,30 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := watermelonwithme_shared - -LOCAL_MODULE_FILENAME := libwatermelonwithme - -LOCAL_SRC_FILES := watermelonwithme/main.cpp \ - ../../Classes/AppDelegate.cpp - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes - -LOCAL_WHOLE_STATIC_LIBRARIES := cocos_jsb_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_chipmunk_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_extension_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_localstorage_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_network_static -LOCAL_WHOLE_STATIC_LIBRARIES += jsb_builder_static - -LOCAL_EXPORT_CFLAGS := -DCOCOS2D_DEBUG=2 -DCOCOS2D_JAVASCRIPT - -include $(BUILD_SHARED_LIBRARY) - -$(call import-module,scripting/javascript/bindings) -$(call import-module,scripting/javascript/bindings/chipmunk) -$(call import-module,scripting/javascript/bindings/extension) -$(call import-module,scripting/javascript/bindings/localstorage) -$(call import-module,scripting/javascript/bindings/network) -$(call import-module,scripting/javascript/bindings/cocosbuilder) diff --git a/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk b/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk deleted file mode 100644 index 47d8add103..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/jni/Application.mk +++ /dev/null @@ -1,5 +0,0 @@ -APP_STL := gnustl_static - -# add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] -# in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char diff --git a/samples/Javascript/WatermelonWithMe/proj.android/jni/watermelonwithme/main.cpp b/samples/Javascript/WatermelonWithMe/proj.android/jni/watermelonwithme/main.cpp deleted file mode 100644 index 9793beefb1..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/jni/watermelonwithme/main.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "AppDelegate.h" -#include "cocos2d.h" -#include "platform/android/jni/JniHelper.h" -#include "CCEventType.h" -#include -#include - -#define LOG_TAG "main" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) - -using namespace cocos2d; - -void cocos_android_app_init (struct android_app* app) { - LOGD("cocos_android_app_init"); - AppDelegate *pAppDelegate = new AppDelegate(); -} diff --git a/samples/Javascript/WatermelonWithMe/proj.android/ndkgdb.sh b/samples/Javascript/WatermelonWithMe/proj.android/ndkgdb.sh deleted file mode 100644 index 5df7332ceb..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/ndkgdb.sh +++ /dev/null @@ -1,47 +0,0 @@ -APPNAME="TestJavascript" -APP_ANDROID_NAME="org.cocos2dx.testjavascript" - -if [ -z "${SDK_ROOT+aaa}" ]; then -# ... if SDK_ROOT is not set, use "$HOME/bin/android-sdk" - SDK_ROOT="$HOME/bin/android-sdk" -fi - -if [ -z "${NDK_ROOT+aaa}" ]; then -# ... if NDK_ROOT is not set, use "$HOME/bin/android-ndk" - NDK_ROOT="$HOME/bin/android-ndk" -fi - -if [ -z "${COCOS2DX_ROOT+aaa}" ]; then -# ... if COCOS2DX_ROOT is not set -# ... find current working directory - DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -# ... use paths relative to current directory - COCOS2DX_ROOT="$DIR/../../.." - APP_ROOT="$DIR/.." - APP_ANDROID_ROOT="$DIR" -else - APP_ROOT="$COCOS2DX_ROOT/samples/$APPNAME" - APP_ANDROID_ROOT="$COCOS2DX_ROOT/samples/$APPNAME/proj.android" -fi - -echo "NDK_ROOT = $NDK_ROOT" -echo "SDK_ROOT = $SDK_ROOT" -echo "COCOS2DX_ROOT = $COCOS2DX_ROOT" -echo "APP_ROOT = $APP_ROOT" -echo "APP_ANDROID_ROOT = $APP_ANDROID_ROOT" -echo "APP_ANDROID_NAME = $APP_ANDROID_NAME" - -echo -echo "Killing and restarting ${APP_ANDROID_NAME}" -echo - -set -x - -"${SDK_ROOT}"/platform-tools/adb shell am force-stop "${APP_ANDROID_NAME}" - -NDK_MODULE_PATH="${COCOS2DX_ROOT}":"${COCOS2DX_ROOT}"/cocos2dx/platform/third_party/android/prebuilt \ - "${NDK_ROOT}"/ndk-gdb \ - --adb="${SDK_ROOT}"/platform-tools/adb \ - --verbose \ - --start \ - --force diff --git a/samples/Javascript/WatermelonWithMe/proj.android/proguard-project.txt b/samples/Javascript/WatermelonWithMe/proj.android/proguard-project.txt deleted file mode 100644 index f2fe1559a2..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/proguard-project.txt +++ /dev/null @@ -1,20 +0,0 @@ -# To enable ProGuard in your project, edit project.properties -# to define the proguard.config property as described in that file. -# -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in ${sdk.dir}/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the ProGuard -# include property in project.properties. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/samples/Javascript/WatermelonWithMe/proj.android/project.properties b/samples/Javascript/WatermelonWithMe/proj.android/project.properties deleted file mode 100644 index 0a6dc6664d..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/project.properties +++ /dev/null @@ -1,13 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "ant.properties", and override values to adapt the script to your -# project structure. - -# Project target. -target=android-10 - -android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Javascript/WatermelonWithMe/proj.android/res/values/strings.xml b/samples/Javascript/WatermelonWithMe/proj.android/res/values/strings.xml deleted file mode 100644 index 89aa34dcac..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/res/values/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - WatermelonWithMe - diff --git a/samples/Javascript/WatermelonWithMe/proj.android/src/org/cocos2dx/watermelonwithme/Cocos2dxActivity.java b/samples/Javascript/WatermelonWithMe/proj.android/src/org/cocos2dx/watermelonwithme/Cocos2dxActivity.java deleted file mode 100644 index 3fd0f293cf..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.android/src/org/cocos2dx/watermelonwithme/Cocos2dxActivity.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.cocos2dx.watermelonwithme; - -import android.app.NativeActivity; -import android.graphics.PixelFormat; -import android.os.Bundle; - -public class Cocos2dxActivity extends NativeActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - //For supports translucency - - //1.change "attribs" in cocos\2d\platform\android\nativeactivity.cpp - /*const EGLint attribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - //EGL_BLUE_SIZE, 5, -->delete - //EGL_GREEN_SIZE, 6, -->delete - //EGL_RED_SIZE, 5, -->delete - EGL_BUFFER_SIZE, 32, //-->new field - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - };*/ - - //2.Set the format of window - // getWindow().setFormat(PixelFormat.TRANSLUCENT); - - } -} diff --git a/samples/Javascript/WatermelonWithMe/proj.ios/AppController.h b/samples/Javascript/WatermelonWithMe/proj.ios/AppController.h deleted file mode 100644 index 10287bd13f..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.ios/AppController.h +++ /dev/null @@ -1,17 +0,0 @@ -// -// testjsAppController.h -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -@class RootViewController; - -@interface AppController : NSObject { - UIWindow *window; - RootViewController *viewController; -} - -@end - diff --git a/samples/Javascript/WatermelonWithMe/proj.ios/AppController.mm b/samples/Javascript/WatermelonWithMe/proj.ios/AppController.mm deleted file mode 100644 index ca23f1b7f8..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.ios/AppController.mm +++ /dev/null @@ -1,119 +0,0 @@ -// -// testjsAppController.mm -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// -#import -#import "AppController.h" -#import "cocos2d.h" -#import "EAGLView.h" -#import "AppDelegate.h" - -#import "RootViewController.h" - -@implementation AppController - -#pragma mark - -#pragma mark Application lifecycle - -// cocos2d application instance -static AppDelegate s_sharedApplication; - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - - // Override point for customization after application launch. - - // Add the view controller's view to the window and display. - window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; - CCEAGLView *__glView = [CCEAGLView viewWithFrame: [window bounds] - pixelFormat: kEAGLColorFormatRGBA8 - depthFormat: GL_DEPTH_COMPONENT16 //_OES - preserveBackbuffer: NO - sharegroup: nil - multiSampling: NO - numberOfSamples: 0 ]; - - // Use RootViewController manage CCEAGLView - viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; - viewController.wantsFullScreenLayout = YES; - viewController.view = __glView; - - // Set RootViewController to window - if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) - { - // warning: addSubView doesn't work on iOS6 - [window addSubview: viewController.view]; - } - else - { - // use this method on ios6 - [window setRootViewController:viewController]; - } - - [window makeKeyAndVisible]; - - [[UIApplication sharedApplication] setStatusBarHidden: YES]; - - cocos2d::Application::getInstance()->run(); - return YES; -} - - -- (void)applicationWillResignActive:(UIApplication *)application { - /* - Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. - */ - cocos2d::Director::getInstance()->pause(); -} - -- (void)applicationDidBecomeActive:(UIApplication *)application { - /* - Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - */ - cocos2d::Director::getInstance()->resume(); -} - -- (void)applicationDidEnterBackground:(UIApplication *)application { - /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - If your application supports background execution, called instead of applicationWillTerminate: when the user quits. - */ - cocos2d::Application::getInstance()->applicationDidEnterBackground(); -} - -- (void)applicationWillEnterForeground:(UIApplication *)application { - /* - Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. - */ - cocos2d::Application::getInstance()->applicationWillEnterForeground(); -} - -- (void)applicationWillTerminate:(UIApplication *)application { - /* - Called when the application is about to terminate. - See also applicationDidEnterBackground:. - */ -} - - -#pragma mark - -#pragma mark Memory management - -- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { - /* - Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. - */ - cocos2d::Director::getInstance()->purgeCachedData(); -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end - diff --git a/samples/Javascript/WatermelonWithMe/proj.ios/Default-568h@2x.png.REMOVED.git-id b/samples/Javascript/WatermelonWithMe/proj.ios/Default-568h@2x.png.REMOVED.git-id deleted file mode 100644 index 8f5838f3a8..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.ios/Default-568h@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -66c6d1cead373b45218424f6a82f370897e443e4 \ No newline at end of file diff --git a/samples/Javascript/WatermelonWithMe/proj.ios/Default@2x.png.REMOVED.git-id b/samples/Javascript/WatermelonWithMe/proj.ios/Default@2x.png.REMOVED.git-id deleted file mode 100644 index 8843505b20..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.ios/Default@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -84689888a14a2123d2b39f7f2f61be8c15207479 \ No newline at end of file diff --git a/samples/Javascript/WatermelonWithMe/proj.ios/Prefix.pch b/samples/Javascript/WatermelonWithMe/proj.ios/Prefix.pch deleted file mode 100644 index b056d8694a..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.ios/Prefix.pch +++ /dev/null @@ -1,8 +0,0 @@ -// -// Prefix header for all source files of the 'testjs' target in the 'testjs' project -// - -#ifdef __OBJC__ - #import - #import -#endif diff --git a/samples/Javascript/WatermelonWithMe/proj.ios/RootViewController.h b/samples/Javascript/WatermelonWithMe/proj.ios/RootViewController.h deleted file mode 100644 index 11dfc4bf88..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.ios/RootViewController.h +++ /dev/null @@ -1,33 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2010 Ricardo Quesada - - 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. - ****************************************************************************/ - -#import - - -@interface RootViewController : UIViewController { - -} -- (BOOL)prefersStatusBarHidden; -@end diff --git a/samples/Javascript/WatermelonWithMe/proj.ios/RootViewController.mm b/samples/Javascript/WatermelonWithMe/proj.ios/RootViewController.mm deleted file mode 100644 index 8438d7a420..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.ios/RootViewController.mm +++ /dev/null @@ -1,79 +0,0 @@ -// -// testjsAppController.h -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -#import "RootViewController.h" - - -@implementation RootViewController - -/* - // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { - if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { - // Custom initialization - } - return self; -} -*/ - -/* -// Implement loadView to create a view hierarchy programmatically, without using a nib. -- (void)loadView { -} -*/ - -/* -// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -- (void)viewDidLoad { - [super viewDidLoad]; -} - -*/ -// Override to allow orientations other than the default portrait orientation. -// This method is deprecated on ios6 -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { - return UIInterfaceOrientationIsLandscape( interfaceOrientation ); -} - -// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead -- (NSUInteger) supportedInterfaceOrientations{ -#ifdef __IPHONE_6_0 - return UIInterfaceOrientationMaskAllButUpsideDown; -#endif -} - -- (BOOL) shouldAutorotate { - return YES; -} - -//fix not hide status on ios7 -- (BOOL)prefersStatusBarHidden -{ - return YES; -} - -- (void)didReceiveMemoryWarning { - // Releases the view if it doesn't have a superview. - [super didReceiveMemoryWarning]; - - // Release any cached data, images, etc that aren't in use. -} - -- (void)viewDidUnload { - [super viewDidUnload]; - // Release any retained subviews of the main view. - // e.g. self.myOutlet = nil; -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end diff --git a/samples/Javascript/WatermelonWithMe/proj.ios/main.m b/samples/Javascript/WatermelonWithMe/proj.ios/main.m deleted file mode 100644 index e3dedca28b..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.ios/main.m +++ /dev/null @@ -1,17 +0,0 @@ -// -// main.m -// testjs -// -// Created by Rolando Abarca on 3/19/12. -// Copyright __MyCompanyName__ 2012. All rights reserved. -// - -#import - -int main(int argc, char *argv[]) { - - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - int retVal = UIApplicationMain(argc, argv, nil, @"AppController"); - [pool release]; - return retVal; -} diff --git a/samples/Javascript/WatermelonWithMe/proj.mac/Icon.icns.REMOVED.git-id b/samples/Javascript/WatermelonWithMe/proj.mac/Icon.icns.REMOVED.git-id deleted file mode 100644 index 9874ec6979..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.mac/Icon.icns.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Javascript/WatermelonWithMe/proj.mac/en.lproj/InfoPlist.strings b/samples/Javascript/WatermelonWithMe/proj.mac/en.lproj/InfoPlist.strings deleted file mode 100644 index 477b28ff8f..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.mac/en.lproj/InfoPlist.strings +++ /dev/null @@ -1,2 +0,0 @@ -/* Localized versions of Info.plist keys */ - diff --git a/samples/Javascript/WatermelonWithMe/proj.mac/en.lproj/MainMenu.xib b/samples/Javascript/WatermelonWithMe/proj.mac/en.lproj/MainMenu.xib deleted file mode 100644 index 3dacdedbd0..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.mac/en.lproj/MainMenu.xib +++ /dev/null @@ -1,812 +0,0 @@ - - - - 1060 - 10K549 - 1938 - 1038.36 - 461.00 - - com.apple.InterfaceBuilder.CocoaPlugin - 1938 - - - YES - NSMenuItem - NSCustomObject - NSMenu - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - - - PluginDependencyRecalculationVersion - - - - YES - - NSApplication - - - FirstResponder - - - NSApplication - - - AMainMenu - - YES - - - TestCpp - - 1048576 - 2147483647 - - NSImage - NSMenuCheckmark - - - NSImage - NSMenuMixedState - - submenuAction: - - TestCpp - - YES - - - About TestCpp - - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Preferences… - , - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Services - - 1048576 - 2147483647 - - - submenuAction: - - Services - - YES - - _NSServicesMenu - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Hide TestCpp - h - 1048576 - 2147483647 - - - - - - Hide Others - h - 1572864 - 2147483647 - - - - - - Show All - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Quit TestCpp - q - 1048576 - 2147483647 - - - - - _NSAppleMenu - - - - - View - - 1048576 - 2147483647 - - - submenuAction: - - View - - YES - - - Toggle Fullscreen - f - 1048576 - 2147483647 - - - - - - - - - Window - - 1048576 - 2147483647 - - - submenuAction: - - Window - - YES - - - Minimize - m - 1048576 - 2147483647 - - - - - - Zoom - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Bring All to Front - - 1048576 - 2147483647 - - - - - _NSWindowsMenu - - - - - Help - - 2147483647 - - - submenuAction: - - Help - - YES - - - TestCpp Help - ? - 1048576 - 2147483647 - - - - - _NSHelpMenu - - - - _NSMainMenu - - - AppController - - - NSFontManager - - - - - YES - - - terminate: - - - - 449 - - - - orderFrontStandardAboutPanel: - - - - 142 - - - - delegate - - - - 495 - - - - performMiniaturize: - - - - 37 - - - - arrangeInFront: - - - - 39 - - - - performZoom: - - - - 240 - - - - hide: - - - - 367 - - - - hideOtherApplications: - - - - 368 - - - - unhideAllApplications: - - - - 370 - - - - showHelp: - - - - 493 - - - - toggleFullScreen: - - - - 537 - - - - - YES - - 0 - - YES - - - - - - -2 - - - File's Owner - - - -1 - - - First Responder - - - -3 - - - Application - - - 29 - - - YES - - - - - - - - - 19 - - - YES - - - - - - 56 - - - YES - - - - - - 57 - - - YES - - - - - - - - - - - - - - - - 58 - - - - - 134 - - - - - 150 - - - - - 136 - - - - - 144 - - - - - 129 - - - - - 143 - - - - - 236 - - - - - 131 - - - YES - - - - - - 149 - - - - - 145 - - - - - 130 - - - - - 24 - - - YES - - - - - - - - - 92 - - - - - 5 - - - - - 239 - - - - - 23 - - - - - 295 - - - YES - - - - - - 296 - - - YES - - - - - - 420 - - - - - 490 - - - YES - - - - - - 491 - - - YES - - - - - - 492 - - - - - 494 - - - - - 536 - - - - - - - YES - - YES - -1.IBPluginDependency - -2.IBPluginDependency - -3.IBPluginDependency - 129.IBPluginDependency - 130.IBPluginDependency - 131.IBPluginDependency - 134.IBPluginDependency - 136.IBPluginDependency - 143.IBPluginDependency - 144.IBPluginDependency - 145.IBPluginDependency - 149.IBPluginDependency - 150.IBPluginDependency - 19.IBPluginDependency - 23.IBPluginDependency - 236.IBPluginDependency - 239.IBPluginDependency - 24.IBPluginDependency - 29.IBPluginDependency - 295.IBPluginDependency - 296.IBPluginDependency - 420.IBPluginDependency - 490.IBPluginDependency - 491.IBPluginDependency - 492.IBPluginDependency - 494.IBPluginDependency - 5.IBPluginDependency - 536.IBPluginDependency - 56.IBPluginDependency - 57.IBPluginDependency - 58.IBPluginDependency - 92.IBPluginDependency - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - - - - YES - - - - - - YES - - - - - 541 - - - - YES - - AppController - NSObject - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - id - id - - - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - - exitFullScreen: - id - - - toggleFullScreen: - id - - - - - YES - - YES - glView - window - - - YES - EAGLView - NSWindow - - - - YES - - YES - glView - window - - - YES - - glView - EAGLView - - - window - NSWindow - - - - - IBProjectSource - ./Classes/AppController.h - - - - EAGLView - NSOpenGLView - - IBProjectSource - ./Classes/EAGLView.h - - - - - 0 - IBCocoaFramework - - com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 - - - YES - 3 - - YES - - YES - NSMenuCheckmark - NSMenuMixedState - - - YES - {9, 8} - {7, 2} - - - - diff --git a/samples/Javascript/WatermelonWithMe/proj.mac/main.cpp b/samples/Javascript/WatermelonWithMe/proj.mac/main.cpp deleted file mode 100644 index f492ffc573..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.mac/main.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010 cocos2d-x.org - - 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 "AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -int main(int argc, char *argv[]) -{ - AppDelegate app; - EGLView eglView; - eglView.init("WatermelonWithMe",900,640); - return Application::getInstance()->run(); -} - diff --git a/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj b/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj deleted file mode 100644 index 0f76fa0e57..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj +++ /dev/null @@ -1,237 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {BE092D9E-95AE-4F86-84CE-F4519E4F3F15} - WatermelonWithMe - - - - Application - Unicode - v100 - v110 - v110_xp - - - Application - Unicode - v100 - v110 - v110_xp - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.40219.1 - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - false - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - false - AllRules.ruleset - - - AllRules.ruleset - - - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - - _DEBUG;%(PreprocessorDefinitions) - false - Win32 - true - $(IntDir)testjs.tlb - testjs.h - - - testjs_i.c - testjs_p.c - - - Disabled - $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;_DEBUG;DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - - - Level3 - EditAndContinue - 4267;4251;4244;%(DisableSpecificWarnings) - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - - - - libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) - $(OutDir);%(AdditionalLibraryDirectories) - true - Windows - MachineX86 - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -if exist "$(OutDir)\WatermelonWithMeRes" rd /s /q "$(OutDir)\WatermelonWithMeRes" -mkdir "$(OutDir)\WatermelonWithMeRes" -xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\WatermelonWithMeRes" /e /Y -xcopy "$(ProjectDir)..\..\Shared\games\WatermelonWithMe" "$(OutDir)\WatermelonWithMeRes\" /e /Y - - - Copy js and resource files. - - - - - NDEBUG;%(PreprocessorDefinitions) - false - Win32 - true - $(IntDir)testjs.tlb - testjs.h - - - testjs_i.c - testjs_p.c - - - $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;NDEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - MultiThreadedDLL - - - Level3 - - - 4267;4251;4244;%(DisableSpecificWarnings) - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" - - - - libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;%(AdditionalDependencies) - $(OutDir);%(AdditionalLibraryDirectories) - Windows - MachineX86 - true - - - if not exist "$(OutDir)" mkdir "$(OutDir)" -if exist "$(OutDir)\WatermelonWithMeRes" rd /s /q "$(OutDir)\WatermelonWithMeRes" -mkdir "$(OutDir)\WatermelonWithMeRes" -xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\WatermelonWithMeRes" /e /Y -xcopy "$(ProjectDir)..\..\Shared\games\WatermelonWithMe" "$(OutDir)\WatermelonWithMeRes\" /e /Y - Copy js and resource files. - - - - - - - - - - - - - - - - - - - - {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - - - {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - - - {811c0dab-7b96-4bd3-a154-b7572b58e4ab} - - - {b57cf53f-2e49-4031-9822-047cc0e6bde2} - - - {7e06e92c-537a-442b-9e4a-4761c84f8a1a} - - - {df2638c0-8128-4847-867c-6eafe3dee7b5} - - - {21070e58-eec6-4e16-8b4f-6d083df55790} - - - {f9da0fc1-651b-457b-962e-a4d61cebf5fd} - - - {625f7391-9a91-48a1-8cfc-79508c822637} - - - {68f5f371-bd7b-4c30-ae5b-0b08f22e0cde} - - - {39379840-825a-45a0-b363-c09ffef864bd} - - - {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} - - - {21b2c324-891f-48ea-ad1a-5ae13de12e28} - - - {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} - - - - - - \ No newline at end of file diff --git a/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj.filters b/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj.filters deleted file mode 100644 index 56df37ce6f..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj.filters +++ /dev/null @@ -1,44 +0,0 @@ - - - - - {ca9c9e15-d942-43a1-aa7a-5f0b74ca1afd} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;jpg;jpeg;jpe;png;manifest - - - {ccb2323b-1cfa-41ea-bcf4-ba5f07309396} - - - {e93a77e1-af1e-4400-87d3-504b62ebdbb0} - - - - - win32 - - - Classes - - - - - win32 - - - win32 - - - Classes - - - - - resource - - - - - resource - - - \ No newline at end of file diff --git a/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj.user b/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj.user deleted file mode 100644 index 93f348ba68..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.win32/WatermelonWithMe.vcxproj.user +++ /dev/null @@ -1,11 +0,0 @@ - - - - $(OutDir)\WatermelonWithMeRes - WindowsLocalDebugger - - - $(OutDir)\WatermelonWithMeRes - WindowsLocalDebugger - - \ No newline at end of file diff --git a/samples/Javascript/WatermelonWithMe/proj.win32/main.cpp b/samples/Javascript/WatermelonWithMe/proj.win32/main.cpp deleted file mode 100644 index 3c69549eac..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.win32/main.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "main.h" -#include "AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -// uncomment below line, open debug console -// #define USE_WIN32_CONSOLE - -int APIENTRY _tWinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - UNREFERENCED_PARAMETER(hPrevInstance); - UNREFERENCED_PARAMETER(lpCmdLine); - -#ifdef USE_WIN32_CONSOLE - AllocConsole(); - freopen("CONIN$", "r", stdin); - freopen("CONOUT$", "w", stdout); - freopen("CONOUT$", "w", stderr); -#endif - - // create the application instance - AppDelegate app; - EGLView eglView; - eglView.init("WatermelonWithMe",900,640); - - int ret = Application::getInstance()->run(); - -#ifdef USE_WIN32_CONSOLE - FreeConsole(); -#endif - - return ret; -} diff --git a/samples/Javascript/WatermelonWithMe/proj.win32/main.h b/samples/Javascript/WatermelonWithMe/proj.win32/main.h deleted file mode 100644 index e29aeedb3a..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.win32/main.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef __MAIN_H__ -#define __MAIN_H__ - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -// Windows Header Files: -#include - -// C RunTime Header Files -#include "CCStdC.h" - -#endif // __WINMAIN_H__ diff --git a/samples/Javascript/WatermelonWithMe/proj.win32/res/testjs.ico b/samples/Javascript/WatermelonWithMe/proj.win32/res/testjs.ico deleted file mode 100644 index feaf932a74..0000000000 Binary files a/samples/Javascript/WatermelonWithMe/proj.win32/res/testjs.ico and /dev/null differ diff --git a/samples/Javascript/WatermelonWithMe/proj.win32/resource.h b/samples/Javascript/WatermelonWithMe/proj.win32/resource.h deleted file mode 100644 index a4cfa38af8..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.win32/resource.h +++ /dev/null @@ -1,20 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by testjs.RC -// - -#define IDS_PROJNAME 100 -#define IDR_TESTJS 100 - -#define ID_FILE_NEW_WINDOW 32771 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 201 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 32775 -#endif -#endif diff --git a/samples/Javascript/WatermelonWithMe/proj.win32/testjs.rc b/samples/Javascript/WatermelonWithMe/proj.win32/testjs.rc deleted file mode 100644 index 99e7360397..0000000000 --- a/samples/Javascript/WatermelonWithMe/proj.win32/testjs.rc +++ /dev/null @@ -1,86 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#define APSTUDIO_HIDDEN_SYMBOLS -#include "windows.h" -#undef APSTUDIO_HIDDEN_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -#endif // APSTUDIO_INVOKED - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDR_MAINFRAME ICON "res\\testjs.ico" - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "CompanyName", "\0" - VALUE "FileDescription", "testjs Module\0" - VALUE "FileVersion", "1, 0, 0, 1\0" - VALUE "InternalName", "testjs\0" - VALUE "LegalCopyright", "Copyright \0" - VALUE "OriginalFilename", "testjs.exe\0" - VALUE "ProductName", "testjs Module\0" - VALUE "ProductVersion", "1, 0, 0, 1\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 0x04B0 - END -END - -///////////////////////////////////////////////////////////////////////////// -#endif // !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) diff --git a/samples/Lua/HelloLua/CMakeLists.txt b/samples/Lua/HelloLua/CMakeLists.txt deleted file mode 100644 index 894fc66565..0000000000 --- a/samples/Lua/HelloLua/CMakeLists.txt +++ /dev/null @@ -1,40 +0,0 @@ -set(APP_NAME hellolua) - -set(SAMPLE_SRC - proj.linux/main.cpp - Classes/AppDelegate.cpp -) - -include_directories( - Classes - ../../../cocos/scripting/lua/bindings - ../../../external/lua/lua - ../../../external/lua/tolua -) - -# add the executable -add_executable(${APP_NAME} - ${SAMPLE_SRC} -) - -target_link_libraries(${APP_NAME} - luabinding - gui - network - cocostudio - cocosbuilder - extensions - audio - cocos2d -) - -set(APP_BIN_DIR "${CMAKE_BINARY_DIR}/bin/${APP_NAME}") - -set_target_properties(${APP_NAME} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${APP_BIN_DIR}") - -pre_build(${APP_NAME} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources - COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources - COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/cocos/scripting/lua/script ${APP_BIN_DIR}/Resources - ) diff --git a/samples/Lua/HelloLua/Classes/AppDelegate.cpp b/samples/Lua/HelloLua/Classes/AppDelegate.cpp deleted file mode 100644 index d693936216..0000000000 --- a/samples/Lua/HelloLua/Classes/AppDelegate.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include "cocos2d.h" -#include "AppDelegate.h" -#include "SimpleAudioEngine.h" -#include "CCScriptSupport.h" -#include "CCLuaEngine.h" - -USING_NS_CC; -using namespace CocosDenshion; - -AppDelegate::AppDelegate() -{ - // fixed me - //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF); -} - -AppDelegate::~AppDelegate() -{ - // end simple audio engine here, or it may crashed on win32 - SimpleAudioEngine::getInstance()->end(); - //CCScriptEngineManager::destroyInstance(); -} - -bool AppDelegate::applicationDidFinishLaunching() -{ - // initialize director - auto pDirector = Director::getInstance(); - pDirector->setOpenGLView(EGLView::getInstance()); - - EGLView::getInstance()->setDesignResolutionSize(480, 320, ResolutionPolicy::NO_BORDER); - - // turn on display FPS - pDirector->setDisplayStats(true); - - // set FPS. the default value is 1.0/60 if you don't call this - pDirector->setAnimationInterval(1.0 / 60); - - // register lua engine - LuaEngine* pEngine = LuaEngine::getInstance(); - ScriptEngineManager::getInstance()->setScriptEngine(pEngine); - - std::string path = FileUtils::getInstance()->fullPathForFilename("hello.lua"); - pEngine->executeScriptFile(path.c_str()); - - return true; -} - -// This function will be called when the app is inactive. When comes a phone call,it's be invoked too -void AppDelegate::applicationDidEnterBackground() -{ - Director::getInstance()->stopAnimation(); - SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); -} - -// this function will be called when the app is active again -void AppDelegate::applicationWillEnterForeground() -{ - Director::getInstance()->startAnimation(); - SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); -} diff --git a/samples/Lua/HelloLua/Classes/AppDelegate.h b/samples/Lua/HelloLua/Classes/AppDelegate.h deleted file mode 100644 index b708f4bdca..0000000000 --- a/samples/Lua/HelloLua/Classes/AppDelegate.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef _APP_DELEGATE_H_ -#define _APP_DELEGATE_H_ - -#include "CCApplication.h" - -/** -@brief The cocos2d Application. - -The reason for implement as private inheritance is to hide some interface call by Director. -*/ -class AppDelegate : private cocos2d::Application -{ -public: - AppDelegate(); - virtual ~AppDelegate(); - - /** - @brief Implement Director and Scene init code here. - @return true Initialize success, app continue. - @return false Initialize failed, app terminate. - */ - virtual bool applicationDidFinishLaunching(); - - /** - @brief The function be called when the application enter background - @param the pointer of the application - */ - virtual void applicationDidEnterBackground(); - - /** - @brief The function be called when the application enter foreground - @param the pointer of the application - */ - virtual void applicationWillEnterForeground(); -}; - -#endif // _APP_DELEGATE_H_ - diff --git a/samples/Lua/HelloLua/Resources/.gitignore b/samples/Lua/HelloLua/Resources/.gitignore deleted file mode 100644 index 1d65afe366..0000000000 --- a/samples/Lua/HelloLua/Resources/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -#Do now ignore Marmalade icf files -!*.icf diff --git a/samples/Lua/HelloLua/Resources/background.mp3.REMOVED.git-id b/samples/Lua/HelloLua/Resources/background.mp3.REMOVED.git-id deleted file mode 100644 index cfc16a8a4e..0000000000 --- a/samples/Lua/HelloLua/Resources/background.mp3.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -aec1c0a8c8068377fddca5ddd32084d8c3c3c419 \ No newline at end of file diff --git a/samples/Lua/HelloLua/Resources/farm.jpg.REMOVED.git-id b/samples/Lua/HelloLua/Resources/farm.jpg.REMOVED.git-id deleted file mode 100644 index 4609f3cf02..0000000000 --- a/samples/Lua/HelloLua/Resources/farm.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -d7290c34702d1c6bdb368acb060d93b42d5deff8 \ No newline at end of file diff --git a/samples/Lua/HelloLua/Resources/hello.lua b/samples/Lua/HelloLua/Resources/hello.lua deleted file mode 100644 index 607b7d7508..0000000000 --- a/samples/Lua/HelloLua/Resources/hello.lua +++ /dev/null @@ -1,205 +0,0 @@ -require "Cocos2d" --- cclog -cclog = function(...) - print(string.format(...)) -end - --- for CCLuaEngine traceback -function __G__TRACKBACK__(msg) - cclog("----------------------------------------") - cclog("LUA ERROR: " .. tostring(msg) .. "\n") - cclog(debug.traceback()) - cclog("----------------------------------------") -end - -local function main() - -- avoid memory leak - collectgarbage("setpause", 100) - collectgarbage("setstepmul", 5000) - - require "hello2" - cclog("result is " .. myadd(1, 1)) - - --------------- - - local visibleSize = cc.Director:getInstance():getVisibleSize() - local origin = cc.Director:getInstance():getVisibleOrigin() - - -- add the moving dog - local function creatDog() - local frameWidth = 105 - local frameHeight = 95 - - -- create dog animate - local textureDog = cc.TextureCache:getInstance():addImage("dog.png") - local rect = cc.rect(0, 0, frameWidth, frameHeight) - local frame0 = cc.SpriteFrame:createWithTexture(textureDog, rect) - rect = cc.rect(frameWidth, 0, frameWidth, frameHeight) - local frame1 = cc.SpriteFrame:createWithTexture(textureDog, rect) - - local spriteDog = cc.Sprite:createWithSpriteFrame(frame0) - spriteDog.isPaused = false - spriteDog:setPosition(origin.x, origin.y + visibleSize.height / 4 * 3) ---[[ - local animFrames = CCArray:create() - - animFrames:addObject(frame0) - animFrames:addObject(frame1) -]]-- - - local animation = cc.Animation:createWithSpriteFrames({frame0,frame1}, 0.5) - local animate = cc.Animate:create(animation); - spriteDog:runAction(cc.RepeatForever:create(animate)) - - -- moving dog at every frame - local function tick() - if spriteDog.isPaused then return end - local x, y = spriteDog:getPosition() - if x > origin.x + visibleSize.width then - x = origin.x - else - x = x + 1 - end - - spriteDog:setPositionX(x) - end - - cc.Director:getInstance():getScheduler():scheduleScriptFunc(tick, 0, false) - - return spriteDog - end - - -- create farm - local function createLayerFarm() - local layerFarm = cc.Layer:create() - - -- add in farm background - local bg = cc.Sprite:create("farm.jpg") - bg:setPosition(origin.x + visibleSize.width / 2 + 80, origin.y + visibleSize.height / 2) - layerFarm:addChild(bg) - - -- add land sprite - for i = 0, 3 do - for j = 0, 1 do - local spriteLand = cc.Sprite:create("land.png") - spriteLand:setPosition(200 + j * 180 - i % 2 * 90, 10 + i * 95 / 2) - layerFarm:addChild(spriteLand) - end - end - - -- add crop - local frameCrop = cc.SpriteFrame:create("crop.png", cc.rect(0, 0, 105, 95)) - for i = 0, 3 do - for j = 0, 1 do - local spriteCrop = cc.Sprite:createWithSpriteFrame(frameCrop); - spriteCrop:setPosition(10 + 200 + j * 180 - i % 2 * 90, 30 + 10 + i * 95 / 2) - layerFarm:addChild(spriteCrop) - end - end - - -- add moving dog - local spriteDog = creatDog() - layerFarm:addChild(spriteDog) - - -- handing touch events - local touchBeginPoint = nil - - local function onTouchBegan(x, y) - cclog("onTouchBegan: %0.2f, %0.2f", x, y) - touchBeginPoint = {x = x, y = y} - spriteDog.isPaused = true - -- CCTOUCHBEGAN event must return true - return true - end - - local function onTouchMoved(x, y) - cclog("onTouchMoved: %0.2f, %0.2f", x, y) - if touchBeginPoint then - local cx, cy = layerFarm:getPosition() - layerFarm:setPosition(cx + x - touchBeginPoint.x, - cy + y - touchBeginPoint.y) - touchBeginPoint = {x = x, y = y} - end - end - - local function onTouchEnded(x, y) - cclog("onTouchEnded: %0.2f, %0.2f", x, y) - touchBeginPoint = nil - spriteDog.isPaused = false - end - - local function onTouch(eventType, x, y) - if eventType == "began" then - return onTouchBegan(x, y) - elseif eventType == "moved" then - return onTouchMoved(x, y) - else - return onTouchEnded(x, y) - end - end - - layerFarm:registerScriptTouchHandler(onTouch) - layerFarm:setTouchEnabled(true) - - return layerFarm - end - - - -- create menu - local function createLayerMenu() - local layerMenu = cc.Layer:create() - - local menuPopup, menuTools, effectID - - local function menuCallbackClosePopup() - -- stop test sound effect - cc.SimpleAudioEngine:getInstance():stopEffect(effectID) - menuPopup:setVisible(false) - end - - local function menuCallbackOpenPopup() - -- loop test sound effect - local effectPath = cc.FileUtils:getInstance():fullPathForFilename("effect1.wav") - effectID = cc.SimpleAudioEngine:getInstance():playEffect(effectPath) - menuPopup:setVisible(true) - end - - -- add a popup menu - local menuPopupItem = cc.MenuItemImage:create("menu2.png", "menu2.png") - menuPopupItem:setPosition(0, 0) - menuPopupItem:registerScriptTapHandler(menuCallbackClosePopup) - menuPopup = cc.Menu:create(menuPopupItem) - menuPopup:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2) - menuPopup:setVisible(false) - layerMenu:addChild(menuPopup) - - -- add the left-bottom "tools" menu to invoke menuPopup - local menuToolsItem = cc.MenuItemImage:create("menu1.png", "menu1.png") - menuToolsItem:setPosition(0, 0) - menuToolsItem:registerScriptTapHandler(menuCallbackOpenPopup) - menuTools = cc.Menu:create(menuToolsItem) - local itemWidth = menuToolsItem:getContentSize().width - local itemHeight = menuToolsItem:getContentSize().height - menuTools:setPosition(origin.x + itemWidth/2, origin.y + itemHeight/2) - layerMenu:addChild(menuTools) - - return layerMenu - end - - -- play background music, preload effect - - -- uncomment below for the BlackBerry version - -- local bgMusicPath = CCFileUtils:getInstance():fullPathForFilename("background.ogg") - local bgMusicPath = cc.FileUtils:getInstance():fullPathForFilename("background.mp3") - cc.SimpleAudioEngine:getInstance():playMusic(bgMusicPath, true) - local effectPath = cc.FileUtils:getInstance():fullPathForFilename("effect1.wav") - cc.SimpleAudioEngine:getInstance():preloadEffect(effectPath) - - -- run - local sceneGame = cc.Scene:create() - sceneGame:addChild(createLayerFarm()) - sceneGame:addChild(createLayerMenu()) - cc.Director:getInstance():runWithScene(sceneGame) -end - -xpcall(main, __G__TRACKBACK__) diff --git a/samples/Lua/HelloLua/Resources/hello2.lua b/samples/Lua/HelloLua/Resources/hello2.lua deleted file mode 100644 index 27158aa788..0000000000 --- a/samples/Lua/HelloLua/Resources/hello2.lua +++ /dev/null @@ -1,3 +0,0 @@ -function myadd(x, y) - return x + y -end \ No newline at end of file diff --git a/samples/Lua/HelloLua/proj.android/.classpath b/samples/Lua/HelloLua/proj.android/.classpath deleted file mode 100644 index 0b08408342..0000000000 --- a/samples/Lua/HelloLua/proj.android/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/samples/Lua/HelloLua/proj.android/.externalToolBuilders/Javah_jni_builder.launch b/samples/Lua/HelloLua/proj.android/.externalToolBuilders/Javah_jni_builder.launch deleted file mode 100644 index 3506e4e944..0000000000 --- a/samples/Lua/HelloLua/proj.android/.externalToolBuilders/Javah_jni_builder.launch +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/samples/Lua/HelloLua/proj.android/.settings/org.eclipse.cdt.codan.core.prefs b/samples/Lua/HelloLua/proj.android/.settings/org.eclipse.cdt.codan.core.prefs deleted file mode 100644 index bad4196993..0000000000 --- a/samples/Lua/HelloLua/proj.android/.settings/org.eclipse.cdt.codan.core.prefs +++ /dev/null @@ -1,68 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.cdt.codan.checkers.errnoreturn=-Warning -org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.checkers.errreturnvalue=-Error -org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.checkers.noreturn=-Error -org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},implicit\=>false} -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=-Error -org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=-Error -org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},no_break_comment\=>"no break",last_case_param\=>true,empty_case_param\=>false} -org.eclipse.cdt.codan.internal.checkers.CatchByReference=-Warning -org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},unknown\=>false,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=-Error -org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=-Warning -org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},skip\=>true} -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidArguments=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=-Error -org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info -org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},pattern\=>"^[a-z]",macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.OverloadProblem=-Error -org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>()} -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},paramNot\=>false} -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},else\=>false,afterelse\=>false} -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true} -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=-Warning -org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},macro\=>true,exceptions\=>("@(\#)","$Id")} -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=-Error -org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true}} -useParentScope=false diff --git a/samples/Lua/HelloLua/proj.android/AndroidManifest.xml b/samples/Lua/HelloLua/proj.android/AndroidManifest.xml deleted file mode 100644 index 087e4852fb..0000000000 --- a/samples/Lua/HelloLua/proj.android/AndroidManifest.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Lua/HelloLua/proj.android/ant.properties b/samples/Lua/HelloLua/proj.android/ant.properties deleted file mode 100644 index b0971e891e..0000000000 --- a/samples/Lua/HelloLua/proj.android/ant.properties +++ /dev/null @@ -1,17 +0,0 @@ -# This file is used to override default values used by the Ant build system. -# -# This file must be checked into Version Control Systems, as it is -# integral to the build system of your project. - -# This file is only used by the Ant script. - -# You can use this to override default values such as -# 'source.dir' for the location of your java source folder and -# 'out.dir' for the location of your output folder. - -# You can also use it define how the release builds are signed by declaring -# the following properties: -# 'key.store' for the location of your keystore and -# 'key.alias' for the name of the key to use. -# The password will be asked during the build when you use the 'release' target. - diff --git a/samples/Lua/HelloLua/proj.android/build.xml b/samples/Lua/HelloLua/proj.android/build.xml deleted file mode 100644 index ff293087f2..0000000000 --- a/samples/Lua/HelloLua/proj.android/build.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/Lua/HelloLua/proj.android/jni/Android.mk b/samples/Lua/HelloLua/proj.android/jni/Android.mk deleted file mode 100644 index 2c3b9124cf..0000000000 --- a/samples/Lua/HelloLua/proj.android/jni/Android.mk +++ /dev/null @@ -1,20 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_MODULE := hellolua_shared - -LOCAL_MODULE_FILENAME := libhellolua - -LOCAL_SRC_FILES := hellolua/main.cpp \ - ../../Classes/AppDelegate.cpp - -LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes \ - $(LOCAL_PATH)/../../../../../external/lua/tolua \ - -LOCAL_WHOLE_STATIC_LIBRARIES := cocos_lua_static - - -include $(BUILD_SHARED_LIBRARY) - -$(call import-module,scripting/lua/bindings) diff --git a/samples/Lua/HelloLua/proj.android/jni/Application.mk b/samples/Lua/HelloLua/proj.android/jni/Application.mk deleted file mode 100644 index 540e49c358..0000000000 --- a/samples/Lua/HelloLua/proj.android/jni/Application.mk +++ /dev/null @@ -1,8 +0,0 @@ -APP_STL := gnustl_static - -# add -Wno-literal-suffix to avoid warning: warning: invalid suffix on literal; C++11 requires a space between literal and identifier [-Wliteral-suffix] -# in NDK_ROOT/arch-arm/usr/include/sys/cdefs_elf.h:35:28: when using ndk-r9 -APP_CPPFLAGS := -frtti -DCOCOS2D_DEBUG=1 -std=c++11 -Wno-literal-suffix -fsigned-char - -APP_CPPFLAGS += -fexceptions - diff --git a/samples/Lua/HelloLua/proj.android/jni/hellolua/main.cpp b/samples/Lua/HelloLua/proj.android/jni/hellolua/main.cpp deleted file mode 100644 index 20e2ea1f45..0000000000 --- a/samples/Lua/HelloLua/proj.android/jni/hellolua/main.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "AppDelegate.h" -#include "cocos2d.h" -#include "platform/android/jni/JniHelper.h" -#include -#include - -#define LOG_TAG "main" -#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) - -using namespace cocos2d; - -void cocos_android_app_init (struct android_app* app) { - LOGD("cocos_android_app_init"); - AppDelegate *pAppDelegate = new AppDelegate(); -} diff --git a/samples/Lua/HelloLua/proj.android/proguard-project.txt b/samples/Lua/HelloLua/proj.android/proguard-project.txt deleted file mode 100644 index f2fe1559a2..0000000000 --- a/samples/Lua/HelloLua/proj.android/proguard-project.txt +++ /dev/null @@ -1,20 +0,0 @@ -# To enable ProGuard in your project, edit project.properties -# to define the proguard.config property as described in that file. -# -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in ${sdk.dir}/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the ProGuard -# include property in project.properties. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/samples/Lua/HelloLua/proj.android/project.properties b/samples/Lua/HelloLua/proj.android/project.properties deleted file mode 100644 index 0a6dc6664d..0000000000 --- a/samples/Lua/HelloLua/proj.android/project.properties +++ /dev/null @@ -1,13 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "ant.properties", and override values to adapt the script to your -# project structure. - -# Project target. -target=android-10 - -android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Lua/HelloLua/proj.android/res/values/strings.xml b/samples/Lua/HelloLua/proj.android/res/values/strings.xml deleted file mode 100644 index d2c2ebdfb1..0000000000 --- a/samples/Lua/HelloLua/proj.android/res/values/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - HelloLua - diff --git a/samples/Lua/HelloLua/proj.android/src/org/cocos2dx/hellolua/Cocos2dxActivity.java b/samples/Lua/HelloLua/proj.android/src/org/cocos2dx/hellolua/Cocos2dxActivity.java deleted file mode 100644 index 9933cf14fd..0000000000 --- a/samples/Lua/HelloLua/proj.android/src/org/cocos2dx/hellolua/Cocos2dxActivity.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.cocos2dx.hellolua; - -import android.app.NativeActivity; -import android.graphics.PixelFormat; -import android.os.Bundle; - -public class Cocos2dxActivity extends NativeActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - // TODO Auto-generated method stub - super.onCreate(savedInstanceState); - - //For supports translucency - - //1.change "attribs" in cocos\2d\platform\android\nativeactivity.cpp - /*const EGLint attribs[] = { - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - //EGL_BLUE_SIZE, 5, -->delete - //EGL_GREEN_SIZE, 6, -->delete - //EGL_RED_SIZE, 5, -->delete - EGL_BUFFER_SIZE, 32, //-->new field - EGL_DEPTH_SIZE, 16, - EGL_STENCIL_SIZE, 8, - EGL_NONE - };*/ - - //2.Set the format of window - // getWindow().setFormat(PixelFormat.TRANSLUCENT); - - } -} diff --git a/samples/Lua/HelloLua/proj.ios/Default-568h@2x.png.REMOVED.git-id b/samples/Lua/HelloLua/proj.ios/Default-568h@2x.png.REMOVED.git-id deleted file mode 100644 index 8f5838f3a8..0000000000 --- a/samples/Lua/HelloLua/proj.ios/Default-568h@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -66c6d1cead373b45218424f6a82f370897e443e4 \ No newline at end of file diff --git a/samples/Lua/HelloLua/proj.ios/Default@2x.png.REMOVED.git-id b/samples/Lua/HelloLua/proj.ios/Default@2x.png.REMOVED.git-id deleted file mode 100644 index 8843505b20..0000000000 --- a/samples/Lua/HelloLua/proj.ios/Default@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -84689888a14a2123d2b39f7f2f61be8c15207479 \ No newline at end of file diff --git a/samples/Lua/HelloLua/proj.ios/HelloLua_Prefix.pch b/samples/Lua/HelloLua/proj.ios/HelloLua_Prefix.pch deleted file mode 100644 index b4311a0a3d..0000000000 --- a/samples/Lua/HelloLua/proj.ios/HelloLua_Prefix.pch +++ /dev/null @@ -1,8 +0,0 @@ -// -// Prefix header for all source files of the 'HelloLua' target in the 'HelloLua' project -// - -#ifdef __OBJC__ - #import - #import -#endif diff --git a/samples/Lua/HelloLua/proj.ios/RootViewController.h b/samples/Lua/HelloLua/proj.ios/RootViewController.h deleted file mode 100644 index 11dfc4bf88..0000000000 --- a/samples/Lua/HelloLua/proj.ios/RootViewController.h +++ /dev/null @@ -1,33 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2010 Ricardo Quesada - - 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. - ****************************************************************************/ - -#import - - -@interface RootViewController : UIViewController { - -} -- (BOOL)prefersStatusBarHidden; -@end diff --git a/samples/Lua/HelloLua/proj.ios/main.m b/samples/Lua/HelloLua/proj.ios/main.m deleted file mode 100644 index 27ca9796f7..0000000000 --- a/samples/Lua/HelloLua/proj.ios/main.m +++ /dev/null @@ -1,16 +0,0 @@ -// -// main.m -// HelloLua -// -// Created by Walzer on 11-6-15. -// Copyright __MyCompanyName__ 2011. All rights reserved. -// - -#import - -int main(int argc, char *argv[]) { - NSAutoreleasePool *pool = [NSAutoreleasePool new]; - int retVal = UIApplicationMain(argc, argv, nil, @"AppController"); - [pool release]; - return retVal; -} diff --git a/samples/Lua/HelloLua/proj.mac/HelloLua_Prefix.pch b/samples/Lua/HelloLua/proj.mac/HelloLua_Prefix.pch deleted file mode 100644 index 46c36a7e99..0000000000 --- a/samples/Lua/HelloLua/proj.mac/HelloLua_Prefix.pch +++ /dev/null @@ -1,7 +0,0 @@ -// -// Prefix header for all source files of the 'Paralaxer' target in the 'Paralaxer' project -// - -#ifdef __OBJC__ - #import -#endif diff --git a/samples/Lua/HelloLua/proj.mac/Icon.icns.REMOVED.git-id b/samples/Lua/HelloLua/proj.mac/Icon.icns.REMOVED.git-id deleted file mode 100644 index 9874ec6979..0000000000 --- a/samples/Lua/HelloLua/proj.mac/Icon.icns.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Lua/HelloLua/proj.mac/en.lproj/InfoPlist.strings b/samples/Lua/HelloLua/proj.mac/en.lproj/InfoPlist.strings deleted file mode 100644 index 477b28ff8f..0000000000 --- a/samples/Lua/HelloLua/proj.mac/en.lproj/InfoPlist.strings +++ /dev/null @@ -1,2 +0,0 @@ -/* Localized versions of Info.plist keys */ - diff --git a/samples/Lua/HelloLua/proj.mac/en.lproj/MainMenu.xib b/samples/Lua/HelloLua/proj.mac/en.lproj/MainMenu.xib deleted file mode 100644 index 9f99439250..0000000000 --- a/samples/Lua/HelloLua/proj.mac/en.lproj/MainMenu.xib +++ /dev/null @@ -1,812 +0,0 @@ - - - - 1060 - 10K549 - 1938 - 1038.36 - 461.00 - - com.apple.InterfaceBuilder.CocoaPlugin - 1938 - - - YES - NSMenuItem - NSCustomObject - NSMenu - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - - - PluginDependencyRecalculationVersion - - - - YES - - NSApplication - - - FirstResponder - - - NSApplication - - - AMainMenu - - YES - - - HelloCpp - - 1048576 - 2147483647 - - NSImage - NSMenuCheckmark - - - NSImage - NSMenuMixedState - - submenuAction: - - HelloCpp - - YES - - - About HelloCpp - - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Preferences… - , - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Services - - 1048576 - 2147483647 - - - submenuAction: - - Services - - YES - - _NSServicesMenu - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Hide HelloCpp - h - 1048576 - 2147483647 - - - - - - Hide Others - h - 1572864 - 2147483647 - - - - - - Show All - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Quit HelloCpp - q - 1048576 - 2147483647 - - - - - _NSAppleMenu - - - - - View - - 1048576 - 2147483647 - - - submenuAction: - - View - - YES - - - Toggle Fullscreen - f - 1048576 - 2147483647 - - - - - - - - - Window - - 1048576 - 2147483647 - - - submenuAction: - - Window - - YES - - - Minimize - m - 1048576 - 2147483647 - - - - - - Zoom - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Bring All to Front - - 1048576 - 2147483647 - - - - - _NSWindowsMenu - - - - - Help - - 2147483647 - - - submenuAction: - - Help - - YES - - - HelloCpp Help - ? - 1048576 - 2147483647 - - - - - _NSHelpMenu - - - - _NSMainMenu - - - AppController - - - NSFontManager - - - - - YES - - - terminate: - - - - 449 - - - - orderFrontStandardAboutPanel: - - - - 142 - - - - delegate - - - - 495 - - - - performMiniaturize: - - - - 37 - - - - arrangeInFront: - - - - 39 - - - - performZoom: - - - - 240 - - - - hide: - - - - 367 - - - - hideOtherApplications: - - - - 368 - - - - unhideAllApplications: - - - - 370 - - - - showHelp: - - - - 493 - - - - toggleFullScreen: - - - - 537 - - - - - YES - - 0 - - YES - - - - - - -2 - - - File's Owner - - - -1 - - - First Responder - - - -3 - - - Application - - - 29 - - - YES - - - - - - - - - 19 - - - YES - - - - - - 56 - - - YES - - - - - - 57 - - - YES - - - - - - - - - - - - - - - - 58 - - - - - 134 - - - - - 150 - - - - - 136 - - - - - 144 - - - - - 129 - - - - - 143 - - - - - 236 - - - - - 131 - - - YES - - - - - - 149 - - - - - 145 - - - - - 130 - - - - - 24 - - - YES - - - - - - - - - 92 - - - - - 5 - - - - - 239 - - - - - 23 - - - - - 295 - - - YES - - - - - - 296 - - - YES - - - - - - 420 - - - - - 490 - - - YES - - - - - - 491 - - - YES - - - - - - 492 - - - - - 494 - - - - - 536 - - - - - - - YES - - YES - -1.IBPluginDependency - -2.IBPluginDependency - -3.IBPluginDependency - 129.IBPluginDependency - 130.IBPluginDependency - 131.IBPluginDependency - 134.IBPluginDependency - 136.IBPluginDependency - 143.IBPluginDependency - 144.IBPluginDependency - 145.IBPluginDependency - 149.IBPluginDependency - 150.IBPluginDependency - 19.IBPluginDependency - 23.IBPluginDependency - 236.IBPluginDependency - 239.IBPluginDependency - 24.IBPluginDependency - 29.IBPluginDependency - 295.IBPluginDependency - 296.IBPluginDependency - 420.IBPluginDependency - 490.IBPluginDependency - 491.IBPluginDependency - 492.IBPluginDependency - 494.IBPluginDependency - 5.IBPluginDependency - 536.IBPluginDependency - 56.IBPluginDependency - 57.IBPluginDependency - 58.IBPluginDependency - 92.IBPluginDependency - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - - - - YES - - - - - - YES - - - - - 541 - - - - YES - - AppController - NSObject - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - id - id - - - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - - exitFullScreen: - id - - - toggleFullScreen: - id - - - - - YES - - YES - glView - window - - - YES - EAGLView - Window - - - - YES - - YES - glView - window - - - YES - - glView - EAGLView - - - window - Window - - - - - IBProjectSource - ./Classes/AppController.h - - - - EAGLView - NSOpenGLView - - IBProjectSource - ./Classes/EAGLView.h - - - - - 0 - IBCocoaFramework - - com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 - - - YES - 3 - - YES - - YES - NSMenuCheckmark - NSMenuMixedState - - - YES - {9, 8} - {7, 2} - - - - diff --git a/samples/Lua/HelloLua/proj.win32/HelloLua.vcxproj b/samples/Lua/HelloLua/proj.win32/HelloLua.vcxproj deleted file mode 100644 index dc57ee0d68..0000000000 --- a/samples/Lua/HelloLua/proj.win32/HelloLua.vcxproj +++ /dev/null @@ -1,196 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {13E55395-94A2-4CD9-BFC2-1A051F80C17D} - HelloLua.win32 - - - - Application - Unicode - v100 - v110 - v110_xp - - - Application - Unicode - v100 - v110 - v110_xp - - - - - - - - - - - - - - - - - <_ProjectFileVersion>10.0.40219.1 - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - true - $(SolutionDir)$(Configuration).win32\ - $(Configuration).win32\ - false - AllRules.ruleset - - - AllRules.ruleset - - - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\lib;$(LibraryPath) - - - - _DEBUG;%(PreprocessorDefinitions) - false - Win32 - true - $(IntDir)HelloLua.tlb - HelloLua.h - - - HelloLua_i.c - HelloLua_p.c - - - Disabled - $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;_DEBUG;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - false - EnableFastChecks - MultiThreadedDebugDLL - - - Level3 - EditAndContinue - 4267;4251;4244;%(DisableSpecificWarnings) - true - - - _DEBUG;%(PreprocessorDefinitions) - 0x0409 - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - - - libcurl_imp.lib;lua51.lib;websockets.lib;%(AdditionalDependencies) - $(OutDir);%(AdditionalLibraryDirectories) - true - Windows - MachineX86 - - - xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\lua\script" "$(ProjectDir)..\..\HelloLua\Resources" /e /Y - - - - - NDEBUG;%(PreprocessorDefinitions) - false - Win32 - true - $(IntDir)HelloLua.tlb - HelloLua.h - - - HelloLua_i.c - HelloLua_p.c - - - $(ProjectDir)..\Classes;$(EngineRoot)cocos\scripting\auto-generated\lua-bindings;$(EngineRoot)cocos\scripting\lua\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\lua\lua;$(EngineRoot)external\lua\tolua;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;NDEBUG;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) - - - MultiThreadedDLL - - - Level3 - - - 4267;4251;4244;%(DisableSpecificWarnings) - true - - - NDEBUG;%(PreprocessorDefinitions) - 0x0409 - $(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;$(IntDir);%(AdditionalIncludeDirectories) - - - lua51.lib;websockets.lib;%(AdditionalDependencies) - $(OutDir);%(AdditionalLibraryDirectories) - Windows - MachineX86 - true - - - - - - - - - - - - - {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - - - {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - - - {811c0dab-7b96-4bd3-a154-b7572b58e4ab} - - - {b57cf53f-2e49-4031-9822-047cc0e6bde2} - - - {b7c2a162-dec9-4418-972e-240ab3cbfcae} - - - {7e06e92c-537a-442b-9e4a-4761c84f8a1a} - - - {df2638c0-8128-4847-867c-6eafe3dee7b5} - - - {ddc3e27f-004d-4dd4-9dd3-931a013d2159} - - - {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} - - - {21b2c324-891f-48ea-ad1a-5ae13de12e28} - - - {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} - - - - - - \ No newline at end of file diff --git a/samples/Lua/HelloLua/proj.win32/HelloLua.vcxproj.filters b/samples/Lua/HelloLua/proj.win32/HelloLua.vcxproj.filters deleted file mode 100644 index 5de7838f8f..0000000000 --- a/samples/Lua/HelloLua/proj.win32/HelloLua.vcxproj.filters +++ /dev/null @@ -1,27 +0,0 @@ - - - - - {83371666-be62-4e91-b8cc-395730853621} - - - {917fb40f-fc6d-4ee9-9a20-26debabe41aa} - - - - - Classes - - - win32 - - - - - Classes - - - win32 - - - \ No newline at end of file diff --git a/samples/Lua/HelloLua/proj.win32/HelloLua.vcxproj.user b/samples/Lua/HelloLua/proj.win32/HelloLua.vcxproj.user deleted file mode 100644 index 32a6296820..0000000000 --- a/samples/Lua/HelloLua/proj.win32/HelloLua.vcxproj.user +++ /dev/null @@ -1,11 +0,0 @@ - - - - $(ProjectDir)..\Resources - WindowsLocalDebugger - - - $(ProjectDir)..\Resources - WindowsLocalDebugger - - \ No newline at end of file diff --git a/samples/Lua/HelloLua/proj.win32/main.cpp b/samples/Lua/HelloLua/proj.win32/main.cpp deleted file mode 100644 index b07e50bc66..0000000000 --- a/samples/Lua/HelloLua/proj.win32/main.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "main.h" -#include "AppDelegate.h" -#include "CCEGLView.h" - -USING_NS_CC; - -// uncomment below line, open debug console -#define USE_WIN32_CONSOLE - -int APIENTRY _tWinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) -{ - UNREFERENCED_PARAMETER(hPrevInstance); - UNREFERENCED_PARAMETER(lpCmdLine); - -#ifdef USE_WIN32_CONSOLE - AllocConsole(); - freopen("CONIN$", "r", stdin); - freopen("CONOUT$", "w", stdout); - freopen("CONOUT$", "w", stderr); -#endif - - // create the application instance - AppDelegate app; - EGLView eglView; - eglView.init("HelloLua",900,640); - - int ret = Application::getInstance()->run(); - -#ifdef USE_WIN32_CONSOLE - FreeConsole(); -#endif - - return ret; -} diff --git a/samples/Lua/HelloLua/proj.win32/main.h b/samples/Lua/HelloLua/proj.win32/main.h deleted file mode 100644 index e74708bdf2..0000000000 --- a/samples/Lua/HelloLua/proj.win32/main.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __MAIN_H__ -#define __MAIN_H__ - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - -// Windows Header Files: -#include -#include - -// C RunTime Header Files -#include "CCStdC.h" - -#endif // __MAIN_H__ diff --git a/samples/Lua/TestLua/Resources/luaScript/AccelerometerTest/AccelerometerTest.lua b/samples/Lua/TestLua/Resources/luaScript/AccelerometerTest/AccelerometerTest.lua deleted file mode 100644 index 0aa26faf6c..0000000000 --- a/samples/Lua/TestLua/Resources/luaScript/AccelerometerTest/AccelerometerTest.lua +++ /dev/null @@ -1,67 +0,0 @@ -local function AccelerometerMainLayer() - - local function title() - return "AccelerometerTest" - end - local layer = cc.Layer:create() - - layer:setAccelerometerEnabled(true) - - local label = cc.LabelTTF:create(title(), "Arial", 32) - layer:addChild(label, 1) - label:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 50) ) - - local ball = cc.Sprite:create("Images/ball.png") - ball:setPosition(cc.p(VisibleRect:center().x, VisibleRect:center().y)) - layer:addChild(ball) - - ball:retain() - - local function didAccelerate(x,y,z,timestamp) - - if nil == ball then - return - end - - local director = cc.Director:getInstance() - local szBall = ball:getContentSize() - local ptNowX,ptNowY = ball:getPosition() - local ptTemp = director:convertToUI(cc.p(ptNowX,ptNowY)) - - ptTemp.x = ptTemp.x + x * 9.81 - ptTemp.y = ptTemp.y - y * 9.81 - - local ptNext = director:convertToGL(cc.p(ptTemp.x,ptTemp.y)) - - local minX = math.floor(VisibleRect:left().x + szBall.width / 2.0) - local maxX = math.floor(VisibleRect:right().x - szBall.width / 2.0) - if ptNext.x < minX then - ptNext.x = minX - elseif ptNext.x > maxX then - ptNext.x = maxX - end - - local minY = math.floor(VisibleRect:bottom().y + szBall.height / 2.0) - local maxY = math.floor(VisibleRect:top().y - szBall.height / 2.0) - if ptNext.y < minY then - ptNext.y = minY - elseif ptNext.y > maxY then - ptNext.y = maxY - end - - ball:setPosition(cc.p(ptNext.x , ptNext.y)) - end - - layer:registerScriptAccelerateHandler(didAccelerate) - - return layer -end - - -function AccelerometerMain() - cclog("AccelerometerMain") - local scene = cc.Scene:create() - scene:addChild(AccelerometerMainLayer()) - scene:addChild(CreateBackMenuItem()) - return scene -end diff --git a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioGUITest/CocoStudioGUITest.lua.REMOVED.git-id b/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioGUITest/CocoStudioGUITest.lua.REMOVED.git-id deleted file mode 100644 index 8d7bc14119..0000000000 --- a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioGUITest/CocoStudioGUITest.lua.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -1cb290e913d84d8cd141945c8b4a78ea45481cd5 \ No newline at end of file diff --git a/samples/Lua/TestLua/Resources/luaScript/KeypadTest/KeypadTest.lua b/samples/Lua/TestLua/Resources/luaScript/KeypadTest/KeypadTest.lua deleted file mode 100644 index 9771efe28e..0000000000 --- a/samples/Lua/TestLua/Resources/luaScript/KeypadTest/KeypadTest.lua +++ /dev/null @@ -1,38 +0,0 @@ -local function KeypadMainLayer() - local pLayer = cc.Layer:create() - - local s = cc.Director:getInstance():getWinSize() - local label = cc.LabelTTF:create("Keypad Test", "Arial", 28) - pLayer:addChild(label, 0) - label:setPosition( cc.p(s.width/2, s.height-50) ) - - pLayer:setKeypadEnabled(true) - - -- create a label to display the tip string - local pLabelTip = cc.LabelTTF:create("Please press any key...", "Arial", 22) - pLabelTip:setPosition(cc.p(s.width / 2, s.height / 2)) - pLayer:addChild(pLabelTip, 0) - - pLabelTip:retain() - - local function KeypadHandler(strEvent) - if "backClicked" == strEvent then - pLabelTip:setString("BACK clicked!"); - elseif "menuClicked" == strEvent then - pLabelTip:setString("MENU clicked!"); - end - end - - pLayer:registerScriptKeypadHandler(KeypadHandler) - - return pLayer -end - - -function KeypadTestMain() - cclog("KeypadTestMain") - local scene = cc.Scene:create() - scene:addChild(KeypadMainLayer()) - scene:addChild(CreateBackMenuItem()) - return scene -end diff --git a/samples/Lua/TestLua/Resources/luaScript/TouchesTest/Paddle.lua b/samples/Lua/TestLua/Resources/luaScript/TouchesTest/Paddle.lua deleted file mode 100644 index 61da0a5171..0000000000 --- a/samples/Lua/TestLua/Resources/luaScript/TouchesTest/Paddle.lua +++ /dev/null @@ -1,62 +0,0 @@ -require "extern" -require "luaScript/VisibleRect" - -Paddle = class("Paddle", function(texture) - return cc.Sprite:createWithTexture(texture) -end) - -Paddle.__index = Paddle - -local kPaddleStateGrabbed = 0 -local kPaddleStateUngrabbed = 1 - -Paddle.m_state = kPaddleStateGrabbed - - -function Paddle:rect() - local s = self:getTexture():getContentSize() - return cc.rect(-s.width / 2, -s.height / 2, s.width, s.height) -end - -function Paddle:containsTouchLocation(x,y) - local position = cc.p(self:getPosition()) - local s = self:getTexture():getContentSize() - local touchRect = cc.rect(-s.width / 2 + position.x, -s.height / 2 + position.y, s.width, s.height) - local b = cc.rectContainsPoint(touchRect, cc.p(x,y)) - return b -end - -function Paddle:ccTouchBegan(x, y) - if (self.m_state ~= kPaddleStateUngrabbed) then - return false - end - - self.m_state = kPaddleStateGrabbed; - return true; -end - -function Paddle:ccTouchMoved(x, y) - self:setPosition( cc.p(x,y) ); -end - -function Paddle:ccTouchEnded(x, y) - self.m_state = kPaddleStateUngrabbed; -end - -function Paddle:onTouch(eventType, x, y) - if eventType == "began" then - return self:ccTouchBegan(x,y) - elseif eventType == "moved" then - return self:ccTouchMoved(x,y) - elseif eventType == "ended" then - return self:ccTouchEnded(x, y) - end -end - -function Paddle:paddleWithTexture(aTexture) - local pPaddle = Paddle.new(aTexture); - self.m_state = kPaddleStateUngrabbed; - return pPaddle; -end - - diff --git a/samples/Lua/TestLua/proj.android/.classpath b/samples/Lua/TestLua/proj.android/.classpath deleted file mode 100644 index 0b08408342..0000000000 --- a/samples/Lua/TestLua/proj.android/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/samples/Lua/TestLua/proj.android/ant.properties b/samples/Lua/TestLua/proj.android/ant.properties deleted file mode 100644 index b0971e891e..0000000000 --- a/samples/Lua/TestLua/proj.android/ant.properties +++ /dev/null @@ -1,17 +0,0 @@ -# This file is used to override default values used by the Ant build system. -# -# This file must be checked into Version Control Systems, as it is -# integral to the build system of your project. - -# This file is only used by the Ant script. - -# You can use this to override default values such as -# 'source.dir' for the location of your java source folder and -# 'out.dir' for the location of your output folder. - -# You can also use it define how the release builds are signed by declaring -# the following properties: -# 'key.store' for the location of your keystore and -# 'key.alias' for the name of the key to use. -# The password will be asked during the build when you use the 'release' target. - diff --git a/samples/Lua/TestLua/proj.android/proguard-project.txt b/samples/Lua/TestLua/proj.android/proguard-project.txt deleted file mode 100644 index f2fe1559a2..0000000000 --- a/samples/Lua/TestLua/proj.android/proguard-project.txt +++ /dev/null @@ -1,20 +0,0 @@ -# To enable ProGuard in your project, edit project.properties -# to define the proguard.config property as described in that file. -# -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in ${sdk.dir}/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the ProGuard -# include property in project.properties. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/samples/Lua/TestLua/proj.android/project.properties b/samples/Lua/TestLua/proj.android/project.properties deleted file mode 100644 index 0a6dc6664d..0000000000 --- a/samples/Lua/TestLua/proj.android/project.properties +++ /dev/null @@ -1,13 +0,0 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system use, -# "ant.properties", and override values to adapt the script to your -# project structure. - -# Project target. -target=android-10 - -android.library.reference.1=../../../../cocos/2d/platform/android/java diff --git a/samples/Lua/TestLua/proj.ios/Default-568h@2x.png.REMOVED.git-id b/samples/Lua/TestLua/proj.ios/Default-568h@2x.png.REMOVED.git-id deleted file mode 100644 index 8f5838f3a8..0000000000 --- a/samples/Lua/TestLua/proj.ios/Default-568h@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -66c6d1cead373b45218424f6a82f370897e443e4 \ No newline at end of file diff --git a/samples/Lua/TestLua/proj.ios/Default@2x.png.REMOVED.git-id b/samples/Lua/TestLua/proj.ios/Default@2x.png.REMOVED.git-id deleted file mode 100644 index 8843505b20..0000000000 --- a/samples/Lua/TestLua/proj.ios/Default@2x.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -84689888a14a2123d2b39f7f2f61be8c15207479 \ No newline at end of file diff --git a/samples/Lua/TestLua/proj.ios/RootViewController.h b/samples/Lua/TestLua/proj.ios/RootViewController.h deleted file mode 100644 index 11dfc4bf88..0000000000 --- a/samples/Lua/TestLua/proj.ios/RootViewController.h +++ /dev/null @@ -1,33 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2010 Ricardo Quesada - - 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. - ****************************************************************************/ - -#import - - -@interface RootViewController : UIViewController { - -} -- (BOOL)prefersStatusBarHidden; -@end diff --git a/samples/Lua/TestLua/proj.ios/RootViewController.mm b/samples/Lua/TestLua/proj.ios/RootViewController.mm deleted file mode 100644 index a00da00584..0000000000 --- a/samples/Lua/TestLua/proj.ios/RootViewController.mm +++ /dev/null @@ -1,96 +0,0 @@ -/**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2010 Ricardo Quesada - - 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. - ****************************************************************************/ - -#import "RootViewController.h" - - -@implementation RootViewController - -/* - // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { - if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { - // Custom initialization - } - return self; -} -*/ - -/* -// Implement loadView to create a view hierarchy programmatically, without using a nib. -- (void)loadView { -} -*/ - -/* -// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. -- (void)viewDidLoad { - [super viewDidLoad]; -} - -*/ -// Override to allow orientations other than the default portrait orientation. -// This method is deprecated on ios6 -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { - return UIInterfaceOrientationIsLandscape( interfaceOrientation ); -} - -// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead -- (NSUInteger) supportedInterfaceOrientations{ -#ifdef __IPHONE_6_0 - return UIInterfaceOrientationMaskAllButUpsideDown; -#endif -} - -- (BOOL) shouldAutorotate { - return YES; -} - -//fix not hide status on ios7 -- (BOOL)prefersStatusBarHidden -{ - return YES; -} - -- (void)didReceiveMemoryWarning { - // Releases the view if it doesn't have a superview. - [super didReceiveMemoryWarning]; - - // Release any cached data, images, etc that aren't in use. -} - -- (void)viewDidUnload { - [super viewDidUnload]; - // Release any retained subviews of the main view. - // e.g. self.myOutlet = nil; -} - - -- (void)dealloc { - [super dealloc]; -} - - -@end diff --git a/samples/Lua/TestLua/proj.linux/main.cpp b/samples/Lua/TestLua/proj.linux/main.cpp deleted file mode 100644 index 67f1f00575..0000000000 --- a/samples/Lua/TestLua/proj.linux/main.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "../Classes/AppDelegate.h" -#include "cocos2d.h" -#include "CCEGLView.h" - -#include -#include -#include -#include - -USING_NS_CC; - -int main(int argc, char **argv) -{ - // create the application instance - AppDelegate app; - EGLView eglView; - eglView.init("TestLua",900,640); - return Application::getInstance()->run(); -} diff --git a/samples/Lua/TestLua/proj.mac/Icon.icns.REMOVED.git-id b/samples/Lua/TestLua/proj.mac/Icon.icns.REMOVED.git-id deleted file mode 100644 index 9874ec6979..0000000000 --- a/samples/Lua/TestLua/proj.mac/Icon.icns.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3d09e8fb4f4ca1c1ae7ab0a6948db592c7c3d9a0 \ No newline at end of file diff --git a/samples/Lua/TestLua/proj.mac/en.lproj/InfoPlist.strings b/samples/Lua/TestLua/proj.mac/en.lproj/InfoPlist.strings deleted file mode 100644 index 477b28ff8f..0000000000 --- a/samples/Lua/TestLua/proj.mac/en.lproj/InfoPlist.strings +++ /dev/null @@ -1,2 +0,0 @@ -/* Localized versions of Info.plist keys */ - diff --git a/samples/Lua/TestLua/proj.mac/en.lproj/MainMenu.xib b/samples/Lua/TestLua/proj.mac/en.lproj/MainMenu.xib deleted file mode 100644 index 9f99439250..0000000000 --- a/samples/Lua/TestLua/proj.mac/en.lproj/MainMenu.xib +++ /dev/null @@ -1,812 +0,0 @@ - - - - 1060 - 10K549 - 1938 - 1038.36 - 461.00 - - com.apple.InterfaceBuilder.CocoaPlugin - 1938 - - - YES - NSMenuItem - NSCustomObject - NSMenu - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - - - PluginDependencyRecalculationVersion - - - - YES - - NSApplication - - - FirstResponder - - - NSApplication - - - AMainMenu - - YES - - - HelloCpp - - 1048576 - 2147483647 - - NSImage - NSMenuCheckmark - - - NSImage - NSMenuMixedState - - submenuAction: - - HelloCpp - - YES - - - About HelloCpp - - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Preferences… - , - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Services - - 1048576 - 2147483647 - - - submenuAction: - - Services - - YES - - _NSServicesMenu - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Hide HelloCpp - h - 1048576 - 2147483647 - - - - - - Hide Others - h - 1572864 - 2147483647 - - - - - - Show All - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Quit HelloCpp - q - 1048576 - 2147483647 - - - - - _NSAppleMenu - - - - - View - - 1048576 - 2147483647 - - - submenuAction: - - View - - YES - - - Toggle Fullscreen - f - 1048576 - 2147483647 - - - - - - - - - Window - - 1048576 - 2147483647 - - - submenuAction: - - Window - - YES - - - Minimize - m - 1048576 - 2147483647 - - - - - - Zoom - - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Bring All to Front - - 1048576 - 2147483647 - - - - - _NSWindowsMenu - - - - - Help - - 2147483647 - - - submenuAction: - - Help - - YES - - - HelloCpp Help - ? - 1048576 - 2147483647 - - - - - _NSHelpMenu - - - - _NSMainMenu - - - AppController - - - NSFontManager - - - - - YES - - - terminate: - - - - 449 - - - - orderFrontStandardAboutPanel: - - - - 142 - - - - delegate - - - - 495 - - - - performMiniaturize: - - - - 37 - - - - arrangeInFront: - - - - 39 - - - - performZoom: - - - - 240 - - - - hide: - - - - 367 - - - - hideOtherApplications: - - - - 368 - - - - unhideAllApplications: - - - - 370 - - - - showHelp: - - - - 493 - - - - toggleFullScreen: - - - - 537 - - - - - YES - - 0 - - YES - - - - - - -2 - - - File's Owner - - - -1 - - - First Responder - - - -3 - - - Application - - - 29 - - - YES - - - - - - - - - 19 - - - YES - - - - - - 56 - - - YES - - - - - - 57 - - - YES - - - - - - - - - - - - - - - - 58 - - - - - 134 - - - - - 150 - - - - - 136 - - - - - 144 - - - - - 129 - - - - - 143 - - - - - 236 - - - - - 131 - - - YES - - - - - - 149 - - - - - 145 - - - - - 130 - - - - - 24 - - - YES - - - - - - - - - 92 - - - - - 5 - - - - - 239 - - - - - 23 - - - - - 295 - - - YES - - - - - - 296 - - - YES - - - - - - 420 - - - - - 490 - - - YES - - - - - - 491 - - - YES - - - - - - 492 - - - - - 494 - - - - - 536 - - - - - - - YES - - YES - -1.IBPluginDependency - -2.IBPluginDependency - -3.IBPluginDependency - 129.IBPluginDependency - 130.IBPluginDependency - 131.IBPluginDependency - 134.IBPluginDependency - 136.IBPluginDependency - 143.IBPluginDependency - 144.IBPluginDependency - 145.IBPluginDependency - 149.IBPluginDependency - 150.IBPluginDependency - 19.IBPluginDependency - 23.IBPluginDependency - 236.IBPluginDependency - 239.IBPluginDependency - 24.IBPluginDependency - 29.IBPluginDependency - 295.IBPluginDependency - 296.IBPluginDependency - 420.IBPluginDependency - 490.IBPluginDependency - 491.IBPluginDependency - 492.IBPluginDependency - 494.IBPluginDependency - 5.IBPluginDependency - 536.IBPluginDependency - 56.IBPluginDependency - 57.IBPluginDependency - 58.IBPluginDependency - 92.IBPluginDependency - - - YES - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - - - - YES - - - - - - YES - - - - - 541 - - - - YES - - AppController - NSObject - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - id - id - - - - YES - - YES - exitFullScreen: - toggleFullScreen: - - - YES - - exitFullScreen: - id - - - toggleFullScreen: - id - - - - - YES - - YES - glView - window - - - YES - EAGLView - Window - - - - YES - - YES - glView - window - - - YES - - glView - EAGLView - - - window - Window - - - - - IBProjectSource - ./Classes/AppController.h - - - - EAGLView - NSOpenGLView - - IBProjectSource - ./Classes/EAGLView.h - - - - - 0 - IBCocoaFramework - - com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 - - - YES - 3 - - YES - - YES - NSMenuCheckmark - NSMenuMixedState - - - YES - {9, 8} - {7, 2} - - - - diff --git a/template/multi-platform-cpp/CMakeLists.txt b/template/multi-platform-cpp/CMakeLists.txt index b2bfd73699..226d0e9779 100644 --- a/template/multi-platform-cpp/CMakeLists.txt +++ b/template/multi-platform-cpp/CMakeLists.txt @@ -48,12 +48,14 @@ set(GAME_SRC set(COCOS2D_ROOT ${CMAKE_SOURCE_DIR}/cocos2d) include_directories( + /usr/local/include/GLFW ${COCOS2D_ROOT} ${COCOS2D_ROOT}/cocos ${COCOS2D_ROOT}/cocos/audio/include ${COCOS2D_ROOT}/cocos/2d ${COCOS2D_ROOT}/cocos/2d/renderer ${COCOS2D_ROOT}/cocos/2d/platform + ${COCOS2D_ROOT}/cocos/2d/platform/desktop ${COCOS2D_ROOT}/cocos/2d/platform/linux ${COCOS2D_ROOT}/cocos/base ${COCOS2D_ROOT}/cocos/physics @@ -65,8 +67,6 @@ include_directories( ${COCOS2D_ROOT}/external/jpeg/include/linux ${COCOS2D_ROOT}/external/tiff/include/linux ${COCOS2D_ROOT}/external/webp/include/linux - ${COCOS2D_ROOT}/external/glfw3/include/linux - ${COCOS2D_ROOT}/external/curl/include/linux/${ARCH_DIR} ${COCOS2D_ROOT}/external/tinyxml2 ${COCOS2D_ROOT}/external/unzip ${COCOS2D_ROOT}/external/chipmunk/include/chipmunk @@ -80,7 +80,6 @@ link_directories( ${COCOS2D_ROOT}/external/tiff/prebuilt/linux/${ARCH_DIR} ${COCOS2D_ROOT}/external/webp/prebuilt/linux/${ARCH_DIR} ${COCOS2D_ROOT}/external/freetype2/prebuilt/linux/${ARCH_DIR} - ${COCOS2D_ROOT}/external/curl/prebuilt/linux/${ARCH_DIR} ${COCOS2D_ROOT}/external/linux-specific/fmod/prebuilt/${ARCH_DIR} ) diff --git a/template/multi-platform-cpp/Classes/AppDelegate.cpp b/template/multi-platform-cpp/Classes/AppDelegate.cpp index 41659181d6..6b5298dab3 100644 --- a/template/multi-platform-cpp/Classes/AppDelegate.cpp +++ b/template/multi-platform-cpp/Classes/AppDelegate.cpp @@ -14,10 +14,12 @@ AppDelegate::~AppDelegate() bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); - auto eglView = EGLView::getInstance(); + auto glview = director->getOpenGLView(); + if(!glview) { + glview = GLView::create("My Game"); + director->setOpenGLView(glview); + } - director->setOpenGLView(eglView); - // turn on display FPS director->setDisplayStats(true); diff --git a/template/multi-platform-cpp/proj.android/AndroidManifest.xml b/template/multi-platform-cpp/proj.android/AndroidManifest.xml index d2a87966cc..fc2ab5cfd2 100644 --- a/template/multi-platform-cpp/proj.android/AndroidManifest.xml +++ b/template/multi-platform-cpp/proj.android/AndroidManifest.xml @@ -15,7 +15,7 @@ android:label="@string/app_name" android:screenOrientation="landscape" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" - android:configChanges="orientation|screenSize|smallestScreenSize"> + android:configChanges="orientation"> setOpenGLView(glview); + cocos2d::Application::getInstance()->run(); return YES; diff --git a/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.h b/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.h index 25f728b12d..a1669019e2 100644 --- a/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.h +++ b/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.h @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + Copyright (c) 2013-2014 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. + ****************************************************************************/ + #import diff --git a/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm b/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm index 187b274b91..b7d78629ab 100644 --- a/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm +++ b/template/multi-platform-cpp/proj.ios_mac/ios/RootViewController.mm @@ -1,6 +1,31 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + Copyright (c) 2013-2014 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. + ****************************************************************************/ + #import "RootViewController.h" #import "cocos2d.h" -#import "EAGLView.h" +#import "CCEAGLView.h" @implementation RootViewController @@ -25,7 +50,7 @@ - (void)viewDidLoad { [super viewDidLoad]; } - + */ // Override to allow orientations other than the default portrait orientation. // This method is deprecated on ios6 @@ -47,7 +72,10 @@ - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; - CGSize s = CGSizeMake([[CCEAGLView sharedEGLView] getWidth], [[CCEAGLView sharedEGLView] getHeight]); + cocos2d::GLView *glview = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView*) glview->getEAGLView(); + + CGSize s = CGSizeMake([eaglview getWidth], [eaglview getHeight]); cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); } @@ -61,7 +89,7 @@ - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; - + // Release any cached data, images, etc that aren't in use. } diff --git a/template/multi-platform-cpp/proj.ios_mac/mac/main.cpp b/template/multi-platform-cpp/proj.ios_mac/mac/main.cpp index 1d6fd403f1..1814d16c15 100644 --- a/template/multi-platform-cpp/proj.ios_mac/mac/main.cpp +++ b/template/multi-platform-cpp/proj.ios_mac/mac/main.cpp @@ -23,14 +23,11 @@ ****************************************************************************/ #include "AppDelegate.h" -#include "CCEGLView.h" USING_NS_CC; int main(int argc, char *argv[]) { AppDelegate app; - EGLView eglView; - eglView.init("Hello World",900,640); return Application::getInstance()->run(); } diff --git a/template/multi-platform-cpp/proj.linux/build.sh b/template/multi-platform-cpp/proj.linux/build.sh deleted file mode 100755 index 99dcf294d3..0000000000 --- a/template/multi-platform-cpp/proj.linux/build.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash - -# Exit on error -set -e - -rm -rf ../bin -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -#make global libs -cd ../cocos2d -#install depend libs -sudo ./build/install-deps-linux.sh -mkdir -p linux-build -cd linux-build -cmake .. -DBUILD_LIBS_LUA=OFF -DBUILD_HelloCpp=OFF -DBUILD_TestCpp=OFF -DBUILD_HelloLua=OFF -DBUILD_TestLua=OFF -make -j4 - -#make bin -cd $DIR -rm -rf bin -mkdir -p build -cd build -cmake ../.. -make -j4 -cd .. -mv ../bin bin diff --git a/template/multi-platform-cpp/proj.linux/main.cpp b/template/multi-platform-cpp/proj.linux/main.cpp index 78a0c780cb..c5b735da78 100644 --- a/template/multi-platform-cpp/proj.linux/main.cpp +++ b/template/multi-platform-cpp/proj.linux/main.cpp @@ -1,6 +1,4 @@ #include "../Classes/AppDelegate.h" -#include "cocos2d.h" -#include "CCEGLView.h" #include #include @@ -13,7 +11,5 @@ int main(int argc, char **argv) { // create the application instance AppDelegate app; - EGLView eglView; - eglView.init("Cocos2d-x Game",900,640); return Application::getInstance()->run(); } diff --git a/template/multi-platform-cpp/proj.win32/main.cpp b/template/multi-platform-cpp/proj.win32/main.cpp index 3e192c981c..46ce5bf290 100644 --- a/template/multi-platform-cpp/proj.win32/main.cpp +++ b/template/multi-platform-cpp/proj.win32/main.cpp @@ -1,6 +1,5 @@ #include "main.h" #include "AppDelegate.h" -#include "CCEGLView.h" USING_NS_CC; @@ -14,7 +13,5 @@ int APIENTRY _tWinMain(HINSTANCE hInstance, // create the application instance AppDelegate app; - EGLView eglView; - eglView.init("TestCPP",900,640); return Application::getInstance()->run(); } diff --git a/template/multi-platform-js/Classes/AppDelegate.cpp b/template/multi-platform-js/Classes/AppDelegate.cpp index e409b974b5..53be703216 100644 --- a/template/multi-platform-js/Classes/AppDelegate.cpp +++ b/template/multi-platform-js/Classes/AppDelegate.cpp @@ -26,15 +26,19 @@ AppDelegate::~AppDelegate() bool AppDelegate::applicationDidFinishLaunching() { // initialize director - Director *director = Director::getInstance(); - director->setOpenGLView(EGLView::getInstance()); - + auto director = Director::getInstance(); + auto glview = director->getOpenGLView(); + if(!glview) { + glview = GLView::create("My Game"); + director->setOpenGLView(glview); + } + // turn on display FPS director->setDisplayStats(true); - + // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0 / 60); - + ScriptingCore* sc = ScriptingCore::getInstance(); sc->addRegisterCallback(register_all_cocos2dx); sc->addRegisterCallback(register_all_cocos2dx_extension); @@ -44,32 +48,12 @@ bool AppDelegate::applicationDidFinishLaunching() sc->addRegisterCallback(JSB_register_opengl); sc->addRegisterCallback(jsb_register_system); sc->start(); - + ScriptEngineProtocol *engine = ScriptingCore::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(engine); ScriptingCore::getInstance()->runScript("cocos2d-jsb.js"); - - return true; -} -void handle_signal(int signal) { - static int internal_state = 0; - ScriptingCore* sc = ScriptingCore::getInstance(); - // should start everything back - Director* director = Director::getInstance(); - if (director->getRunningScene()) { - director->popToRootScene(); - } else { - PoolManager::sharedPoolManager()->finalize(); - if (internal_state == 0) { - //sc->dumpRoot(NULL, 0, NULL); - sc->start(); - internal_state = 1; - } else { - sc->runScript("hello.js"); - internal_state = 0; - } - } + return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too diff --git a/template/multi-platform-js/Classes/AppDelegate.h b/template/multi-platform-js/Classes/AppDelegate.h index df8f12f70f..9a158eae61 100644 --- a/template/multi-platform-js/Classes/AppDelegate.h +++ b/template/multi-platform-js/Classes/AppDelegate.h @@ -9,7 +9,7 @@ #ifndef _APP_DELEGATE_H_ #define _APP_DELEGATE_H_ -#include "CCApplication.h" +#include "cocos2d.h" /** @brief The cocos2d Application. diff --git a/template/multi-platform-js/Resources/src/resource.js b/template/multi-platform-js/Resources/src/resource.js index 145f7ac6ab..5bfb37a53b 100644 --- a/template/multi-platform-js/Resources/src/resource.js +++ b/template/multi-platform-js/Resources/src/resource.js @@ -2,7 +2,7 @@ var s_HelloWorld = "res/HelloWorld.png"; var s_CloseNormal = "res/CloseNormal.png"; var s_CloseSelected = "res/CloseSelected.png"; -var g_ressources = [ +var g_resources = [ //image {src:s_HelloWorld}, {src:s_CloseNormal}, @@ -17,4 +17,4 @@ var g_ressources = [ //bgm //effect -]; \ No newline at end of file +]; diff --git a/template/multi-platform-js/proj.android/AndroidManifest.xml b/template/multi-platform-js/proj.android/AndroidManifest.xml index 9b92bfa562..3c3045b22c 100644 --- a/template/multi-platform-js/proj.android/AndroidManifest.xml +++ b/template/multi-platform-js/proj.android/AndroidManifest.xml @@ -14,7 +14,7 @@ android:label="@string/app_name" android:screenOrientation="landscape" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" - android:configChanges="orientation|screenSize|smallestScreenSize"> + android:configChanges="orientation"> #import "AppController.h" #import "cocos2d.h" -#import "EAGLView.h" +#import "CCEAGLView.h" #import "AppDelegate.h" #import "RootViewController.h" @@ -21,7 +45,7 @@ static AppDelegate s_sharedApplication; // Add the view controller's view to the window and display. window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; - CCEAGLView *__glView = [CCEAGLView viewWithFrame: [window bounds] + CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds] pixelFormat: kEAGLColorFormatRGBA8 depthFormat: GL_DEPTH_COMPONENT16 //_OES preserveBackbuffer: NO @@ -29,12 +53,12 @@ static AppDelegate s_sharedApplication; multiSampling: NO numberOfSamples: 0 ]; - [__glView setMultipleTouchEnabled:YES]; + [eaglView setMultipleTouchEnabled:YES]; // Use RootViewController manage CCEAGLView viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; viewController.wantsFullScreenLayout = YES; - viewController.view = __glView; + viewController.view = eaglView; // Set RootViewController to window if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) @@ -51,6 +75,10 @@ static AppDelegate s_sharedApplication; [window makeKeyAndVisible]; [[UIApplication sharedApplication] setStatusBarHidden: YES]; + + // IMPORTANT: Setting the GLView should be done after creating the RootViewController + cocos2d::GLView *glview = cocos2d::GLView::createWithEAGLView(eaglView); + cocos2d::Director::getInstance()->setOpenGLView(glview); cocos2d::Application::getInstance()->run(); return YES; diff --git a/template/multi-platform-js/proj.ios_mac/ios/RootViewController.h b/template/multi-platform-js/proj.ios_mac/ios/RootViewController.h index 11dfc4bf88..a68782316e 100644 --- a/template/multi-platform-js/proj.ios_mac/ios/RootViewController.h +++ b/template/multi-platform-js/proj.ios_mac/ios/RootViewController.h @@ -1,6 +1,6 @@ /**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2010 Ricardo Quesada + Copyright (c) 2013 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm b/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm index 187b274b91..2374fae2d2 100644 --- a/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm +++ b/template/multi-platform-js/proj.ios_mac/ios/RootViewController.mm @@ -1,6 +1,31 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + Copyright (c) 2013-2014 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. + ****************************************************************************/ + #import "RootViewController.h" #import "cocos2d.h" -#import "EAGLView.h" +#import "CCEAGLView.h" @implementation RootViewController @@ -46,8 +71,11 @@ - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + + cocos2d::GLView *glview = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView*) glview->getEAGLView(); - CGSize s = CGSizeMake([[CCEAGLView sharedEGLView] getWidth], [[CCEAGLView sharedEGLView] getHeight]); + CGSize s = CGSizeMake([eaglview getWidth], [eaglview getHeight]); cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); } diff --git a/template/multi-platform-js/proj.ios_mac/mac/main.cpp b/template/multi-platform-js/proj.ios_mac/mac/main.cpp index 1d6fd403f1..1814d16c15 100644 --- a/template/multi-platform-js/proj.ios_mac/mac/main.cpp +++ b/template/multi-platform-js/proj.ios_mac/mac/main.cpp @@ -23,14 +23,11 @@ ****************************************************************************/ #include "AppDelegate.h" -#include "CCEGLView.h" USING_NS_CC; int main(int argc, char *argv[]) { AppDelegate app; - EGLView eglView; - eglView.init("Hello World",900,640); return Application::getInstance()->run(); } diff --git a/template/multi-platform-js/proj.win32/HelloJavascript.vcxproj b/template/multi-platform-js/proj.win32/HelloJavascript.vcxproj index caf0791fc7..a3b73dc491 100644 --- a/template/multi-platform-js/proj.win32/HelloJavascript.vcxproj +++ b/template/multi-platform-js/proj.win32/HelloJavascript.vcxproj @@ -80,7 +80,7 @@ Disabled $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\audio\include;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;DEBUG;_DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_WINDOWS;STRICT;_DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks MultiThreadedDebugDLL @@ -102,7 +102,7 @@ xcopy /Y /Q "$(EngineRoot)external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\win32\*.*" "$(OutDir)" - libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-27.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -157,7 +157,7 @@ xcopy /Y /Q "$(EngineRoot)external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\win32\*.*" "$(OutDir)" - libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-27.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 diff --git a/template/multi-platform-js/proj.win32/main.cpp b/template/multi-platform-js/proj.win32/main.cpp index e9fef1d86d..69c3b8c9bb 100644 --- a/template/multi-platform-js/proj.win32/main.cpp +++ b/template/multi-platform-js/proj.win32/main.cpp @@ -1,6 +1,5 @@ #include "main.h" #include "AppDelegate.h" -#include "CCEGLView.h" USING_NS_CC; @@ -24,9 +23,6 @@ int APIENTRY _tWinMain(HINSTANCE hInstance, // create the application instance AppDelegate app; - EGLView eglView; - eglView.init("TestCPP",900,640); - int ret = Application::getInstance()->run(); #ifdef USE_WIN32_CONSOLE diff --git a/template/multi-platform-lua/CMakeLists.txt b/template/multi-platform-lua/CMakeLists.txt index ccf8e4b634..9a09170a9f 100644 --- a/template/multi-platform-lua/CMakeLists.txt +++ b/template/multi-platform-lua/CMakeLists.txt @@ -47,6 +47,7 @@ set(GAME_SRC set(COCOS2D_ROOT ${CMAKE_SOURCE_DIR}/cocos2d) include_directories( + /usr/local/include/GLFW Classes ${COCOS2D_ROOT}/cocos/scripting/lua/bindings ${COCOS2D_ROOT}/external/lua/lua @@ -57,6 +58,7 @@ include_directories( ${COCOS2D_ROOT}/cocos/2d ${COCOS2D_ROOT}/cocos/2d/renderer ${COCOS2D_ROOT}/cocos/2d/platform + ${COCOS2D_ROOT}/cocos/2d/platform/desktop ${COCOS2D_ROOT}/cocos/2d/platform/linux ${COCOS2D_ROOT}/cocos/base ${COCOS2D_ROOT}/cocos/physics @@ -68,8 +70,6 @@ include_directories( ${COCOS2D_ROOT}/external/jpeg/include/linux ${COCOS2D_ROOT}/external/tiff/include/linux ${COCOS2D_ROOT}/external/webp/include/linux - ${COCOS2D_ROOT}/external/glfw3/include/linux - ${COCOS2D_ROOT}/external/curl/include/linux/${ARCH_DIR} ${COCOS2D_ROOT}/external/tinyxml2 ${COCOS2D_ROOT}/external/unzip ${COCOS2D_ROOT}/external/chipmunk/include/chipmunk @@ -83,7 +83,6 @@ link_directories( ${COCOS2D_ROOT}/external/tiff/prebuilt/linux/${ARCH_DIR} ${COCOS2D_ROOT}/external/webp/prebuilt/linux/${ARCH_DIR} ${COCOS2D_ROOT}/external/freetype2/prebuilt/linux/${ARCH_DIR} - ${COCOS2D_ROOT}/external/curl/prebuilt/linux/${ARCH_DIR} ${COCOS2D_ROOT}/external/linux-specific/fmod/prebuilt/${ARCH_DIR} ) diff --git a/template/multi-platform-lua/Classes/AppDelegate.cpp b/template/multi-platform-lua/Classes/AppDelegate.cpp index ae4f700060..38c73e160f 100644 --- a/template/multi-platform-lua/Classes/AppDelegate.cpp +++ b/template/multi-platform-lua/Classes/AppDelegate.cpp @@ -1,5 +1,3 @@ -#include "cocos2d.h" -#include "CCEGLView.h" #include "AppDelegate.h" #include "CCLuaEngine.h" #include "SimpleAudioEngine.h" @@ -21,9 +19,13 @@ bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); - director->setOpenGLView(EGLView::getInstance()); + auto glview = director->getOpenGLView(); + if(!glview) { + glview = GLView::create("My Game"); + director->setOpenGLView(glview); + } - EGLView::getInstance()->setDesignResolutionSize(480, 320, ResolutionPolicy::NO_BORDER); + glview->setDesignResolutionSize(480, 320, ResolutionPolicy::NO_BORDER); // turn on display FPS director->setDisplayStats(true); @@ -34,10 +36,11 @@ bool AppDelegate::applicationDidFinishLaunching() // register lua engine auto engine = LuaEngine::getInstance(); ScriptEngineManager::getInstance()->setScriptEngine(engine); - - std::string path = FileUtils::getInstance()->fullPathForFilename("hello.lua"); - engine->executeScriptFile(path.c_str()); + //The call was commented because it will lead to ZeroBrane Studio can't find correct context when debugging + //engine->executeScriptFile("hello.lua"); + engine->executeString("require 'hello.lua'"); + return true; } diff --git a/template/multi-platform-lua/Resources/hello.lua b/template/multi-platform-lua/Resources/hello.lua index 607b7d7508..770e922c9d 100644 --- a/template/multi-platform-lua/Resources/hello.lua +++ b/template/multi-platform-lua/Resources/hello.lua @@ -17,6 +17,14 @@ local function main() collectgarbage("setpause", 100) collectgarbage("setstepmul", 5000) + --support debug + local targetPlatform = cc.Application:getInstance():getTargetPlatform() + if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) or + (cc.PLATFORM_OS_ANDROID == targetPlatform) or (cc.PLATFORM_OS_WINDOWS == targetPlatform) or + (cc.PLATFORM_OS_MAC == targetPlatform) then + local host = 'localhost' -- please change localhost to your PC's IP for on-device debugging + require('mobdebug').start(host) + end require "hello2" cclog("result is " .. myadd(1, 1)) @@ -103,43 +111,39 @@ local function main() -- handing touch events local touchBeginPoint = nil - - local function onTouchBegan(x, y) - cclog("onTouchBegan: %0.2f, %0.2f", x, y) - touchBeginPoint = {x = x, y = y} + local function onTouchBegan(touch, event) + local location = touch:getLocation() + cclog("onTouchBegan: %0.2f, %0.2f", location.x, location.y) + touchBeginPoint = {x = location.x, y = location.y} spriteDog.isPaused = true -- CCTOUCHBEGAN event must return true return true end - local function onTouchMoved(x, y) - cclog("onTouchMoved: %0.2f, %0.2f", x, y) + local function onTouchMoved(touch, event) + local location = touch:getLocation() + cclog("onTouchMoved: %0.2f, %0.2f", location.x, location.y) if touchBeginPoint then local cx, cy = layerFarm:getPosition() - layerFarm:setPosition(cx + x - touchBeginPoint.x, - cy + y - touchBeginPoint.y) - touchBeginPoint = {x = x, y = y} + layerFarm:setPosition(cx + location.x - touchBeginPoint.x, + cy + location.y - touchBeginPoint.y) + touchBeginPoint = {x = location.x, y = location.y} end end - local function onTouchEnded(x, y) - cclog("onTouchEnded: %0.2f, %0.2f", x, y) + local function onTouchEnded(touch, event) + local location = touch:getLocation() + cclog("onTouchEnded: %0.2f, %0.2f", location.x, location.y) touchBeginPoint = nil spriteDog.isPaused = false end - local function onTouch(eventType, x, y) - if eventType == "began" then - return onTouchBegan(x, y) - elseif eventType == "moved" then - return onTouchMoved(x, y) - else - return onTouchEnded(x, y) - end - end - - layerFarm:registerScriptTouchHandler(onTouch) - layerFarm:setTouchEnabled(true) + local listener = cc.EventListenerTouchOneByOne:create() + listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN ) + listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED ) + listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED ) + local eventDispatcher = layerFarm:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layerFarm) return layerFarm end diff --git a/template/multi-platform-lua/Resources/mobdebug.lua b/template/multi-platform-lua/Resources/mobdebug.lua new file mode 100644 index 0000000000..31ef8af06b --- /dev/null +++ b/template/multi-platform-lua/Resources/mobdebug.lua @@ -0,0 +1,1465 @@ +-- +-- MobDebug 0.542 +-- Copyright 2011-13 Paul Kulchenko +-- Based on RemDebug 1.0 Copyright Kepler Project 2005 +-- + +local mobdebug = { + _NAME = "mobdebug", + _VERSION = 0.542, + _COPYRIGHT = "Paul Kulchenko", + _DESCRIPTION = "Mobile Remote Debugger for the Lua programming language", + port = os and os.getenv and os.getenv("MOBDEBUG_PORT") or 8172, + checkcount = 200, + yieldtimeout = 0.02, +} + +local coroutine = coroutine +local error = error +local getfenv = getfenv +local setfenv = setfenv +local loadstring = loadstring or load -- "load" replaced "loadstring" in Lua 5.2 +local io = io +local os = os +local pairs = pairs +local require = require +local setmetatable = setmetatable +local string = string +local tonumber = tonumber +local unpack = table.unpack or unpack +local rawget = rawget + +-- if strict.lua is used, then need to avoid referencing some global +-- variables, as they can be undefined; +-- use rawget to to avoid complaints from strict.lua at run-time. +-- it's safe to do the initialization here as all these variables +-- should get defined values (of any) before the debugging starts. +-- there is also global 'wx' variable, which is checked as part of +-- the debug loop as 'wx' can be loaded at any time during debugging. +local genv = _G or _ENV +local jit = rawget(genv, "jit") +local MOAICoroutine = rawget(genv, "MOAICoroutine") + +if not setfenv then -- Lua 5.2 + -- based on http://lua-users.org/lists/lua-l/2010-06/msg00314.html + -- this assumes f is a function + local function findenv(f) + local level = 1 + repeat + local name, value = debug.getupvalue(f, level) + if name == '_ENV' then return level, value end + level = level + 1 + until name == nil + return nil end + getfenv = function (f) return(select(2, findenv(f)) or _G) end + setfenv = function (f, t) + local level = findenv(f) + if level then debug.setupvalue(f, level, t) end + return f end +end + +-- check for OS and convert file names to lower case on windows +-- (its file system is case insensitive, but case preserving), as setting a +-- breakpoint on x:\Foo.lua will not work if the file was loaded as X:\foo.lua. +-- OSX and Windows behave the same way (case insensitive, but case preserving) +local iscasepreserving = os and os.getenv and (os.getenv('WINDIR') + or (os.getenv('OS') or ''):match('[Ww]indows') + or os.getenv('DYLD_LIBRARY_PATH')) + or not io.open("/proc") + +-- turn jit off based on Mike Pall's comment in this discussion: +-- http://www.freelists.org/post/luajit/Debug-hooks-and-JIT,2 +-- "You need to turn it off at the start if you plan to receive +-- reliable hook calls at any later point in time." +if jit and jit.off then jit.off() end + +local socket = require "socket" +local debug = require "debug" +local coro_debugger +local coro_debugee +local coroutines = {}; setmetatable(coroutines, {__mode = "k"}) -- "weak" keys +local events = { BREAK = 1, WATCH = 2, RESTART = 3, STACK = 4 } +local breakpoints = {} +local watches = {} +local lastsource +local lastfile +local watchescnt = 0 +local abort -- default value is nil; this is used in start/loop distinction +local seen_hook = false +local checkcount = 0 +local step_into = false +local step_over = false +local step_level = 0 +local stack_level = 0 +local server +local buf +local outputs = {} +local iobase = {print = print} +local basedir = "" +local deferror = "execution aborted at default debugee" +local debugee = function () + local a = 1 + for _ = 1, 10 do a = a + 1 end + error(deferror) +end +local function q(s) return s:gsub('([%(%)%.%%%+%-%*%?%[%^%$%]])','%%%1') end + +local serpent = (function() ---- include Serpent module for serialization +local n, v = "serpent", 0.25 -- (C) 2012-13 Paul Kulchenko; MIT License +local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" +local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} +local badtype = {thread = true, userdata = true, cdata = true} +local keyword, globals, G = {}, {}, (_G or _ENV) +for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', + 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', + 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end +for k,v in pairs(G) do globals[v] = k end -- build func to name mapping +for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do + for k,v in pairs(G[g]) do globals[v] = g..'.'..k end end + +local function s(t, opts) + local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum + local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge + local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) + local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) + local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 + local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", + -- tostring(val) is needed because __tostring may return a non-string value + function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return syms[s] end)) end + local function safestr(s) return type(s) == "number" and (huge and snum[tostring(s)] or s) + or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 + or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end + local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end + local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal + and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end + local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] + local n = name == nil and '' or name + local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] + local safe = plain and n or '['..safestr(n)..']' + return (path or '')..(plain and path and '.' or '')..safe, safe end + local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding + local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} + local function padnum(d) return ("%0"..maxn.."d"):format(d) end + table.sort(k, function(a,b) + -- sort numeric keys first: k[key] is non-nil for numeric keys + return (k[a] and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) + < (k[b] and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end + local function val2str(t, name, indent, insref, path, plainindex, level) + local ttype, level, mt = type(t), (level or 0), getmetatable(t) + local spath, sname = safename(path, name) + local tag = plainindex and + ((type(name) == "number") and '' or name..space..'='..space) or + (name ~= nil and sname..space..'='..space or '') + if seen[t] then -- already seen this element + sref[#sref+1] = spath..space..'='..space..seen[t] + return tag..'nil'..comment('ref', level) end + if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself + seen[t] = insref or spath + if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end + ttype = type(t) end -- new value falls through to be serialized + if ttype == "table" then + if level >= maxl then return tag..'{}'..comment('max', level) end + seen[t] = insref or spath + if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty + local maxn, o, out = math.min(#t, maxnum or #t), {}, {} + for key = 1, maxn do o[key] = key end + if not maxnum or #o < maxnum then + local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables + for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end + if maxnum and #o > maxnum then o[maxnum+1] = nil end + if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end + local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) + for n, key in ipairs(o) do + local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse + if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing + or opts.keyallow and not opts.keyallow[key] + or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types + or sparse and value == nil then -- skipping nils; do nothing + elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then + if not seen[key] and not globals[key] then + sref[#sref+1] = 'placeholder' + local sname = safename(iname, gensym(key)) -- iname is table for local variables + sref[#sref] = val2str(key,sname,indent,sname,iname,true) end + sref[#sref+1] = 'placeholder' + local path = seen[t]..'['..(seen[key] or globals[key] or gensym(key))..']' + sref[#sref] = path..space..'='..space..(seen[value] or val2str(value,nil,indent,path)) + else + out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) + end + end + local prefix = string.rep(indent or '', level) + local head = indent and '{\n'..prefix..indent or '{' + local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) + local tail = indent and "\n"..prefix..'}' or '}' + return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) + elseif badtype[ttype] then + seen[t] = insref or spath + return tag..globerr(t, level) + elseif ttype == 'function' then + seen[t] = insref or spath + local ok, res = pcall(string.dump, t) + local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or + "loadstring("..safestr(res)..",'@serialized')")..comment(t, level)) + return tag..(func or globerr(t, level)) + else return tag..safestr(t) end -- handle all other types + end + local sepr = indent and "\n" or ";"..space + local body = val2str(t, name, indent) -- this call also populates sref + local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' + local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' + return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" +end + +local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end +return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, + dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, + line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, + block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end } +end)() ---- end of Serpent module + +local function removebasedir(path, basedir) + if iscasepreserving then + -- check if the lowercased path matches the basedir + -- if so, return substring of the original path (to not lowercase it) + return path:lower():find('^'..q(basedir:lower())) + and path:sub(#basedir+1) or path + else + return string.gsub(path, '^'..q(basedir), '') + end +end + +local function stack(start) + local function vars(f) + local func = debug.getinfo(f, "f").func + local i = 1 + local locals = {} + while true do + local name, value = debug.getlocal(f, i) + if not name then break end + if string.sub(name, 1, 1) ~= '(' then locals[name] = {value, tostring(value)} end + i = i + 1 + end + i = 1 + local ups = {} + while func and true do -- check for func as it may be nil for tail calls + local name, value = debug.getupvalue(func, i) + if not name then break end + ups[name] = {value, tostring(value)} + i = i + 1 + end + return locals, ups + end + + local stack = {} + for i = (start or 0), 100 do + local source = debug.getinfo(i, "Snl") + if not source then break end + + local src = source.source + if src:find("@") == 1 then + src = src:sub(2):gsub("\\", "/") + if src:find("%./") == 1 then src = src:sub(3) end + end + + table.insert(stack, { -- remove basedir from source + {source.name, removebasedir(src, basedir), source.linedefined, + source.currentline, source.what, source.namewhat, source.short_src}, + vars(i+1)}) + if source.what == 'main' then break end + end + return stack +end + +local function set_breakpoint(file, line) + if file == '-' and lastfile then file = lastfile + elseif iscasepreserving then file = string.lower(file) end + if not breakpoints[line] then breakpoints[line] = {} end + breakpoints[line][file] = true +end + +local function remove_breakpoint(file, line) + if file == '-' and lastfile then file = lastfile + elseif iscasepreserving then file = string.lower(file) end + if breakpoints[line] then breakpoints[line][file] = nil end +end + +local function has_breakpoint(file, line) + return breakpoints[line] + and breakpoints[line][iscasepreserving and string.lower(file) or file] +end + +local function restore_vars(vars) + if type(vars) ~= 'table' then return end + + -- locals need to be processed in the reverse order, starting from + -- the inner block out, to make sure that the localized variables + -- are correctly updated with only the closest variable with + -- the same name being changed + -- first loop find how many local variables there is, while + -- the second loop processes them from i to 1 + local i = 1 + while true do + local name = debug.getlocal(3, i) + if not name then break end + i = i + 1 + end + i = i - 1 + local written_vars = {} + while i > 0 do + local name = debug.getlocal(3, i) + if not written_vars[name] then + if string.sub(name, 1, 1) ~= '(' then + debug.setlocal(3, i, rawget(vars, name)) + end + written_vars[name] = true + end + i = i - 1 + end + + i = 1 + local func = debug.getinfo(3, "f").func + while true do + local name = debug.getupvalue(func, i) + if not name then break end + if not written_vars[name] then + if string.sub(name, 1, 1) ~= '(' then + debug.setupvalue(func, i, rawget(vars, name)) + end + written_vars[name] = true + end + i = i + 1 + end +end + +local function capture_vars(level) + local vars = {} + local func = debug.getinfo(level or 3, "f").func + local i = 1 + while true do + local name, value = debug.getupvalue(func, i) + if not name then break end + if string.sub(name, 1, 1) ~= '(' then vars[name] = value end + i = i + 1 + end + i = 1 + while true do + local name, value = debug.getlocal(level or 3, i) + if not name then break end + if string.sub(name, 1, 1) ~= '(' then vars[name] = value end + i = i + 1 + end + -- returned 'vars' table plays a dual role: (1) it captures local values + -- and upvalues to be restored later (in case they are modified in "eval"), + -- and (2) it provides an environment for evaluated chunks. + -- getfenv(func) is needed to provide proper environment for functions, + -- including access to globals, but this causes vars[name] to fail in + -- restore_vars on local variables or upvalues with `nil` values when + -- 'strict' is in effect. To avoid this `rawget` is used in restore_vars. + setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) }) + return vars +end + +local function stack_depth(start_depth) + for i = start_depth, 0, -1 do + if debug.getinfo(i, "l") then return i+1 end + end + return start_depth +end + +local function is_safe(stack_level) + -- the stack grows up: 0 is getinfo, 1 is is_safe, 2 is debug_hook, 3 is user function + if stack_level == 3 then return true end + for i = 3, stack_level do + -- return if it is not safe to abort + local info = debug.getinfo(i, "S") + if not info then return true end + if info.what == "C" then return false end + end + return true +end + +local function in_debugger() + local this = debug.getinfo(1, "S").source + -- only need to check few frames as mobdebug frames should be close + for i = 3, 7 do + local info = debug.getinfo(i, "S") + if not info then return false end + if info.source == this then return true end + end + return false +end + +local function is_pending(peer) + -- if there is something already in the buffer, skip check + if not buf and checkcount >= mobdebug.checkcount then + peer:settimeout(0) -- non-blocking + buf = peer:receive(1) + peer:settimeout() -- back to blocking + checkcount = 0 + end + return buf +end + +local function debug_hook(event, line) + -- (1) LuaJIT needs special treatment. Because debug_hook is set for + -- *all* coroutines, and not just the one being debugged as in regular Lua + -- (http://lua-users.org/lists/lua-l/2011-06/msg00513.html), + -- need to avoid debugging mobdebug's own code as LuaJIT doesn't + -- always correctly generate call/return hook events (there are more + -- calls than returns, which breaks stack depth calculation and + -- 'step' and 'step over' commands stop working; possibly because + -- 'tail return' events are not generated by LuaJIT). + -- the next line checks if the debugger is run under LuaJIT and if + -- one of debugger methods is present in the stack, it simply returns. + if jit then + -- when luajit is compiled with LUAJIT_ENABLE_LUA52COMPAT, + -- coroutine.running() returns non-nil for the main thread. + local coro, main = coroutine.running() + if not coro or main then coro = 'main' end + local disabled = coroutines[coro] == false + or coroutines[coro] == nil and coro ~= (coro_debugee or 'main') + if coro_debugee and disabled or not coro_debugee and (disabled or in_debugger()) + then return end + end + + -- (2) check if abort has been requested and it's safe to abort + if abort and is_safe(stack_level) then error(abort) end + + -- (3) also check if this debug hook has not been visited for any reason. + -- this check is needed to avoid stepping in too early + -- (for example, when coroutine.resume() is executed inside start()). + if not seen_hook and in_debugger() then return end + + if event == "call" then + stack_level = stack_level + 1 + elseif event == "return" or event == "tail return" then + stack_level = stack_level - 1 + elseif event == "line" then + -- may need to fall through because of the following: + -- (1) step_into + -- (2) step_over and stack_level <= step_level (need stack_level) + -- (3) breakpoint; check for line first as it's known; then for file + -- (4) socket call (only do every Xth check) + -- (5) at least one watch is registered + if not ( + step_into or step_over or breakpoints[line] or watchescnt > 0 + or is_pending(server) + ) then checkcount = checkcount + 1; return end + + checkcount = mobdebug.checkcount -- force check on the next command + + -- this is needed to check if the stack got shorter or longer. + -- unfortunately counting call/return calls is not reliable. + -- the discrepancy may happen when "pcall(load, '')" call is made + -- or when "error()" is called in a function. + -- in either case there are more "call" than "return" events reported. + -- this validation is done for every "line" event, but should be "cheap" + -- as it checks for the stack to get shorter (or longer by one call). + -- start from one level higher just in case we need to grow the stack. + -- this may happen after coroutine.resume call to a function that doesn't + -- have any other instructions to execute. it triggers three returns: + -- "return, tail return, return", which needs to be accounted for. + stack_level = stack_depth(stack_level+1) + + local caller = debug.getinfo(2, "S") + + -- grab the filename and fix it if needed + local file = lastfile + if (lastsource ~= caller.source) then + file, lastsource = caller.source, caller.source + -- technically, users can supply names that may not use '@', + -- for example when they call loadstring('...', 'filename.lua'). + -- Unfortunately, there is no reliable/quick way to figure out + -- what is the filename and what is the source code. + -- The following will work if the supplied filename uses Unix path. + if file:find("^@") then + file = file:gsub("^@", ""):gsub("\\", "/") + -- need this conversion to be applied to relative and absolute + -- file names as you may write "require 'Foo'" to + -- load "foo.lua" (on a case insensitive file system) and breakpoints + -- set on foo.lua will not work if not converted to the same case. + if iscasepreserving then file = string.lower(file) end + if file:find("%./") == 1 then file = file:sub(3) + else file = file:gsub('^'..q(basedir), '') end + -- some file systems allow newlines in file names; remove these. + file = file:gsub("\n", ' ') + else + -- this is either a file name coming from loadstring("chunk", "file"), + -- or the actual source code that needs to be serialized (as it may + -- include newlines); assume it's a file name if it's all on one line. + file = file:find("[\r\n]") and serpent.line(file) or file + end + + -- set to true if we got here; this only needs to be done once per + -- session, so do it here to at least avoid setting it for every line. + seen_hook = true + lastfile = file + end + + local vars, status, res + if (watchescnt > 0) then + vars = capture_vars() + for index, value in pairs(watches) do + setfenv(value, vars) + local ok, fired = pcall(value) + if ok and fired then + status, res = coroutine.resume(coro_debugger, events.WATCH, vars, file, line, index) + break -- any one watch is enough; don't check multiple times + end + end + end + + -- need to get into the "regular" debug handler, but only if there was + -- no watch that was fired. If there was a watch, handle its result. + local getin = (status == nil) and + (step_into + or (step_over and stack_level <= step_level) + or has_breakpoint(file, line) + or is_pending(server)) + + if getin then + vars = vars or capture_vars() + step_into = false + step_over = false + status, res = coroutine.resume(coro_debugger, events.BREAK, vars, file, line) + end + + -- handle 'stack' command that provides stack() information to the debugger + if status and res == 'stack' then + while status and res == 'stack' do + -- resume with the stack trace and variables + if vars then restore_vars(vars) end -- restore vars so they are reflected in stack values + -- this may fail if __tostring method fails at run-time + local ok, snapshot = pcall(stack, 4) + status, res = coroutine.resume(coro_debugger, ok and events.STACK or events.BREAK, snapshot, file, line) + end + end + + -- need to recheck once more as resume after 'stack' command may + -- return something else (for example, 'exit'), which needs to be handled + if status and res and res ~= 'stack' then + if abort == nil and res == "exit" then os.exit(1); return end + abort = res + -- only abort if safe; if not, there is another (earlier) check inside + -- debug_hook, which will abort execution at the first safe opportunity + if is_safe(stack_level) then error(abort) end + elseif not status and res then + error(res, 2) -- report any other (internal) errors back to the application + end + + if vars then restore_vars(vars) end + end +end + +local function stringify_results(status, ...) + if not status then return status, ... end -- on error report as it + + local t = {...} + for i,v in pairs(t) do -- stringify each of the returned values + local ok, res = pcall(serpent.line, v, {nocode = true, comment = 1}) + t[i] = ok and res or ("%q"):format(res):gsub("\010","n"):gsub("\026","\\026") + end + -- stringify table with all returned values + -- this is done to allow each returned value to be used (serialized or not) + -- intependently and to preserve "original" comments + return pcall(serpent.dump, t, {sparse = false}) +end + +local function debugger_loop(sev, svars, sfile, sline) + local command + local app, osname + local eval_env = svars or {} + local function emptyWatch () return false end + local loaded = {} + for k in pairs(package.loaded) do loaded[k] = true end + + while true do + local line, err + local wx = rawget(genv, "wx") -- use rawread to make strict.lua happy + if (wx or mobdebug.yield) and server.settimeout then server:settimeout(mobdebug.yieldtimeout) end + while true do + line, err = server:receive() + if not line and err == "timeout" then + -- yield for wx GUI applications if possible to avoid "busyness" + app = app or (wx and wx.wxGetApp and wx.wxGetApp()) + if app then + local win = app:GetTopWindow() + local inloop = app:IsMainLoopRunning() + osname = osname or wx.wxPlatformInfo.Get():GetOperatingSystemFamilyName() + if win and not inloop then + -- process messages in a regular way + -- and exit as soon as the event loop is idle + if osname == 'Unix' then wx.wxTimer(app):Start(10, true) end + local exitLoop = function() + win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_IDLE) + win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_TIMER) + app:ExitMainLoop() + end + win:Connect(wx.wxEVT_IDLE, exitLoop) + win:Connect(wx.wxEVT_TIMER, exitLoop) + app:MainLoop() + end + elseif mobdebug.yield then mobdebug.yield() + end + elseif not line and err == "closed" then + error("Debugger connection unexpectedly closed", 0) + else + -- if there is something in the pending buffer, prepend it to the line + if buf then line = buf .. line; buf = nil end + break + end + end + if server.settimeout then server:settimeout() end -- back to blocking + command = string.sub(line, string.find(line, "^[A-Z]+")) + if command == "SETB" then + local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$") + if file and line then + set_breakpoint(file, tonumber(line)) + server:send("200 OK\n") + else + server:send("400 Bad Request\n") + end + elseif command == "DELB" then + local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$") + if file and line then + remove_breakpoint(file, tonumber(line)) + server:send("200 OK\n") + else + server:send("400 Bad Request\n") + end + elseif command == "EXEC" then + local _, _, chunk = string.find(line, "^[A-Z]+%s+(.+)$") + if chunk then + local func, res = loadstring(chunk) + local status + if func then + setfenv(func, eval_env) + status, res = stringify_results(pcall(func)) + end + if status then + server:send("200 OK " .. #res .. "\n") + server:send(res) + else + server:send("401 Error in Expression " .. #res .. "\n") + server:send(res) + end + else + server:send("400 Bad Request\n") + end + elseif command == "LOAD" then + local _, _, size, name = string.find(line, "^[A-Z]+%s+(%d+)%s+(%S.-)%s*$") + size = tonumber(size) + + if abort == nil then -- no LOAD/RELOAD allowed inside start() + if size > 0 then server:receive(size) end + if sfile and sline then + server:send("201 Started " .. sfile .. " " .. sline .. "\n") + else + server:send("200 OK 0\n") + end + else + -- reset environment to allow required modules to load again + -- remove those packages that weren't loaded when debugger started + for k in pairs(package.loaded) do + if not loaded[k] then package.loaded[k] = nil end + end + + if size == 0 and name == '-' then -- RELOAD the current script being debugged + server:send("200 OK 0\n") + coroutine.yield("load") + else + -- receiving 0 bytes blocks (at least in luasocket 2.0.2), so skip reading + local chunk = size == 0 and "" or server:receive(size) + if chunk then -- LOAD a new script for debugging + local func, res = loadstring(chunk, "@"..name) + if func then + server:send("200 OK 0\n") + debugee = func + coroutine.yield("load") + else + server:send("401 Error in Expression " .. #res .. "\n") + server:send(res) + end + else + server:send("400 Bad Request\n") + end + end + end + elseif command == "SETW" then + local _, _, exp = string.find(line, "^[A-Z]+%s+(.+)%s*$") + if exp then + local func, res = loadstring("return(" .. exp .. ")") + if func then + watchescnt = watchescnt + 1 + local newidx = #watches + 1 + watches[newidx] = func + server:send("200 OK " .. newidx .. "\n") + else + server:send("401 Error in Expression " .. #res .. "\n") + server:send(res) + end + else + server:send("400 Bad Request\n") + end + elseif command == "DELW" then + local _, _, index = string.find(line, "^[A-Z]+%s+(%d+)%s*$") + index = tonumber(index) + if index > 0 and index <= #watches then + watchescnt = watchescnt - (watches[index] ~= emptyWatch and 1 or 0) + watches[index] = emptyWatch + server:send("200 OK\n") + else + server:send("400 Bad Request\n") + end + elseif command == "RUN" then + server:send("200 OK\n") + + local ev, vars, file, line, idx_watch = coroutine.yield() + eval_env = vars + if ev == events.BREAK then + server:send("202 Paused " .. file .. " " .. line .. "\n") + elseif ev == events.WATCH then + server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n") + elseif ev == events.RESTART then + -- nothing to do + else + server:send("401 Error in Execution " .. #file .. "\n") + server:send(file) + end + elseif command == "STEP" then + server:send("200 OK\n") + step_into = true + + local ev, vars, file, line, idx_watch = coroutine.yield() + eval_env = vars + if ev == events.BREAK then + server:send("202 Paused " .. file .. " " .. line .. "\n") + elseif ev == events.WATCH then + server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n") + elseif ev == events.RESTART then + -- nothing to do + else + server:send("401 Error in Execution " .. #file .. "\n") + server:send(file) + end + elseif command == "OVER" or command == "OUT" then + server:send("200 OK\n") + step_over = true + + -- OVER and OUT are very similar except for + -- the stack level value at which to stop + if command == "OUT" then step_level = stack_level - 1 + else step_level = stack_level end + + local ev, vars, file, line, idx_watch = coroutine.yield() + eval_env = vars + if ev == events.BREAK then + server:send("202 Paused " .. file .. " " .. line .. "\n") + elseif ev == events.WATCH then + server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n") + elseif ev == events.RESTART then + -- nothing to do + else + server:send("401 Error in Execution " .. #file .. "\n") + server:send(file) + end + elseif command == "BASEDIR" then + local _, _, dir = string.find(line, "^[A-Z]+%s+(.+)%s*$") + if dir then + basedir = iscasepreserving and string.lower(dir) or dir + -- reset cached source as it may change with basedir + lastsource = nil + server:send("200 OK\n") + else + server:send("400 Bad Request\n") + end + elseif command == "SUSPEND" then + -- do nothing; it already fulfilled its role + elseif command == "STACK" then + -- first check if we can execute the stack command + -- as it requires yielding back to debug_hook it cannot be executed + -- if we have not seen the hook yet as happens after start(). + -- in this case we simply return an empty result + local vars, ev = {} + if seen_hook then + ev, vars = coroutine.yield("stack") + end + if ev and ev ~= events.STACK then + server:send("401 Error in Execution " .. #vars .. "\n") + server:send(vars) + else + local ok, res = pcall(serpent.dump, vars, {nocode = true, sparse = false}) + if ok then + server:send("200 OK " .. res .. "\n") + else + server:send("401 Error in Execution " .. #res .. "\n") + server:send(res) + end + end + elseif command == "OUTPUT" then + local _, _, stream, mode = string.find(line, "^[A-Z]+%s+(%w+)%s+([dcr])%s*$") + if stream and mode and stream == "stdout" then + -- assign "print" in the global environment + genv.print = mode == 'd' and iobase.print or coroutine.wrap(function(...) + -- wrapping into coroutine.wrap protects this function from + -- being stepped through in the debugger + local tbl = {...} + while true do + if mode == 'c' then iobase.print(unpack(tbl)) end + for n = 1, #tbl do + tbl[n] = select(2, pcall(serpent.line, tbl[n], {nocode = true, comment = false})) end + local file = table.concat(tbl, "\t").."\n" + server:send("204 Output " .. stream .. " " .. #file .. "\n" .. file) + tbl = {coroutine.yield()} + end + end) + server:send("200 OK\n") + else + server:send("400 Bad Request\n") + end + elseif command == "EXIT" then + server:send("200 OK\n") + coroutine.yield("exit") + else + server:send("400 Bad Request\n") + end + end +end + +local function connect(controller_host, controller_port) + return (socket.connect4 or socket.connect)(controller_host, controller_port) +end + +local function isrunning() + return coro_debugger and coroutine.status(coro_debugger) == 'suspended' +end + +local lasthost, lastport + +-- Starts a debug session by connecting to a controller +local function start(controller_host, controller_port) + -- only one debugging session can be run (as there is only one debug hook) + if isrunning() then return end + + lasthost = controller_host or lasthost + lastport = controller_port or lastport + + controller_host = lasthost or "localhost" + controller_port = lastport or mobdebug.port + + local err + server, err = (socket.connect4 or socket.connect)(controller_host, controller_port) + if server then + -- correct stack depth which already has some calls on it + -- so it doesn't go into negative when those calls return + -- as this breaks subsequence checks in stack_depth(). + -- start from 16th frame, which is sufficiently large for this check. + stack_level = stack_depth(16) + + -- provide our own traceback function to report the error remotely + do + local dtraceback = debug.traceback + debug.traceback = function (...) + if select('#', ...) >= 1 then + local err, lvl = ... + if err and type(err) ~= 'thread' then + local trace = dtraceback(err, (lvl or 2)+1) + if genv.print == iobase.print then -- no remote redirect + return trace + else + genv.print(trace) -- report the error remotely + return -- don't report locally to avoid double reporting + end + end + end + -- direct call to debug.traceback: return the original. + -- debug.traceback(nil, level) doesn't work in Lua 5.1 + -- (http://lua-users.org/lists/lua-l/2011-06/msg00574.html), so + -- simply remove first frame from the stack trace + return (dtraceback(...):gsub("(stack traceback:\n)[^\n]*\n", "%1")) + end + end + coro_debugger = coroutine.create(debugger_loop) + debug.sethook(debug_hook, "lcr") + seen_hook = nil -- reset in case the last start() call was refused + step_into = true -- start with step command + return true + else + print(("Could not connect to %s:%s: %s") + :format(controller_host, controller_port, err or "unknown error")) + end +end + +local function controller(controller_host, controller_port, scratchpad) + -- only one debugging session can be run (as there is only one debug hook) + if isrunning() then return end + + lasthost = controller_host or lasthost + lastport = controller_port or lastport + + controller_host = lasthost or "localhost" + controller_port = lastport or mobdebug.port + + local exitonerror = not scratchpad + local err + server, err = (socket.connect4 or socket.connect)(controller_host, controller_port) + if server then + local function report(trace, err) + local msg = err .. "\n" .. trace + server:send("401 Error in Execution " .. #msg .. "\n") + server:send(msg) + return err + end + + seen_hook = true -- allow to accept all commands + coro_debugger = coroutine.create(debugger_loop) + + while true do + step_into = true -- start with step command + abort = false -- reset abort flag from the previous loop + if scratchpad then checkcount = mobdebug.checkcount end -- force suspend right away + + coro_debugee = coroutine.create(debugee) + debug.sethook(coro_debugee, debug_hook, "lcr") + local status, err = coroutine.resume(coro_debugee) + + -- was there an error or is the script done? + -- 'abort' state is allowed here; ignore it + if abort then + if tostring(abort) == 'exit' then break end + else + if status then -- normal execution is done + break + elseif err and not tostring(err):find(deferror) then + -- report the error back + -- err is not necessarily a string, so convert to string to report + report(debug.traceback(coro_debugee), tostring(err)) + if exitonerror then break end + -- resume once more to clear the response the debugger wants to send + -- need to use capture_vars(2) as three would be the level of + -- the caller for controller(), but because of the tail call, + -- the caller may not exist; + -- This is not entirely safe as the user may see the local + -- variable from console, but they will be reset anyway. + -- This functionality is used when scratchpad is paused to + -- gain access to remote console to modify global variables. + local status, err = coroutine.resume(coro_debugger, events.RESTART, capture_vars(2)) + if not status or status and err == "exit" then break end + end + end + end + else + print(("Could not connect to %s:%s: %s") + :format(controller_host, controller_port, err or "unknown error")) + return false + end + return true +end + +local function scratchpad(controller_host, controller_port) + return controller(controller_host, controller_port, true) +end + +local function loop(controller_host, controller_port) + return controller(controller_host, controller_port, false) +end + +local function on() + if not (isrunning() and server) then return end + + -- main is set to true under Lua5.2 for the "main" chunk. + -- Lua5.1 returns co as `nil` in that case. + local co, main = coroutine.running() + if main then co = nil end + if co then + coroutines[co] = true + debug.sethook(co, debug_hook, "lcr") + else + if jit then coroutines.main = true end + debug.sethook(debug_hook, "lcr") + end +end + +local function off() + if not (isrunning() and server) then return end + + -- main is set to true under Lua5.2 for the "main" chunk. + -- Lua5.1 returns co as `nil` in that case. + local co, main = coroutine.running() + if main then co = nil end + + -- don't remove coroutine hook under LuaJIT as there is only one (global) hook + if co then + coroutines[co] = false + if not jit then debug.sethook(co) end + else + if jit then coroutines.main = false end + if not jit then debug.sethook() end + end + + -- check if there is any thread that is still being debugged under LuaJIT; + -- if not, turn the debugging off + if jit then + local remove = true + for co, debugged in pairs(coroutines) do + if debugged then remove = false; break end + end + if remove then debug.sethook() end + end +end + +-- Handles server debugging commands +local function handle(params, client, options) + local _, _, command = string.find(params, "^([a-z]+)") + local file, line, watch_idx + if command == "run" or command == "step" or command == "out" + or command == "over" or command == "exit" then + client:send(string.upper(command) .. "\n") + client:receive() -- this should consume the first '200 OK' response + while true do + local done = true + local breakpoint = client:receive() + if not breakpoint then + print("Program finished") + os.exit() + return -- use return here for those cases where os.exit() is not wanted + end + local _, _, status = string.find(breakpoint, "^(%d+)") + if status == "200" then + -- don't need to do anything + elseif status == "202" then + _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$") + if file and line then + print("Paused at file " .. file .. " line " .. line) + end + elseif status == "203" then + _, _, file, line, watch_idx = string.find(breakpoint, "^203 Paused%s+(.-)%s+(%d+)%s+(%d+)%s*$") + if file and line and watch_idx then + print("Paused at file " .. file .. " line " .. line .. " (watch expression " .. watch_idx .. ": [" .. watches[watch_idx] .. "])") + end + elseif status == "204" then + local _, _, stream, size = string.find(breakpoint, "^204 Output (%w+) (%d+)$") + if stream and size then + local msg = client:receive(tonumber(size)) + print(msg) + if outputs[stream] then outputs[stream](msg) end + -- this was just the output, so go back reading the response + done = false + end + elseif status == "401" then + local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)$") + if size then + local msg = client:receive(tonumber(size)) + print("Error in remote application: " .. msg) + os.exit(1) + return nil, nil, msg -- use return here for those cases where os.exit() is not wanted + end + else + print("Unknown error") + os.exit(1) + -- use return here for those cases where os.exit() is not wanted + return nil, nil, "Debugger error: unexpected response '" .. breakpoint .. "'" + end + if done then break end + end + elseif command == "setb" then + _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$") + if file and line then + -- if this is a file name, and not a file source + if not file:find('^".*"$') then + file = string.gsub(file, "\\", "/") -- convert slash + file = removebasedir(file, basedir) + end + client:send("SETB " .. file .. " " .. line .. "\n") + if client:receive() == "200 OK" then + set_breakpoint(file, line) + else + print("Error: breakpoint not inserted") + end + else + print("Invalid command") + end + elseif command == "setw" then + local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$") + if exp then + client:send("SETW " .. exp .. "\n") + local answer = client:receive() + local _, _, watch_idx = string.find(answer, "^200 OK (%d+)%s*$") + if watch_idx then + watches[watch_idx] = exp + print("Inserted watch exp no. " .. watch_idx) + else + local _, _, size = string.find(answer, "^401 Error in Expression (%d+)$") + if size then + local err = client:receive(tonumber(size)):gsub(".-:%d+:%s*","") + print("Error: watch expression not set: " .. err) + else + print("Error: watch expression not set") + end + end + else + print("Invalid command") + end + elseif command == "delb" then + _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$") + if file and line then + -- if this is a file name, and not a file source + if not file:find('^".*"$') then + file = string.gsub(file, "\\", "/") -- convert slash + file = removebasedir(file, basedir) + end + client:send("DELB " .. file .. " " .. line .. "\n") + if client:receive() == "200 OK" then + remove_breakpoint(file, line) + else + print("Error: breakpoint not removed") + end + else + print("Invalid command") + end + elseif command == "delallb" then + for line, breaks in pairs(breakpoints) do + for file, _ in pairs(breaks) do + client:send("DELB " .. file .. " " .. line .. "\n") + if client:receive() == "200 OK" then + remove_breakpoint(file, line) + else + print("Error: breakpoint at file " .. file .. " line " .. line .. " not removed") + end + end + end + elseif command == "delw" then + local _, _, index = string.find(params, "^[a-z]+%s+(%d+)%s*$") + if index then + client:send("DELW " .. index .. "\n") + if client:receive() == "200 OK" then + watches[index] = nil + else + print("Error: watch expression not removed") + end + else + print("Invalid command") + end + elseif command == "delallw" then + for index, exp in pairs(watches) do + client:send("DELW " .. index .. "\n") + if client:receive() == "200 OK" then + watches[index] = nil + else + print("Error: watch expression at index " .. index .. " [" .. exp .. "] not removed") + end + end + elseif command == "eval" or command == "exec" + or command == "load" or command == "loadstring" + or command == "reload" then + local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$") + if exp or (command == "reload") then + if command == "eval" or command == "exec" then + exp = (exp:gsub("%-%-%[(=*)%[.-%]%1%]", "") -- remove comments + :gsub("%-%-.-\n", " ") -- remove line comments + :gsub("\n", " ")) -- convert new lines + if command == "eval" then exp = "return " .. exp end + client:send("EXEC " .. exp .. "\n") + elseif command == "reload" then + client:send("LOAD 0 -\n") + elseif command == "loadstring" then + local _, _, _, file, lines = string.find(exp, "^([\"'])(.-)%1%s+(.+)") + if not file then + _, _, file, lines = string.find(exp, "^(%S+)%s+(.+)") + end + client:send("LOAD " .. #lines .. " " .. file .. "\n") + client:send(lines) + else + local file = io.open(exp, "r") + if not file and pcall(require, "winapi") then + -- if file is not open and winapi is there, try with a short path; + -- this may be needed for unicode paths on windows + winapi.set_encoding(winapi.CP_UTF8) + file = io.open(winapi.short_path(exp), "r") + end + if not file then error("Cannot open file " .. exp) end + -- read the file and remove the shebang line as it causes a compilation error + local lines = file:read("*all"):gsub("^#!.-\n", "\n") + file:close() + + local file = string.gsub(exp, "\\", "/") -- convert slash + file = removebasedir(file, basedir) + client:send("LOAD " .. #lines .. " " .. file .. "\n") + if #lines > 0 then client:send(lines) end + end + while true do + local params, err = client:receive() + if not params then + return nil, nil, "Debugger connection " .. (err or "error") + end + local done = true + local _, _, status, len = string.find(params, "^(%d+).-%s+(%d+)%s*$") + if status == "200" then + len = tonumber(len) + if len > 0 then + local status, res + local str = client:receive(len) + -- handle serialized table with results + local func, err = loadstring(str) + if func then + status, res = pcall(func) + if not status then err = res + elseif type(res) ~= "table" then + err = "received "..type(res).." instead of expected 'table'" + end + end + if err then + print("Error in processing results: " .. err) + return nil, nil, "Error in processing results: " .. err + end + print(unpack(res)) + return res[1], res + end + elseif status == "201" then + _, _, file, line = string.find(params, "^201 Started%s+(.-)%s+(%d+)%s*$") + elseif status == "202" or params == "200 OK" then + -- do nothing; this only happens when RE/LOAD command gets the response + -- that was for the original command that was aborted + elseif status == "204" then + local _, _, stream, size = string.find(params, "^204 Output (%w+) (%d+)$") + if stream and size then + local msg = client:receive(tonumber(size)) + print(msg) + if outputs[stream] then outputs[stream](msg) end + -- this was just the output, so go back reading the response + done = false + end + elseif status == "401" then + len = tonumber(len) + local res = client:receive(len) + print("Error in expression: " .. res) + return nil, nil, res + else + print("Unknown error") + return nil, nil, "Debugger error: unexpected response after EXEC/LOAD '" .. params .. "'" + end + if done then break end + end + else + print("Invalid command") + end + elseif command == "listb" then + for l, v in pairs(breakpoints) do + for f in pairs(v) do + print(f .. ": " .. l) + end + end + elseif command == "listw" then + for i, v in pairs(watches) do + print("Watch exp. " .. i .. ": " .. v) + end + elseif command == "suspend" then + client:send("SUSPEND\n") + elseif command == "stack" then + client:send("STACK\n") + local resp = client:receive() + local _, _, status, res = string.find(resp, "^(%d+)%s+%w+%s+(.+)%s*$") + if status == "200" then + local func, err = loadstring(res) + if func == nil then + print("Error in stack information: " .. err) + return nil, nil, err + end + local ok, stack = pcall(func) + if not ok then + print("Error in stack information: " .. stack) + return nil, nil, stack + end + for _,frame in ipairs(stack) do + print(serpent.line(frame[1], {comment = false})) + end + return stack + elseif status == "401" then + local _, _, len = string.find(resp, "%s+(%d+)%s*$") + len = tonumber(len) + local res = len > 0 and client:receive(len) or "Invalid stack information." + print("Error in expression: " .. res) + return nil, nil, res + else + print("Unknown error") + return nil, nil, "Debugger error: unexpected response after STACK" + end + elseif command == "output" then + local _, _, stream, mode = string.find(params, "^[a-z]+%s+(%w+)%s+([dcr])%s*$") + if stream and mode then + client:send("OUTPUT "..stream.." "..mode.."\n") + local resp = client:receive() + local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$") + if status == "200" then + print("Stream "..stream.." redirected") + outputs[stream] = type(options) == 'table' and options.handler or nil + else + print("Unknown error") + return nil, nil, "Debugger error: can't redirect "..stream + end + else + print("Invalid command") + end + elseif command == "basedir" then + local _, _, dir = string.find(params, "^[a-z]+%s+(.+)$") + if dir then + dir = string.gsub(dir, "\\", "/") -- convert slash + if not string.find(dir, "/$") then dir = dir .. "/" end + + local remdir = dir:match("\t(.+)") + if remdir then dir = dir:gsub("/?\t.+", "/") end + basedir = dir + + client:send("BASEDIR "..(remdir or dir).."\n") + local resp = client:receive() + local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$") + if status == "200" then + print("New base directory is " .. basedir) + else + print("Unknown error") + return nil, nil, "Debugger error: unexpected response after BASEDIR" + end + else + print(basedir) + end + elseif command == "help" then + print("setb -- sets a breakpoint") + print("delb -- removes a breakpoint") + print("delallb -- removes all breakpoints") + print("setw -- adds a new watch expression") + print("delw -- removes the watch expression at index") + print("delallw -- removes all watch expressions") + print("run -- runs until next breakpoint") + print("step -- runs until next line, stepping into function calls") + print("over -- runs until next line, stepping over function calls") + print("out -- runs until line after returning from current function") + print("listb -- lists breakpoints") + print("listw -- lists watch expressions") + print("eval -- evaluates expression on the current context and returns its value") + print("exec -- executes statement on the current context") + print("load -- loads a local file for debugging") + print("reload -- restarts the current debugging session") + print("stack -- reports stack trace") + print("output stdout -- capture and redirect io stream (default|copy|redirect)") + print("basedir [] -- sets the base path of the remote application, or shows the current one") + print("exit -- exits debugger") + else + local _, _, spaces = string.find(params, "^(%s*)$") + if not spaces then + print("Invalid command") + return nil, nil, "Invalid command" + end + end + return file, line +end + +-- Starts debugging server +local function listen(host, port) + host = host or "*" + port = port or mobdebug.port + + local socket = require "socket" + + print("Lua Remote Debugger") + print("Run the program you wish to debug") + + local server = socket.bind(host, port) + local client = server:accept() + + client:send("STEP\n") + client:receive() + + local breakpoint = client:receive() + local _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$") + if file and line then + print("Paused at file " .. file ) + print("Type 'help' for commands") + else + local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)%s*$") + if size then + print("Error in remote application: ") + print(client:receive(size)) + end + end + + while true do + io.write("> ") + local line = io.read("*line") + handle(line, client) + end +end + +local cocreate +local function coro() + if cocreate then return end -- only set once + cocreate = cocreate or coroutine.create + coroutine.create = function(f, ...) + return cocreate(function(...) + require("mobdebug").on() + return f(...) + end, ...) + end +end + +local moconew +local function moai() + if moconew then return end -- only set once + moconew = moconew or (MOAICoroutine and MOAICoroutine.new) + if not moconew then return end + MOAICoroutine.new = function(...) + local thread = moconew(...) + -- need to support both thread.run and getmetatable(thread).run, which + -- was used in earlier MOAI versions + local mt = thread.run and thread or getmetatable(thread) + local patched = mt.run + mt.run = function(self, f, ...) + return patched(self, function(...) + require("mobdebug").on() + return f(...) + end, ...) + end + return thread + end +end + +-- this is a function that removes all hooks and closes the socket to +-- report back to the controller that the debugging is done. +-- the script that called `done` can still continue. +local function done() + if not (isrunning() and server) then return end + + if not jit then + for co, debugged in pairs(coroutines) do + if debugged then debug.sethook(co) end + end + end + + debug.sethook() + server:close() + + coro_debugger = nil -- to make sure isrunning() returns `false` + seen_hook = nil -- to make sure that the next start() call works + abort = nil -- to make sure that callback calls use proper "abort" value +end + +-- make public functions available +mobdebug.listen = listen +mobdebug.loop = loop +mobdebug.scratchpad = scratchpad +mobdebug.handle = handle +mobdebug.connect = connect +mobdebug.start = start +mobdebug.on = on +mobdebug.off = off +mobdebug.moai = moai +mobdebug.coro = coro +mobdebug.done = done +mobdebug.line = serpent.line +mobdebug.dump = serpent.dump +mobdebug.yield = nil -- callback + +-- this is needed to make "require 'modebug'" to work when mobdebug +-- module is loaded manually +package.loaded.mobdebug = mobdebug + +return mobdebug diff --git a/template/multi-platform-lua/proj.android/AndroidManifest.xml b/template/multi-platform-lua/proj.android/AndroidManifest.xml index fb69c258c2..ba17733142 100644 --- a/template/multi-platform-lua/proj.android/AndroidManifest.xml +++ b/template/multi-platform-lua/proj.android/AndroidManifest.xml @@ -14,7 +14,7 @@ android:label="@string/app_name" android:screenOrientation="landscape" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" - android:configChanges="orientation|screenSize|smallestScreenSize"> + android:configChanges="orientation"> + diff --git a/template/multi-platform-lua/proj.android/build_native.py b/template/multi-platform-lua/proj.android/build_native.py index 7414dd23af..f5d485da07 100755 --- a/template/multi-platform-lua/proj.android/build_native.py +++ b/template/multi-platform-lua/proj.android/build_native.py @@ -8,6 +8,23 @@ import os, os.path import shutil from optparse import OptionParser +def get_num_of_cpu(): + ''' The build process can be accelerated by running multiple concurrent job processes using the -j-option. + ''' + try: + platform = sys.platform + if platform == 'win32': + if 'NUMBER_OF_PROCESSORS' in os.environ: + return int(os.environ['NUMBER_OF_PROCESSORS']) + else: + return 1 + else: + from numpy.distutils import cpuinfo + return cpuinfo.cpu._getNCPUs() + except Exception: + print "Can't know cpuinfo, use default 1 cpu" + return 1 + def check_environment_variables_sdk(): ''' Checking the environment ANDROID_SDK_ROOT, which will be used for building ''' @@ -62,10 +79,12 @@ def do_build(cocos_root, ndk_root, app_android_root,ndk_build_param,sdk_root,and else: ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + num_of_cpu = get_num_of_cpu() + if ndk_build_param == None: - command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + command = '%s -j%d -C %s %s' % (ndk_path, num_of_cpu, app_android_root, ndk_module_path) else: - command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) + command = '%s -j%d -C %s %s %s' % (ndk_path, num_of_cpu, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) if os.system(command) != 0: raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!") elif android_platform is not None: diff --git a/template/multi-platform-lua/proj.ios_mac/HelloLua.xcodeproj/project.pbxproj b/template/multi-platform-lua/proj.ios_mac/HelloLua.xcodeproj/project.pbxproj index eecc14f8cb..c078a091f1 100644 --- a/template/multi-platform-lua/proj.ios_mac/HelloLua.xcodeproj/project.pbxproj +++ b/template/multi-platform-lua/proj.ios_mac/HelloLua.xcodeproj/project.pbxproj @@ -55,6 +55,8 @@ 15A8A4851834C73500142BE0 /* libCocosDenshion Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 15A8A41F1834BDA200142BE0 /* libCocosDenshion Mac.a */; }; 15A8A4861834C73500142BE0 /* libluabindings Mac.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 15A8A4231834BDA200142BE0 /* libluabindings Mac.a */; }; 15A8A4881834C90F00142BE0 /* libcurl.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 15A8A4871834C90E00142BE0 /* libcurl.dylib */; }; + 15FFA0FD1894DDEF00C96D45 /* mobdebug.lua in Resources */ = {isa = PBXBuildFile; fileRef = 15FFA0FC1894DDEF00C96D45 /* mobdebug.lua */; }; + 15FFA0FE1894DDEF00C96D45 /* mobdebug.lua in Resources */ = {isa = PBXBuildFile; fileRef = 15FFA0FC1894DDEF00C96D45 /* mobdebug.lua */; }; 1AC3622F16D47C5C000847F2 /* background.mp3 in Resources */ = {isa = PBXBuildFile; fileRef = 1AC3622316D47C5C000847F2 /* background.mp3 */; }; 1AC3623016D47C5C000847F2 /* background.ogg in Resources */ = {isa = PBXBuildFile; fileRef = 1AC3622416D47C5C000847F2 /* background.ogg */; }; 1AC3623116D47C5C000847F2 /* crop.png in Resources */ = {isa = PBXBuildFile; fileRef = 1AC3622516D47C5C000847F2 /* crop.png */; }; @@ -246,6 +248,7 @@ 15A8A4631834C6AD00142BE0 /* StudioConstants.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = StudioConstants.lua; path = ../cocos2d/cocos/scripting/lua/script/StudioConstants.lua; sourceTree = ""; }; 15A8A4871834C90E00142BE0 /* libcurl.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libcurl.dylib; path = usr/lib/libcurl.dylib; sourceTree = SDKROOT; }; 15C1568D1683131500D239F2 /* libcurl.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libcurl.a; path = ../cocos2d/cocos2dx/platform/third_party/ios/libraries/libcurl.a; sourceTree = ""; }; + 15FFA0FC1894DDEF00C96D45 /* mobdebug.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = mobdebug.lua; sourceTree = ""; }; 1AC3622316D47C5C000847F2 /* background.mp3 */ = {isa = PBXFileReference; lastKnownFileType = audio.mp3; name = background.mp3; path = ../Resources/background.mp3; sourceTree = ""; }; 1AC3622416D47C5C000847F2 /* background.ogg */ = {isa = PBXFileReference; lastKnownFileType = file; name = background.ogg; path = ../Resources/background.ogg; sourceTree = ""; }; 1AC3622516D47C5C000847F2 /* crop.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = crop.png; path = ../Resources/crop.png; sourceTree = ""; }; @@ -509,6 +512,7 @@ F293BC4615EB859D00256477 /* Resources */ = { isa = PBXGroup; children = ( + 15FFA0FC1894DDEF00C96D45 /* mobdebug.lua */, 1AC3622316D47C5C000847F2 /* background.mp3 */, 1AC3622416D47C5C000847F2 /* background.ogg */, 1AC3622516D47C5C000847F2 /* crop.png */, @@ -707,6 +711,7 @@ buildActionMask = 2147483647; files = ( 15A8A4711834C6AD00142BE0 /* DeprecatedEnum.lua in Resources */, + 15FFA0FE1894DDEF00C96D45 /* mobdebug.lua in Resources */, 5023814817EBBCE400990C9B /* background.mp3 in Resources */, 5023814917EBBCE400990C9B /* background.ogg in Resources */, 5023814A17EBBCE400990C9B /* crop.png in Resources */, @@ -769,6 +774,7 @@ 15A8A46A1834C6AD00142BE0 /* Cocos2dConstants.lua in Resources */, 1AC3623616D47C5C000847F2 /* hello.lua in Resources */, 5091733917ECE17A00D62437 /* Icon-58.png in Resources */, + 15FFA0FD1894DDEF00C96D45 /* mobdebug.lua in Resources */, 15A8A4641834C6AD00142BE0 /* AudioEngine.lua in Resources */, 1AC3623716D47C5C000847F2 /* hello2.lua in Resources */, 1AC3623816D47C5C000847F2 /* land.png in Resources */, diff --git a/template/multi-platform-lua/proj.ios_mac/ios/AppController.h b/template/multi-platform-lua/proj.ios_mac/ios/AppController.h index 3d51064ca0..ee440a30a8 100644 --- a/template/multi-platform-lua/proj.ios_mac/ios/AppController.h +++ b/template/multi-platform-lua/proj.ios_mac/ios/AppController.h @@ -1,5 +1,6 @@ /**************************************************************************** - Copyright (c) 2010 cocos2d-x.org + Copyright (c) 2013 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/template/multi-platform-lua/proj.ios_mac/ios/AppController.mm b/template/multi-platform-lua/proj.ios_mac/ios/AppController.mm index ef011c8dd2..7bc89f9022 100644 --- a/template/multi-platform-lua/proj.ios_mac/ios/AppController.mm +++ b/template/multi-platform-lua/proj.ios_mac/ios/AppController.mm @@ -1,5 +1,6 @@ /**************************************************************************** - Copyright (c) 2010 cocos2d-x.org + Copyright (c) 2013 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -24,7 +25,7 @@ #import #import "AppController.h" #import "cocos2d.h" -#import "EAGLView.h" +#import "CCEAGLView.h" #import "AppDelegate.h" #import "RootViewController.h" @@ -43,7 +44,7 @@ static AppDelegate s_sharedApplication; // Add the view controller's view to the window and display. window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; - CCEAGLView *__glView = [CCEAGLView viewWithFrame: [window bounds] + CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds] pixelFormat: kEAGLColorFormatRGBA8 depthFormat: GL_DEPTH_COMPONENT16 preserveBackbuffer: NO @@ -51,11 +52,11 @@ static AppDelegate s_sharedApplication; multiSampling: NO numberOfSamples: 0 ]; - [__glView setMultipleTouchEnabled:YES]; + [eaglView setMultipleTouchEnabled:YES]; // Use RootViewController manage CCEAGLView viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; viewController.wantsFullScreenLayout = YES; - viewController.view = __glView; + viewController.view = eaglView; // Set RootViewController to window if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) @@ -72,6 +73,10 @@ static AppDelegate s_sharedApplication; [window makeKeyAndVisible]; [[UIApplication sharedApplication] setStatusBarHidden: YES]; + + // IMPORTANT: Setting the GLView should be done after creating the RootViewController + cocos2d::GLView *glview = cocos2d::GLView::createWithEAGLView(eaglView); + cocos2d::Director::getInstance()->setOpenGLView(glview); cocos2d::Application::getInstance()->run(); return YES; diff --git a/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.h b/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.h index 11dfc4bf88..a68782316e 100644 --- a/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.h +++ b/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.h @@ -1,6 +1,6 @@ /**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2010 Ricardo Quesada + Copyright (c) 2013 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org diff --git a/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm b/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm index 093a9b4c3a..2374fae2d2 100644 --- a/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm +++ b/template/multi-platform-lua/proj.ios_mac/ios/RootViewController.mm @@ -1,6 +1,6 @@ /**************************************************************************** - Copyright (c) 2010-2011 cocos2d-x.org - Copyright (c) 2010 Ricardo Quesada + Copyright (c) 2013 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -25,7 +25,7 @@ #import "RootViewController.h" #import "cocos2d.h" -#import "EAGLView.h" +#import "CCEAGLView.h" @implementation RootViewController @@ -71,8 +71,11 @@ - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; + + cocos2d::GLView *glview = cocos2d::Director::getInstance()->getOpenGLView(); + CCEAGLView *eaglview = (CCEAGLView*) glview->getEAGLView(); - CGSize s = CGSizeMake([[CCEAGLView sharedEGLView] getWidth], [[CCEAGLView sharedEGLView] getHeight]); + CGSize s = CGSizeMake([eaglview getWidth], [eaglview getHeight]); cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height); } diff --git a/template/multi-platform-lua/proj.ios_mac/mac/main.cpp b/template/multi-platform-lua/proj.ios_mac/mac/main.cpp index 1d6fd403f1..1814d16c15 100644 --- a/template/multi-platform-lua/proj.ios_mac/mac/main.cpp +++ b/template/multi-platform-lua/proj.ios_mac/mac/main.cpp @@ -23,14 +23,11 @@ ****************************************************************************/ #include "AppDelegate.h" -#include "CCEGLView.h" USING_NS_CC; int main(int argc, char *argv[]) { AppDelegate app; - EGLView eglView; - eglView.init("Hello World",900,640); return Application::getInstance()->run(); } diff --git a/template/multi-platform-lua/proj.linux/build.sh b/template/multi-platform-lua/proj.linux/build.sh deleted file mode 100755 index d1408e62a4..0000000000 --- a/template/multi-platform-lua/proj.linux/build.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash - -# Exit on error -set -e - -rm -rf ../bin -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -#make global libs -cd ../cocos2d -#install depend libs -sudo ./build/install-deps-linux.sh -mkdir -p linux-build -cd linux-build -cmake .. -DBUILD_HelloCpp=OFF -DBUILD_TestCpp=OFF -DBUILD_HelloLua=OFF -DBUILD_TestLua=OFF -make -j4 - -#make bin -cd $DIR -rm -rf bin -mkdir -p build -cd build -cmake ../.. -make -j4 -cd .. -mv ../bin bin -cp ../cocos2d/cocos/scripting/lua/script/* bin/Resources diff --git a/template/multi-platform-lua/proj.linux/main.cpp b/template/multi-platform-lua/proj.linux/main.cpp index 5e5565893c..c5b735da78 100644 --- a/template/multi-platform-lua/proj.linux/main.cpp +++ b/template/multi-platform-lua/proj.linux/main.cpp @@ -1,6 +1,4 @@ #include "../Classes/AppDelegate.h" -#include "cocos2d.h" -#include "CCEGLView.h" #include #include @@ -13,7 +11,5 @@ int main(int argc, char **argv) { // create the application instance AppDelegate app; - EGLView eglView; - eglView.init("Cocos2d-x Game Using LUA",900,640); return Application::getInstance()->run(); } diff --git a/template/multi-platform-lua/proj.win32/main.cpp b/template/multi-platform-lua/proj.win32/main.cpp index 4dfce357f9..d9b2ddaa2e 100644 --- a/template/multi-platform-lua/proj.win32/main.cpp +++ b/template/multi-platform-lua/proj.win32/main.cpp @@ -24,9 +24,6 @@ int APIENTRY _tWinMain(HINSTANCE hInstance, // create the application instance AppDelegate app; - EGLView eglView; - eglView.init("TestCPP",900,640); - int ret = Application::getInstance()->run(); #ifdef USE_WIN32_CONSOLE diff --git a/samples/Cpp/TestCpp/Android.mk b/tests/test-cpp/Android.mk similarity index 97% rename from samples/Cpp/TestCpp/Android.mk rename to tests/test-cpp/Android.mk index 32917fb7c3..fa93be3210 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/tests/test-cpp/Android.mk @@ -121,7 +121,11 @@ Classes/PerformanceTest/PerformanceTest.cpp \ Classes/PerformanceTest/PerformanceTextureTest.cpp \ Classes/PerformanceTest/PerformanceTouchesTest.cpp \ Classes/PerformanceTest/PerformanceLabelTest.cpp \ +Classes/PerformanceTest/PerformanceRendererTest.cpp \ +Classes/PerformanceTest/PerformanceContainerTest.cpp \ +Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp \ Classes/PhysicsTest/PhysicsTest.cpp \ +Classes/ReleasePoolTest/ReleasePoolTest.cpp \ Classes/RenderTextureTest/RenderTextureTest.cpp \ Classes/RotateWorldTest/RotateWorldTest.cpp \ Classes/SceneTest/SceneTest.cpp \ diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/tests/test-cpp/CMakeLists.txt similarity index 97% rename from samples/Cpp/TestCpp/CMakeLists.txt rename to tests/test-cpp/CMakeLists.txt index 5f409f7601..bdc404e01f 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/tests/test-cpp/CMakeLists.txt @@ -116,7 +116,11 @@ set(SAMPLE_SRC Classes/PerformanceTest/PerformanceTextureTest.cpp Classes/PerformanceTest/PerformanceTouchesTest.cpp Classes/PerformanceTest/PerformanceLabelTest.cpp + Classes/PerformanceTest/PerformanceRendererTest.cpp + Classes/PerformanceTest/PerformanceContainerTest.cpp + Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp Classes/PhysicsTest/PhysicsTest.cpp + Classes/ReleasePoolTest/ReleasePoolTest.cpp Classes/RenderTextureTest/RenderTextureTest.cpp Classes/RotateWorldTest/RotateWorldTest.cpp Classes/SceneTest/SceneTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp b/tests/test-cpp/Classes/AccelerometerTest/AccelerometerTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.cpp rename to tests/test-cpp/Classes/AccelerometerTest/AccelerometerTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.h b/tests/test-cpp/Classes/AccelerometerTest/AccelerometerTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/AccelerometerTest/AccelerometerTest.h rename to tests/test-cpp/Classes/AccelerometerTest/AccelerometerTest.h diff --git a/samples/Cpp/TestCpp/Classes/ActionManagerTest/ActionManagerTest.cpp b/tests/test-cpp/Classes/ActionManagerTest/ActionManagerTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ActionManagerTest/ActionManagerTest.cpp rename to tests/test-cpp/Classes/ActionManagerTest/ActionManagerTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ActionManagerTest/ActionManagerTest.h b/tests/test-cpp/Classes/ActionManagerTest/ActionManagerTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ActionManagerTest/ActionManagerTest.h rename to tests/test-cpp/Classes/ActionManagerTest/ActionManagerTest.h diff --git a/samples/Cpp/TestCpp/Classes/ActionsEaseTest/ActionsEaseTest.cpp b/tests/test-cpp/Classes/ActionsEaseTest/ActionsEaseTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ActionsEaseTest/ActionsEaseTest.cpp rename to tests/test-cpp/Classes/ActionsEaseTest/ActionsEaseTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ActionsEaseTest/ActionsEaseTest.h b/tests/test-cpp/Classes/ActionsEaseTest/ActionsEaseTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ActionsEaseTest/ActionsEaseTest.h rename to tests/test-cpp/Classes/ActionsEaseTest/ActionsEaseTest.h diff --git a/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.cpp b/tests/test-cpp/Classes/ActionsProgressTest/ActionsProgressTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.cpp rename to tests/test-cpp/Classes/ActionsProgressTest/ActionsProgressTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.h b/tests/test-cpp/Classes/ActionsProgressTest/ActionsProgressTest.h similarity index 97% rename from samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.h rename to tests/test-cpp/Classes/ActionsProgressTest/ActionsProgressTest.h index 9e16818164..f453ac0c2f 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.h +++ b/tests/test-cpp/Classes/ActionsProgressTest/ActionsProgressTest.h @@ -24,7 +24,7 @@ ****************************************************************************/ #ifndef _ACTIONS__PROGRESS_TEST_H_ -#define _ACTIONS_PROGRESS_TEST_H_ +#define _ACTIONS__PROGRESS_TEST_H_ #include "../testBasic.h" #include "../BaseTest.h" @@ -99,4 +99,4 @@ public: virtual void runThisTest(); }; -#endif +#endif // _ACTIONS__PROGRESS_TEST_H_ diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp b/tests/test-cpp/Classes/ActionsTest/ActionsTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp rename to tests/test-cpp/Classes/ActionsTest/ActionsTest.cpp index fa40b74f0a..b290364d39 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp +++ b/tests/test-cpp/Classes/ActionsTest/ActionsTest.cpp @@ -1314,7 +1314,7 @@ void ActionFollow::onEnter() void ActionFollow::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionFollow::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); @@ -1630,7 +1630,7 @@ void ActionCatmullRomStacked::draw() kmGLPopMatrix(); kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionCatmullRomStacked::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -1745,7 +1745,7 @@ void ActionCardinalSplineStacked::draw() kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); kmGLPopMatrix(); - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionCardinalSplineStacked::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -2107,7 +2107,7 @@ void ActionCatmullRom::draw() kmGLPopMatrix(); kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionCatmullRom::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -2207,7 +2207,7 @@ void ActionCardinalSpline::draw() kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); kmGLPopMatrix(); - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionCardinalSpline::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h b/tests/test-cpp/Classes/ActionsTest/ActionsTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h rename to tests/test-cpp/Classes/ActionsTest/ActionsTest.h diff --git a/tests/test-cpp/Classes/AppDelegate.cpp b/tests/test-cpp/Classes/AppDelegate.cpp new file mode 100644 index 0000000000..8c577cd02c --- /dev/null +++ b/tests/test-cpp/Classes/AppDelegate.cpp @@ -0,0 +1,136 @@ +/**************************************************************************** + Copyright (c) 2013 cocos2d-x.org + Copyright (c) 2013-2014 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. + ****************************************************************************/ + +#include "AppDelegate.h" + +#include "cocos2d.h" +#include "controller.h" +#include "SimpleAudioEngine.h" +#include "cocostudio/CocoStudio.h" +#include "extensions/cocos-ext.h" + +USING_NS_CC; +using namespace CocosDenshion; + +AppDelegate::AppDelegate() +{ +} + +AppDelegate::~AppDelegate() +{ +// SimpleAudioEngine::end(); + cocostudio::ArmatureDataManager::destroyInstance(); +} + +bool AppDelegate::applicationDidFinishLaunching() +{ + // As an example, load config file + // XXX: This should be loaded before the Director is initialized, + // XXX: but at this point, the director is already initialized + Configuration::getInstance()->loadConfigFile("configs/config-example.plist"); + + // initialize director + auto director = Director::getInstance(); + auto glview = director->getOpenGLView(); + if(!glview) { + glview = GLView::create("Test Cpp"); + director->setOpenGLView(glview); + } + + director->setDisplayStats(true); + director->setAnimationInterval(1.0 / 60); + + auto screenSize = glview->getFrameSize(); + + auto designSize = Size(480, 320); + + auto fileUtils = FileUtils::getInstance(); + std::vector searchPaths; + + if (screenSize.height > 320) + { + auto resourceSize = Size(960, 640); + searchPaths.push_back("hd"); + searchPaths.push_back("hd/scenetest"); + searchPaths.push_back("hd/scenetest/ArmatureComponentTest"); + searchPaths.push_back("hd/scenetest/AttributeComponentTest"); + searchPaths.push_back("hd/scenetest/BackgroundComponentTest"); + searchPaths.push_back("hd/scenetest/EffectComponentTest"); + searchPaths.push_back("hd/scenetest/LoadSceneEdtiorFileTest"); + searchPaths.push_back("hd/scenetest/ParticleComponentTest"); + searchPaths.push_back("hd/scenetest/SpriteComponentTest"); + searchPaths.push_back("hd/scenetest/TmxMapComponentTest"); + searchPaths.push_back("hd/scenetest/UIComponentTest"); + searchPaths.push_back("hd/scenetest/TriggerTest"); + director->setContentScaleFactor(resourceSize.height/designSize.height); + } + else + { + searchPaths.push_back("scenetest/ArmatureComponentTest"); + searchPaths.push_back("scenetest/AttributeComponentTest"); + searchPaths.push_back("scenetest/BackgroundComponentTest"); + searchPaths.push_back("scenetest/EffectComponentTest"); + searchPaths.push_back("scenetest/LoadSceneEdtiorFileTest"); + searchPaths.push_back("scenetest/ParticleComponentTest"); + searchPaths.push_back("scenetest/SpriteComponentTest"); + searchPaths.push_back("scenetest/TmxMapComponentTest"); + searchPaths.push_back("scenetest/UIComponentTest"); + searchPaths.push_back("scenetest/TriggerTest"); + } + + fileUtils->setSearchPaths(searchPaths); + +// glview->setDesignResolutionSize(screenSize.width, screenSize.height, ResolutionPolicy::NO_BORDER); + glview->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::NO_BORDER); + + auto scene = Scene::create(); + auto layer = new TestController(); + layer->autorelease(); + + scene->addChild(layer); + director->runWithScene(scene); + + // Enable Remote Console + auto console = director->getConsole(); + console->listenOnTCP(5678); + + return true; +} + +// This function will be called when the app is inactive. When comes a phone call,it's be invoked too +void AppDelegate::applicationDidEnterBackground() +{ + Director::getInstance()->stopAnimation(); + SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); + SimpleAudioEngine::getInstance()->pauseAllEffects(); +} + +// this function will be called when the app is active again +void AppDelegate::applicationWillEnterForeground() +{ + Director::getInstance()->startAnimation(); + SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); + SimpleAudioEngine::getInstance()->resumeAllEffects(); +} diff --git a/cocos/2d/CCFontAtlasFactory.cpp b/tests/test-cpp/Classes/AppDelegate.h similarity index 56% rename from cocos/2d/CCFontAtlasFactory.cpp rename to tests/test-cpp/Classes/AppDelegate.h index c9d3ebbb3b..bd170afca7 100644 --- a/cocos/2d/CCFontAtlasFactory.cpp +++ b/tests/test-cpp/Classes/AppDelegate.h @@ -1,7 +1,7 @@ /**************************************************************************** - Copyright (c) 2013 Zynga Inc. + Copyright (c) 2013 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. - + http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy @@ -23,41 +23,41 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCFontAtlasFactory.h" -#include "CCFontFNT.h" +#ifndef _APP_DELEGATE_H_ +#define _APP_DELEGATE_H_ -// carloX this NEEDS to be changed -#include "CCLabelBMFont.h" +#include "cocos2d.h" -NS_CC_BEGIN +/** +@brief The cocos2d Application. -FontAtlas * FontAtlasFactory::createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs, bool useDistanceField) +The reason for implement as private inheritance is to hide some interface call by Director. +*/ +class AppDelegate : private cocos2d::Application { - - Font *font = Font::createWithTTF(fntFilePath, fontSize, glyphs, customGlyphs); - if (font) - { - font->setDistanceFieldEnabled(useDistanceField); - return font->createFontAtlas(); - } - else - { - return nullptr; - } -} +public: + AppDelegate(); + virtual ~AppDelegate(); -FontAtlas * FontAtlasFactory::createAtlasFromFNT(const std::string& fntFilePath) -{ - Font *font = Font::createWithFNT(fntFilePath); - - if(font) - { - return font->createFontAtlas(); - } - else - { - return nullptr; - } -} + /** + @brief Implement Director and Scene init code here. + @return true Initialize success, app continue. + @return false Initialize failed, app terminate. + */ + virtual bool applicationDidFinishLaunching(); + + /** + @brief The function be called when the application enter background + @param the pointer of the application + */ + virtual void applicationDidEnterBackground(); + + /** + @brief The function be called when the application enter foreground + @param the pointer of the application + */ + virtual void applicationWillEnterForeground(); +}; + +#endif // _APP_DELEGATE_H_ -NS_CC_END diff --git a/samples/Cpp/TestCpp/Classes/BaseTest.cpp b/tests/test-cpp/Classes/BaseTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/BaseTest.cpp rename to tests/test-cpp/Classes/BaseTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/BaseTest.h b/tests/test-cpp/Classes/BaseTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/BaseTest.h rename to tests/test-cpp/Classes/BaseTest.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp b/tests/test-cpp/Classes/Box2DTest/Box2dTest.cpp similarity index 95% rename from samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp rename to tests/test-cpp/Classes/Box2DTest/Box2dTest.cpp index 70e55dae5d..941cf42b4d 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp +++ b/tests/test-cpp/Classes/Box2DTest/Box2dTest.cpp @@ -17,9 +17,12 @@ Box2DTestLayer::Box2DTestLayer() , world(NULL) { #if CC_ENABLE_BOX2D_INTEGRATION - setTouchEnabled( true ); - setAccelerometerEnabled( true ); - + auto dispatcher = Director::getInstance()->getEventDispatcher(); + + auto touchListener = EventListenerTouchAllAtOnce::create(); + touchListener->onTouchesEnded = CC_CALLBACK_2(Box2DTestLayer::onTouchesEnded, this); + dispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + // init physics this->initPhysics(); // create reset button @@ -149,7 +152,7 @@ void Box2DTestLayer::draw() kmGLPushMatrix(); kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV); - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Box2DTestLayer::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.h b/tests/test-cpp/Classes/Box2DTest/Box2dTest.h similarity index 95% rename from samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.h rename to tests/test-cpp/Classes/Box2DTest/Box2dTest.h index 24d0b43c65..167e2f6fb5 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.h +++ b/tests/test-cpp/Classes/Box2DTest/Box2dTest.h @@ -23,7 +23,6 @@ public: void update(float dt); void onTouchesEnded(const std::vector& touches, Event* event); - //CREATE_NODE(Box2DTestLayer); #if CC_ENABLE_BOX2D_INTEGRATION protected: kmMat4 _modelViewMV; diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp b/tests/test-cpp/Classes/Box2DTestBed/Box2dView.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp rename to tests/test-cpp/Classes/Box2DTestBed/Box2dView.cpp index dd8d3f8693..2b05f4a60b 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp +++ b/tests/test-cpp/Classes/Box2DTestBed/Box2dView.cpp @@ -211,7 +211,7 @@ void Box2DView::draw() { Layer::draw(); - _customCmd.init(0, _vertexZ); + _customCmd.init(_globalZOrder); _customCmd.func = CC_CALLBACK_0(Box2DView::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCmd); } diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.h b/tests/test-cpp/Classes/Box2DTestBed/Box2dView.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.h rename to tests/test-cpp/Classes/Box2DTestBed/Box2dView.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/GLES-Render.cpp b/tests/test-cpp/Classes/Box2DTestBed/GLES-Render.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/GLES-Render.cpp rename to tests/test-cpp/Classes/Box2DTestBed/GLES-Render.cpp diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/GLES-Render.h b/tests/test-cpp/Classes/Box2DTestBed/GLES-Render.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/GLES-Render.h rename to tests/test-cpp/Classes/Box2DTestBed/GLES-Render.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Test.cpp b/tests/test-cpp/Classes/Box2DTestBed/Test.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Test.cpp rename to tests/test-cpp/Classes/Box2DTestBed/Test.cpp diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Test.h b/tests/test-cpp/Classes/Box2DTestBed/Test.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Test.h rename to tests/test-cpp/Classes/Box2DTestBed/Test.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/TestEntries.cpp b/tests/test-cpp/Classes/Box2DTestBed/TestEntries.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/TestEntries.cpp rename to tests/test-cpp/Classes/Box2DTestBed/TestEntries.cpp diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/AddPair.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/AddPair.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/AddPair.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/AddPair.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ApplyForce.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/ApplyForce.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ApplyForce.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/ApplyForce.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/BodyTypes.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/BodyTypes.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/BodyTypes.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/BodyTypes.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Breakable.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Breakable.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Breakable.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Breakable.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Bridge.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Bridge.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Bridge.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Bridge.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/BulletTest.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/BulletTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/BulletTest.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/BulletTest.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Cantilever.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Cantilever.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Cantilever.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Cantilever.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Car.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Car.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Car.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Car.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Chain.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Chain.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Chain.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Chain.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CharacterCollision.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/CharacterCollision.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CharacterCollision.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/CharacterCollision.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CollisionFiltering.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/CollisionFiltering.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CollisionFiltering.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/CollisionFiltering.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CollisionProcessing.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/CollisionProcessing.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CollisionProcessing.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/CollisionProcessing.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CompoundShapes.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/CompoundShapes.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/CompoundShapes.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/CompoundShapes.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Confined.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Confined.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Confined.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Confined.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ContinuousTest.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/ContinuousTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ContinuousTest.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/ContinuousTest.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ConvexHull.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/ConvexHull.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ConvexHull.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/ConvexHull.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ConveyorBelt.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/ConveyorBelt.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ConveyorBelt.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/ConveyorBelt.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DistanceTest.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/DistanceTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DistanceTest.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/DistanceTest.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Dominos.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Dominos.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Dominos.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Dominos.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DumpShell.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/DumpShell.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DumpShell.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/DumpShell.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DynamicTreeTest.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/DynamicTreeTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/DynamicTreeTest.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/DynamicTreeTest.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/EdgeShapes.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/EdgeShapes.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/EdgeShapes.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/EdgeShapes.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/EdgeTest.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/EdgeTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/EdgeTest.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/EdgeTest.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Gears.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Gears.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Gears.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Gears.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Mobile.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Mobile.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Mobile.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Mobile.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/MobileBalanced.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/MobileBalanced.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/MobileBalanced.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/MobileBalanced.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/MotorJoint.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/MotorJoint.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/MotorJoint.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/MotorJoint.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/OneSidedPlatform.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/OneSidedPlatform.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/OneSidedPlatform.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/OneSidedPlatform.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pinball.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Pinball.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pinball.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Pinball.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/PolyCollision.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/PolyCollision.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/PolyCollision.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/PolyCollision.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/PolyShapes.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/PolyShapes.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/PolyShapes.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/PolyShapes.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Prismatic.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Prismatic.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Prismatic.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Prismatic.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pulleys.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Pulleys.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pulleys.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Pulleys.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pyramid.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Pyramid.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Pyramid.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Pyramid.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/RayCast.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/RayCast.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/RayCast.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/RayCast.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Revolute.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Revolute.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Revolute.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Revolute.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Rope.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Rope.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Rope.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Rope.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/RopeJoint.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/RopeJoint.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/RopeJoint.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/RopeJoint.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SensorTest.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/SensorTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SensorTest.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/SensorTest.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ShapeEditing.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/ShapeEditing.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/ShapeEditing.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/ShapeEditing.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SliderCrank.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/SliderCrank.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SliderCrank.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/SliderCrank.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SphereStack.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/SphereStack.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/SphereStack.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/SphereStack.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/TheoJansen.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/TheoJansen.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/TheoJansen.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/TheoJansen.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Tiles.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Tiles.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Tiles.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Tiles.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/TimeOfImpact.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/TimeOfImpact.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/TimeOfImpact.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/TimeOfImpact.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Tumbler.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Tumbler.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Tumbler.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Tumbler.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VaryingFriction.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/VaryingFriction.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VaryingFriction.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/VaryingFriction.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VaryingRestitution.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/VaryingRestitution.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VaryingRestitution.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/VaryingRestitution.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VerticalStack.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/VerticalStack.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/VerticalStack.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/VerticalStack.h diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Web.h b/tests/test-cpp/Classes/Box2DTestBed/Tests/Web.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Box2DTestBed/Tests/Web.h rename to tests/test-cpp/Classes/Box2DTestBed/Tests/Web.h diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-1159.cpp b/tests/test-cpp/Classes/BugsTest/Bug-1159.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-1159.cpp rename to tests/test-cpp/Classes/BugsTest/Bug-1159.cpp diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-1159.h b/tests/test-cpp/Classes/BugsTest/Bug-1159.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-1159.h rename to tests/test-cpp/Classes/BugsTest/Bug-1159.h diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-1174.cpp b/tests/test-cpp/Classes/BugsTest/Bug-1174.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-1174.cpp rename to tests/test-cpp/Classes/BugsTest/Bug-1174.cpp diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-1174.h b/tests/test-cpp/Classes/BugsTest/Bug-1174.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-1174.h rename to tests/test-cpp/Classes/BugsTest/Bug-1174.h diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-350.cpp b/tests/test-cpp/Classes/BugsTest/Bug-350.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-350.cpp rename to tests/test-cpp/Classes/BugsTest/Bug-350.cpp diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-350.h b/tests/test-cpp/Classes/BugsTest/Bug-350.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-350.h rename to tests/test-cpp/Classes/BugsTest/Bug-350.h diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.cpp b/tests/test-cpp/Classes/BugsTest/Bug-422.cpp similarity index 95% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.cpp rename to tests/test-cpp/Classes/BugsTest/Bug-422.cpp index 577b99d093..e72fd35deb 100644 --- a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.cpp +++ b/tests/test-cpp/Classes/BugsTest/Bug-422.cpp @@ -49,7 +49,7 @@ void Bug422Layer::check(Node* t) { auto& children = t->getChildren(); for(const auto &child : children) { - log("%p, rc: %d", child, child->retainCount()); + log("%p, rc: %d", child, child->getReferenceCount()); check(child); } } diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.h b/tests/test-cpp/Classes/BugsTest/Bug-422.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-422.h rename to tests/test-cpp/Classes/BugsTest/Bug-422.h diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-458/Bug-458.cpp b/tests/test-cpp/Classes/BugsTest/Bug-458/Bug-458.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-458/Bug-458.cpp rename to tests/test-cpp/Classes/BugsTest/Bug-458/Bug-458.cpp diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-458/Bug-458.h b/tests/test-cpp/Classes/BugsTest/Bug-458/Bug-458.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-458/Bug-458.h rename to tests/test-cpp/Classes/BugsTest/Bug-458/Bug-458.h diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp b/tests/test-cpp/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp rename to tests/test-cpp/Classes/BugsTest/Bug-458/QuestionContainerSprite.cpp diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-458/QuestionContainerSprite.h b/tests/test-cpp/Classes/BugsTest/Bug-458/QuestionContainerSprite.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-458/QuestionContainerSprite.h rename to tests/test-cpp/Classes/BugsTest/Bug-458/QuestionContainerSprite.h diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp b/tests/test-cpp/Classes/BugsTest/Bug-624.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.cpp rename to tests/test-cpp/Classes/BugsTest/Bug-624.cpp diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h b/tests/test-cpp/Classes/BugsTest/Bug-624.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-624.h rename to tests/test-cpp/Classes/BugsTest/Bug-624.h diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-886.cpp b/tests/test-cpp/Classes/BugsTest/Bug-886.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-886.cpp rename to tests/test-cpp/Classes/BugsTest/Bug-886.cpp diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-886.h b/tests/test-cpp/Classes/BugsTest/Bug-886.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-886.h rename to tests/test-cpp/Classes/BugsTest/Bug-886.h diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-899.cpp b/tests/test-cpp/Classes/BugsTest/Bug-899.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-899.cpp rename to tests/test-cpp/Classes/BugsTest/Bug-899.cpp diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-899.h b/tests/test-cpp/Classes/BugsTest/Bug-899.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-899.h rename to tests/test-cpp/Classes/BugsTest/Bug-899.h diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp b/tests/test-cpp/Classes/BugsTest/Bug-914.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.cpp rename to tests/test-cpp/Classes/BugsTest/Bug-914.cpp diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.h b/tests/test-cpp/Classes/BugsTest/Bug-914.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/Bug-914.h rename to tests/test-cpp/Classes/BugsTest/Bug-914.h diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp b/tests/test-cpp/Classes/BugsTest/BugsTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.cpp rename to tests/test-cpp/Classes/BugsTest/BugsTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.h b/tests/test-cpp/Classes/BugsTest/BugsTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/BugsTest/BugsTest.h rename to tests/test-cpp/Classes/BugsTest/BugsTest.h diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp b/tests/test-cpp/Classes/ChipmunkTest/ChipmunkTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp rename to tests/test-cpp/Classes/ChipmunkTest/ChipmunkTest.cpp index 3faf685bf1..8c0c94afec 100644 --- a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.cpp +++ b/tests/test-cpp/Classes/ChipmunkTest/ChipmunkTest.cpp @@ -85,15 +85,16 @@ void ChipmunkTestLayer::toggleDebugCallback(Object* sender) ChipmunkTestLayer::~ChipmunkTestLayer() { +#if CC_ENABLE_CHIPMUNK_INTEGRATION // manually Free rogue shapes for( int i=0;i<4;i++) { cpShapeFree( _walls[i] ); } cpSpaceFree( _space ); - - Device::setAccelerometerEnabled(false); + Device::setAccelerometerEnabled(false); +#endif } void ChipmunkTestLayer::initPhysics() diff --git a/samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h b/tests/test-cpp/Classes/ChipmunkTest/ChipmunkTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ChipmunkTest/ChipmunkTest.h rename to tests/test-cpp/Classes/ChipmunkTest/ChipmunkTest.h diff --git a/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp b/tests/test-cpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp rename to tests/test-cpp/Classes/ClickAndMoveTest/ClickAndMoveTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.h b/tests/test-cpp/Classes/ClickAndMoveTest/ClickAndMoveTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ClickAndMoveTest/ClickAndMoveTest.h rename to tests/test-cpp/Classes/ClickAndMoveTest/ClickAndMoveTest.h diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/tests/test-cpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp rename to tests/test-cpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp index 68a584d577..829c8766dc 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/tests/test-cpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -611,7 +611,7 @@ void RawStencilBufferTest::draw() auto iter = _renderCmds.begin(); - iter->init(0, _vertexZ); + iter->init(_globalZOrder); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onEnableStencil, this); renderer->addCommand(&(*iter)); ++iter; @@ -628,7 +628,7 @@ void RawStencilBufferTest::draw() spritePoint.y = 0; _sprites.at(i)->setPosition( spritePoint ); - iter->init(0, _vertexZ); + iter->init(_globalZOrder); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawClip, this, i, stencilPoint); renderer->addCommand(&(*iter)); ++iter; @@ -638,7 +638,7 @@ void RawStencilBufferTest::draw() _sprites.at(i)->visit(); kmGLPopMatrix(); - iter->init(0, _vertexZ); + iter->init(_globalZOrder); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawSprite, this, i, winPoint); renderer->addCommand(&(*iter)); ++iter; @@ -649,7 +649,7 @@ void RawStencilBufferTest::draw() kmGLPopMatrix(); } - iter->init(0, _vertexZ); + iter->init(_globalZOrder); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onDisableStencil, this); renderer->addCommand(&(*iter)); diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h b/tests/test-cpp/Classes/ClippingNodeTest/ClippingNodeTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.h rename to tests/test-cpp/Classes/ClippingNodeTest/ClippingNodeTest.h diff --git a/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp b/tests/test-cpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp rename to tests/test-cpp/Classes/CocosDenshionTest/CocosDenshionTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.h b/tests/test-cpp/Classes/CocosDenshionTest/CocosDenshionTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/CocosDenshionTest/CocosDenshionTest.h rename to tests/test-cpp/Classes/CocosDenshionTest/CocosDenshionTest.h diff --git a/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp b/tests/test-cpp/Classes/ConfigurationTest/ConfigurationTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp rename to tests/test-cpp/Classes/ConfigurationTest/ConfigurationTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.h b/tests/test-cpp/Classes/ConfigurationTest/ConfigurationTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.h rename to tests/test-cpp/Classes/ConfigurationTest/ConfigurationTest.h diff --git a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp b/tests/test-cpp/Classes/ConsoleTest/ConsoleTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp rename to tests/test-cpp/Classes/ConsoleTest/ConsoleTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.h b/tests/test-cpp/Classes/ConsoleTest/ConsoleTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.h rename to tests/test-cpp/Classes/ConsoleTest/ConsoleTest.h diff --git a/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp b/tests/test-cpp/Classes/CurlTest/CurlTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.cpp rename to tests/test-cpp/Classes/CurlTest/CurlTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.h b/tests/test-cpp/Classes/CurlTest/CurlTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/CurlTest/CurlTest.h rename to tests/test-cpp/Classes/CurlTest/CurlTest.h diff --git a/samples/Cpp/TestCpp/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp b/tests/test-cpp/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp rename to tests/test-cpp/Classes/CurrentLanguageTest/CurrentLanguageTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/CurrentLanguageTest/CurrentLanguageTest.h b/tests/test-cpp/Classes/CurrentLanguageTest/CurrentLanguageTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/CurrentLanguageTest/CurrentLanguageTest.h rename to tests/test-cpp/Classes/CurrentLanguageTest/CurrentLanguageTest.h diff --git a/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp b/tests/test-cpp/Classes/DataVisitorTest/DataVisitorTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.cpp rename to tests/test-cpp/Classes/DataVisitorTest/DataVisitorTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.h b/tests/test-cpp/Classes/DataVisitorTest/DataVisitorTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/DataVisitorTest/DataVisitorTest.h rename to tests/test-cpp/Classes/DataVisitorTest/DataVisitorTest.h diff --git a/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp b/tests/test-cpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp rename to tests/test-cpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp index 61aa2aa0b2..622220f09d 100644 --- a/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp +++ b/tests/test-cpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp @@ -116,7 +116,7 @@ DrawPrimitivesTest::DrawPrimitivesTest() void DrawPrimitivesTest::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(DrawPrimitivesTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.h b/tests/test-cpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.h rename to tests/test-cpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.h diff --git a/samples/Cpp/TestCpp/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp b/tests/test-cpp/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp rename to tests/test-cpp/Classes/EffectsAdvancedTest/EffectsAdvancedTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/EffectsAdvancedTest/EffectsAdvancedTest.h b/tests/test-cpp/Classes/EffectsAdvancedTest/EffectsAdvancedTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/EffectsAdvancedTest/EffectsAdvancedTest.h rename to tests/test-cpp/Classes/EffectsAdvancedTest/EffectsAdvancedTest.h diff --git a/samples/Cpp/TestCpp/Classes/EffectsTest/EffectsTest.cpp b/tests/test-cpp/Classes/EffectsTest/EffectsTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/EffectsTest/EffectsTest.cpp rename to tests/test-cpp/Classes/EffectsTest/EffectsTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/EffectsTest/EffectsTest.h b/tests/test-cpp/Classes/EffectsTest/EffectsTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/EffectsTest/EffectsTest.h rename to tests/test-cpp/Classes/EffectsTest/EffectsTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp similarity index 98% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 1349970d67..88a63ce1f9 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -503,7 +503,7 @@ void TestChangeZorder::changeZorder(float dt) Node *node = getChildByTag(currentTag); - node->setZOrder(CCRANDOM_0_1() * 3); + node->setLocalZOrder(CCRANDOM_0_1() * 3); currentTag ++; currentTag = currentTag % 3; @@ -637,7 +637,7 @@ void TestParticleDisplay::onEnter() bone->addDisplay(p1, 0); bone->changeDisplayWithIndex(0, true); bone->setIgnoreMovementBoneData(true); - bone->setZOrder(100); + bone->setLocalZOrder(100); bone->setScale(1.2f); armature->addBone(bone, "bady-a3"); @@ -645,7 +645,7 @@ void TestParticleDisplay::onEnter() bone->addDisplay(p2, 0); bone->changeDisplayWithIndex(0, true); bone->setIgnoreMovementBoneData(true); - bone->setZOrder(100); + bone->setLocalZOrder(100); bone->setScale(1.2f); armature->addBone(bone, "bady-a30"); } @@ -1067,8 +1067,22 @@ void TestColliderDetector::update(float delta) } void TestColliderDetector::draw() { - armature2->drawContour(); + _customCommand.init(_globalZOrder); + _customCommand.func = CC_CALLBACK_0(TestColliderDetector::onDraw, this); + Director::getInstance()->getRenderer()->addCommand(&_customCommand); } + +void TestColliderDetector::onDraw() +{ + kmMat4 oldMat; + kmGLGetMatrix(KM_GL_MODELVIEW, &oldMat); + kmGLLoadMatrix(&_modelViewTransform); + + armature2->drawContour(); + + kmGLLoadMatrix(&oldMat); +} + #endif @@ -1094,7 +1108,7 @@ std::string TestBoundingBox::title() const } void TestBoundingBox::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(TestBoundingBox::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h similarity index 98% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index c3b64debb9..9a07cc0d5d 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -271,6 +271,7 @@ public: virtual std::string title() const override; virtual void update(float delta); virtual void draw(); + void onDraw(); void onFrameEvent(cocostudio::Bone *bone, const std::string& evt, int originFrameIndex, int currentFrameIndex); @@ -278,6 +279,7 @@ public: cocostudio::Armature *armature; cocostudio::Armature *armature2; + CustomCommand _customCommand; //new render needed this for drawing primitives cocos2d::Sprite *bullet; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/GameOverScene.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/PlayerController.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/ProjectileController.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioComponentsTest/SceneController.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/CocosGUIScene.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIButtonTest/UIButtonTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp similarity index 98% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp index a06f00d592..5253040a66 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp +++ b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp @@ -56,7 +56,7 @@ bool UIImageViewTest::init() _uiLayer->addChild(sprite); */ -// imageView->setZOrder(20); +// imageView->setLocalZOrder(20); return true; } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelAtlasTest/UILabelAtlasTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelBMFontTest/UILabelBMFontTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILabelTest/UILabelTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILayoutTest/UILayoutTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILayoutTest/UILayoutTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILayoutTest/UILayoutTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILayoutTest/UILayoutTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILayoutTest/UILayoutTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILayoutTest/UILayoutTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILayoutTest/UILayoutTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILayoutTest/UILayoutTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIListViewTest/UIListViewTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScene.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UISceneManager.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioGUITest/UIWidgetAddNodeTest/UIWidgetAddNodeTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/EventDef.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/EventDef.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/EventDef.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/EventDef.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.h b/tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.h rename to tests/test-cpp/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsLayerLoader.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsLayerLoader.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsLayerLoader.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsLayerLoader.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/AnimationsTest/AnimationsTestLayer.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayerLoader.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayerLoader.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayerLoader.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayerLoader.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/CocosBuilderTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayerLoader.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayerLoader.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayerLoader.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayerLoader.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayer.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayer.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayer.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayer.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayerLoader.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayerLoader.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayerLoader.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/LabelTest/LabelTestLayerLoader.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayerLoader.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayerLoader.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayerLoader.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayerLoader.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayer.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayer.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayer.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayer.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayerLoader.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayerLoader.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayerLoader.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ParticleSystemTest/ParticleSystemTestLayerLoader.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayer.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayer.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayer.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayer.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayerLoader.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayerLoader.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayerLoader.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/ScrollViewTest/ScrollViewTestLayerLoader.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayer.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayer.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayer.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayer.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayerLoader.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayerLoader.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayerLoader.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/SpriteTest/SpriteTestLayerLoader.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayerLoader.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayerLoader.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayerLoader.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayerLoader.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackLayerLoader.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackLayerLoader.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackLayerLoader.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackLayerLoader.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h b/tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h rename to tests/test-cpp/Classes/ExtensionsTest/CocosBuilderTest/TimelineCallbackTest/TimelineCallbackTestLayer.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.h b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.h rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.h b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.h rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.h b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.h rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.h b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.h rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSceneManager.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.h b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.h rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.h b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.h rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.h b/tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.h rename to tests/test-cpp/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp similarity index 96% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp index 961f9f8e2d..eb788bb2b2 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp +++ b/tests/test-cpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp @@ -15,8 +15,9 @@ USING_NS_CC_EXT; EditBoxTest::EditBoxTest() { - auto visibleOrigin = EGLView::getInstance()->getVisibleOrigin(); - auto visibleSize = EGLView::getInstance()->getVisibleSize(); + auto glview = Director::getInstance()->getOpenGLView(); + auto visibleOrigin = glview->getVisibleOrigin(); + auto visibleSize = glview->getVisibleSize(); auto pBg = Sprite::create("Images/HelloWorld.png"); pBg->setPosition(Point(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+visibleSize.height/2)); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.h b/tests/test-cpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.h rename to tests/test-cpp/Classes/ExtensionsTest/EditBoxTest/EditBoxTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/ExtensionsTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/ExtensionsTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.h b/tests/test-cpp/Classes/ExtensionsTest/ExtensionsTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/ExtensionsTest.h rename to tests/test-cpp/Classes/ExtensionsTest/ExtensionsTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.h b/tests/test-cpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.h rename to tests/test-cpp/Classes/ExtensionsTest/NetworkTest/HttpClientTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h b/tests/test-cpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h rename to tests/test-cpp/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h b/tests/test-cpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h rename to tests/test-cpp/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.h b/tests/test-cpp/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.h rename to tests/test-cpp/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp b/tests/test-cpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp rename to tests/test-cpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.h b/tests/test-cpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.h rename to tests/test-cpp/Classes/ExtensionsTest/Scale9SpriteTest/Scale9SpriteTest.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp b/tests/test-cpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp rename to tests/test-cpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h b/tests/test-cpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h rename to tests/test-cpp/Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.h diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp b/tests/test-cpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp rename to tests/test-cpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h b/tests/test-cpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h rename to tests/test-cpp/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h diff --git a/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp b/tests/test-cpp/Classes/FileUtilsTest/FileUtilsTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.cpp rename to tests/test-cpp/Classes/FileUtilsTest/FileUtilsTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.h b/tests/test-cpp/Classes/FileUtilsTest/FileUtilsTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/FileUtilsTest/FileUtilsTest.h rename to tests/test-cpp/Classes/FileUtilsTest/FileUtilsTest.h diff --git a/samples/Cpp/TestCpp/Classes/FontTest/FontTest.cpp b/tests/test-cpp/Classes/FontTest/FontTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/FontTest/FontTest.cpp rename to tests/test-cpp/Classes/FontTest/FontTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/FontTest/FontTest.h b/tests/test-cpp/Classes/FontTest/FontTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/FontTest/FontTest.h rename to tests/test-cpp/Classes/FontTest/FontTest.h diff --git a/samples/Cpp/TestCpp/Classes/InputTest/MouseTest.cpp b/tests/test-cpp/Classes/InputTest/MouseTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/InputTest/MouseTest.cpp rename to tests/test-cpp/Classes/InputTest/MouseTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/InputTest/MouseTest.h b/tests/test-cpp/Classes/InputTest/MouseTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/InputTest/MouseTest.h rename to tests/test-cpp/Classes/InputTest/MouseTest.h diff --git a/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp b/tests/test-cpp/Classes/IntervalTest/IntervalTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.cpp rename to tests/test-cpp/Classes/IntervalTest/IntervalTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.h b/tests/test-cpp/Classes/IntervalTest/IntervalTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/IntervalTest/IntervalTest.h rename to tests/test-cpp/Classes/IntervalTest/IntervalTest.h diff --git a/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp b/tests/test-cpp/Classes/KeyboardTest/KeyboardTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.cpp rename to tests/test-cpp/Classes/KeyboardTest/KeyboardTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.h b/tests/test-cpp/Classes/KeyboardTest/KeyboardTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/KeyboardTest/KeyboardTest.h rename to tests/test-cpp/Classes/KeyboardTest/KeyboardTest.h diff --git a/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp b/tests/test-cpp/Classes/KeypadTest/KeypadTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.cpp rename to tests/test-cpp/Classes/KeypadTest/KeypadTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.h b/tests/test-cpp/Classes/KeypadTest/KeypadTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/KeypadTest/KeypadTest.h rename to tests/test-cpp/Classes/KeypadTest/KeypadTest.h diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp b/tests/test-cpp/Classes/LabelTest/LabelTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp rename to tests/test-cpp/Classes/LabelTest/LabelTest.cpp index d85049bc94..416d928ea5 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp +++ b/tests/test-cpp/Classes/LabelTest/LabelTest.cpp @@ -210,7 +210,7 @@ void Atlas1::draw() // GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY // GL_TEXTURE_2D - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Atlas1::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); @@ -419,7 +419,11 @@ Atlas3::Atlas3() label2->setAnchorPoint( Point(0.5f, 0.5f) ); label2->setColor( Color3B::RED ); addChild(label2, 0, kTagBitmapAtlas2); - label2->runAction( repeat->clone() ); + auto tint = Sequence::create(TintTo::create(1, 255, 0, 0), + TintTo::create(1, 0, 255, 0), + TintTo::create(1, 0, 0, 255), + NULL); + label2->runAction( RepeatForever::create(tint) ); auto label3 = LabelBMFont::create("Test", "fonts/bitmapFontTest2.fnt"); // testing anchors @@ -526,7 +530,7 @@ Atlas4::Atlas4() void Atlas4::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Atlas4::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -1612,7 +1616,7 @@ std::string LabelBMFontBounds::subtitle() const void LabelBMFontBounds::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(LabelBMFontBounds::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h b/tests/test-cpp/Classes/LabelTest/LabelTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.h rename to tests/test-cpp/Classes/LabelTest/LabelTest.h diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/tests/test-cpp/Classes/LabelTest/LabelTestNew.cpp similarity index 68% rename from samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp rename to tests/test-cpp/Classes/LabelTest/LabelTestNew.cpp index 9d3d063102..e0ee9e3a5a 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/tests/test-cpp/Classes/LabelTest/LabelTestNew.cpp @@ -66,7 +66,11 @@ static std::function createFunctions[] = CL(LabelTTFUnicodeNew), CL(LabelBMFontTestNew), CL(LabelTTFDistanceField), - CL(LabelTTFDistanceFieldEffect) + CL(LabelTTFDistanceFieldEffect), + CL(LabelCharMapTest), + CL(LabelCharMapColorTest), + CL(LabelCrashTest), + CL(LabelTTFOldNew) }; #define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) @@ -158,22 +162,21 @@ LabelTTFAlignmentNew::LabelTTFAlignmentNew() { auto s = Director::getInstance()->getWinSize(); - auto ttf0 = Label::createWithTTF("Alignment 0\nnew line", "fonts/tahoma.ttf", 32); - ttf0->setAlignment(TextHAlignment::LEFT); + TTFConfig config("fonts/tahoma.ttf",32); + + auto ttf0 = Label::createWithTTF(config,"Alignment 0\nnew line",TextHAlignment::LEFT); ttf0->setPosition(Point(s.width/2,(s.height/6)*2 - 30)); - ttf0->setAnchorPoint(Point(0.5f,0.5f)); + ttf0->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(ttf0); - auto ttf1 = Label::createWithTTF("Alignment 1\nnew line", "fonts/tahoma.ttf", 32); - ttf1->setAlignment(TextHAlignment::CENTER); + auto ttf1 = Label::createWithTTF(config,"Alignment 1\nnew line",TextHAlignment::CENTER); ttf1->setPosition(Point(s.width/2,(s.height/6)*3 - 30)); - ttf1->setAnchorPoint(Point(0.5f,0.5f)); + ttf1->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(ttf1); - auto ttf2 = Label::createWithTTF("Alignment 2\nnew line", "fonts/tahoma.ttf", 32); - ttf1->setAlignment(TextHAlignment::RIGHT); + auto ttf2 = Label::createWithTTF(config,"Alignment 2\nnew line",TextHAlignment::RIGHT); ttf2->setPosition(Point(s.width/2,(s.height/6)*4 - 30)); - ttf2->setAnchorPoint(Point(0.5f,0.5f)); + ttf2->setAnchorPoint(Point::ANCHOR_MIDDLE); this->addChild(ttf2); } @@ -194,7 +197,7 @@ LabelFNTColorAndOpacity::LabelFNTColorAndOpacity() auto col = LayerColor::create( Color4B(128,128,128,255) ); addChild(col, -10); - auto label1 = Label::createWithBMFont("Test", "fonts/bitmapFontTest2.fnt"); + auto label1 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Test"); label1->setAnchorPoint( Point(0,0) ); addChild(label1, 0, kTagBitmapAtlas1); @@ -204,13 +207,17 @@ LabelFNTColorAndOpacity::LabelFNTColorAndOpacity() auto repeat = RepeatForever::create(seq); label1->runAction(repeat); - auto label2 = Label::createWithBMFont("Test", "fonts/bitmapFontTest2.fnt"); - label2->setAnchorPoint( Point(0.5f, 0.5f) ); + auto label2 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Test"); + label2->setAnchorPoint( Point::ANCHOR_MIDDLE ); label2->setColor( Color3B::RED ); addChild(label2, 0, kTagBitmapAtlas2); - label2->runAction( repeat->clone() ); + auto tint = Sequence::create(TintTo::create(1, 255, 0, 0), + TintTo::create(1, 0, 255, 0), + TintTo::create(1, 0, 0, 255), + NULL); + label2->runAction( RepeatForever::create(tint) ); - auto label3 = Label::createWithBMFont("Test", "fonts/bitmapFontTest2.fnt"); + auto label3 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Test"); label3->setAnchorPoint( Point(1,1) ); addChild(label3, 0, kTagBitmapAtlas3); @@ -252,13 +259,13 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() _time = 0; // Upper Label - auto label = Label::createWithBMFont("Bitmap Font Atlas", "fonts/bitmapFontTest.fnt"); + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Bitmap Font Atlas"); addChild(label); auto s = Director::getInstance()->getWinSize(); label->setPosition( Point(s.width/2, s.height/2) ); - label->setAnchorPoint( Point(0.5f, 0.5f) ); + label->setAnchorPoint( Point::ANCHOR_MIDDLE ); auto BChar = (Sprite*) label->getLetter(0); @@ -289,9 +296,10 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() // Bottom Label - auto label2 = Label::createWithBMFont("00.0", "fonts/bitmapFontTest.fnt"); + auto label2 = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "00.0"); addChild(label2, 0, kTagBitmapAtlas2); label2->setPosition( Point(s.width/2.0f, 80) ); + label2->setAnchorPoint( Point::ANCHOR_MIDDLE ); auto lastChar = (Sprite*) label2->getLetter(3); lastChar->runAction( rot_4ever->clone() ); @@ -301,7 +309,7 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() void LabelFNTSpriteActions::draw() { - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(LabelFNTSpriteActions::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); @@ -341,13 +349,13 @@ std::string LabelFNTSpriteActions::subtitle() const LabelFNTPadding::LabelFNTPadding() { - auto label = Label::createWithBMFont("abcdefg", "fonts/bitmapFontTest4.fnt"); + auto label = Label::createWithBMFont("fonts/bitmapFontTest4.fnt", "abcdefg"); addChild(label); auto s = Director::getInstance()->getWinSize(); label->setPosition( Point(s.width/2, s.height/2) ); - label->setAnchorPoint( Point(0.5f, 0.5f) ); + label->setAnchorPoint( Point::ANCHOR_MIDDLE ); } std::string LabelFNTPadding::title() const @@ -365,20 +373,20 @@ LabelFNTOffset::LabelFNTOffset() auto s = Director::getInstance()->getWinSize(); Label* label = NULL; - label = Label::createWithBMFont("FaFeFiFoFu", "fonts/bitmapFontTest5.fnt"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "FaFeFiFoFu"); addChild(label); label->setPosition( Point(s.width/2, s.height/2+50) ); - label->setAnchorPoint( Point(0.5f, 0.5f) ) ; + label->setAnchorPoint( Point::ANCHOR_MIDDLE ) ; - label = Label::createWithBMFont("fafefifofu", "fonts/bitmapFontTest5.fnt"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "fafefifofu"); addChild(label); label->setPosition( Point(s.width/2, s.height/2) ); - label->setAnchorPoint( Point(0.5f, 0.5f) ); + label->setAnchorPoint( Point::ANCHOR_MIDDLE ); - label = Label::createWithBMFont("aeiou", "fonts/bitmapFontTest5.fnt"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "aeiou"); addChild(label); label->setPosition( Point(s.width/2, s.height/2-50) ); - label->setAnchorPoint( Point(0.5f, 0.5f) ); + label->setAnchorPoint( Point::ANCHOR_MIDDLE ); } std::string LabelFNTOffset::title() const @@ -396,22 +404,22 @@ LabelFNTColor::LabelFNTColor() auto s = Director::getInstance()->getWinSize(); Label* label = NULL; - label = Label::createWithBMFont("Blue", "fonts/bitmapFontTest5.fnt"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Blue"); label->setColor( Color3B::BLUE ); addChild(label); label->setPosition( Point(s.width/2, s.height/4) ); - label->setAnchorPoint( Point(0.5f, 0.5f) ); + label->setAnchorPoint( Point::ANCHOR_MIDDLE ); - label = Label::createWithBMFont("Red", "fonts/bitmapFontTest5.fnt"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Red"); addChild(label); label->setPosition( Point(s.width/2, 2*s.height/4) ); - label->setAnchorPoint( Point(0.5f, 0.5f) ); + label->setAnchorPoint( Point::ANCHOR_MIDDLE ); label->setColor( Color3B::RED ); - label = Label::createWithBMFont("G", "fonts/bitmapFontTest5.fnt"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Green"); addChild(label); label->setPosition( Point(s.width/2, 3*s.height/4) ); - label->setAnchorPoint( Point(0.5f, 0.5f) ); + label->setAnchorPoint( Point::ANCHOR_MIDDLE ); label->setColor( Color3B::GREEN ); label->setString("Green"); } @@ -433,14 +441,14 @@ LabelFNTHundredLabels::LabelFNTHundredLabels() { char str[6] = {0}; sprintf(str, "-%d-", i); - auto label = Label::createWithBMFont(str, "fonts/bitmapFontTest.fnt"); + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", str); addChild(label); auto s = Director::getInstance()->getWinSize(); auto p = Point( CCRANDOM_0_1() * s.width, CCRANDOM_0_1() * s.height); label->setPosition( p ); - label->setAnchorPoint(Point(0.5f, 0.5f)); + label->setAnchorPoint(Point::ANCHOR_MIDDLE); } } @@ -459,7 +467,7 @@ LabelFNTMultiLine::LabelFNTMultiLine() Size s; // Left - auto label1 = Label::createWithBMFont(" Multi line\nLeft", "fonts/bitmapFontTest3.fnt"); + auto label1 = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", " Multi line\nLeft"); label1->setAnchorPoint(Point(0,0)); addChild(label1, 0, kTagBitmapAtlas1); @@ -468,15 +476,15 @@ LabelFNTMultiLine::LabelFNTMultiLine() // Center - auto label2 = Label::createWithBMFont("Multi line\nCenter", "fonts/bitmapFontTest3.fnt"); - label2->setAnchorPoint(Point(0.5f, 0.5f)); + auto label2 = Label::createWithBMFont( "fonts/bitmapFontTest3.fnt", "Multi line\nCenter"); + label2->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label2, 0, kTagBitmapAtlas2); s= label2->getContentSize(); CCLOG("content size: %.2fx%.2f", s.width, s.height); // right - auto label3 = Label::createWithBMFont("Multi line\nRight\nThree lines Three", "fonts/bitmapFontTest3.fnt"); + auto label3 = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "Multi line\nRight\nThree lines Three"); label3->setAnchorPoint(Point(1, 1)); addChild(label3, 0, kTagBitmapAtlas3); @@ -501,21 +509,24 @@ std::string LabelFNTMultiLine::subtitle() const LabelFNTandTTFEmpty::LabelFNTandTTFEmpty() { auto s = Director::getInstance()->getWinSize(); - float delta = s.height/4; // LabelBMFont - auto label1 = Label::createWithBMFont("", "fonts/bitmapFontTest3.fnt", TextHAlignment::CENTER, s.width); + auto label1 = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "", TextHAlignment::CENTER, s.width); addChild(label1, 0, kTagBitmapAtlas1); - label1->setAnchorPoint(Point(0.5f, 0.5f)); - label1->setPosition(Point(s.width/2, delta)); + label1->setAnchorPoint(Point::ANCHOR_MIDDLE); + label1->setPosition(Point(s.width/2, s.height - 100)); // LabelTTF - auto label2 = Label::createWithTTF("", "fonts/arial.ttf", 48, s.width, TextHAlignment::CENTER,GlyphCollection::NEHE); + TTFConfig ttfConfig("fonts/arial.ttf",48); + auto label2 = Label::createWithTTF(ttfConfig,"", TextHAlignment::CENTER,s.width); addChild(label2, 0, kTagBitmapAtlas2); - label2->setAnchorPoint(Point(0.5f, 0.5f)); - label2->setPosition(Point(s.width/2, delta * 2)); + label2->setAnchorPoint(Point::ANCHOR_MIDDLE); + label2->setPosition(Point(s.width/2, s.height / 2)); - + auto label3 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); + label3->setAnchorPoint(Point::ANCHOR_MIDDLE); + addChild(label3, 0, kTagBitmapAtlas3); + label3->setPosition(Point(s.width/2, 100)); schedule(schedule_selector(LabelFNTandTTFEmpty::updateStrings), 1.0f); @@ -526,11 +537,13 @@ void LabelFNTandTTFEmpty::updateStrings(float dt) { auto label1 = static_cast( getChildByTag(kTagBitmapAtlas1) ); auto label2 = static_cast( getChildByTag(kTagBitmapAtlas2) ); + auto label3 = static_cast( getChildByTag(kTagBitmapAtlas3) ); if( ! setEmpty ) { label1->setString("not empty"); label2->setString("not empty"); + label3->setString("hi"); setEmpty = true; } @@ -538,6 +551,7 @@ void LabelFNTandTTFEmpty::updateStrings(float dt) { label1->setString(""); label2->setString(""); + label3->setString(""); setEmpty = false; } @@ -550,7 +564,7 @@ std::string LabelFNTandTTFEmpty::title() const std::string LabelFNTandTTFEmpty::subtitle() const { - return "2 empty labels: new Label + .FNT and new Label + .TTF"; + return "3 empty labels: new Label + FNT/TTF/CharMap"; } LabelFNTRetina::LabelFNTRetina() @@ -558,8 +572,8 @@ LabelFNTRetina::LabelFNTRetina() auto s = Director::getInstance()->getWinSize(); // LabelBMFont - auto label1 = Label::createWithBMFont("TESTING RETINA DISPLAY", "fonts/konqa32.fnt"); - label1->setAnchorPoint(Point(0.5f, 0.5f)); + auto label1 = Label::createWithBMFont("fonts/konqa32.fnt", "TESTING RETINA DISPLAY"); + label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); label1->setPosition(Point(s.width/2, s.height/2)); } @@ -582,8 +596,8 @@ LabelFNTGlyphDesigner::LabelFNTGlyphDesigner() addChild(layer, -10); // LabelBMFont - auto label1 = Label::createWithBMFont("Testing Glyph Designer", "fonts/futura-48.fnt"); - label1->setAnchorPoint(Point(0.5f, 0.5f)); + auto label1 = Label::createWithBMFont("fonts/futura-48.fnt", "Testing Glyph Designer"); + label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); label1->setPosition(Point(s.width/2, s.height/2)); } @@ -603,8 +617,9 @@ LabelTTFUnicodeChinese::LabelTTFUnicodeChinese() auto size = Director::getInstance()->getWinSize(); // Adding "啊" letter at the end of string to make VS2012 happy, otherwise VS will generate errors // like "Error 3 error C2146: syntax error : missing ')' before identifier 'label'"; - auto label = Label::createWithTTF("美好的一天啊", "fonts/wt021.ttf", 55, size.width, TextHAlignment::CENTER, GlyphCollection::CUSTOM, "美好的一天啊"); - label->setAnchorPoint(Point(0.5f, 0.5f)); + TTFConfig ttfConfig("fonts/wt021.ttf",55,GlyphCollection::CUSTOM, "美好的一天啊"); + auto label = Label::createWithTTF(ttfConfig,"美好的一天啊", TextHAlignment::CENTER, size.width); + label->setAnchorPoint(Point::ANCHOR_MIDDLE); label->setPosition(Point(size.width / 2, size.height /2)); this->addChild(label); } @@ -622,8 +637,8 @@ std::string LabelTTFUnicodeChinese::subtitle() const LabelFNTUnicodeChinese::LabelFNTUnicodeChinese() { auto size = Director::getInstance()->getWinSize(); - auto label = Label::createWithBMFont("中国", "fonts/bitmapFontChinese.fnt"); - label->setAnchorPoint(Point(0.5f, 0.5f)); + auto label = Label::createWithBMFont("fonts/bitmapFontChinese.fnt", "中国"); + label->setAnchorPoint(Point::ANCHOR_MIDDLE); label->setPosition(Point(size.width / 2, size.height /2)); this->addChild(label); } @@ -671,9 +686,8 @@ LabelFNTMultiLineAlignment::LabelFNTMultiLineAlignment() auto size = Director::getInstance()->getWinSize(); // create and initialize a Label - this->_labelShouldRetain = Label::createWithBMFont(LongSentencesExample, "fonts/markerFelt.fnt", TextHAlignment::CENTER, size.width/1.5); - //this->_labelShouldRetain = Label::createWithBMFont(LongSentencesExample, "fonts/bitmapFontTest.fnt", TextHAlignment::CENTER, size.width/1.5); - this->_labelShouldRetain->setAnchorPoint(Point(0.5f, 0.5f)); + this->_labelShouldRetain = Label::createWithBMFont("fonts/markerFelt.fnt", LongSentencesExample, TextHAlignment::CENTER, size.width/1.5); + this->_labelShouldRetain->setAnchorPoint(Point::ANCHOR_MIDDLE); this->_labelShouldRetain->retain(); this->_arrowsBarShouldRetain = Sprite::create("Images/arrowsBar.png"); @@ -855,24 +869,24 @@ LabelFNTUNICODELanguages::LabelFNTUNICODELanguages() auto s = Director::getInstance()->getWinSize(); - auto label1 = Label::createWithBMFont(spanish, "fonts/arial-unicode-26.fnt", TextHAlignment::CENTER, 200); + auto label1 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", spanish, TextHAlignment::CENTER, 200); addChild(label1); - label1->setAnchorPoint(Point(0.5f, 0.5f)); + label1->setAnchorPoint(Point::ANCHOR_MIDDLE); label1->setPosition(Point(s.width/2, s.height/5*3)); - auto label2 = Label::createWithBMFont(chinese, "fonts/arial-unicode-26.fnt"); + auto label2 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", chinese); addChild(label2); - label2->setAnchorPoint(Point(0.5f, 0.5f)); + label2->setAnchorPoint(Point::ANCHOR_MIDDLE); label2->setPosition(Point(s.width/2, s.height/5*2.5)); - auto label3 = Label::createWithBMFont(russian, "fonts/arial-26-en-ru.fnt"); + auto label3 = Label::createWithBMFont("fonts/arial-26-en-ru.fnt", russian); addChild(label3); - label3->setAnchorPoint(Point(0.5f, 0.5f)); + label3->setAnchorPoint(Point::ANCHOR_MIDDLE); label3->setPosition(Point(s.width/2, s.height/5*2)); - auto label4 = Label::createWithBMFont(japanese, "fonts/arial-unicode-26.fnt"); + auto label4 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", japanese); addChild(label4); - label4->setAnchorPoint(Point(0.5f, 0.5f)); + label4->setAnchorPoint(Point::ANCHOR_MIDDLE); label4->setPosition(Point(s.width/2, s.height/5*1.5)); } @@ -894,8 +908,8 @@ LabelFNTBounds::LabelFNTBounds() addChild(layer, -10); // LabelBMFont - label1 = Label::createWithBMFont("Testing Glyph Designer", "fonts/boundsTestFont.fnt", TextHAlignment::CENTER, s.width); - label1->setAnchorPoint(Point(0.5f, 0.5f)); + label1 = Label::createWithBMFont("fonts/boundsTestFont.fnt", "Testing Glyph Designer", TextHAlignment::CENTER, s.width); + label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); label1->setPosition(Point(s.width/2, s.height/2)); } @@ -912,7 +926,7 @@ std::string LabelFNTBounds::subtitle() const void LabelFNTBounds::draw() { - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(LabelFNTBounds::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } @@ -946,7 +960,8 @@ LabelTTFLongLineWrapping::LabelTTFLongLineWrapping() auto size = Director::getInstance()->getWinSize(); // Long sentence - auto label1 = Label::createWithTTF(LongSentencesExample, "fonts/arial.ttf", 28, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + TTFConfig ttfConfig("fonts/arial.ttf", 28); + auto label1 = Label::createWithTTF(ttfConfig, LongSentencesExample, TextHAlignment::CENTER,size.width); label1->setPosition( Point(size.width/2, size.height/2) ); label1->setAnchorPoint(Point(0.5, 1.0)); addChild(label1); @@ -966,25 +981,26 @@ LabelTTFColor::LabelTTFColor() { auto size = Director::getInstance()->getWinSize(); + TTFConfig ttfConfig("fonts/arial.ttf", 35); // Green - auto label1 = Label::createWithTTF("Green", "fonts/arial.ttf", 35, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + auto label1 = Label::createWithTTF(ttfConfig,"Green", TextHAlignment::CENTER, size.width); label1->setPosition( Point(size.width/2, size.height/5 * 1.5) ); label1->setColor( Color3B::GREEN ); - label1->setAnchorPoint(Point(0.5, 0.5)); + label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); // Red - auto label2 = Label::createWithTTF("Red", "fonts/arial.ttf", 35, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + auto label2 = Label::createWithTTF(ttfConfig,"Red", TextHAlignment::CENTER, size.width); label2->setPosition( Point(size.width/2, size.height/5 * 2.0) ); label2->setColor( Color3B::RED ); - label2->setAnchorPoint(Point(0.5, 0.5)); + label2->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label2); // Blue - auto label3 = Label::createWithTTF("Blue", "fonts/arial.ttf", 35, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + auto label3 = Label::createWithTTF(ttfConfig,"Blue", TextHAlignment::CENTER, size.width); label3->setPosition( Point(size.width/2, size.height/5 * 2.5) ); label3->setColor( Color3B::BLUE ); - label3->setAnchorPoint(Point(0.5, 0.5)); + label3->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label3); } @@ -1001,12 +1017,10 @@ std::string LabelTTFColor::subtitle() const LabelTTFDynamicAlignment::LabelTTFDynamicAlignment() { auto size = Director::getInstance()->getWinSize(); - - _label = Label::createWithTTF(LongSentencesExample, "fonts/arial.ttf", 45, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + TTFConfig ttfConfig("fonts/arial.ttf", 45); + _label = Label::createWithTTF(ttfConfig,LongSentencesExample, TextHAlignment::CENTER, size.width); _label->setPosition( Point(size.width/2, size.height/2) ); - _label->setAnchorPoint(Point(0.5, 0.5)); - - + _label->setAnchorPoint(Point::ANCHOR_MIDDLE); auto menu = Menu::create( MenuItemFont::create("Left", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentLeft, this)), @@ -1074,23 +1088,26 @@ LabelTTFUnicodeNew::LabelTTFUnicodeNew() float vStep = size.height/9; float vSize = size.height; - + TTFConfig ttfConfig("fonts/arial.ttf", 45,GlyphCollection::ASCII); // Spanish - auto label1 = Label::createWithTTF("Buen día, ¿cómo te llamas?", "fonts/arial.ttf", 45, size.width, TextHAlignment::CENTER, GlyphCollection::ASCII); + auto label1 = Label::createWithTTF(ttfConfig,"Buen día, ¿cómo te llamas?", TextHAlignment::CENTER, size.width); label1->setPosition( Point(size.width/2, vSize - (vStep * 4.5)) ); - label1->setAnchorPoint(Point(0.5, 0.5)); + label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); // German - auto label2 = Label::createWithTTF("In welcher Straße haben Sie gelebt?", "fonts/arial.ttf", 45, size.width, TextHAlignment::CENTER, GlyphCollection::ASCII); + auto label2 = Label::createWithTTF(ttfConfig,"In welcher Straße haben Sie gelebt?", TextHAlignment::CENTER,size.width); label2->setPosition( Point(size.width/2, vSize - (vStep * 5.5)) ); - label2->setAnchorPoint(Point(0.5, 0.5)); + label2->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label2); // chinese - auto label3 = Label::createWithTTF(chinese, "fonts/wt021.ttf", 45, size.width, TextHAlignment::CENTER, GlyphCollection::CUSTOM, chinese.c_str()); + ttfConfig.fontFilePath = "fonts/wt021.ttf"; + ttfConfig.glyphs = GlyphCollection::CUSTOM; + ttfConfig.customGlyphs = chinese.c_str(); + auto label3 = Label::createWithTTF(ttfConfig,chinese, TextHAlignment::CENTER,size.width); label3->setPosition( Point(size.width/2, vSize - (vStep * 6.5)) ); - label3->setAnchorPoint(Point(0.5, 0.5)); + label3->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label3); } @@ -1118,15 +1135,16 @@ LabelTTFFontsTestNew::LabelTTFFontsTestNew() #define arraysize(ar) (sizeof(ar) / sizeof(ar[0])) auto size = Director::getInstance()->getWinSize(); - + TTFConfig ttfConfig(ttfpaths[0],40, GlyphCollection::NEHE); for(size_t i=0;i < arraysize(ttfpaths); ++i) { - auto label = Label::createWithTTF( ttfpaths[i], ttfpaths[i], 40, 0, TextHAlignment::CENTER, GlyphCollection::NEHE); + ttfConfig.fontFilePath = ttfpaths[i]; + auto label = Label::createWithTTF(ttfConfig, ttfpaths[i], TextHAlignment::CENTER,0); if( label ) { label->setPosition( Point(size.width/2, ((size.height * 0.6)/arraysize(ttfpaths) * i) + (size.height/5))); addChild(label); - label->setAnchorPoint(Point(0.5, 0.5)); + label->setAnchorPoint(Point::ANCHOR_MIDDLE); } else { log("ERROR: Cannot load: %s", ttfpaths[i]); } @@ -1147,9 +1165,9 @@ LabelBMFontTestNew::LabelBMFontTestNew() { auto size = Director::getInstance()->getWinSize(); - auto label1 = Label::createWithBMFont("Hello World, this is testing the new Label using fnt file", "fonts/bitmapFontTest2.fnt", TextHAlignment::CENTER, size.width); + auto label1 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Hello World, this is testing the new Label using fnt file", TextHAlignment::CENTER, size.width); label1->setPosition( Point(size.width/2, size.height/2) ); - label1->setAnchorPoint(Point(0.5, 0.5)); + label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); } @@ -1166,11 +1184,12 @@ std::string LabelBMFontTestNew::subtitle() const LabelTTFDistanceField::LabelTTFDistanceField() { auto size = Director::getInstance()->getWinSize(); + TTFConfig ttfConfig("fonts/arial.ttf", 80, GlyphCollection::DYNAMIC,nullptr,true); - auto label1 = Label::createWithTTF("Distance Field", "fonts/arial.ttf", 80, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr,true); - label1->setPosition( Point(size.width/2, size.height/2) ); + auto label1 = Label::createWithTTF(ttfConfig,"Distance Field",TextHAlignment::CENTER,size.width); + label1->setPosition( Point(size.width/2, size.height * 0.6f) ); label1->setColor( Color3B::GREEN ); - label1->setAnchorPoint(Point(0.5, 0.5)); + label1->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label1); auto action = Sequence::create( @@ -1180,10 +1199,10 @@ LabelTTFDistanceField::LabelTTFDistanceField() nullptr); label1->runAction(RepeatForever::create(action)); - auto label2 = Label::createWithTTF("Distance Field", "fonts/arial.ttf", 80, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr,true); - label2->setPosition( Point(size.width/2, size.height/5) ); + auto label2 = Label::createWithTTF(ttfConfig,"Distance Field",TextHAlignment::CENTER,size.width); + label2->setPosition( Point(size.width/2, size.height * 0.3f) ); label2->setColor( Color3B::RED ); - label2->setAnchorPoint(Point(0.5, 0.5)); + label2->setAnchorPoint(Point::ANCHOR_MIDDLE); addChild(label2); } @@ -1205,24 +1224,26 @@ LabelTTFDistanceFieldEffect::LabelTTFDistanceFieldEffect() auto bg = LayerColor::create(Color4B(200,191,231,255)); this->addChild(bg); - auto label1 = Label::createWithTTF("Glow", "fonts/arial.ttf", 80, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr,true); - label1->setPosition( Point(size.width/2, size.height*0.5) ); + TTFConfig ttfConfig("fonts/arial.ttf", 80, GlyphCollection::DYNAMIC,nullptr,true); + + auto label1 = Label::createWithTTF(ttfConfig,"Glow", TextHAlignment::CENTER, size.width); + label1->setPosition( Point(size.width/2, size.height*0.65) ); label1->setColor( Color3B::GREEN ); - label1->setAnchorPoint(Point(0.5, 0.5)); + label1->setAnchorPoint(Point::ANCHOR_MIDDLE); label1->setLabelEffect(LabelEffect::GLOW,Color3B::YELLOW); addChild(label1); - auto label2 = Label::createWithTTF("Outline", "fonts/arial.ttf", 80, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr,true); - label2->setPosition( Point(size.width/2, size.height*0.375) ); + auto label2 = Label::createWithTTF(ttfConfig,"Outline", TextHAlignment::CENTER, size.width); + label2->setPosition( Point(size.width/2, size.height*0.5) ); label2->setColor( Color3B::RED ); - label2->setAnchorPoint(Point(0.5, 0.5)); + label2->setAnchorPoint(Point::ANCHOR_MIDDLE); label2->setLabelEffect(LabelEffect::OUTLINE,Color3B::BLUE); addChild(label2); - auto label3 = Label::createWithTTF("Shadow", "fonts/arial.ttf", 80, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr,true); - label3->setPosition( Point(size.width/2, size.height*0.25f) ); + auto label3 = Label::createWithTTF(ttfConfig,"Shadow", TextHAlignment::CENTER, size.width); + label3->setPosition( Point(size.width/2, size.height*0.35f) ); label3->setColor( Color3B::RED ); - label3->setAnchorPoint(Point(0.5, 0.5)); + label3->setAnchorPoint(Point::ANCHOR_MIDDLE); label3->setLabelEffect(LabelEffect::SHADOW,Color3B::BLACK); addChild(label3); @@ -1237,3 +1258,183 @@ std::string LabelTTFDistanceFieldEffect::subtitle() const { return "Testing effect base on DistanceField"; } + +LabelCharMapTest::LabelCharMapTest() +{ + _time = 0.0f; + + auto label1 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); + addChild(label1, 0, kTagSprite1); + label1->setPosition( Point(10,100) ); + label1->setOpacity( 200 ); + + auto label2 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); + addChild(label2, 0, kTagSprite2); + label2->setPosition( Point(10,200) ); + label2->setOpacity( 32 ); + + schedule(schedule_selector(LabelCharMapTest::step)); +} + +void LabelCharMapTest::step(float dt) +{ + _time += dt; + char string[12] = {0}; + sprintf(string, "%2.2f Test", _time); + + auto label1 = (Label*)getChildByTag(kTagSprite1); + label1->setString(string); + + auto label2 = (Label*)getChildByTag(kTagSprite2); + sprintf(string, "%d", (int)_time); + label2->setString(string); +} + +std::string LabelCharMapTest::title() const +{ + return "New Label + char map file"; +} + +std::string LabelCharMapTest::subtitle() const +{ + return "Updating label should be fast."; +} + +//------------------------------------------------------------------ +// +// LabelCharMapColorTest +// +//------------------------------------------------------------------ +LabelCharMapColorTest::LabelCharMapColorTest() +{ + auto label1 = Label::createWithCharMap( "fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); + addChild(label1, 0, kTagSprite1); + label1->setPosition( Point(10,100) ); + label1->setOpacity( 200 ); + + auto label2 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); + addChild(label2, 0, kTagSprite2); + label2->setPosition( Point(10,200) ); + label2->setColor( Color3B::RED ); + + auto fade = FadeOut::create(1.0f); + auto fade_in = fade->reverse(); + auto cb = CallFunc::create(CC_CALLBACK_0(LabelCharMapColorTest::actionFinishCallback, this)); + auto seq = Sequence::create(fade, fade_in, cb, NULL); + auto repeat = RepeatForever::create( seq ); + label2->runAction( repeat ); + + _time = 0; + + schedule( schedule_selector(LabelCharMapColorTest::step) ); //:@selector(step:)]; +} + +void LabelCharMapColorTest::actionFinishCallback() +{ + CCLOG("Action finished"); +} + +void LabelCharMapColorTest::step(float dt) +{ + _time += dt; + char string[12] = {0}; + sprintf(string, "%2.2f Test", _time); + auto label1 = (Label*)getChildByTag(kTagSprite1); + label1->setString(string); + + auto label2 = (Label*)getChildByTag(kTagSprite2); + sprintf(string, "%d", (int)_time); + label2->setString( string ); +} + +std::string LabelCharMapColorTest::title() const +{ + return "New Label + CharMap"; +} + +std::string LabelCharMapColorTest::subtitle() const +{ + return "Opacity + Color should work at the same time"; +} + +LabelCrashTest::LabelCrashTest() +{ + auto size = Director::getInstance()->getWinSize(); + + TTFConfig ttfConfig("fonts/arial.ttf", 80, GlyphCollection::DYNAMIC,nullptr,true); + + auto label1 = Label::createWithTTF(ttfConfig,"Test崩溃123", TextHAlignment::CENTER, size.width); + label1->setPosition( Point(size.width/2, size.height/2) ); + label1->setAnchorPoint(Point::ANCHOR_MIDDLE); + addChild(label1); +} + +std::string LabelCrashTest::title() const +{ + return "New Label Crash Test"; +} + +std::string LabelCrashTest::subtitle() const +{ + return "Not crash and show [Test123] when using unknown character."; +} + +LabelTTFOldNew::LabelTTFOldNew() +{ + auto s = Director::getInstance()->getWinSize(); + float delta = s.height/4; + + auto label1 = LabelTTF::create("Cocos2d-x Label Test", "arial", 24); + addChild(label1, 0, kTagBitmapAtlas1); + label1->setAnchorPoint(Point::ANCHOR_MIDDLE); + label1->setPosition(Point(s.width/2, delta * 2)); + label1->setColor(Color3B::RED); + + TTFConfig ttfConfig("fonts/arial.ttf", 48); + auto label2 = Label::createWithTTF(ttfConfig, "Cocos2d-x Label Test"); + addChild(label2, 0, kTagBitmapAtlas2); + label2->setAnchorPoint(Point::ANCHOR_MIDDLE); + label2->setPosition(Point(s.width/2, delta * 2)); +} + +void LabelTTFOldNew::onDraw() +{ + kmMat4 oldMat; + kmGLGetMatrix(KM_GL_MODELVIEW, &oldMat); + kmGLLoadMatrix(&_modelViewTransform); + + auto label1 = (Label*)getChildByTag(kTagBitmapAtlas2); + auto labelSize = label1->getContentSize(); + auto origin = Director::getInstance()->getWinSize(); + + origin.width = origin.width / 2 - (labelSize.width / 2); + origin.height = origin.height / 2 - (labelSize.height / 2); + + Point vertices[4]= + { + Point(origin.width, origin.height), + Point(labelSize.width + origin.width, origin.height), + Point(labelSize.width + origin.width, labelSize.height + origin.height), + Point(origin.width, labelSize.height + origin.height) + }; + DrawPrimitives::drawPoly(vertices, 4, true); + + kmGLLoadMatrix(&oldMat); +} + +void LabelTTFOldNew::draw() +{ + _renderCmd.init(_globalZOrder); + _renderCmd.func = CC_CALLBACK_0(LabelTTFOldNew::onDraw, this); + Director::getInstance()->getRenderer()->addCommand(&_renderCmd); +} + +std::string LabelTTFOldNew::title() const +{ + return "New / Old TTF"; +} + +std::string LabelTTFOldNew::subtitle() const +{ + return "Comparison between old(red) and new(white) TTF label"; +} diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h b/tests/test-cpp/Classes/LabelTest/LabelTestNew.h similarity index 87% rename from samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h rename to tests/test-cpp/Classes/LabelTest/LabelTestNew.h index ad6b53211c..3d5e99f368 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h +++ b/tests/test-cpp/Classes/LabelTest/LabelTestNew.h @@ -347,6 +347,65 @@ public: virtual std::string subtitle() const override; }; +class LabelCharMapTest : public AtlasDemoNew +{ +public: + CREATE_FUNC(LabelCharMapTest); + + LabelCharMapTest(); + + virtual std::string title() const override; + virtual std::string subtitle() const override; + + void step(float dt); + +private: + float _time; +}; + +class LabelCharMapColorTest : public AtlasDemoNew +{ +public: + CREATE_FUNC(LabelCharMapColorTest); + + LabelCharMapColorTest(); + + virtual std::string title() const override; + virtual std::string subtitle() const override; + + void step(float dt); + void actionFinishCallback(); + +private: + float _time; +}; + +class LabelCrashTest : public AtlasDemoNew +{ +public: + CREATE_FUNC(LabelCrashTest); + + LabelCrashTest(); + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class LabelTTFOldNew : public AtlasDemoNew +{ +public: + CREATE_FUNC(LabelTTFOldNew); + + LabelTTFOldNew(); + + virtual void draw() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +protected: + CustomCommand _renderCmd; + void onDraw(); +}; // we don't support linebreak mode diff --git a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp b/tests/test-cpp/Classes/LayerTest/LayerTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp rename to tests/test-cpp/Classes/LayerTest/LayerTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h b/tests/test-cpp/Classes/LayerTest/LayerTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h rename to tests/test-cpp/Classes/LayerTest/LayerTest.h diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp b/tests/test-cpp/Classes/MenuTest/MenuTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp rename to tests/test-cpp/Classes/MenuTest/MenuTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h b/tests/test-cpp/Classes/MenuTest/MenuTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h rename to tests/test-cpp/Classes/MenuTest/MenuTest.h diff --git a/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp b/tests/test-cpp/Classes/MotionStreakTest/MotionStreakTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.cpp rename to tests/test-cpp/Classes/MotionStreakTest/MotionStreakTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.h b/tests/test-cpp/Classes/MotionStreakTest/MotionStreakTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/MotionStreakTest/MotionStreakTest.h rename to tests/test-cpp/Classes/MotionStreakTest/MotionStreakTest.h diff --git a/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp b/tests/test-cpp/Classes/MutiTouchTest/MutiTouchTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.cpp rename to tests/test-cpp/Classes/MutiTouchTest/MutiTouchTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.h b/tests/test-cpp/Classes/MutiTouchTest/MutiTouchTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/MutiTouchTest/MutiTouchTest.h rename to tests/test-cpp/Classes/MutiTouchTest/MutiTouchTest.h diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/tests/test-cpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp similarity index 75% rename from samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp rename to tests/test-cpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index d23091db12..1495970cec 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/tests/test-cpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -22,6 +22,8 @@ std::function createFunctions[] = CL(RemoveAndRetainNodeTest), CL(RemoveListenerAfterAddingTest), CL(DirectorEventTest), + CL(GlobalZTouchTest), + CL(StopPropagationTest), }; unsigned int TEST_CASE_COUNT = sizeof(createFunctions) / sizeof(createFunctions[0]); @@ -166,11 +168,11 @@ void TouchableSpriteTest::onEnter() target->setOpacity(255); if (target == sprite2) { - sprite1->setZOrder(100); + sprite1->setLocalZOrder(100); } else if(target == sprite1) { - sprite1->setZOrder(0); + sprite1->setLocalZOrder(0); } }; @@ -764,20 +766,22 @@ void DirectorEventTest::onEnter() Size s = Director::getInstance()->getWinSize(); - _label1 = Label::createWithTTF("Update: 0", "fonts/arial.ttf", 20); + TTFConfig ttfConfig("fonts/arial.ttf", 20); + + _label1 = Label::createWithTTF(ttfConfig, "Update: 0"); _label1->setPosition(30,s.height/2 + 60); this->addChild(_label1); - _label2 = Label::createWithTTF("Visit: 0", "fonts/arial.ttf", 20); + _label2 = Label::createWithTTF(ttfConfig, "Visit: 0"); _label2->setPosition(30,s.height/2 + 20); this->addChild(_label2); - _label3 = Label::createWithTTF("Draw: 0", "fonts/arial.ttf", 20); + _label3 = Label::createWithTTF(ttfConfig, "Draw: 0"); _label3->setPosition(30,30); _label3->setPosition(30,s.height/2 - 20); this->addChild(_label3); - _label4 = Label::createWithTTF("Projection: 0", "fonts/arial.ttf", 20); + _label4 = Label::createWithTTF(ttfConfig, "Projection: 0"); _label4->setPosition(30,30); _label4->setPosition(30,s.height/2 - 60); this->addChild(_label4); @@ -857,4 +861,230 @@ std::string DirectorEventTest::subtitle() const return "after visit, after draw, after update, projection changed"; } +// GlobalZTouchTest +GlobalZTouchTest::GlobalZTouchTest() +: _sprite(nullptr) +, _accum(0) +{ + + auto listener = EventListenerTouchOneByOne::create(); + listener->setSwallowTouches(true); + + listener->onTouchBegan = [](Touch* touch, Event* event){ + auto target = static_cast(event->getCurrentTarget()); + + Point locationInNode = target->convertToNodeSpace(touch->getLocation()); + Size s = target->getContentSize(); + Rect rect = Rect(0, 0, s.width, s.height); + + if (rect.containsPoint(locationInNode)) + { + log("sprite began... x = %f, y = %f", locationInNode.x, locationInNode.y); + target->setOpacity(180); + return true; + } + return false; + }; + + listener->onTouchMoved = [](Touch* touch, Event* event){ + auto target = static_cast(event->getCurrentTarget()); + target->setPosition(target->getPosition() + touch->getDelta()); + }; + + listener->onTouchEnded = [=](Touch* touch, Event* event){ + auto target = static_cast(event->getCurrentTarget()); + log("sprite onTouchesEnded.. "); + target->setOpacity(255); + }; + + const int SPRITE_COUNT = 8; + + for (int i = 0; i < SPRITE_COUNT; i++) + { + Sprite *sprite; + if(i==4) + { + sprite = Sprite::create("Images/CyanSquare.png"); + _sprite = sprite; + _sprite->setGlobalZOrder(-1); + } + else + { + sprite = Sprite::create("Images/YellowSquare.png"); + } + + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), sprite); + + this->addChild(sprite); + + Size visibleSize = Director::getInstance()->getVisibleSize(); + sprite->setPosition(VisibleRect::left().x + visibleSize.width / (SPRITE_COUNT - 1) * i, VisibleRect::center().y); + } + + this->scheduleUpdate(); +} +void GlobalZTouchTest::update(float dt) +{ + _accum += dt; + if( _accum > 2.0f) { + float z = _sprite->getGlobalZOrder(); + _sprite->setGlobalZOrder(-z); + _accum = 0; + } +} + +std::string GlobalZTouchTest::title() const +{ + return "Global Z Value, Try touch blue sprite"; +} + +std::string GlobalZTouchTest::subtitle() const +{ + return "Blue Sprite should change go from foreground to background"; +} + +StopPropagationTest::StopPropagationTest() +{ + static const int TAG_BLUE_SPRITE = 101; + static const int TAG_BLUE_SPRITE2 = 102; + + auto touchOneByOneListener = EventListenerTouchOneByOne::create(); + touchOneByOneListener->setSwallowTouches(true); + + touchOneByOneListener->onTouchBegan = [=](Touch* touch, Event* event){ + // Skip if don't touch top half screen. + if (!this->isPointInTopHalfAreaOfScreen(touch->getLocation())) + return false; + + auto target = static_cast(event->getCurrentTarget()); + CCASSERT(target->getTag() == TAG_BLUE_SPRITE, "Yellow blocks shouldn't response event."); + + if (this->isPointInNode(touch->getLocation(), target)) + { + target->setOpacity(180); + return true; + } + + // Stop propagation, so yellow blocks will not be able to receive event. + event->stopPropagation(); + return false; + }; + + touchOneByOneListener->onTouchEnded = [=](Touch* touch, Event* event){ + auto target = static_cast(event->getCurrentTarget()); + target->setOpacity(255); + }; + + auto touchAllAtOnceListener = EventListenerTouchAllAtOnce::create(); + touchAllAtOnceListener->onTouchesBegan = [=](const std::vector& touches, Event* event){ + // Skip if don't touch top half screen. + if (this->isPointInTopHalfAreaOfScreen(touches[0]->getLocation())) + return; + + auto target = static_cast(event->getCurrentTarget()); + CCASSERT(target->getTag() == TAG_BLUE_SPRITE2, "Yellow blocks shouldn't response event."); + + if (this->isPointInNode(touches[0]->getLocation(), target)) + { + target->setOpacity(180); + } + // Stop propagation, so yellow blocks will not be able to receive event. + event->stopPropagation(); + }; + + touchAllAtOnceListener->onTouchesEnded = [=](const std::vector& touches, Event* event){ + // Skip if don't touch top half screen. + if (this->isPointInTopHalfAreaOfScreen(touches[0]->getLocation())) + return; + + auto target = static_cast(event->getCurrentTarget()); + CCASSERT(target->getTag() == TAG_BLUE_SPRITE2, "Yellow blocks shouldn't response event."); + + if (this->isPointInNode(touches[0]->getLocation(), target)) + { + target->setOpacity(255); + } + // Stop propagation, so yellow blocks will not be able to receive event. + event->stopPropagation(); + }; + + auto keyboardEventListener = EventListenerKeyboard::create(); + keyboardEventListener->onKeyPressed = [](EventKeyboard::KeyCode key, Event* event){ + auto target = static_cast(event->getCurrentTarget()); + CCASSERT(target->getTag() == TAG_BLUE_SPRITE || target->getTag() == TAG_BLUE_SPRITE2, "Yellow blocks shouldn't response event."); + // Stop propagation, so yellow blocks will not be able to receive event. + event->stopPropagation(); + }; + + const int SPRITE_COUNT = 8; + + for (int i = 0; i < SPRITE_COUNT; i++) + { + Sprite* sprite; + Sprite* sprite2; + + if(i==4) + { + sprite = Sprite::create("Images/CyanSquare.png"); + sprite->setTag(TAG_BLUE_SPRITE); + addChild(sprite, 100); + + sprite2 = Sprite::create("Images/CyanSquare.png"); + sprite2->setTag(TAG_BLUE_SPRITE2); + addChild(sprite2, 100); + } + else + { + sprite = Sprite::create("Images/YellowSquare.png"); + addChild(sprite, 0); + sprite2 = Sprite::create("Images/YellowSquare.png"); + addChild(sprite2, 0); + } + + _eventDispatcher->addEventListenerWithSceneGraphPriority(touchOneByOneListener->clone(), sprite); + _eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardEventListener->clone(), sprite); + + _eventDispatcher->addEventListenerWithSceneGraphPriority(touchAllAtOnceListener->clone(), sprite2); + _eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardEventListener->clone(), sprite2); + + + Size visibleSize = Director::getInstance()->getVisibleSize(); + sprite->setPosition(VisibleRect::left().x + visibleSize.width / (SPRITE_COUNT - 1) * i, VisibleRect::center().y + sprite2->getContentSize().height/2 +10); + sprite2->setPosition(VisibleRect::left().x + visibleSize.width / (SPRITE_COUNT - 1) * i, VisibleRect::center().y - sprite2->getContentSize().height/2-10); + } +} + +bool StopPropagationTest::isPointInNode(Point pt, Node* node) +{ + Point locationInNode = node->convertToNodeSpace(pt); + Size s = node->getContentSize(); + Rect rect = Rect(0, 0, s.width, s.height); + + if (rect.containsPoint(locationInNode)) + { + return true; + } + return false; +} + +bool StopPropagationTest::isPointInTopHalfAreaOfScreen(Point pt) +{ + Size winSize = Director::getInstance()->getWinSize(); + + if (pt.y >= winSize.height/2) { + return true; + } + + return false; +} + +std::string StopPropagationTest::title() const +{ + return "Stop Propagation Test"; +} + +std::string StopPropagationTest::subtitle() const +{ + return "Shouldn't crash and only blue block could be clicked"; +} diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h b/tests/test-cpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h similarity index 83% rename from samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h rename to tests/test-cpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h index 2de772a6af..bb5b33b502 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h +++ b/tests/test-cpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h @@ -22,7 +22,7 @@ public: class EventDispatcherTestDemo : public BaseTest { public: - virtual void onEnter(); + virtual void onEnter() override; virtual std::string title() const override; virtual std::string subtitle() const override; void backCallback(Object* sender); @@ -135,4 +135,34 @@ protected: EventListenerCustom *_event1, *_event2, *_event3, *_event4; }; +class GlobalZTouchTest : public EventDispatcherTestDemo +{ +public: + CREATE_FUNC(GlobalZTouchTest); + GlobalZTouchTest(); + + virtual void update(float dt) override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; + +protected: + Sprite* _sprite; + float _accum; +}; + +class StopPropagationTest : public EventDispatcherTestDemo +{ +public: + CREATE_FUNC(StopPropagationTest); + StopPropagationTest(); + + virtual std::string title() const override; + virtual std::string subtitle() const override; + +protected: + bool isPointInNode(Point pt, Node* node); + bool isPointInTopHalfAreaOfScreen(Point pt); +}; + #endif /* defined(__samples__NewEventDispatcherTest__) */ diff --git a/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp b/tests/test-cpp/Classes/NewRendererTest/NewRendererTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp rename to tests/test-cpp/Classes/NewRendererTest/NewRendererTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.h b/tests/test-cpp/Classes/NewRendererTest/NewRendererTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.h rename to tests/test-cpp/Classes/NewRendererTest/NewRendererTest.h diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/tests/test-cpp/Classes/NodeTest/NodeTest.cpp similarity index 93% rename from samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp rename to tests/test-cpp/Classes/NodeTest/NodeTest.cpp index 4d69c14542..381b2728fc 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/tests/test-cpp/Classes/NodeTest/NodeTest.cpp @@ -63,10 +63,13 @@ static std::function createFunctions[] = CL(NodeToWorld3D), CL(SchedulerTest1), CL(CameraOrbitTest), - CL(CameraZoomTest), + //Camera has been removed from CCNode + //todo add new feature to support it + //CL(CameraZoomTest), CL(ConvertToNode), CL(NodeOpaqueTest), CL(NodeNonOpaqueTest), + CL(NodeGlobalZValueTest), }; #define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) @@ -458,16 +461,16 @@ std::string StressTest2::title() const SchedulerTest1::SchedulerTest1() { auto layer = Layer::create(); - //CCLOG("retain count after init is %d", layer->retainCount()); // 1 + //CCLOG("retain count after init is %d", layer->getReferenceCount()); // 1 addChild(layer, 0); - //CCLOG("retain count after addChild is %d", layer->retainCount()); // 2 + //CCLOG("retain count after addChild is %d", layer->getReferenceCount()); // 2 layer->schedule( schedule_selector(SchedulerTest1::doSomething) ); - //CCLOG("retain count after schedule is %d", layer->retainCount()); // 3 : (object-c viersion), but win32 version is still 2, because Timer class don't save target. + //CCLOG("retain count after schedule is %d", layer->getReferenceCount()); // 3 : (object-c viersion), but win32 version is still 2, because Timer class don't save target. layer->unschedule(schedule_selector(SchedulerTest1::doSomething)); - //CCLOG("retain count after unschedule is %d", layer->retainCount()); // STILL 3! (win32 is '2') + //CCLOG("retain count after unschedule is %d", layer->getReferenceCount()); // STILL 3! (win32 is '2') } void SchedulerTest1::doSomething(float dt) @@ -905,6 +908,55 @@ std::string NodeNonOpaqueTest::subtitle() const return "Node rendered with GL_BLEND enabled"; } +/// NodeGlobalZValueTest + +NodeGlobalZValueTest::NodeGlobalZValueTest() +{ + Size s = Director::getInstance()->getWinSize(); + for (int i = 0; i < 9; i++) + { + Sprite *sprite; + auto parent = Node::create(); + if(i==4) { + sprite = Sprite::create("Images/grossinis_sister2.png"); + _sprite = sprite; + _sprite->setGlobalZOrder(-1); + } + else + sprite = Sprite::create("Images/grossinis_sister1.png"); + + parent->addChild(sprite); + this->addChild(parent); + + float w = sprite->getContentSize().width; + sprite->setPosition(s.width/2 - w*0.7*(i-5), s.height/2); + } + + this->scheduleUpdate(); +} + +void NodeGlobalZValueTest::update(float dt) +{ + static float accum = 0; + + accum += dt; + if( accum > 1) { + float z = _sprite->getGlobalZOrder(); + _sprite->setGlobalZOrder(-z); + accum = 0; + } +} + +std::string NodeGlobalZValueTest::title() const +{ + return "Global Z Value"; +} + +std::string NodeGlobalZValueTest::subtitle() const +{ + return "Center Sprite should change go from foreground to background"; +} + // // MySprite: Used by CameraTest1 and CameraTest2 @@ -932,7 +984,7 @@ protected: void MySprite::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(MySprite::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -946,8 +998,8 @@ void MySprite::onDraw() GL::bindTexture2D( _texture->getName() ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX ); -#define kQuadSize sizeof(_quad.bl) - long offset = (long)&_quad; + #define kQuadSize sizeof(_quad.bl) + size_t offset = (size_t)&_quad; // vertex int diff = offsetof( V3F_C4B_T2F, vertices); diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h b/tests/test-cpp/Classes/NodeTest/NodeTest.h similarity index 94% rename from samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h rename to tests/test-cpp/Classes/NodeTest/NodeTest.h index 2207c65f7c..334e2df08a 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h +++ b/tests/test-cpp/Classes/NodeTest/NodeTest.h @@ -249,6 +249,20 @@ protected: NodeNonOpaqueTest(); }; +class NodeGlobalZValueTest : public TestCocosNodeDemo +{ +public: + CREATE_FUNC(NodeGlobalZValueTest); + virtual std::string title() const override; + virtual std::string subtitle() const override; + + virtual void update(float dt) override; + +protected: + NodeGlobalZValueTest(); + Sprite *_sprite; +}; + class CocosNodeTestScene : public TestScene { public: diff --git a/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp b/tests/test-cpp/Classes/ParallaxTest/ParallaxTest.cpp similarity index 73% rename from samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp rename to tests/test-cpp/Classes/ParallaxTest/ParallaxTest.cpp index 994be54d62..80f2ce193c 100644 --- a/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.cpp +++ b/tests/test-cpp/Classes/ParallaxTest/ParallaxTest.cpp @@ -148,6 +148,86 @@ std::string Parallax2::title() const return "Parallax: drag screen"; } +//------------------------------------------------------------------ +// +// Issue2572 +// +//------------------------------------------------------------------ +Issue2572::Issue2572() +: _preListSize(0) +, _printCount(0) +, _moveTimer(0.0f) +, _addTimer(0.0f) +{ + _addChildStep = 1.0f; + _wholeMoveTime = 3.0f; + _wholeMoveSize = Point(-300, 0); + + // create a parallax node, a parent node + _paraNode = ParallaxNode::create(); + addChild(_paraNode, 0, kTagNode); + + this->scheduleUpdate(); +} + +void Issue2572::update(float dt) +{ + _addTimer += dt; + _moveTimer += dt; + if (_moveTimer >= _wholeMoveTime) { + this->unscheduleUpdate(); + return; + } + + _paraNode->setPosition(_paraNode->getPosition() + _wholeMoveSize * dt / _wholeMoveTime); + + if (_addTimer >= _addChildStep) { + _addTimer = 0.0f; + + auto child = Sprite::create("Images/Icon.png"); + Size viewSize = Director::getInstance()->getVisibleSize(); + Point offset = Point(viewSize.width / 2, viewSize.height/2); + _paraNode->addChild(child, 1, Point( 1, 0 ), offset ); + + _childList.pushBack(child); + } + + // After a child added, output the position of the children 3 times. + // Bug : The first output is much different with the second one & the third one. + if (_childList.size() != _preListSize) { + switch (_printCount) { + case 0: + case 1: + case 2: + log( "--child count-- %zd", _childList.size()); + for (const auto& obj : _childList) + { + Sprite* obstacle = dynamic_cast( obj ); + log("child position : (%.2f, %.2f)", obstacle->getPositionX(), obstacle->getPositionY()); + } + log("-------------------"); + _printCount++; + break; + case 3: + _preListSize = _childList.size(); + _printCount = 0; + break; + default: + break; + } + } +} + +std::string Issue2572::title() const +{ + return "Issue 2572"; +} + +std::string Issue2572::subtitle() const +{ + return "Look at the output in console"; +} + //------------------------------------------------------------------ // // ParallaxDemo @@ -156,7 +236,7 @@ std::string Parallax2::title() const static int sceneIdx = -1; -#define MAX_LAYER 2 +#define MAX_LAYER 3 Layer* createParallaxTestLayer(int nIndex) { @@ -164,6 +244,7 @@ Layer* createParallaxTestLayer(int nIndex) { case 0: return new Parallax1(); case 1: return new Parallax2(); + case 2: return new Issue2572(); } return NULL; diff --git a/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.h b/tests/test-cpp/Classes/ParallaxTest/ParallaxTest.h similarity index 69% rename from samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.h rename to tests/test-cpp/Classes/ParallaxTest/ParallaxTest.h index 1840174406..57945c8552 100644 --- a/samples/Cpp/TestCpp/Classes/ParallaxTest/ParallaxTest.h +++ b/tests/test-cpp/Classes/ParallaxTest/ParallaxTest.h @@ -48,6 +48,29 @@ public: virtual std::string title() const override; }; +class Issue2572 : public ParallaxDemo +{ +protected: + ParallaxNode* _paraNode; + float _moveTimer; + float _addTimer; + Vector _childList; + int _preListSize; + int _printCount; + + float _addChildStep; + float _wholeMoveTime; + Point _wholeMoveSize; + + virtual void update(float dt) override; + +public: + Issue2572(); + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + class ParallaxTestScene : public TestScene { public: diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp b/tests/test-cpp/Classes/ParticleTest/ParticleTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp rename to tests/test-cpp/Classes/ParticleTest/ParticleTest.cpp index 54a2095f42..4893e74bdb 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/tests/test-cpp/Classes/ParticleTest/ParticleTest.cpp @@ -1790,7 +1790,7 @@ void ReorderParticleSystems::onEnter() void ReorderParticleSystems::reorderSystem(float time) { auto system = static_cast(_batchNode->getChildren().at(1)); - _batchNode->reorderChild(system, system->getZOrder() - 1); + _batchNode->reorderChild(system, system->getLocalZOrder() - 1); } diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.h b/tests/test-cpp/Classes/ParticleTest/ParticleTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.h rename to tests/test-cpp/Classes/ParticleTest/ParticleTest.h diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.cpp b/tests/test-cpp/Classes/PerformanceTest/PerformanceAllocTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.cpp rename to tests/test-cpp/Classes/PerformanceTest/PerformanceAllocTest.cpp index f14ca83fac..cf1f0a1859 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.cpp +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceAllocTest.cpp @@ -292,6 +292,7 @@ void NodeDeallocTest::update(float dt) for( int i=0; iretain(); } CC_PROFILER_START(this->profilerName()); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.h b/tests/test-cpp/Classes/PerformanceTest/PerformanceAllocTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceAllocTest.h rename to tests/test-cpp/Classes/PerformanceTest/PerformanceAllocTest.h diff --git a/tests/test-cpp/Classes/PerformanceTest/PerformanceContainerTest.cpp b/tests/test-cpp/Classes/PerformanceTest/PerformanceContainerTest.cpp new file mode 100644 index 0000000000..7754582947 --- /dev/null +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceContainerTest.cpp @@ -0,0 +1,1369 @@ +/* + * + */ +#include "PerformanceContainerTest.h" + +#include + +// Enable profiles for this file +#undef CC_PROFILER_DISPLAY_TIMERS +#define CC_PROFILER_DISPLAY_TIMERS() Profiler::getInstance()->displayTimers() +#undef CC_PROFILER_PURGE_ALL +#define CC_PROFILER_PURGE_ALL() Profiler::getInstance()->releaseAllTimers() + +#undef CC_PROFILER_START +#define CC_PROFILER_START(__name__) ProfilingBeginTimingBlock(__name__) +#undef CC_PROFILER_STOP +#define CC_PROFILER_STOP(__name__) ProfilingEndTimingBlock(__name__) +#undef CC_PROFILER_RESET +#define CC_PROFILER_RESET(__name__) ProfilingResetTimingBlock(__name__) + +#undef CC_PROFILER_START_CATEGORY +#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingBeginTimingBlock(__name__); } while(0) +#undef CC_PROFILER_STOP_CATEGORY +#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingEndTimingBlock(__name__); } while(0) +#undef CC_PROFILER_RESET_CATEGORY +#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingResetTimingBlock(__name__); } while(0) + +#undef CC_PROFILER_START_INSTANCE +#define CC_PROFILER_START_INSTANCE(__id__, __name__) do{ ProfilingBeginTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0) +#undef CC_PROFILER_STOP_INSTANCE +#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do{ ProfilingEndTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0) +#undef CC_PROFILER_RESET_INSTANCE +#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do{ ProfilingResetTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0) + +static std::function createFunctions[] = +{ + CL(TemplateVectorPerfTest), + CL(ArrayPerfTest), + CL(TemplateMapStringKeyPerfTest), + CL(DictionaryStringKeyPerfTest), + CL(TemplateMapIntKeyPerfTest), + CL(DictionaryIntKeyPerfTest) +}; + +#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) + +enum { + kTagInfoLayer = 1, + + kTagBase = 20000, +}; + +enum { + kMaxNodes = 15000, + kNodesIncrease = 500, +}; + +static int g_curCase = 0; + +//////////////////////////////////////////////////////// +// +// ContainerBasicLayer +// +//////////////////////////////////////////////////////// + +ContainerBasicLayer::ContainerBasicLayer(bool bControlMenuVisible, int nMaxCases, int nCurCase) +: PerformBasicLayer(bControlMenuVisible, nMaxCases, nCurCase) +{ +} + +void ContainerBasicLayer::showCurrentTest() +{ + int nodes = ((PerformanceContainerScene*)getParent())->getQuantityOfNodes(); + + auto scene = createFunctions[_curCase](); + + g_curCase = _curCase; + + if (scene) + { + scene->initWithQuantityOfNodes(nodes); + + Director::getInstance()->replaceScene(scene); + } +} + +//////////////////////////////////////////////////////// +// +// PerformanceContainerScene +// +//////////////////////////////////////////////////////// +void PerformanceContainerScene::initWithQuantityOfNodes(unsigned int nNodes) +{ + _type = 0; + //srand(time()); + auto s = Director::getInstance()->getWinSize(); + + // Title + auto label = LabelTTF::create(title().c_str(), "Arial", 40); + addChild(label, 1, TAG_TITLE); + label->setPosition(Point(s.width/2, s.height-32)); + label->setColor(Color3B(255,255,40)); + + // Subtitle + std::string strSubTitle = subtitle(); + if(strSubTitle.length()) + { + auto l = LabelTTF::create(strSubTitle.c_str(), "Thonburi", 16); + addChild(l, 1, TAG_SUBTITLE); + l->setPosition(Point(s.width/2, s.height-80)); + } + + lastRenderedCount = 0; + currentQuantityOfNodes = 0; + quantityOfNodes = nNodes; + + MenuItemFont::setFontSize(65); + auto decrease = MenuItemFont::create(" - ", [&](Object *sender) { + quantityOfNodes -= kNodesIncrease; + if( quantityOfNodes < 0 ) + quantityOfNodes = 0; + + updateQuantityLabel(); + updateQuantityOfNodes(); + updateProfilerName(); + CC_PROFILER_PURGE_ALL(); + srand(0); + }); + decrease->setColor(Color3B(0,200,20)); + _decrease = decrease; + + auto increase = MenuItemFont::create(" + ", [&](Object *sender) { + quantityOfNodes += kNodesIncrease; + if( quantityOfNodes > kMaxNodes ) + quantityOfNodes = kMaxNodes; + + updateQuantityLabel(); + updateQuantityOfNodes(); + updateProfilerName(); + CC_PROFILER_PURGE_ALL(); + srand(0); + }); + increase->setColor(Color3B(0,200,20)); + _increase = increase; + + auto menu = Menu::create(decrease, increase, NULL); + menu->alignItemsHorizontally(); + menu->setPosition(Point(s.width/2, s.height/2+15)); + addChild(menu, 1); + + auto infoLabel = LabelTTF::create("0 nodes", "Marker Felt", 30); + infoLabel->setColor(Color3B(0,200,20)); + infoLabel->setPosition(Point(s.width/2, s.height/2-15)); + addChild(infoLabel, 1, kTagInfoLayer); + + auto menuLayer = new ContainerBasicLayer(true, MAX_LAYER, g_curCase); + addChild(menuLayer); + menuLayer->release(); + + printf("Size of Node: %lu\n", sizeof(Node)); + + int oldFontSize = MenuItemFont::getFontSize(); + MenuItemFont::setFontSize(24); + + Vector toggleItems; + + generateTestFunctions(); + + CCASSERT(!_testFunctions.empty(), "Should not be empty after generate test functions"); + + + for (const auto& f : _testFunctions) + { + toggleItems.pushBack(MenuItemFont::create(f.name)); + } + + auto toggle = MenuItemToggle::createWithCallback([this](Object* sender){ + auto toggle = static_cast(sender); + this->_type = toggle->getSelectedIndex(); + auto label = static_cast(this->getChildByTag(TAG_SUBTITLE)); + label->setString(StringUtils::format("Test '%s', See console", this->_testFunctions[this->_type].name)); + this->updateProfilerName(); + }, toggleItems); + + toggle->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); + toggle->setPosition(VisibleRect::left()); + _toggle = toggle; + + auto start = MenuItemFont::create("start", [this](Object* sender){ + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + + CC_PROFILER_PURGE_ALL(); + sched->scheduleSelector(schedule_selector(PerformanceContainerScene::dumpProfilerInfo), this, 2, false); + + this->unscheduleUpdate(); + this->scheduleUpdate(); + this->_startItem->setEnabled(false); + this->_stopItem->setEnabled(true); + this->_toggle->setEnabled(false); + this->_increase->setEnabled(false); + this->_decrease->setEnabled(false); + }); + start->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); + start->setPosition(VisibleRect::right() + Point(0, 40)); + _startItem = start; + + auto stop = MenuItemFont::create("stop", [this](Object* sender){ + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + + sched->unscheduleSelector(schedule_selector(PerformanceContainerScene::dumpProfilerInfo), this); + + this->unscheduleUpdate(); + this->_startItem->setEnabled(true); + this->_stopItem->setEnabled(false); + this->_toggle->setEnabled(true); + this->_increase->setEnabled(true); + this->_decrease->setEnabled(true); + }); + + stop->setEnabled(false); + stop->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); + stop->setPosition(VisibleRect::right() + Point(0, -40)); + _stopItem = stop; + + auto menu2 = Menu::create(toggle, start, stop, NULL); + menu2->setPosition(Point::ZERO); + addChild(menu2); + + MenuItemFont::setFontSize(oldFontSize); + + updateQuantityLabel(); + updateQuantityOfNodes(); + updateProfilerName(); +} + +std::string PerformanceContainerScene::title() const +{ + return "No title"; +} + +std::string PerformanceContainerScene::subtitle() const +{ + return ""; +} + +void PerformanceContainerScene::updateQuantityLabel() +{ + if( quantityOfNodes != lastRenderedCount ) + { + auto infoLabel = static_cast( getChildByTag(kTagInfoLayer) ); + char str[20] = {0}; + sprintf(str, "%u nodes", quantityOfNodes); + infoLabel->setString(str); + + lastRenderedCount = quantityOfNodes; + } +} + +const char * PerformanceContainerScene::profilerName() +{ + return _profilerName; +} + +void PerformanceContainerScene::updateProfilerName() +{ + snprintf(_profilerName, sizeof(_profilerName)-1, "%s(%d)", testName(), quantityOfNodes); +} + +void PerformanceContainerScene::dumpProfilerInfo(float dt) +{ + CC_PROFILER_DISPLAY_TIMERS(); +} + +void PerformanceContainerScene::update(float dt) +{ + _testFunctions[_type].func(); +} + +void PerformanceContainerScene::updateQuantityOfNodes() +{ + currentQuantityOfNodes = quantityOfNodes; +} + +const char* PerformanceContainerScene::testName() +{ + return _testFunctions[_type].name; +} + +//////////////////////////////////////////////////////// +// +// TemplateVectorPerfTest +// +//////////////////////////////////////////////////////// + +void TemplateVectorPerfTest::generateTestFunctions() +{ + auto createVector = [this](){ + Vector ret; + + for( int i=0; isetTag(i); + ret.pushBack(node); + } + return ret; + }; + + TestFunction testFunctions[] = { + { "pushBack", [=](){ + Vector nodeVector; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + { "insert", [=](){ + Vector nodeVector; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + { "replace", [=](){ + Vector nodeVector = createVector(); + + srand(time(nullptr)); + ssize_t index = rand() % quantityOfNodes; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + { "getIndex", [=](){ + + Vector nodeVector = createVector(); + Node* objToGet = nodeVector.at(quantityOfNodes/3); + ssize_t index = 0; + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + // Uses `index` to avoids `getIndex` invoking was optimized in release mode + if (index == quantityOfNodes/3) + { + nodeVector.clear(); + } + } } , + { "find", [=](){ + Vector nodeVector = createVector(); + Node* objToGet = nodeVector.at(quantityOfNodes/3); + Vector::iterator iter; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + // Uses `iter` to avoids `find` invoking was optimized in release mode + if (*iter == objToGet) + { + nodeVector.clear(); + } + + } } , + { "at", [=](){ + Vector nodeVector = createVector(); + Node* objToGet = nullptr; + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + // Uses `objToGet` to avoids `at` invoking was optimized in release mode + if (nodeVector.getIndex(objToGet) == quantityOfNodes/3) + { + nodeVector.clear(); + } + } } , + { "contains", [=](){ + Vector nodeVector = createVector(); + Node* objToGet = nodeVector.at(quantityOfNodes/3); + + bool ret = false; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + // Uses `ret` to avoids `contains` invoking was optimized in release mode + if (ret) + { + nodeVector.clear(); + } + } } , + { "eraseObject", [=](){ + Vector nodeVector = createVector(); + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + + for (int i = 0; i < quantityOfNodes; ++i) + { + nodes[i] = nodeVector.at(i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CCASSERT(nodeVector.empty(), "nodeVector was not empty."); + + free(nodes); + } } , + { "erase", [=](){ + Vector nodeVector = createVector(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CCASSERT(nodeVector.empty(), "nodeVector was not empty."); + + } } , + { "clear", [=](){ + Vector nodeVector = createVector(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CCASSERT(nodeVector.empty(), "nodeVector was not empty."); + } } , + { "swap by index", [=](){ + Vector nodeVector = createVector(); + + int swapIndex1 = quantityOfNodes / 3; + int swapIndex2 = quantityOfNodes / 3 * 2; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + + { "swap by object", [=](){ + Vector nodeVector = createVector(); + + Node* swapNode1 = nodeVector.at(quantityOfNodes / 3); + Node* swapNode2 = nodeVector.at(quantityOfNodes / 3 * 2); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + + { "reverse", [=](){ + Vector nodeVector = createVector(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + + { "c++11 Range Loop", [=](){ + Vector nodeVector = createVector(); + + CC_PROFILER_START(this->profilerName()); + for (const auto& e : nodeVector) + { + e->setTag(111); + } + CC_PROFILER_STOP(this->profilerName()); + } } , + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +std::string TemplateVectorPerfTest::title() const +{ + return "Vector Perf test"; +} + +std::string TemplateVectorPerfTest::subtitle() const +{ + return "Test 'pushBack', See console"; +} + +//////////////////////////////////////////////////////// +// +// ArrayPerfTest +// +//////////////////////////////////////////////////////// + +std::string ArrayPerfTest::title() const +{ + return "Array Perf test"; +} + +std::string ArrayPerfTest::subtitle() const +{ + return "Test `addObject`, See console"; +} + +void ArrayPerfTest::generateTestFunctions() +{ + auto createArray = [this](){ + Array* ret = Array::create(); + + for( int i=0; isetTag(i); + ret->addObject(node); + } + return ret; + }; + + TestFunction testFunctions[] = { + { "addObject", [=](){ + Array* nodeVector = Array::create(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iaddObject(Node::create()); + CC_PROFILER_STOP(this->profilerName()); + } } , + { "insertObject", [=](){ + Array* nodeVector = Array::create(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iinsertObject(Node::create(), 0); + CC_PROFILER_STOP(this->profilerName()); + } } , + { "setObject", [=](){ + Array* nodeVector = createArray(); + + srand(time(nullptr)); + ssize_t index = rand() % quantityOfNodes; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; isetObject(Node::create(), index); + CC_PROFILER_STOP(this->profilerName()); + } } , + { "getIndexOfObject", [=](){ + Array* nodeVector = createArray(); + Object* objToGet = nodeVector->getObjectAtIndex(quantityOfNodes/3); + ssize_t index = 0; + CC_PROFILER_START(this->profilerName()); + for( int i=0; igetIndexOfObject(objToGet); + CC_PROFILER_STOP(this->profilerName()); + // Uses `index` to avoids `getIndex` invoking was optimized in release mode + if (index == quantityOfNodes/3) + { + nodeVector->removeAllObjects(); + } + } } , + { "getObjectAtIndex", [=](){ + Array* nodeVector = createArray(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; igetObjectAtIndex(quantityOfNodes/3); + CC_PROFILER_STOP(this->profilerName()); + } } , + { "containsObject", [=](){ + Array* nodeVector = createArray(); + Object* objToGet = nodeVector->getObjectAtIndex(quantityOfNodes/3); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; icontainsObject(objToGet); + CC_PROFILER_STOP(this->profilerName()); + } } , + { "removeObject", [=](){ + Array* nodeVector = createArray(); + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + + for (int i = 0; i < quantityOfNodes; ++i) + { + nodes[i] = static_cast(nodeVector->getObjectAtIndex(i)); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iremoveObject(nodes[i]); + CC_PROFILER_STOP(this->profilerName()); + + CCASSERT(nodeVector->count() == 0, "nodeVector was not empty."); + + free(nodes); + } } , + { "removeObjectAtIndex", [=](){ + Array* nodeVector = createArray(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iremoveObjectAtIndex(0); + CC_PROFILER_STOP(this->profilerName()); + + CCASSERT(nodeVector->count() == 0, "nodeVector was not empty."); + + } } , + { "removeAllObjects", [=](){ + Array* nodeVector = createArray(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iremoveAllObjects(); + CC_PROFILER_STOP(this->profilerName()); + + CCASSERT(nodeVector->count() == 0, "nodeVector was not empty."); + } } , + { "swap by index", [=](){ + Array* nodeVector = createArray(); + + int swapIndex1 = quantityOfNodes / 3; + int swapIndex2 = quantityOfNodes / 3 * 2; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iswap(swapIndex1, swapIndex2); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "swap by object", [=](){ + Array* nodeVector = createArray(); + + Object* swapNode1 = nodeVector->getObjectAtIndex(quantityOfNodes / 3); + Object* swapNode2 = nodeVector->getObjectAtIndex(quantityOfNodes / 3 * 2); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iexchangeObject(swapNode1, swapNode2); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "reverseObjects", [=](){ + Array* nodeVector = createArray(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; ireverseObjects(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "CCARRAY_FOREACH", [=](){ + Array* nodeVector = createArray(); + Object* obj; + CC_PROFILER_START(this->profilerName()); + + CCARRAY_FOREACH(nodeVector, obj) + { + static_cast(obj)->setTag(111); + } + CC_PROFILER_STOP(this->profilerName()); + } } , + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +//////////////////////////////////////////////////////// +// +// TemplateMapStringKeyPerfTest +// +//////////////////////////////////////////////////////// + +void TemplateMapStringKeyPerfTest::generateTestFunctions() +{ + auto createMap = [this](){ + Map ret; + + for( int i=0; isetTag(i); + ret.insert(StringUtils::format("key_%d", i), node); + } + return ret; + }; + + TestFunction testFunctions[] = { + { "insert", [=](){ + Map map; + + std::string* keys = new std::string[quantityOfNodes]; + + for (int i = 0; i < quantityOfNodes; ++i) + { + keys[i] = StringUtils::format("key_%d", i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CC_SAFE_DELETE_ARRAY(keys); + } } , + + { "at", [=](){ + Map map = createMap(); + + std::string* keys = new std::string[quantityOfNodes]; + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + for (int i = 0; i < quantityOfNodes; ++i) + { + keys[i] = StringUtils::format("key_%d", i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CC_SAFE_DELETE_ARRAY(keys); + + for (int i = 0; i < quantityOfNodes; ++i) + { + nodes[i]->setTag(100); + } + + CC_SAFE_FREE(nodes); + } } , + + { "erase", [=](){ + auto map = createMap(); + + std::string* keys = new std::string[quantityOfNodes]; + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + for (int i = 0; i < quantityOfNodes; ++i) + { + keys[i] = StringUtils::format("key_%d", i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CC_SAFE_DELETE_ARRAY(keys); + + CC_SAFE_FREE(nodes); + } } , + + { "clear", [=](){ + auto map = createMap(); + + CC_PROFILER_START(this->profilerName()); + map.clear(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "size", [=](){ + auto map = createMap(); + + ssize_t size = 0; + CC_PROFILER_START(this->profilerName()); + size = map.size(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "keys(all)", [=](){ + auto map = createMap(); + + CC_PROFILER_START(this->profilerName()); + auto keys = map.keys(); + CC_PROFILER_STOP(this->profilerName()); + + std::string allKeysString; + for (const auto& key : keys) + { + allKeysString += "_" + key; + } + } } , + + { "keys(object)", [=](){ + Map map; + + Node** nodes = (Node**) malloc(sizeof(Node*) * quantityOfNodes); + Node* sameNode = Node::create(); + + for( int i=0; isetTag(i); + map.insert(StringUtils::format("key_%d", i), node); + } + } + + CC_PROFILER_START(this->profilerName()); + auto keys = map.keys(sameNode); + CC_PROFILER_STOP(this->profilerName()); + + std::string allKeysString; + for (const auto& key : keys) + { + allKeysString += "_" + key; + } + + CC_SAFE_FREE(nodes); + } } , + + { "c++11 range loop", [=](){ + auto map = createMap(); + + CC_PROFILER_START(this->profilerName()); + + for (const auto& e : map) + { + e.second->setTag(100); + } + + CC_PROFILER_STOP(this->profilerName()); + } } , + + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +std::string TemplateMapStringKeyPerfTest::title() const +{ + return "Map String Key Perf test"; +} + +std::string TemplateMapStringKeyPerfTest::subtitle() const +{ + return "Test 'insert', See console"; +} + +//////////////////////////////////////////////////////// +// +// DictionaryStringKeyPerfTest +// +//////////////////////////////////////////////////////// + +void DictionaryStringKeyPerfTest::generateTestFunctions() +{ + auto createDict = [this](){ + Dictionary* ret = Dictionary::create(); + + for( int i=0; isetTag(i); + ret->setObject(node, StringUtils::format("key_%d", i)); + } + return ret; + }; + + TestFunction testFunctions[] = { + { "setObject", [=](){ + Dictionary* dict = Dictionary::create(); + + std::string* keys = new std::string[quantityOfNodes]; + + for (int i = 0; i < quantityOfNodes; ++i) + { + keys[i] = StringUtils::format("key_%d", i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; isetObject(Node::create(), keys[i]); + CC_PROFILER_STOP(this->profilerName()); + + CC_SAFE_DELETE_ARRAY(keys); + } } , + + { "objectForKey", [=](){ + auto dict = createDict(); + + std::string* keys = new std::string[quantityOfNodes]; + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + for (int i = 0; i < quantityOfNodes; ++i) + { + keys[i] = StringUtils::format("key_%d", i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; i(dict->objectForKey(keys[i])); + CC_PROFILER_STOP(this->profilerName()); + + CC_SAFE_DELETE_ARRAY(keys); + + for (int i = 0; i < quantityOfNodes; ++i) + { + nodes[i]->setTag(100); + } + + CC_SAFE_FREE(nodes); + } } , + + { "removeObjectForKey", [=](){ + auto dict = createDict(); + + std::string* keys = new std::string[quantityOfNodes]; + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + for (int i = 0; i < quantityOfNodes; ++i) + { + keys[i] = StringUtils::format("key_%d", i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iremoveObjectForKey(keys[i]); + CC_PROFILER_STOP(this->profilerName()); + + CC_SAFE_DELETE_ARRAY(keys); + + CC_SAFE_FREE(nodes); + } } , + + { "removeAllObjects", [=](){ + auto dict = createDict(); + + CC_PROFILER_START(this->profilerName()); + dict->removeAllObjects(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "count", [=](){ + auto dict = createDict(); + + ssize_t size = 0; + CC_PROFILER_START(this->profilerName()); + size = dict->count(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "allKeys", [=](){ + auto dict = createDict(); + + CC_PROFILER_START(this->profilerName()); + auto keys = dict->allKeys(); + CC_PROFILER_STOP(this->profilerName()); + + std::string allKeysString; + Object* obj; + CCARRAY_FOREACH(keys, obj) + { + auto key = static_cast(obj); + allKeysString += (std::string("_") + key->getCString()); + } + } } , + + { "allKeysForObject", [=](){ + Dictionary* dict = Dictionary::create(); + + Node** nodes = (Node**) malloc(sizeof(Node*) * quantityOfNodes); + Node* sameNode = Node::create(); + + for( int i=0; isetObject(sameNode, StringUtils::format("key_%d", i)); + } + else + { + auto node = Node::create(); + node->setTag(i); + dict->setObject(node, StringUtils::format("key_%d", i)); + } + } + + CC_PROFILER_START(this->profilerName()); + auto keys = dict->allKeysForObject(sameNode); + CC_PROFILER_STOP(this->profilerName()); + + std::string allKeysString; + Object* obj; + CCARRAY_FOREACH(keys, obj) + { + auto key = static_cast(obj); + allKeysString += (std::string("_") + key->getCString()); + } + + CC_SAFE_FREE(nodes); + } } , + + { "CCDICT_FOREACH", [=](){ + auto dict = createDict(); + + CC_PROFILER_START(this->profilerName()); + + DictElement* e = nullptr; + CCDICT_FOREACH(dict, e) + { + static_cast(e->getObject())->setTag(100); + } + + CC_PROFILER_STOP(this->profilerName()); + } } , + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +std::string DictionaryStringKeyPerfTest::title() const +{ + return "Dictionary String Key Perf test"; +} + +std::string DictionaryStringKeyPerfTest::subtitle() const +{ + return "Test `setObject`, See console"; +} + + +//////////////////////////////////////////////////////// +// +// TemplateMapIntKeyPerfTest +// +//////////////////////////////////////////////////////// + +void TemplateMapIntKeyPerfTest::generateTestFunctions() +{ + auto createMap = [this](){ + Map ret; + + for( int i=0; isetTag(i); + ret.insert(100+i, node); + } + return ret; + }; + + TestFunction testFunctions[] = { + { "insert", [=](){ + Map map; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + + { "at", [=](){ + auto map = createMap(); + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + for (int i = 0; i < quantityOfNodes; ++i) + { + nodes[i]->setTag(100); + } + + CC_SAFE_FREE(nodes); + } } , + + { "erase", [=](){ + auto map = createMap(); + + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CC_SAFE_FREE(nodes); + } } , + + { "clear", [=](){ + auto map = createMap(); + + CC_PROFILER_START(this->profilerName()); + map.clear(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "size", [=](){ + auto map = createMap(); + + ssize_t size = 0; + CC_PROFILER_START(this->profilerName()); + size = map.size(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "keys(all)", [=](){ + auto map = createMap(); + + CC_PROFILER_START(this->profilerName()); + auto keys = map.keys(); + CC_PROFILER_STOP(this->profilerName()); + + int allKeysInt = 0; + for (const auto& key : keys) + { + allKeysInt += key; + } + } } , + + { "keys(object)", [=](){ + Map map; + + Node** nodes = (Node**) malloc(sizeof(Node*) * quantityOfNodes); + Node* sameNode = Node::create(); + + for( int i=0; isetTag(i); + map.insert(100 + i, node); + } + } + + CC_PROFILER_START(this->profilerName()); + auto keys = map.keys(sameNode); + CC_PROFILER_STOP(this->profilerName()); + + int allKeysInt = 0; + for (const auto& key : keys) + { + allKeysInt += key; + } + + CC_SAFE_FREE(nodes); + } } , + + { "c++11 range loop", [=](){ + auto map = createMap(); + + CC_PROFILER_START(this->profilerName()); + + for (const auto& e : map) + { + e.second->setTag(100); + } + + CC_PROFILER_STOP(this->profilerName()); + } } , + + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +std::string TemplateMapIntKeyPerfTest::title() const +{ + return "Map Integer Key Perf test"; +} + +std::string TemplateMapIntKeyPerfTest::subtitle() const +{ + return "Test 'insert', See console"; +} + +//////////////////////////////////////////////////////// +// +// DictionaryIntKeyPerfTest +// +//////////////////////////////////////////////////////// + +void DictionaryIntKeyPerfTest::generateTestFunctions() +{ + auto createDict = [this](){ + Dictionary* ret = Dictionary::create(); + + for( int i=0; isetTag(i); + ret->setObject(node, 100 + i); + } + return ret; + }; + + TestFunction testFunctions[] = { + { "setObject", [=](){ + Dictionary* dict = Dictionary::create(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; isetObject(Node::create(), 100 + i); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "objectForKey", [=](){ + auto dict = createDict(); + + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; i(dict->objectForKey(100 + i)); + CC_PROFILER_STOP(this->profilerName()); + + for (int i = 0; i < quantityOfNodes; ++i) + { + nodes[i]->setTag(100); + } + + CC_SAFE_FREE(nodes); + } } , + + { "removeObjectForKey", [=](){ + auto dict = createDict(); + + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iremoveObjectForKey(100 + i); + CC_PROFILER_STOP(this->profilerName()); + + CC_SAFE_FREE(nodes); + } } , + + { "removeAllObjects", [=](){ + auto dict = createDict(); + + CC_PROFILER_START(this->profilerName()); + dict->removeAllObjects(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "count", [=](){ + auto dict = createDict(); + + unsigned int size = 0; + CC_PROFILER_START(this->profilerName()); + size = dict->count(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "allKeys", [=](){ + auto dict = createDict(); + + CC_PROFILER_START(this->profilerName()); + auto keys = dict->allKeys(); + CC_PROFILER_STOP(this->profilerName()); + + int allKeysInt = 0; + Object* obj; + CCARRAY_FOREACH(keys, obj) + { + auto key = static_cast(obj); + allKeysInt += key->getValue(); + } + } } , + + { "allKeysForObject", [=](){ + Dictionary* dict = Dictionary::create(); + + Node** nodes = (Node**) malloc(sizeof(Node*) * quantityOfNodes); + Node* sameNode = Node::create(); + + for( int i=0; isetObject(sameNode, 100 + i); + } + else + { + auto node = Node::create(); + node->setTag(i); + dict->setObject(node, 100 + i); + } + } + + CC_PROFILER_START(this->profilerName()); + auto keys = dict->allKeysForObject(sameNode); + CC_PROFILER_STOP(this->profilerName()); + + int allKeysInt = 0; + Object* obj; + CCARRAY_FOREACH(keys, obj) + { + auto key = static_cast(obj); + allKeysInt += key->getValue(); + } + + CC_SAFE_FREE(nodes); + } } , + + { "CCDICT_FOREACH", [=](){ + auto dict = createDict(); + + CC_PROFILER_START(this->profilerName()); + + DictElement* e = nullptr; + CCDICT_FOREACH(dict, e) + { + static_cast(e->getObject())->setTag(100); + } + + CC_PROFILER_STOP(this->profilerName()); + } } , + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +std::string DictionaryIntKeyPerfTest::title() const +{ + return "Dictionary Integer Key Perf test"; +} + +std::string DictionaryIntKeyPerfTest::subtitle() const +{ + return "Test `setObject`, See console"; +} + + +///---------------------------------------- +void runContainerPerformanceTest() +{ + auto scene = createFunctions[g_curCase](); + scene->initWithQuantityOfNodes(kNodesIncrease); + + Director::getInstance()->replaceScene(scene); +} diff --git a/tests/test-cpp/Classes/PerformanceTest/PerformanceContainerTest.h b/tests/test-cpp/Classes/PerformanceTest/PerformanceContainerTest.h new file mode 100644 index 0000000000..603c759f76 --- /dev/null +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceContainerTest.h @@ -0,0 +1,132 @@ +/* + * + */ +#ifndef __PERFORMANCE_CONTAINER_TEST_H__ +#define __PERFORMANCE_CONTAINER_TEST_H__ + +#include "PerformanceTest.h" +#include "CCProfiling.h" + +class ContainerBasicLayer : public PerformBasicLayer +{ +public: + ContainerBasicLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCurCase = 0); + + virtual void showCurrentTest(); +}; + +class PerformanceContainerScene : public Scene +{ +public: + static const int TAG_TITLE = 100; + static const int TAG_SUBTITLE = 101; + + struct TestFunction + { + const char* name; + std::function func; + }; + + virtual void initWithQuantityOfNodes(unsigned int nNodes); + virtual void generateTestFunctions() = 0; + + virtual std::string title() const; + virtual std::string subtitle() const; + virtual void updateQuantityOfNodes(); + + const char* profilerName(); + void updateProfilerName(); + + // for the profiler + virtual const char* testName(); + void updateQuantityLabel(); + int getQuantityOfNodes() { return quantityOfNodes; } + void dumpProfilerInfo(float dt); + + // overrides + virtual void update(float dt) override; + +protected: + char _profilerName[256]; + int lastRenderedCount; + int quantityOfNodes; + int currentQuantityOfNodes; + unsigned int _type; + std::vector _testFunctions; + + MenuItemFont* _increase; + MenuItemFont* _decrease; + MenuItemFont* _startItem; + MenuItemFont* _stopItem; + MenuItemToggle* _toggle; +}; + +class TemplateVectorPerfTest : public PerformanceContainerScene +{ +public: + CREATE_FUNC(TemplateVectorPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class ArrayPerfTest : public PerformanceContainerScene +{ +public: + CREATE_FUNC(ArrayPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class TemplateMapStringKeyPerfTest : public PerformanceContainerScene +{ +public: + CREATE_FUNC(TemplateMapStringKeyPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class DictionaryStringKeyPerfTest : public PerformanceContainerScene +{ +public: + CREATE_FUNC(DictionaryStringKeyPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class TemplateMapIntKeyPerfTest : public PerformanceContainerScene +{ +public: + CREATE_FUNC(TemplateMapIntKeyPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class DictionaryIntKeyPerfTest : public PerformanceContainerScene +{ +public: + CREATE_FUNC(DictionaryIntKeyPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +void runContainerPerformanceTest(); + +#endif // __PERFORMANCE_CONTAINER_TEST_H__ diff --git a/tests/test-cpp/Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp b/tests/test-cpp/Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp new file mode 100644 index 0000000000..28953d22ff --- /dev/null +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp @@ -0,0 +1,795 @@ +// +// PerformanceEventDispatcherTest.cpp +// + +#include "PerformanceEventDispatcherTest.h" + +#include + +// Enable profiles for this file +#undef CC_PROFILER_DISPLAY_TIMERS +#define CC_PROFILER_DISPLAY_TIMERS() Profiler::getInstance()->displayTimers() +#undef CC_PROFILER_PURGE_ALL +#define CC_PROFILER_PURGE_ALL() Profiler::getInstance()->releaseAllTimers() + +#undef CC_PROFILER_START +#define CC_PROFILER_START(__name__) ProfilingBeginTimingBlock(__name__) +#undef CC_PROFILER_STOP +#define CC_PROFILER_STOP(__name__) ProfilingEndTimingBlock(__name__) +#undef CC_PROFILER_RESET +#define CC_PROFILER_RESET(__name__) ProfilingResetTimingBlock(__name__) + +#undef CC_PROFILER_START_CATEGORY +#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingBeginTimingBlock(__name__); } while(0) +#undef CC_PROFILER_STOP_CATEGORY +#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingEndTimingBlock(__name__); } while(0) +#undef CC_PROFILER_RESET_CATEGORY +#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingResetTimingBlock(__name__); } while(0) + +#undef CC_PROFILER_START_INSTANCE +#define CC_PROFILER_START_INSTANCE(__id__, __name__) do{ ProfilingBeginTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0) +#undef CC_PROFILER_STOP_INSTANCE +#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do{ ProfilingEndTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0) +#undef CC_PROFILER_RESET_INSTANCE +#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do{ ProfilingResetTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0) + +static std::function createFunctions[] = +{ + CL(TouchEventDispatchingPerfTest), + CL(KeyboardEventDispatchingPerfTest), + CL(CustomEventDispatchingPerfTest), +}; + +#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) + +enum { + kTagInfoLayer = 1, + + kTagBase = 20000, +}; + +enum { + kMaxNodes = 15000, + kNodesIncrease = 500, +}; + +static int g_curCase = 0; + +//////////////////////////////////////////////////////// +// +// EventDispatcherBasicLayer +// +//////////////////////////////////////////////////////// + +EventDispatcherBasicLayer::EventDispatcherBasicLayer(bool bControlMenuVisible, int nMaxCases, int nCurCase) +: PerformBasicLayer(bControlMenuVisible, nMaxCases, nCurCase) +{ +} + +void EventDispatcherBasicLayer::showCurrentTest() +{ + int nodes = ((PerformanceEventDispatcherScene*)getParent())->getQuantityOfNodes(); + + auto scene = createFunctions[_curCase](); + + g_curCase = _curCase; + + if (scene) + { + scene->initWithQuantityOfNodes(nodes); + + Director::getInstance()->replaceScene(scene); + } +} + +//////////////////////////////////////////////////////// +// +// PerformanceEventDispatcherScene +// +//////////////////////////////////////////////////////// +void PerformanceEventDispatcherScene::initWithQuantityOfNodes(unsigned int nNodes) +{ + _type = 0; + srand(time(nullptr)); + auto s = Director::getInstance()->getWinSize(); + + // Title + auto label = LabelTTF::create(title().c_str(), "Arial", 40); + addChild(label, 1, TAG_TITLE); + label->setPosition(Point(s.width/2, s.height-32)); + label->setColor(Color3B(255,255,40)); + + // Subtitle + std::string strSubTitle = subtitle(); + if(strSubTitle.length()) + { + auto l = LabelTTF::create(strSubTitle.c_str(), "Thonburi", 16); + addChild(l, 1, TAG_SUBTITLE); + l->setPosition(Point(s.width/2, s.height-80)); + } + + _lastRenderedCount = 0; + _currentQuantityOfNodes = 0; + _quantityOfNodes = nNodes; + + MenuItemFont::setFontSize(65); + auto decrease = MenuItemFont::create(" - ", [&](Object *sender) { + _quantityOfNodes -= kNodesIncrease; + if( _quantityOfNodes < 0 ) + _quantityOfNodes = 0; + + updateQuantityLabel(); + updateQuantityOfNodes(); + updateProfilerName(); + CC_PROFILER_PURGE_ALL(); + srand(0); + }); + decrease->setColor(Color3B(0,200,20)); + _decrease = decrease; + + auto increase = MenuItemFont::create(" + ", [&](Object *sender) { + _quantityOfNodes += kNodesIncrease; + if( _quantityOfNodes > kMaxNodes ) + _quantityOfNodes = kMaxNodes; + + updateQuantityLabel(); + updateQuantityOfNodes(); + updateProfilerName(); + CC_PROFILER_PURGE_ALL(); + srand(0); + }); + increase->setColor(Color3B(0,200,20)); + _increase = increase; + + auto menu = Menu::create(decrease, increase, NULL); + menu->alignItemsHorizontally(); + menu->setPosition(Point(s.width/2, s.height/2+15)); + addChild(menu, 1); + + auto infoLabel = LabelTTF::create("0 listeners", "Marker Felt", 30); + infoLabel->setColor(Color3B(0,200,20)); + infoLabel->setPosition(Point(s.width/2, s.height/2-15)); + addChild(infoLabel, 1, kTagInfoLayer); + + auto menuLayer = new EventDispatcherBasicLayer(true, MAX_LAYER, g_curCase); + addChild(menuLayer); + menuLayer->release(); + + printf("Size of Node: %lu\n", sizeof(Node)); + + int oldFontSize = MenuItemFont::getFontSize(); + MenuItemFont::setFontSize(24); + + Vector toggleItems; + + generateTestFunctions(); + + CCASSERT(!_testFunctions.empty(), "Should not be empty after generate test functions"); + + + for (const auto& f : _testFunctions) + { + toggleItems.pushBack(MenuItemFont::create(f.name)); + } + + auto reset = [this](){ + // Removes all nodes + for (auto& node : _nodes) + { + node->removeFromParent(); + } + + _nodes.clear(); + + // Removes all fixed listeners + for (auto& listener : _fixedPriorityListeners) + { + Director::getInstance()->getEventDispatcher()->removeEventListener(listener); + } + + this->_lastRenderedCount = 0; + }; + + auto toggle = MenuItemToggle::createWithCallback([=](Object* sender){ + auto toggle = static_cast(sender); + this->_type = toggle->getSelectedIndex(); + auto label = static_cast(this->getChildByTag(TAG_SUBTITLE)); + label->setString(StringUtils::format("Test '%s', See console", this->_testFunctions[this->_type].name)); + this->updateProfilerName(); + reset(); + }, toggleItems); + + toggle->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); + toggle->setPosition(VisibleRect::left()); + _toggle = toggle; + + auto start = MenuItemFont::create("start", [this](Object* sender){ + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + + CC_PROFILER_PURGE_ALL(); + sched->scheduleSelector(schedule_selector(PerformanceEventDispatcherScene::dumpProfilerInfo), this, 2, false); + + this->unscheduleUpdate(); + this->scheduleUpdate(); + this->_startItem->setEnabled(false); + this->_stopItem->setEnabled(true); + this->_toggle->setEnabled(false); + this->_increase->setEnabled(false); + this->_decrease->setEnabled(false); + }); + start->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); + start->setPosition(VisibleRect::right() + Point(0, 40)); + _startItem = start; + + auto stop = MenuItemFont::create("stop", [=](Object* sender){ + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + + sched->unscheduleSelector(schedule_selector(PerformanceEventDispatcherScene::dumpProfilerInfo), this); + + this->unscheduleUpdate(); + this->_startItem->setEnabled(true); + this->_stopItem->setEnabled(false); + this->_toggle->setEnabled(true); + this->_increase->setEnabled(true); + this->_decrease->setEnabled(true); + + reset(); + }); + + stop->setEnabled(false); + stop->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); + stop->setPosition(VisibleRect::right() + Point(0, -40)); + _stopItem = stop; + + auto menu2 = Menu::create(toggle, start, stop, NULL); + menu2->setPosition(Point::ZERO); + addChild(menu2); + + MenuItemFont::setFontSize(oldFontSize); + + updateQuantityLabel(); + updateQuantityOfNodes(); + updateProfilerName(); +} + +std::string PerformanceEventDispatcherScene::title() const +{ + return "No title"; +} + +std::string PerformanceEventDispatcherScene::subtitle() const +{ + return ""; +} + +void PerformanceEventDispatcherScene::updateQuantityLabel() +{ + if( _quantityOfNodes != _lastRenderedCount ) + { + auto infoLabel = static_cast( getChildByTag(kTagInfoLayer) ); + char str[20] = {0}; + sprintf(str, "%u listeners", _quantityOfNodes); + infoLabel->setString(str); + } +} + +const char * PerformanceEventDispatcherScene::profilerName() +{ + return _profilerName; +} + +void PerformanceEventDispatcherScene::updateProfilerName() +{ + snprintf(_profilerName, sizeof(_profilerName)-1, "%s(%d)", testName(), _quantityOfNodes); +} + +void PerformanceEventDispatcherScene::dumpProfilerInfo(float dt) +{ + CC_PROFILER_DISPLAY_TIMERS(); +} + +void PerformanceEventDispatcherScene::update(float dt) +{ + _testFunctions[_type].func(); +} + +void PerformanceEventDispatcherScene::updateQuantityOfNodes() +{ + _currentQuantityOfNodes = _quantityOfNodes; +} + +const char* PerformanceEventDispatcherScene::testName() +{ + return _testFunctions[_type].name; +} + + +//////////////////////////////////////////////////////// +// +// TouchEventDispatchingPerfTest +// +//////////////////////////////////////////////////////// + +void TouchEventDispatchingPerfTest::generateTestFunctions() +{ + TestFunction testFunctions[] = { + { "OneByOne-scenegraph", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = [](Touch* touch, Event* event){ + return false; + }; + + listener->onTouchMoved = [](Touch* touch, Event* event){}; + listener->onTouchEnded = [](Touch* touch, Event* event){}; + + // Create new touchable nodes + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto node = Node::create(); + node->setTag(1000 + i); + this->addChild(node); + this->_nodes.push_back(node); + dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node); + } + + _lastRenderedCount = _quantityOfNodes; + } + + Size size = Director::getInstance()->getWinSize(); + EventTouch touchEvent; + touchEvent.setEventCode(EventTouch::EventCode::BEGAN); + std::vector touches; + + for (int i = 0; i < 4; ++i) + { + Touch* touch = new Touch(); + touch->autorelease(); + touch->setTouchInfo(i, rand() % 200, rand() % 200); + touches.push_back(touch); + } + touchEvent.setTouches(touches); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&touchEvent); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "OneByOne-fixed", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerTouchOneByOne::create(); + listener->onTouchBegan = [](Touch* touch, Event* event){ + return false; + }; + + listener->onTouchMoved = [](Touch* touch, Event* event){}; + listener->onTouchEnded = [](Touch* touch, Event* event){}; + + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto l = listener->clone(); + this->_fixedPriorityListeners.push_back(l); + dispatcher->addEventListenerWithFixedPriority(l, i+1); + } + + _lastRenderedCount = _quantityOfNodes; + } + + Size size = Director::getInstance()->getWinSize(); + EventTouch touchEvent; + touchEvent.setEventCode(EventTouch::EventCode::BEGAN); + std::vector touches; + + for (int i = 0; i < 4; ++i) + { + Touch* touch = new Touch(); + touch->autorelease(); + touch->setTouchInfo(i, rand() % 200, rand() % 200); + touches.push_back(touch); + } + touchEvent.setTouches(touches); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&touchEvent); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "AllAtOnce-scenegraph", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = [](const std::vector touches, Event* event){}; + listener->onTouchesMoved = [](const std::vector touches, Event* event){}; + listener->onTouchesEnded = [](const std::vector touches, Event* event){}; + + // Create new touchable nodes + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto node = Node::create(); + node->setTag(1000 + i); + this->addChild(node); + this->_nodes.push_back(node); + dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node); + } + + _lastRenderedCount = _quantityOfNodes; + } + + Size size = Director::getInstance()->getWinSize(); + EventTouch touchEvent; + touchEvent.setEventCode(EventTouch::EventCode::BEGAN); + std::vector touches; + + for (int i = 0; i < 4; ++i) + { + Touch* touch = new Touch(); + touch->autorelease(); + touch->setTouchInfo(i, rand() % 200, rand() % 200); + touches.push_back(touch); + } + touchEvent.setTouches(touches); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&touchEvent); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "AllAtOnce-fixed", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerTouchAllAtOnce::create(); + listener->onTouchesBegan = [](const std::vector touches, Event* event){}; + listener->onTouchesMoved = [](const std::vector touches, Event* event){}; + listener->onTouchesEnded = [](const std::vector touches, Event* event){}; + + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto l = listener->clone(); + this->_fixedPriorityListeners.push_back(l); + dispatcher->addEventListenerWithFixedPriority(l, i+1); + } + + _lastRenderedCount = _quantityOfNodes; + } + + Size size = Director::getInstance()->getWinSize(); + EventTouch touchEvent; + touchEvent.setEventCode(EventTouch::EventCode::BEGAN); + std::vector touches; + + for (int i = 0; i < 4; ++i) + { + Touch* touch = new Touch(); + touch->autorelease(); + touch->setTouchInfo(i, rand() % 200, rand() % 200); + touches.push_back(touch); + } + touchEvent.setTouches(touches); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&touchEvent); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "TouchModeMix-scenegraph", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listenerOneByOne = EventListenerTouchOneByOne::create(); + listenerOneByOne->onTouchBegan = [](Touch* touch, Event* event){ + return false; + }; + + listenerOneByOne->onTouchMoved = [](Touch* touch, Event* event){}; + listenerOneByOne->onTouchEnded = [](Touch* touch, Event* event){}; + + auto listenerAllAtOnce = EventListenerTouchAllAtOnce::create(); + listenerAllAtOnce->onTouchesBegan = [](const std::vector touches, Event* event){}; + listenerAllAtOnce->onTouchesMoved = [](const std::vector touches, Event* event){}; + listenerAllAtOnce->onTouchesEnded = [](const std::vector touches, Event* event){}; + + int i = 0; + // Create new touchable nodes + for (; i < this->_quantityOfNodes/2; ++i) + { + auto node = Node::create(); + node->setTag(1000 + i); + this->addChild(node); + this->_nodes.push_back(node); + dispatcher->addEventListenerWithSceneGraphPriority(listenerOneByOne->clone(), node); + } + + for (; i < this->_quantityOfNodes; ++i) + { + auto node = Node::create(); + node->setTag(1000 + i); + this->addChild(node); + this->_nodes.push_back(node); + dispatcher->addEventListenerWithSceneGraphPriority(listenerAllAtOnce->clone(), node); + } + + _lastRenderedCount = _quantityOfNodes; + } + + Size size = Director::getInstance()->getWinSize(); + EventTouch touchEvent; + touchEvent.setEventCode(EventTouch::EventCode::BEGAN); + std::vector touches; + + for (int i = 0; i < 4; ++i) + { + Touch* touch = new Touch(); + touch->autorelease(); + touch->setTouchInfo(i, rand() % 200, rand() % 200); + touches.push_back(touch); + } + touchEvent.setTouches(touches); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&touchEvent); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "TouchModeMix-fixed", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listenerOneByOne = EventListenerTouchOneByOne::create(); + listenerOneByOne->onTouchBegan = [](Touch* touch, Event* event){ + return false; + }; + + listenerOneByOne->onTouchMoved = [](Touch* touch, Event* event){}; + listenerOneByOne->onTouchEnded = [](Touch* touch, Event* event){}; + + auto listenerAllAtOnce = EventListenerTouchAllAtOnce::create(); + listenerAllAtOnce->onTouchesBegan = [](const std::vector touches, Event* event){}; + listenerAllAtOnce->onTouchesMoved = [](const std::vector touches, Event* event){}; + listenerAllAtOnce->onTouchesEnded = [](const std::vector touches, Event* event){}; + + int i = 0; + + for (; i < this->_quantityOfNodes/2; ++i) + { + auto l = listenerOneByOne->clone(); + this->_fixedPriorityListeners.push_back(l); + dispatcher->addEventListenerWithFixedPriority(l, i+1); + } + + for (; i < this->_quantityOfNodes; ++i) + { + auto l = listenerAllAtOnce->clone(); + this->_fixedPriorityListeners.push_back(l); + dispatcher->addEventListenerWithFixedPriority(l, i+1); + } + + _lastRenderedCount = _quantityOfNodes; + } + + Size size = Director::getInstance()->getWinSize(); + EventTouch touchEvent; + touchEvent.setEventCode(EventTouch::EventCode::BEGAN); + std::vector touches; + + for (int i = 0; i < 4; ++i) + { + Touch* touch = new Touch(); + touch->autorelease(); + touch->setTouchInfo(i, rand() % 200, rand() % 200); + touches.push_back(touch); + } + touchEvent.setTouches(touches); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&touchEvent); + CC_PROFILER_STOP(this->profilerName()); + } } , + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +std::string TouchEventDispatchingPerfTest::title() const +{ + return "Touch Event Dispatching Perf test"; +} + +std::string TouchEventDispatchingPerfTest::subtitle() const +{ + return "Test 'OneByOne-scenegraph', See console"; +} + +//////////////////////////////////////////////////////// +// +// KeyboardEventDispatchingPerfTest +// +//////////////////////////////////////////////////////// + +void KeyboardEventDispatchingPerfTest::generateTestFunctions() +{ + TestFunction testFunctions[] = { + { "keyboard-scenegraph", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerKeyboard::create(); + listener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event){}; + listener->onKeyReleased = [](EventKeyboard::KeyCode keyCode, Event* event){}; + + // Create new nodes listen to keyboard event + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto node = Node::create(); + node->setTag(1000 + i); + this->addChild(node); + this->_nodes.push_back(node); + dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node); + } + + _lastRenderedCount = _quantityOfNodes; + } + + EventKeyboard event(EventKeyboard::KeyCode::KEY_RETURN, true); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&event); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "keyboard-fixed", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerKeyboard::create(); + listener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event){}; + listener->onKeyReleased = [](EventKeyboard::KeyCode keyCode, Event* event){}; + + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto l = listener->clone(); + this->_fixedPriorityListeners.push_back(l); + dispatcher->addEventListenerWithFixedPriority(l, i+1); + } + + _lastRenderedCount = _quantityOfNodes; + } + + EventKeyboard event(EventKeyboard::KeyCode::KEY_RETURN, true); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&event); + CC_PROFILER_STOP(this->profilerName()); + } } , + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +std::string KeyboardEventDispatchingPerfTest::title() const +{ + return "Keyboard Event Dispatching Perf test"; +} + +std::string KeyboardEventDispatchingPerfTest::subtitle() const +{ + return "Test 'keyboard-scenegraph', See console"; +} + +//////////////////////////////////////////////////////// +// +// CustomEventDispatchingPerfTest +// +//////////////////////////////////////////////////////// + +void CustomEventDispatchingPerfTest::onEnter() +{ + PerformanceEventDispatcherScene::onEnter(); + + for (int i = 0; i < 2000; i++) + { + auto listener = EventListenerCustom::create(StringUtils::format("custom_event_%d", i), [](EventCustom* event){}); + _eventDispatcher->addEventListenerWithFixedPriority(listener, i + 1); + _customListeners.push_back(listener); + } +} + +void CustomEventDispatchingPerfTest::onExit() +{ + for (auto& l : _customListeners) + { + _eventDispatcher->removeEventListener(l); + } + PerformanceEventDispatcherScene::onExit(); +} + +void CustomEventDispatchingPerfTest::generateTestFunctions() +{ + TestFunction testFunctions[] = { + { "custom-scenegraph", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerCustom::create("custom_event_test_scenegraph", [](EventCustom* event){}); + + // Create new nodes listen to custom event + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto node = Node::create(); + node->setTag(1000 + i); + this->addChild(node); + this->_nodes.push_back(node); + dispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), node); + } + + _lastRenderedCount = _quantityOfNodes; + } + + EventCustom event("custom_event_test_scenegraph"); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&event); + CC_PROFILER_STOP(this->profilerName()); + } } , + { "custom-fixed", [=](){ + auto dispatcher = Director::getInstance()->getEventDispatcher(); + if (_quantityOfNodes != _lastRenderedCount) + { + auto listener = EventListenerCustom::create("custom_event_test_fixed", [](EventCustom* event){}); + + for (int i = 0; i < this->_quantityOfNodes; ++i) + { + auto l = listener->clone(); + this->_fixedPriorityListeners.push_back(l); + dispatcher->addEventListenerWithFixedPriority(l, i+1); + } + + _lastRenderedCount = _quantityOfNodes; + } + + EventCustom event("custom_event_test_fixed"); + + CC_PROFILER_START(this->profilerName()); + dispatcher->dispatchEvent(&event); + CC_PROFILER_STOP(this->profilerName()); + } } , + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +std::string CustomEventDispatchingPerfTest::title() const +{ + return "Custom Event Dispatching Perf test"; +} + +std::string CustomEventDispatchingPerfTest::subtitle() const +{ + return "Test 'custom-scenegraph', See console"; +} + +///---------------------------------------- +void runEventDispatcherPerformanceTest() +{ + auto scene = createFunctions[g_curCase](); + scene->initWithQuantityOfNodes(kNodesIncrease); + + Director::getInstance()->replaceScene(scene); +} + diff --git a/tests/test-cpp/Classes/PerformanceTest/PerformanceEventDispatcherTest.h b/tests/test-cpp/Classes/PerformanceTest/PerformanceEventDispatcherTest.h new file mode 100644 index 0000000000..b8b6022b62 --- /dev/null +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceEventDispatcherTest.h @@ -0,0 +1,106 @@ +// +// PerformanceEventDispatcherTest.h + +#ifndef __PERFORMANCE_EVENTDISPATCHER_TEST_H__ +#define __PERFORMANCE_EVENTDISPATCHER_TEST_H__ + +#include "PerformanceTest.h" +#include "CCProfiling.h" + +class EventDispatcherBasicLayer : public PerformBasicLayer +{ +public: + EventDispatcherBasicLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCurCase = 0); + + virtual void showCurrentTest(); +}; + +class PerformanceEventDispatcherScene : public Scene +{ +public: + static const int TAG_TITLE = 100; + static const int TAG_SUBTITLE = 101; + + struct TestFunction + { + const char* name; + std::function func; + }; + + virtual void initWithQuantityOfNodes(unsigned int nNodes); + virtual void generateTestFunctions() = 0; + + virtual std::string title() const; + virtual std::string subtitle() const; + virtual void updateQuantityOfNodes(); + + const char* profilerName(); + void updateProfilerName(); + + // for the profiler + virtual const char* testName(); + void updateQuantityLabel(); + int getQuantityOfNodes() { return _quantityOfNodes; } + void dumpProfilerInfo(float dt); + + // overrides + virtual void update(float dt) override; + +protected: + char _profilerName[256]; + int _lastRenderedCount; + int _quantityOfNodes; + int _currentQuantityOfNodes; + unsigned int _type; + std::vector _testFunctions; + std::vector _nodes; + std::vector _fixedPriorityListeners; + MenuItemFont* _increase; + MenuItemFont* _decrease; + MenuItemFont* _startItem; + MenuItemFont* _stopItem; + MenuItemToggle* _toggle; +}; + +class TouchEventDispatchingPerfTest : public PerformanceEventDispatcherScene +{ +public: + CREATE_FUNC(TouchEventDispatchingPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class KeyboardEventDispatchingPerfTest : public PerformanceEventDispatcherScene +{ +public: + CREATE_FUNC(KeyboardEventDispatchingPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class CustomEventDispatchingPerfTest : public PerformanceEventDispatcherScene +{ +public: + CREATE_FUNC(CustomEventDispatchingPerfTest); + + virtual void onEnter() override; + virtual void onExit() override; + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; + +private: + std::vector _customListeners; +}; + +void runEventDispatcherPerformanceTest(); + +#endif /* defined(__PERFORMANCE_EVENTDISPATCHER_TEST_H__) */ diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp b/tests/test-cpp/Classes/PerformanceTest/PerformanceLabelTest.cpp similarity index 91% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp rename to tests/test-cpp/Classes/PerformanceTest/PerformanceLabelTest.cpp index 317bbb8a60..4c9f561b5d 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceLabelTest.cpp @@ -86,6 +86,7 @@ void LabelMainScene::initWithSubTest(int nodes) _lastRenderedCount = 0; _quantityNodes = 0; + _accumulativeTime = 0.0f; _labelContainer = Layer::create(); addChild(_labelContainer); @@ -212,15 +213,18 @@ void LabelMainScene::onIncrease(Object* sender) } break; case kCaseLabelUpdate: - for( int i=0;i< kNodesIncrease;i++) { - auto label = Label::createWithTTF("Label", "fonts/arial.ttf", 60, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr,true); - label->setPosition(Point((size.width/2 + rand() % 50), ((int)size.height/2 + rand() % 50))); - _labelContainer->addChild(label, 1, _quantityNodes); + TTFConfig ttfConfig("fonts/arial.ttf", 60, GlyphCollection::DYNAMIC, nullptr, true); + for( int i=0;i< kNodesIncrease;i++) + { + auto label = Label::createWithTTF(ttfConfig, "Label", TextHAlignment::CENTER, size.width); + label->setPosition(Point((size.width/2 + rand() % 50), ((int)size.height/2 + rand() % 50))); + _labelContainer->addChild(label, 1, _quantityNodes); - _quantityNodes++; - } - break; + _quantityNodes++; + } + break; + } case kCaseLabelBMFontBigLabels: for( int i=0;i< kNodesIncrease;i++) { @@ -232,15 +236,18 @@ void LabelMainScene::onIncrease(Object* sender) } break; case kCaseLabelBigLabels: - for( int i=0;i< kNodesIncrease;i++) { - auto label = Label::createWithTTF(LongSentencesExample, "fonts/arial.ttf", 60, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr); - label->setPosition(Point((rand() % 50), rand()%((int)size.height/3))); - _labelContainer->addChild(label, 1, _quantityNodes); + TTFConfig ttfConfig("fonts/arial.ttf", 60, GlyphCollection::DYNAMIC); + for( int i=0;i< kNodesIncrease;i++) + { + auto label = Label::createWithTTF(ttfConfig, LongSentencesExample, TextHAlignment::CENTER, size.width); + label->setPosition(Point((rand() % 50), rand()%((int)size.height/3))); + _labelContainer->addChild(label, 1, _quantityNodes); - _quantityNodes++; - } - break; + _quantityNodes++; + } + break; + } default: break; } @@ -330,7 +337,7 @@ void LabelMainScene::updateText(float dt) case kCaseLabelUpdate: for(const auto &child : children) { Label* label = (Label*)child; - label->setString(text,false); + label->setString(text); } break; default: diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.h b/tests/test-cpp/Classes/PerformanceTest/PerformanceLabelTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.h rename to tests/test-cpp/Classes/PerformanceTest/PerformanceLabelTest.h diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp b/tests/test-cpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp rename to tests/test-cpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp index 96a3aeb67a..ecd42ef59a 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp @@ -397,15 +397,9 @@ void CallFuncsSpriteSheetForEach::update(float dt) CC_PROFILER_START(this->profilerName()); -#if CC_USE_ARRAY_VECTOR - std::for_each(std::begin(children), std::end(children), [](const RCPtr& obj) { - static_cast( static_cast(obj) )->getPosition(); - }); -#else std::for_each(std::begin(children), std::end(children), [](Node* obj) { obj->getPosition(); }); -#endif CC_PROFILER_STOP(this->profilerName()); } diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h b/tests/test-cpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h rename to tests/test-cpp/Classes/PerformanceTest/PerformanceNodeChildrenTest.h diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp b/tests/test-cpp/Classes/PerformanceTest/PerformanceParticleTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.cpp rename to tests/test-cpp/Classes/PerformanceTest/PerformanceParticleTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.h b/tests/test-cpp/Classes/PerformanceTest/PerformanceParticleTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceParticleTest.h rename to tests/test-cpp/Classes/PerformanceTest/PerformanceParticleTest.h diff --git a/tests/test-cpp/Classes/PerformanceTest/PerformanceRendererTest.cpp b/tests/test-cpp/Classes/PerformanceTest/PerformanceRendererTest.cpp new file mode 100644 index 0000000000..60031018c6 --- /dev/null +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceRendererTest.cpp @@ -0,0 +1,55 @@ +// +// PerformanceRendererTest.cpp +// cocos2d_samples +// +// Created by Huabing on 1/10/14. +// +// + +#include "PerformanceRendererTest.h" +#include "PerformanceTextureTest.h" +#include "../testResource.h" + +RenderTestLayer::RenderTestLayer() +: PerformBasicLayer(true, 1, 1) +{ +} + +RenderTestLayer::~RenderTestLayer() +{ +} + +Scene* RenderTestLayer::scene() +{ + auto scene = Scene::create(); + RenderTestLayer *layer = new RenderTestLayer(); + scene->addChild(layer); + layer->release(); + + return scene; +} + +void RenderTestLayer::onEnter() +{ + PerformBasicLayer::onEnter(); + auto map = TMXTiledMap::create("TileMaps/map/sl.tmx"); + + Size CC_UNUSED s = map->getContentSize(); + CCLOG("ContentSize: %f, %f", s.width,s.height); + + addChild(map,-1); + + //map->setAnchorPoint( Point(0, 0) ); + //map->setPosition( Point(-20,-200) ); +} + +void RenderTestLayer::showCurrentTest() +{ + +} + +void runRendererTest() +{ + auto scene = RenderTestLayer::scene(); + Director::getInstance()->replaceScene(scene); +} \ No newline at end of file diff --git a/tests/test-cpp/Classes/PerformanceTest/PerformanceRendererTest.h b/tests/test-cpp/Classes/PerformanceTest/PerformanceRendererTest.h new file mode 100644 index 0000000000..07aeb4bc01 --- /dev/null +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceRendererTest.h @@ -0,0 +1,28 @@ +// +// PerformanceRendererTest.h +// cocos2d_samples +// +// Created by Huabing on 1/10/14. +// +// + +#ifndef __PERFORMANCE_RENDERER_TEST_H__ +#define __PERFORMANCE_RENDERER_TEST_H__ + +#include "PerformanceTest.h" + +class RenderTestLayer : public PerformBasicLayer +{ + +public: + RenderTestLayer(); + virtual ~RenderTestLayer(); + + virtual void onEnter() override; + virtual void showCurrentTest() override; +public: + static Scene* scene(); +}; + +void runRendererTest(); +#endif diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp b/tests/test-cpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp similarity index 88% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp rename to tests/test-cpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp index 431acb25ed..0acc702e08 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp @@ -48,11 +48,7 @@ enum { //////////////////////////////////////////////////////// SubTest::~SubTest() { - if (_batchNode) - { - _batchNode->release(); - _batchNode = NULL; - } + _parentNode->release(); } void SubTest::initWithSubTest(int subtest, Node* p) @@ -60,12 +56,11 @@ void SubTest::initWithSubTest(int subtest, Node* p) srand(0); subtestNumber = subtest; - _parent = p; - _batchNode = nullptr; + _parentNode = nullptr; /* * Tests: * 1: 1 (32-bit) PNG sprite of 52 x 139 - * 2: 1 (32-bit) PNG sprite of 52 x 139 + * 2: 1 (32-bit) PNG sprite of 52 x 139 (same as 1) * 3: 1 (32-bit) PNG Batch Node using 1 sprite of 52 x 139 * 4: 1 (16-bit) PNG Batch Node using 1 sprite of 52 x 139 @@ -90,73 +85,67 @@ void SubTest::initWithSubTest(int subtest, Node* p) { /// case 1: - Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - break; case 2: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); + _parentNode = Node::create(); break; case 3: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - _batchNode = SpriteBatchNode::create("Images/grossinis_sister1.png", 100); - p->addChild(_batchNode, 0); + _parentNode = SpriteBatchNode::create("Images/grossinis_sister1.png", 100); break; case 4: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); - _batchNode = SpriteBatchNode::create("Images/grossinis_sister1.png", 100); - p->addChild(_batchNode, 0); + _parentNode = SpriteBatchNode::create("Images/grossinis_sister1.png", 100); break; /// case 5: - Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - break; case 6: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - _batchNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); + _parentNode = Node::create(); break; case 7: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - _batchNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); - p->addChild(_batchNode, 0); - break; + _parentNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); + break; case 8: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); - _batchNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); - p->addChild(_batchNode, 0); + _parentNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); break; /// case 9: - Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - break; case 10: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - _batchNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); + _parentNode = Node::create(); break; case 11: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - _batchNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); - p->addChild(_batchNode, 0); + _parentNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); break; case 12: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); - _batchNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); - p->addChild(_batchNode, 0); + _parentNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); break; /// + case 13: + Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); + _parentNode = Node::create(); + break; + default: break; } - if (_batchNode) - { - _batchNode->retain(); - } + p->addChild(_parentNode); + _parentNode->retain(); } Sprite* SubTest::createSpriteWithTag(int tag) { + TextureCache *cache = Director::getInstance()->getTextureCache(); + Sprite* sprite = NULL; switch (subtestNumber) { @@ -165,14 +154,15 @@ Sprite* SubTest::createSpriteWithTag(int tag) case 2: { sprite = Sprite::create("Images/grossinis_sister1.png"); - _parent->addChild(sprite, 0, tag+100); + _parentNode->addChild(sprite, 0, tag+100); break; } case 3: case 4: { - sprite = Sprite::createWithTexture(_batchNode->getTexture(), Rect(0, 0, 52, 139)); - _batchNode->addChild(sprite, 0, tag+100); + Texture2D *texture = cache->addImage("Images/grossinis_sister1.png"); + sprite = Sprite::createWithTexture(texture, Rect(0, 0, 52, 139)); + _parentNode->addChild(sprite, 0, tag+100); break; } @@ -183,24 +173,10 @@ Sprite* SubTest::createSpriteWithTag(int tag) char str[32] = {0}; sprintf(str, "Images/grossini_dance_%02d.png", idx); sprite = Sprite::create(str); - _parent->addChild(sprite, 0, tag+100); + _parentNode->addChild(sprite, 0, tag+100); break; } case 6: - { - int y,x; - int r = (CCRANDOM_0_1() * 1400 / 100); - - y = r / 5; - x = r % 5; - - x *= 85; - y *= 121; - sprite = Sprite::createWithTexture(_batchNode->getTexture(), Rect(x,y,85,121)); - _parent->addChild(sprite, 0, tag+100); - break; - } - case 7: case 8: { @@ -212,8 +188,9 @@ Sprite* SubTest::createSpriteWithTag(int tag) x *= 85; y *= 121; - sprite = Sprite::createWithTexture(_batchNode->getTexture(), Rect(x,y,85,121)); - _batchNode->addChild(sprite, 0, tag+100); + Texture2D *texture = cache->addImage("Images/grossini_dance_atlas.png"); + sprite = Sprite::createWithTexture(texture, Rect(x,y,85,121)); + _parentNode->addChild(sprite, 0, tag+100); break; } @@ -229,25 +206,11 @@ Sprite* SubTest::createSpriteWithTag(int tag) char str[40] = {0}; sprintf(str, "Images/sprites_test/sprite-%d-%d.png", x, y); sprite = Sprite::create(str); - _parent->addChild(sprite, 0, tag+100); + _parentNode->addChild(sprite, 0, tag+100); break; } case 10: - { - int y,x; - int r = (CCRANDOM_0_1() * 6400 / 100); - - y = r / 8; - x = r % 8; - - x *= 32; - y *= 32; - sprite = Sprite::createWithTexture(_batchNode->getTexture(), CC_RECT_PIXELS_TO_POINTS(Rect(x,y,32,32))); - _parent->addChild(sprite, 0, tag+100); - break; - } - case 11: case 12: { @@ -259,10 +222,52 @@ Sprite* SubTest::createSpriteWithTag(int tag) x *= 32; y *= 32; - sprite = Sprite::createWithTexture(_batchNode->getTexture(), CC_RECT_PIXELS_TO_POINTS(Rect(x,y,32,32))); - _batchNode->addChild(sprite, 0, tag+100); + Texture2D *texture = cache->addImage("Images/spritesheet1.png"); + sprite = Sprite::createWithTexture(texture, CC_RECT_PIXELS_TO_POINTS(Rect(x,y,32,32))); + _parentNode->addChild(sprite, 0, tag+100); break; } + /// + case 13: + { + int test = (CCRANDOM_0_1() * 3); + + if(test==0) { + // Switch case 1 + sprite = Sprite::create("Images/grossinis_sister1.png"); + _parentNode->addChild(sprite, 0, tag+100); + } + else if(test==1) + { + // Switch case 6 + int y,x; + int r = (CCRANDOM_0_1() * 1400 / 100); + + y = r / 5; + x = r % 5; + + x *= 85; + y *= 121; + Texture2D *texture = cache->addImage("Images/grossini_dance_atlas.png"); + sprite = Sprite::createWithTexture(texture, Rect(x,y,85,121)); + _parentNode->addChild(sprite, 0, tag+100); + + } + else if(test==2) + { + int y,x; + int r = (CCRANDOM_0_1() * 6400 / 100); + + y = r / 8; + x = r % 8; + + x *= 32; + y *= 32; + Texture2D *texture = cache->addImage("Images/spritesheet1.png"); + sprite = Sprite::createWithTexture(texture, CC_RECT_PIXELS_TO_POINTS(Rect(x,y,32,32))); + _parentNode->addChild(sprite, 0, tag+100); + } + } default: break; @@ -273,30 +278,7 @@ Sprite* SubTest::createSpriteWithTag(int tag) void SubTest::removeByTag(int tag) { - switch (subtestNumber) - { - case 1: - case 5: - case 9: - _parent->removeChildByTag(tag+100, true); - break; - - case 2: - case 3: - case 4: - - case 6: - case 7: - case 8: - - case 10: - case 11: - case 12: - _batchNode->removeChildByTag(tag+100, true); - break; - default: - break; - } + _parentNode->removeChildByTag(tag+100, true); } //////////////////////////////////////////////////////// @@ -443,9 +425,9 @@ void SpriteMainScene::initWithSubTest(int asubtest, int nNodes) addChild( menuAutoTest, 3, kTagAutoTestMenu ); // Sub Tests - MenuItemFont::setFontSize(32); + MenuItemFont::setFontSize(28); auto subMenu = Menu::create(); - for (int i = 1; i <= 12; ++i) + for (int i = 1; i <= 13; ++i) { char str[10] = {0}; sprintf(str, "%d ", i); @@ -457,8 +439,10 @@ void SpriteMainScene::initWithSubTest(int asubtest, int nNodes) itemFont->setColor(Color3B(200,20,20)); else if(i <= 8) itemFont->setColor(Color3B(0,200,20)); - else + else if( i<=12) itemFont->setColor(Color3B(0,20,200)); + else + itemFont->setColor(Color3B::GRAY); } subMenu->alignItemsHorizontally(); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h b/tests/test-cpp/Classes/PerformanceTest/PerformanceSpriteTest.h similarity index 98% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h rename to tests/test-cpp/Classes/PerformanceTest/PerformanceSpriteTest.h index b6a4910259..0aa21356c7 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceSpriteTest.h @@ -40,8 +40,7 @@ public: protected: int subtestNumber; - SpriteBatchNode *_batchNode; - Node* _parent; + Node *_parentNode; }; class SpriteMenuLayer : public PerformBasicLayer diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp b/tests/test-cpp/Classes/PerformanceTest/PerformanceTest.cpp similarity index 60% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp rename to tests/test-cpp/Classes/PerformanceTest/PerformanceTest.cpp index e48ef17f28..63ce78dfe3 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceTest.cpp @@ -7,6 +7,9 @@ #include "PerformanceTouchesTest.h" #include "PerformanceAllocTest.h" #include "PerformanceLabelTest.h" +#include "PerformanceRendererTest.h" +#include "PerformanceContainerTest.h" +#include "PerformanceEventDispatcherTest.h" enum { @@ -26,6 +29,9 @@ struct { { "Texture Perf Test",[](Object*sender){runTextureTest();} }, { "Touches Perf Test",[](Object*sender){runTouchesTest();} }, { "Label Perf Test",[](Object*sender){runLabelTest();} }, + { "Renderer Perf Test",[](Object*sender){runRendererTest();} }, + { "Container Perf Test", [](Object* sender ) { runContainerPerformanceTest(); } }, + { "EventDispatcher Perf Test", [](Object* sender ) { runEventDispatcherPerformanceTest(); } }, }; static const int g_testMax = sizeof(g_testsName)/sizeof(g_testsName[0]); @@ -41,18 +47,83 @@ void PerformanceMainLayer::onEnter() auto s = Director::getInstance()->getWinSize(); - auto menu = Menu::create(); - menu->setPosition( Point::ZERO ); + _itemMenu = Menu::create(); + _itemMenu->setPosition( Point::ZERO ); MenuItemFont::setFontName("Arial"); MenuItemFont::setFontSize(24); for (int i = 0; i < g_testMax; ++i) { auto pItem = MenuItemFont::create(g_testsName[i].name, g_testsName[i].callback); pItem->setPosition(Point(s.width / 2, s.height - (i + 1) * LINE_SPACE)); - menu->addChild(pItem, kItemTagBasic + i); + _itemMenu->addChild(pItem, kItemTagBasic + i); } - addChild(menu); + addChild(_itemMenu); + + // Register Touch Event + auto listener = EventListenerTouchOneByOne::create(); + listener->setSwallowTouches(true); + + listener->onTouchBegan = CC_CALLBACK_2(PerformanceMainLayer::onTouchBegan, this); + listener->onTouchMoved = CC_CALLBACK_2(PerformanceMainLayer::onTouchMoved, this); + + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); + + auto mouseListener = EventListenerMouse::create(); + mouseListener->onMouseScroll = CC_CALLBACK_1(PerformanceMainLayer::onMouseScroll, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this); +} + +bool PerformanceMainLayer::onTouchBegan(Touch* touches, Event *event) +{ + _beginPos = touches->getLocation(); + return true; +} +void PerformanceMainLayer::onTouchMoved(Touch* touches, Event *event) +{ + auto touchLocation = touches->getLocation(); + float nMoveY = touchLocation.y - _beginPos.y; + + auto curPos = _itemMenu->getPosition(); + auto nextPos = Point(curPos.x, curPos.y + nMoveY); + + if (nextPos.y < 0.0f) + { + _itemMenu->setPosition(Point::ZERO); + return; + } + + if (nextPos.y > ((g_testMax + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height)) + { + _itemMenu->setPosition(Point(0, ((g_testMax + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height))); + return; + } + + _itemMenu->setPosition(nextPos); + _beginPos = touchLocation; +} + +void PerformanceMainLayer::onMouseScroll(Event *event) +{ + auto mouseEvent = static_cast(event); + float nMoveY = mouseEvent->getScrollY() * 6; + + auto curPos = _itemMenu->getPosition(); + auto nextPos = Point(curPos.x, curPos.y + nMoveY); + + if (nextPos.y < 0.0f) + { + _itemMenu->setPosition(Point::ZERO); + return; + } + + if (nextPos.y > ((g_testMax + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height)) + { + _itemMenu->setPosition(Point(0, ((g_testMax + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height))); + return; + } + + _itemMenu->setPosition(nextPos); } //////////////////////////////////////////////////////// diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.h b/tests/test-cpp/Classes/PerformanceTest/PerformanceTest.h similarity index 78% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.h rename to tests/test-cpp/Classes/PerformanceTest/PerformanceTest.h index 7d4766de30..f06a3c9bbd 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.h +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceTest.h @@ -7,6 +7,14 @@ class PerformanceMainLayer : public Layer { public: virtual void onEnter(); + + bool onTouchBegan(Touch* touches, Event *event); + void onTouchMoved(Touch* touches, Event *event); + + void onMouseScroll(Event *event); +protected: + Point _beginPos; + Menu* _itemMenu; }; class PerformBasicLayer : public Layer diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp b/tests/test-cpp/Classes/PerformanceTest/PerformanceTextureTest.cpp similarity index 98% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp rename to tests/test-cpp/Classes/PerformanceTest/PerformanceTextureTest.cpp index c420ac27ec..c46cb19c34 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.cpp +++ b/tests/test-cpp/Classes/PerformanceTest/PerformanceTextureTest.cpp @@ -85,6 +85,8 @@ void TextureTest::performTestsPNG(const char* filename) struct timeval now; Texture2D *texture; auto cache = Director::getInstance()->getTextureCache(); + + Texture2D::PixelFormat defaultFormat = Texture2D::getDefaultAlphaPixelFormat(); log("RGBA 8888"); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); @@ -125,6 +127,8 @@ void TextureTest::performTestsPNG(const char* filename) else log(" ERROR"); cache->removeTexture(texture); + + Texture2D::setDefaultAlphaPixelFormat(defaultFormat); } void TextureTest::performTests() diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.h b/tests/test-cpp/Classes/PerformanceTest/PerformanceTextureTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTextureTest.h rename to tests/test-cpp/Classes/PerformanceTest/PerformanceTextureTest.h diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp b/tests/test-cpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp rename to tests/test-cpp/Classes/PerformanceTest/PerformanceTouchesTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.h b/tests/test-cpp/Classes/PerformanceTest/PerformanceTouchesTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTouchesTest.h rename to tests/test-cpp/Classes/PerformanceTest/PerformanceTouchesTest.h diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/tests/test-cpp/Classes/PhysicsTest/PhysicsTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp rename to tests/test-cpp/Classes/PhysicsTest/PhysicsTest.cpp index b9c97830bd..aedc0f3e09 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/tests/test-cpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -1151,7 +1151,6 @@ bool PhysicsDemoSlice::slice(PhysicsWorld &world, const PhysicsRayCastInfo& info Point normal = info.end - info.start; normal = normal.getPerp().normalize(); float dist = info.start.dot(normal); - dist = dist; clipPoly(dynamic_cast(info.shape), normal, dist); clipPoly(dynamic_cast(info.shape), -normal, -dist); diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h b/tests/test-cpp/Classes/PhysicsTest/PhysicsTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.h rename to tests/test-cpp/Classes/PhysicsTest/PhysicsTest.h diff --git a/tests/test-cpp/Classes/ReleasePoolTest/ReleasePoolTest.cpp b/tests/test-cpp/Classes/ReleasePoolTest/ReleasePoolTest.cpp new file mode 100644 index 0000000000..061e0f1d19 --- /dev/null +++ b/tests/test-cpp/Classes/ReleasePoolTest/ReleasePoolTest.cpp @@ -0,0 +1,80 @@ +#include "ReleasePoolTest.h" + +using namespace cocos2d; + +class TestObject : public Object +{ +public: + TestObject() : _name(""){} + + TestObject(std::string name) : _name(name) + { + CCLOG("TestObject:%s is created", _name.c_str()); + } + + ~TestObject() + { + if (_name.size() > 0) + CCLOG("TestObject:%s is destroyed", _name.c_str()); + } + +private: + std::string _name; +}; + +void ReleasePoolTestScene::runThisTest() +{ + // title + auto label = LabelTTF::create("AutoreasePool Test", "Arial", 32); + addChild(label, 9999); + label->setPosition(Point(VisibleRect::center().x, VisibleRect::top().y - 30)); + + // reference count should be added when added into auto release pool + + TestObject *obj = new TestObject("testobj"); + obj->autorelease(); + assert(obj->getReferenceCount() == 1); + + // should retain first before invoking autorelease + obj->retain(); + obj->autorelease(); + assert(obj->getReferenceCount() == 2); + + // create an autorelease pool in stack + + { + AutoreleasePool pool1; + + // can invoke autorelease more than once + obj->retain(); + obj->autorelease(); + assert(obj->getReferenceCount() == 3); + obj->retain(); + obj->autorelease(); + assert(obj->getReferenceCount() == 4); + + // retain, release can work together with autorelease pool + obj->retain(); + assert(obj->getReferenceCount() == 5); + obj->release(); + assert(obj->getReferenceCount() == 4); + } + + assert(obj->getReferenceCount() == 2); + + // example of using temple autorelease pool + { + AutoreleasePool pool2; + char name[20]; + for (int i = 0; i < 100; ++i) + { + snprintf(name, 20, "object%d", i); + TestObject *tmpObj = new TestObject(name); + tmpObj->autorelease(); + } + } + + // object in pool2 should be released + + Director::getInstance()->replaceScene(this); +} diff --git a/tests/test-cpp/Classes/ReleasePoolTest/ReleasePoolTest.h b/tests/test-cpp/Classes/ReleasePoolTest/ReleasePoolTest.h new file mode 100644 index 0000000000..abd518b571 --- /dev/null +++ b/tests/test-cpp/Classes/ReleasePoolTest/ReleasePoolTest.h @@ -0,0 +1,18 @@ +/* + * + */ +#ifndef __RELEASE_POOL_TEST_H__ +#define __RELEASE_POOL_TEST_H__ + +#include "../testBasic.h" + +class ReleasePoolTestScene : public TestScene +{ +public: + virtual void runThisTest(); + +private: + +}; + +#endif // __RELEASE_POOL_TEST_H__ diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp b/tests/test-cpp/Classes/RenderTextureTest/RenderTextureTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp rename to tests/test-cpp/Classes/RenderTextureTest/RenderTextureTest.cpp index 9a18f256be..e893f707f7 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/tests/test-cpp/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -470,19 +470,19 @@ RenderTextureTestDepthStencil::~RenderTextureTestDepthStencil() void RenderTextureTestDepthStencil::draw() { - _renderCmds[0].init(0, _vertexZ); + _renderCmds[0].init(_globalZOrder); _renderCmds[0].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onBeforeClear, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[0]); _rend->beginWithClear(0, 0, 0, 0, 0, 0); - _renderCmds[1].init(0, _vertexZ); + _renderCmds[1].init(_globalZOrder); _renderCmds[1].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onBeforeStencil, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[1]); _spriteDS->visit(); - _renderCmds[2].init(0, _vertexZ); + _renderCmds[2].init(_globalZOrder); _renderCmds[2].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onBeforDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[2]); @@ -490,7 +490,7 @@ void RenderTextureTestDepthStencil::draw() _rend->end(); - _renderCmds[3].init(0, _vertexZ); + _renderCmds[3].init(_globalZOrder); _renderCmds[3].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onAfterDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[3]); @@ -638,7 +638,7 @@ SpriteRenderTextureBug::SimpleSprite* SpriteRenderTextureBug::SimpleSprite::crea void SpriteRenderTextureBug::SimpleSprite::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(SpriteRenderTextureBug::SimpleSprite::onBeforeDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h b/tests/test-cpp/Classes/RenderTextureTest/RenderTextureTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.h rename to tests/test-cpp/Classes/RenderTextureTest/RenderTextureTest.h diff --git a/samples/Cpp/TestCpp/Classes/RotateWorldTest/RotateWorldTest.cpp b/tests/test-cpp/Classes/RotateWorldTest/RotateWorldTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/RotateWorldTest/RotateWorldTest.cpp rename to tests/test-cpp/Classes/RotateWorldTest/RotateWorldTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/RotateWorldTest/RotateWorldTest.h b/tests/test-cpp/Classes/RotateWorldTest/RotateWorldTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/RotateWorldTest/RotateWorldTest.h rename to tests/test-cpp/Classes/RotateWorldTest/RotateWorldTest.h diff --git a/samples/Cpp/TestCpp/Classes/SceneTest/SceneTest.cpp b/tests/test-cpp/Classes/SceneTest/SceneTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/SceneTest/SceneTest.cpp rename to tests/test-cpp/Classes/SceneTest/SceneTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/SceneTest/SceneTest.h b/tests/test-cpp/Classes/SceneTest/SceneTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/SceneTest/SceneTest.h rename to tests/test-cpp/Classes/SceneTest/SceneTest.h diff --git a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp b/tests/test-cpp/Classes/SchedulerTest/SchedulerTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp rename to tests/test-cpp/Classes/SchedulerTest/SchedulerTest.cpp index 96b32461d0..a7b1f6da48 100644 --- a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp +++ b/tests/test-cpp/Classes/SchedulerTest/SchedulerTest.cpp @@ -160,7 +160,7 @@ void SchedulerPauseResume::onEnter() schedule(schedule_selector(SchedulerPauseResume::tick1), 0.5f); schedule(schedule_selector(SchedulerPauseResume::tick2), 0.5f); - schedule(schedule_selector(SchedulerPauseResume::pause), 0.5f); + schedule(schedule_selector(SchedulerPauseResume::pause), 3.0f); } void SchedulerPauseResume::tick1(float dt) diff --git a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h b/tests/test-cpp/Classes/SchedulerTest/SchedulerTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h rename to tests/test-cpp/Classes/SchedulerTest/SchedulerTest.h diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp b/tests/test-cpp/Classes/ShaderTest/ShaderTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp rename to tests/test-cpp/Classes/ShaderTest/ShaderTest.cpp index ba6c1f01c1..7ab64428ff 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp +++ b/tests/test-cpp/Classes/ShaderTest/ShaderTest.cpp @@ -193,7 +193,7 @@ void ShaderNode::setPosition(const Point &newPosition) void ShaderNode::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ShaderNode::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -526,7 +526,7 @@ void SpriteBlur::initProgram() void SpriteBlur::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(SpriteBlur::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -547,8 +547,8 @@ void SpriteBlur::onDraw() // // Attributes // -#define kQuadSize sizeof(_quad.bl) - long offset = (long)&_quad; + #define kQuadSize sizeof(_quad.bl) + size_t offset = (size_t)&_quad; // vertex int diff = offsetof( V3F_C4B_T2F, vertices); diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.h b/tests/test-cpp/Classes/ShaderTest/ShaderTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.h rename to tests/test-cpp/Classes/ShaderTest/ShaderTest.h diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp b/tests/test-cpp/Classes/ShaderTest/ShaderTest2.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp rename to tests/test-cpp/Classes/ShaderTest/ShaderTest2.cpp index 569bef3915..9fb0ff3d87 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp +++ b/tests/test-cpp/Classes/ShaderTest/ShaderTest2.cpp @@ -178,7 +178,7 @@ void ShaderSprite::initShader() void ShaderSprite::draw() { - _renderCommand.init(0, _vertexZ); + _renderCommand.init(_globalZOrder); _renderCommand.func = CC_CALLBACK_0(ShaderSprite::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCommand); @@ -197,8 +197,8 @@ void ShaderSprite::onDraw() // // Attributes // -#define kQuadSize sizeof(_quad.bl) - long offset = (long)&_quad; + #define kQuadSize sizeof(_quad.bl) + size_t offset = (size_t)&_quad; // vertex int diff = offsetof( V3F_C4B_T2F, vertices); diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.h b/tests/test-cpp/Classes/ShaderTest/ShaderTest2.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.h rename to tests/test-cpp/Classes/ShaderTest/ShaderTest2.h diff --git a/samples/Cpp/TestCpp/Classes/SpineTest/SpineTest.cpp b/tests/test-cpp/Classes/SpineTest/SpineTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/SpineTest/SpineTest.cpp rename to tests/test-cpp/Classes/SpineTest/SpineTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/SpineTest/SpineTest.h b/tests/test-cpp/Classes/SpineTest/SpineTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/SpineTest/SpineTest.h rename to tests/test-cpp/Classes/SpineTest/SpineTest.h diff --git a/tests/test-cpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/tests/test-cpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id new file mode 100644 index 0000000000..e747e4ff8e --- /dev/null +++ b/tests/test-cpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -0,0 +1 @@ +c098eac3962854bc7d1981ec16aad7d2907c0e33 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h b/tests/test-cpp/Classes/SpriteTest/SpriteTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.h rename to tests/test-cpp/Classes/SpriteTest/SpriteTest.h diff --git a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp b/tests/test-cpp/Classes/TextInputTest/TextInputTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.cpp rename to tests/test-cpp/Classes/TextInputTest/TextInputTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.h b/tests/test-cpp/Classes/TextInputTest/TextInputTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/TextInputTest/TextInputTest.h rename to tests/test-cpp/Classes/TextInputTest/TextInputTest.h diff --git a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp b/tests/test-cpp/Classes/Texture2dTest/Texture2dTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp rename to tests/test-cpp/Classes/Texture2dTest/Texture2dTest.cpp index a3f4a7d564..a4121f8825 100644 --- a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp +++ b/tests/test-cpp/Classes/Texture2dTest/Texture2dTest.cpp @@ -1794,7 +1794,7 @@ void TextureDrawAtPoint::draw() { TextureDemo::draw(); - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TextureDrawAtPoint::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); @@ -1835,7 +1835,7 @@ void TextureDrawInRect::draw() { TextureDemo::draw(); - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TextureDrawInRect::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); diff --git a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.h b/tests/test-cpp/Classes/Texture2dTest/Texture2dTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.h rename to tests/test-cpp/Classes/Texture2dTest/Texture2dTest.h diff --git a/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp b/tests/test-cpp/Classes/TextureCacheTest/TextureCacheTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp rename to tests/test-cpp/Classes/TextureCacheTest/TextureCacheTest.cpp index 31c4beaef9..5df463d27d 100644 --- a/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.cpp +++ b/tests/test-cpp/Classes/TextureCacheTest/TextureCacheTest.cpp @@ -1,8 +1,9 @@ -// enable log -#define COCOS2D_DEBUG 1 #include "TextureCacheTest.h" +// enable log +#define COCOS2D_DEBUG 1 + USING_NS_CC; TextureCacheTest::TextureCacheTest() diff --git a/samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.h b/tests/test-cpp/Classes/TextureCacheTest/TextureCacheTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/TextureCacheTest/TextureCacheTest.h rename to tests/test-cpp/Classes/TextureCacheTest/TextureCacheTest.h diff --git a/samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp b/tests/test-cpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp rename to tests/test-cpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.h b/tests/test-cpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.h rename to tests/test-cpp/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.h diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp b/tests/test-cpp/Classes/TileMapTest/TileMapTest.cpp similarity index 99% rename from samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp rename to tests/test-cpp/Classes/TileMapTest/TileMapTest.cpp index 75f0fd6eee..1b45442fd5 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp +++ b/tests/test-cpp/Classes/TileMapTest/TileMapTest.cpp @@ -599,7 +599,7 @@ TMXOrthoObjectsTest::TMXOrthoObjectsTest() void TMXOrthoObjectsTest::draw() { - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TMXOrthoObjectsTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } @@ -672,7 +672,7 @@ TMXIsoObjectsTest::TMXIsoObjectsTest() void TMXIsoObjectsTest::draw() { - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TMXIsoObjectsTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } @@ -1504,7 +1504,7 @@ TMXGIDObjectsTest::TMXGIDObjectsTest() void TMXGIDObjectsTest::draw() { - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TMXGIDObjectsTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.h b/tests/test-cpp/Classes/TileMapTest/TileMapTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.h rename to tests/test-cpp/Classes/TileMapTest/TileMapTest.h diff --git a/samples/Cpp/TestCpp/Classes/TouchesTest/Ball.cpp b/tests/test-cpp/Classes/TouchesTest/Ball.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/TouchesTest/Ball.cpp rename to tests/test-cpp/Classes/TouchesTest/Ball.cpp diff --git a/samples/Cpp/TestCpp/Classes/TouchesTest/Ball.h b/tests/test-cpp/Classes/TouchesTest/Ball.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/TouchesTest/Ball.h rename to tests/test-cpp/Classes/TouchesTest/Ball.h diff --git a/samples/Cpp/TestCpp/Classes/TouchesTest/Paddle.cpp b/tests/test-cpp/Classes/TouchesTest/Paddle.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/TouchesTest/Paddle.cpp rename to tests/test-cpp/Classes/TouchesTest/Paddle.cpp diff --git a/samples/Cpp/TestCpp/Classes/TouchesTest/Paddle.h b/tests/test-cpp/Classes/TouchesTest/Paddle.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/TouchesTest/Paddle.h rename to tests/test-cpp/Classes/TouchesTest/Paddle.h diff --git a/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp b/tests/test-cpp/Classes/TouchesTest/TouchesTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.cpp rename to tests/test-cpp/Classes/TouchesTest/TouchesTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.h b/tests/test-cpp/Classes/TouchesTest/TouchesTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/TouchesTest/TouchesTest.h rename to tests/test-cpp/Classes/TouchesTest/TouchesTest.h diff --git a/samples/Cpp/TestCpp/Classes/TransitionsTest/TransitionsTest.cpp b/tests/test-cpp/Classes/TransitionsTest/TransitionsTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/TransitionsTest/TransitionsTest.cpp rename to tests/test-cpp/Classes/TransitionsTest/TransitionsTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/TransitionsTest/TransitionsTest.h b/tests/test-cpp/Classes/TransitionsTest/TransitionsTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/TransitionsTest/TransitionsTest.h rename to tests/test-cpp/Classes/TransitionsTest/TransitionsTest.h diff --git a/samples/Cpp/TestCpp/Classes/UnitTest/UnitTest.cpp b/tests/test-cpp/Classes/UnitTest/UnitTest.cpp similarity index 91% rename from samples/Cpp/TestCpp/Classes/UnitTest/UnitTest.cpp rename to tests/test-cpp/Classes/UnitTest/UnitTest.cpp index 5027ac3c43..20c2767b76 100644 --- a/samples/Cpp/TestCpp/Classes/UnitTest/UnitTest.cpp +++ b/tests/test-cpp/Classes/UnitTest/UnitTest.cpp @@ -103,7 +103,7 @@ void TemplateVectorTest::onEnter() auto node1 = Node::create(); node1->setTag(1); vec.pushBack(node1); - CCASSERT(node1->retainCount() == 2, ""); + CCASSERT(node1->getReferenceCount() == 2, ""); auto node2 = Node::create(); node2->setTag(2); @@ -125,8 +125,8 @@ void TemplateVectorTest::onEnter() for (ssize_t i = 0; i < size; ++i) { CCASSERT(vec2.at(i) == vec.at(i), ""); - CCASSERT(vec.at(i)->retainCount() == 3, ""); - CCASSERT(vec2.at(i)->retainCount() == 3, ""); + CCASSERT(vec.at(i)->getReferenceCount() == 3, ""); + CCASSERT(vec2.at(i)->getReferenceCount() == 3, ""); } // Test copy assignment operator @@ -137,9 +137,9 @@ void TemplateVectorTest::onEnter() for (ssize_t i = 0; i < size; ++i) { CCASSERT(vec3.at(i) == vec2.at(i), ""); - CCASSERT(vec3.at(i)->retainCount() == 4, ""); - CCASSERT(vec2.at(i)->retainCount() == 4, ""); - CCASSERT(vec.at(i)->retainCount() == 4, ""); + CCASSERT(vec3.at(i)->getReferenceCount() == 4, ""); + CCASSERT(vec2.at(i)->getReferenceCount() == 4, ""); + CCASSERT(vec.at(i)->getReferenceCount() == 4, ""); } // Test move constructor @@ -164,7 +164,7 @@ void TemplateVectorTest::onEnter() Vector vec4(createVector()); for (const auto& child : vec4) { - CCASSERT(child->retainCount() == 2, ""); + CCASSERT(child->getReferenceCount() == 2, ""); } // Test init Vector with capacity @@ -178,16 +178,16 @@ void TemplateVectorTest::onEnter() auto toRemovedNode = Node::create(); vec5.pushBack(toRemovedNode); - CCASSERT(toRemovedNode->retainCount() == 2, ""); + CCASSERT(toRemovedNode->getReferenceCount() == 2, ""); // Test move assignment operator vec5 = createVector(); - CCASSERT(toRemovedNode->retainCount() == 1, ""); + CCASSERT(toRemovedNode->getReferenceCount() == 1, ""); CCASSERT(vec5.size() == 20, "size should be 20"); for (const auto& child : vec5) { - CCASSERT(child->retainCount() == 2, ""); + CCASSERT(child->getReferenceCount() == 2, ""); } // Test Vector::find @@ -238,7 +238,7 @@ void TemplateVectorTest::onEnter() CCASSERT(vec7.size() == 20, ""); for (const auto& child : vec7) { - CCASSERT(child->retainCount() == 2, ""); + CCASSERT(child->getReferenceCount() == 2, ""); } // Sort @@ -294,7 +294,7 @@ void TemplateVectorTest::onEnter() for (const auto& child : vecSelfAssign) { - CCASSERT(child->retainCount() == 2, ""); + CCASSERT(child->getReferenceCount() == 2, ""); } vecSelfAssign = std::move(vecSelfAssign); @@ -302,7 +302,7 @@ void TemplateVectorTest::onEnter() for (const auto& child : vecSelfAssign) { - CCASSERT(child->retainCount() == 2, ""); + CCASSERT(child->getReferenceCount() == 2, ""); } // const at @@ -350,14 +350,14 @@ void TemplateMapTest::onEnter() Map map2 = createMap(); for (const auto& e : map2) { - CCASSERT(e.second->retainCount() == 2, ""); + CCASSERT(e.second->getReferenceCount() == 2, ""); } // Copy constructor Map map3(map2); for (const auto& e : map3) { - CCASSERT(e.second->retainCount() == 3, ""); + CCASSERT(e.second->getReferenceCount() == 3, ""); } // Move assignment operator @@ -365,10 +365,10 @@ void TemplateMapTest::onEnter() auto unusedNode = Node::create(); map4.insert("unused",unusedNode); map4 = createMap(); - CCASSERT(unusedNode->retainCount() == 1, ""); + CCASSERT(unusedNode->getReferenceCount() == 1, ""); for (const auto& e : map4) { - CCASSERT(e.second->retainCount() == 2, ""); + CCASSERT(e.second->getReferenceCount() == 2, ""); } // Copy assignment operator @@ -376,7 +376,7 @@ void TemplateMapTest::onEnter() map5 = map4; for (const auto& e : map5) { - CCASSERT(e.second->retainCount() == 3, ""); + CCASSERT(e.second->getReferenceCount() == 3, ""); } // Check size @@ -441,9 +441,9 @@ void TemplateMapTest::onEnter() map6.insert("insert02", node2); map6.insert("insert03", node3); - CCASSERT(node1->retainCount() == 2, ""); - CCASSERT(node2->retainCount() == 2, ""); - CCASSERT(node3->retainCount() == 2, ""); + CCASSERT(node1->getReferenceCount() == 2, ""); + CCASSERT(node2->getReferenceCount() == 2, ""); + CCASSERT(node3->getReferenceCount() == 2, ""); CCASSERT(map6.at("insert01") == node1, ""); CCASSERT(map6.at("insert02") == node2, ""); CCASSERT(map6.at("insert03") == node3, ""); @@ -472,7 +472,7 @@ void TemplateMapTest::onEnter() for (const auto& e : mapForClearCopy) { - CCASSERT(e.second->retainCount() == 2, ""); + CCASSERT(e.second->getReferenceCount() == 2, ""); } // get random object @@ -493,7 +493,7 @@ void TemplateMapTest::onEnter() for (const auto& e : mapForSelfAssign) { - CCASSERT(e.second->retainCount() == 2, ""); + CCASSERT(e.second->getReferenceCount() == 2, ""); } mapForSelfAssign = std::move(mapForSelfAssign); @@ -501,7 +501,7 @@ void TemplateMapTest::onEnter() for (const auto& e : mapForSelfAssign) { - CCASSERT(e.second->retainCount() == 2, ""); + CCASSERT(e.second->getReferenceCount() == 2, ""); } } diff --git a/samples/Cpp/TestCpp/Classes/UnitTest/UnitTest.h b/tests/test-cpp/Classes/UnitTest/UnitTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/UnitTest/UnitTest.h rename to tests/test-cpp/Classes/UnitTest/UnitTest.h diff --git a/samples/Cpp/TestCpp/Classes/UserDefaultTest/UserDefaultTest.cpp b/tests/test-cpp/Classes/UserDefaultTest/UserDefaultTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/UserDefaultTest/UserDefaultTest.cpp rename to tests/test-cpp/Classes/UserDefaultTest/UserDefaultTest.cpp index ae440e66db..27a5a8fa1a 100644 --- a/samples/Cpp/TestCpp/Classes/UserDefaultTest/UserDefaultTest.cpp +++ b/tests/test-cpp/Classes/UserDefaultTest/UserDefaultTest.cpp @@ -1,10 +1,10 @@ -// enable log -#define COCOS2D_DEBUG 1 - #include "UserDefaultTest.h" #include "stdio.h" #include "stdlib.h" +// enable log +#define COCOS2D_DEBUG 1 + UserDefaultTest::UserDefaultTest() { auto s = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/UserDefaultTest/UserDefaultTest.h b/tests/test-cpp/Classes/UserDefaultTest/UserDefaultTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/UserDefaultTest/UserDefaultTest.h rename to tests/test-cpp/Classes/UserDefaultTest/UserDefaultTest.h diff --git a/samples/Cpp/TestCpp/Classes/VisibleRect.cpp b/tests/test-cpp/Classes/VisibleRect.cpp similarity index 96% rename from samples/Cpp/TestCpp/Classes/VisibleRect.cpp rename to tests/test-cpp/Classes/VisibleRect.cpp index 2686a1b821..94a494a02e 100644 --- a/samples/Cpp/TestCpp/Classes/VisibleRect.cpp +++ b/tests/test-cpp/Classes/VisibleRect.cpp @@ -6,7 +6,7 @@ void VisibleRect::lazyInit() { if (s_visibleRect.size.width == 0.0f && s_visibleRect.size.height == 0.0f) { - auto glView = EGLView::getInstance(); + auto glView = Director::getInstance()->getOpenGLView(); s_visibleRect.origin = glView->getVisibleOrigin(); s_visibleRect.size = glView->getVisibleSize(); } diff --git a/samples/Cpp/TestCpp/Classes/VisibleRect.h b/tests/test-cpp/Classes/VisibleRect.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/VisibleRect.h rename to tests/test-cpp/Classes/VisibleRect.h diff --git a/samples/Cpp/TestCpp/Classes/ZwoptexTest/ZwoptexTest.cpp b/tests/test-cpp/Classes/ZwoptexTest/ZwoptexTest.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/ZwoptexTest/ZwoptexTest.cpp rename to tests/test-cpp/Classes/ZwoptexTest/ZwoptexTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/ZwoptexTest/ZwoptexTest.h b/tests/test-cpp/Classes/ZwoptexTest/ZwoptexTest.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/ZwoptexTest/ZwoptexTest.h rename to tests/test-cpp/Classes/ZwoptexTest/ZwoptexTest.h diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/tests/test-cpp/Classes/controller.cpp similarity index 98% rename from samples/Cpp/TestCpp/Classes/controller.cpp rename to tests/test-cpp/Classes/controller.cpp index 750ba02a9f..f1f04ae2a2 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/tests/test-cpp/Classes/controller.cpp @@ -73,6 +73,7 @@ struct { { "ParticleTest", [](){return new ParticleTestScene(); } }, { "PerformanceTest", []() { return new PerformanceTestScene(); } }, { "PhysicsTest", []() { return new PhysicsTestScene(); } }, + { "ReleasePoolTest", [](){ return new ReleasePoolTestScene(); } }, { "RenderTextureTest", [](){return new RenderTextureScene(); } }, { "RotateWorldTest", [](){return new RotateWorldTestScene(); } }, { "SceneTest", [](){return new SceneTestScene();} }, @@ -151,12 +152,11 @@ TestController::~TestController() void TestController::menuCallback(Object * sender) { - Director::getInstance()->purgeCachedData(); // get the userdata, it's the index of the menu item clicked auto menuItem = static_cast(sender); - int idx = menuItem->getZOrder() - 10000; + int idx = menuItem->getLocalZOrder() - 10000; // create the test scene and run it auto scene = g_aTestNames[idx].callback(); diff --git a/samples/Cpp/TestCpp/Classes/controller.h b/tests/test-cpp/Classes/controller.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/controller.h rename to tests/test-cpp/Classes/controller.h diff --git a/samples/Cpp/TestCpp/Classes/testBasic.cpp b/tests/test-cpp/Classes/testBasic.cpp similarity index 100% rename from samples/Cpp/TestCpp/Classes/testBasic.cpp rename to tests/test-cpp/Classes/testBasic.cpp diff --git a/samples/Cpp/TestCpp/Classes/testBasic.h b/tests/test-cpp/Classes/testBasic.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/testBasic.h rename to tests/test-cpp/Classes/testBasic.h diff --git a/samples/Cpp/TestCpp/Classes/testResource.h b/tests/test-cpp/Classes/testResource.h similarity index 100% rename from samples/Cpp/TestCpp/Classes/testResource.h rename to tests/test-cpp/Classes/testResource.h diff --git a/samples/Cpp/TestCpp/Classes/tests.h b/tests/test-cpp/Classes/tests.h similarity index 98% rename from samples/Cpp/TestCpp/Classes/tests.h rename to tests/test-cpp/Classes/tests.h index d030ae34f3..9e20f96590 100644 --- a/samples/Cpp/TestCpp/Classes/tests.h +++ b/tests/test-cpp/Classes/tests.h @@ -68,5 +68,6 @@ #include "DataVisitorTest/DataVisitorTest.h" #include "ConfigurationTest/ConfigurationTest.h" #include "PhysicsTest/PhysicsTest.h" +#include "ReleasePoolTest/ReleasePoolTest.h" #endif diff --git a/samples/Cpp/HelloCpp/Resources/.gitignore b/tests/test-cpp/Resources/.gitignore similarity index 100% rename from samples/Cpp/HelloCpp/Resources/.gitignore rename to tests/test-cpp/Resources/.gitignore diff --git a/samples/Cpp/TestCpp/Resources/Hello.png.REMOVED.git-id b/tests/test-cpp/Resources/Hello.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Hello.png.REMOVED.git-id rename to tests/test-cpp/Resources/Hello.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/HelloWorld.png.REMOVED.git-id b/tests/test-cpp/Resources/Images/HelloWorld.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/HelloWorld.png.REMOVED.git-id rename to tests/test-cpp/Resources/Images/HelloWorld.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/PlanetCute-1024x1024.png.REMOVED.git-id b/tests/test-cpp/Resources/Images/PlanetCute-1024x1024.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/PlanetCute-1024x1024.png.REMOVED.git-id rename to tests/test-cpp/Resources/Images/PlanetCute-1024x1024.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/atlastest.png.REMOVED.git-id b/tests/test-cpp/Resources/Images/atlastest.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/atlastest.png.REMOVED.git-id rename to tests/test-cpp/Resources/Images/atlastest.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/background1.png.REMOVED.git-id b/tests/test-cpp/Resources/Images/background1.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/background1.png.REMOVED.git-id rename to tests/test-cpp/Resources/Images/background1.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/background2.jpg.REMOVED.git-id b/tests/test-cpp/Resources/Images/background2.jpg.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/background2.jpg.REMOVED.git-id rename to tests/test-cpp/Resources/Images/background2.jpg.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/background2.png.REMOVED.git-id b/tests/test-cpp/Resources/Images/background2.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/background2.png.REMOVED.git-id rename to tests/test-cpp/Resources/Images/background2.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/bugs/bug886.png.REMOVED.git-id b/tests/test-cpp/Resources/Images/bugs/bug886.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/bugs/bug886.png.REMOVED.git-id rename to tests/test-cpp/Resources/Images/bugs/bug886.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/grossini_dance_atlas-mono.png.REMOVED.git-id b/tests/test-cpp/Resources/Images/grossini_dance_atlas-mono.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/grossini_dance_atlas-mono.png.REMOVED.git-id rename to tests/test-cpp/Resources/Images/grossini_dance_atlas-mono.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/landscape-1024x1024.png.REMOVED.git-id b/tests/test-cpp/Resources/Images/landscape-1024x1024.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/landscape-1024x1024.png.REMOVED.git-id rename to tests/test-cpp/Resources/Images/landscape-1024x1024.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/noise.png.REMOVED.git-id b/tests/test-cpp/Resources/Images/noise.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/noise.png.REMOVED.git-id rename to tests/test-cpp/Resources/Images/noise.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/spritesheet1.png.REMOVED.git-id b/tests/test-cpp/Resources/Images/spritesheet1.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/spritesheet1.png.REMOVED.git-id rename to tests/test-cpp/Resources/Images/spritesheet1.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/stone.png.REMOVED.git-id b/tests/test-cpp/Resources/Images/stone.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/stone.png.REMOVED.git-id rename to tests/test-cpp/Resources/Images/stone.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/test_1021x1024.png.REMOVED.git-id b/tests/test-cpp/Resources/Images/test_1021x1024.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/test_1021x1024.png.REMOVED.git-id rename to tests/test-cpp/Resources/Images/test_1021x1024.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/test_1021x1024_a8.pvr.REMOVED.git-id b/tests/test-cpp/Resources/Images/test_1021x1024_a8.pvr.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/test_1021x1024_a8.pvr.REMOVED.git-id rename to tests/test-cpp/Resources/Images/test_1021x1024_a8.pvr.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/test_1021x1024_rgb888.pvr.REMOVED.git-id b/tests/test-cpp/Resources/Images/test_1021x1024_rgb888.pvr.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/test_1021x1024_rgb888.pvr.REMOVED.git-id rename to tests/test-cpp/Resources/Images/test_1021x1024_rgb888.pvr.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/test_1021x1024_rgb888.pvr.gz.REMOVED.git-id b/tests/test-cpp/Resources/Images/test_1021x1024_rgb888.pvr.gz.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/test_1021x1024_rgb888.pvr.gz.REMOVED.git-id rename to tests/test-cpp/Resources/Images/test_1021x1024_rgb888.pvr.gz.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/test_1021x1024_rgba4444.pvr.REMOVED.git-id b/tests/test-cpp/Resources/Images/test_1021x1024_rgba4444.pvr.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/test_1021x1024_rgba4444.pvr.REMOVED.git-id rename to tests/test-cpp/Resources/Images/test_1021x1024_rgba4444.pvr.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/test_1021x1024_rgba4444.pvr.gz.REMOVED.git-id b/tests/test-cpp/Resources/Images/test_1021x1024_rgba4444.pvr.gz.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/test_1021x1024_rgba4444.pvr.gz.REMOVED.git-id rename to tests/test-cpp/Resources/Images/test_1021x1024_rgba4444.pvr.gz.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/test_1021x1024_rgba8888.pvr.REMOVED.git-id b/tests/test-cpp/Resources/Images/test_1021x1024_rgba8888.pvr.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/test_1021x1024_rgba8888.pvr.REMOVED.git-id rename to tests/test-cpp/Resources/Images/test_1021x1024_rgba8888.pvr.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Images/test_1021x1024_rgba8888.pvr.gz.REMOVED.git-id b/tests/test-cpp/Resources/Images/test_1021x1024_rgba8888.pvr.gz.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/Images/test_1021x1024_rgba8888.pvr.gz.REMOVED.git-id rename to tests/test-cpp/Resources/Images/test_1021x1024_rgba8888.pvr.gz.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/Misc/resources-hd/test4.txt b/tests/test-cpp/Resources/Misc/resources-hd/test4.txt similarity index 100% rename from samples/Cpp/TestCpp/Resources/Misc/resources-hd/test4.txt rename to tests/test-cpp/Resources/Misc/resources-hd/test4.txt diff --git a/samples/Cpp/TestCpp/Resources/Misc/resources-ipad/test2.txt b/tests/test-cpp/Resources/Misc/resources-ipad/test2.txt similarity index 100% rename from samples/Cpp/TestCpp/Resources/Misc/resources-ipad/test2.txt rename to tests/test-cpp/Resources/Misc/resources-ipad/test2.txt diff --git a/samples/Cpp/TestCpp/Resources/Misc/resources-ipadhd/test1.txt b/tests/test-cpp/Resources/Misc/resources-ipadhd/test1.txt similarity index 100% rename from samples/Cpp/TestCpp/Resources/Misc/resources-ipadhd/test1.txt rename to tests/test-cpp/Resources/Misc/resources-ipadhd/test1.txt diff --git a/samples/Cpp/TestCpp/Resources/Misc/resources-iphone/test6.txt b/tests/test-cpp/Resources/Misc/resources-iphone/test6.txt similarity index 100% rename from samples/Cpp/TestCpp/Resources/Misc/resources-iphone/test6.txt rename to tests/test-cpp/Resources/Misc/resources-iphone/test6.txt diff --git a/samples/Cpp/TestCpp/Resources/Misc/resources-mac/test2.txt b/tests/test-cpp/Resources/Misc/resources-mac/test2.txt similarity index 100% rename from samples/Cpp/TestCpp/Resources/Misc/resources-mac/test2.txt rename to tests/test-cpp/Resources/Misc/resources-mac/test2.txt diff --git a/samples/Cpp/TestCpp/Resources/Misc/resources-machd/test1.txt b/tests/test-cpp/Resources/Misc/resources-machd/test1.txt similarity index 100% rename from samples/Cpp/TestCpp/Resources/Misc/resources-machd/test1.txt rename to tests/test-cpp/Resources/Misc/resources-machd/test1.txt diff --git a/samples/Cpp/TestCpp/Resources/Misc/resources-wide/test5.txt b/tests/test-cpp/Resources/Misc/resources-wide/test5.txt similarity index 100% rename from samples/Cpp/TestCpp/Resources/Misc/resources-wide/test5.txt rename to tests/test-cpp/Resources/Misc/resources-wide/test5.txt diff --git a/samples/Cpp/TestCpp/Resources/Misc/resources-widehd/test3.txt b/tests/test-cpp/Resources/Misc/resources-widehd/test3.txt similarity index 100% rename from samples/Cpp/TestCpp/Resources/Misc/resources-widehd/test3.txt rename to tests/test-cpp/Resources/Misc/resources-widehd/test3.txt diff --git a/samples/Cpp/TestCpp/Resources/Misc/searchpath1/file1.txt b/tests/test-cpp/Resources/Misc/searchpath1/file1.txt similarity index 100% rename from samples/Cpp/TestCpp/Resources/Misc/searchpath1/file1.txt rename to tests/test-cpp/Resources/Misc/searchpath1/file1.txt diff --git a/samples/Cpp/TestCpp/Resources/Misc/searchpath2/resources-ipad/file2.txt b/tests/test-cpp/Resources/Misc/searchpath2/resources-ipad/file2.txt similarity index 100% rename from samples/Cpp/TestCpp/Resources/Misc/searchpath2/resources-ipad/file2.txt rename to tests/test-cpp/Resources/Misc/searchpath2/resources-ipad/file2.txt diff --git a/samples/Cpp/TestCpp/Resources/Shaders/example_ColorBars.vsh b/tests/test-cpp/Resources/Shaders/example_ColorBars.vsh similarity index 100% rename from samples/Cpp/TestCpp/Resources/Shaders/example_ColorBars.vsh rename to tests/test-cpp/Resources/Shaders/example_ColorBars.vsh diff --git a/samples/Cpp/TestCpp/Resources/Shaders/example_Flower.vsh b/tests/test-cpp/Resources/Shaders/example_Flower.vsh similarity index 100% rename from samples/Cpp/TestCpp/Resources/Shaders/example_Flower.vsh rename to tests/test-cpp/Resources/Shaders/example_Flower.vsh diff --git a/samples/Cpp/TestCpp/Resources/Shaders/example_Heart.vsh b/tests/test-cpp/Resources/Shaders/example_Heart.vsh similarity index 100% rename from samples/Cpp/TestCpp/Resources/Shaders/example_Heart.vsh rename to tests/test-cpp/Resources/Shaders/example_Heart.vsh diff --git a/samples/Cpp/TestCpp/Resources/Shaders/example_Julia.vsh b/tests/test-cpp/Resources/Shaders/example_Julia.vsh similarity index 100% rename from samples/Cpp/TestCpp/Resources/Shaders/example_Julia.vsh rename to tests/test-cpp/Resources/Shaders/example_Julia.vsh diff --git a/samples/Cpp/TestCpp/Resources/Shaders/example_Mandelbrot.vsh b/tests/test-cpp/Resources/Shaders/example_Mandelbrot.vsh similarity index 100% rename from samples/Cpp/TestCpp/Resources/Shaders/example_Mandelbrot.vsh rename to tests/test-cpp/Resources/Shaders/example_Mandelbrot.vsh diff --git a/samples/Cpp/TestCpp/Resources/Shaders/example_Monjori.vsh b/tests/test-cpp/Resources/Shaders/example_Monjori.vsh similarity index 100% rename from samples/Cpp/TestCpp/Resources/Shaders/example_Monjori.vsh rename to tests/test-cpp/Resources/Shaders/example_Monjori.vsh diff --git a/samples/Cpp/TestCpp/Resources/Shaders/example_Plasma.vsh b/tests/test-cpp/Resources/Shaders/example_Plasma.vsh similarity index 100% rename from samples/Cpp/TestCpp/Resources/Shaders/example_Plasma.vsh rename to tests/test-cpp/Resources/Shaders/example_Plasma.vsh diff --git a/samples/Cpp/TestCpp/Resources/Shaders/example_Twist.vsh b/tests/test-cpp/Resources/Shaders/example_Twist.vsh similarity index 100% rename from samples/Cpp/TestCpp/Resources/Shaders/example_Twist.vsh rename to tests/test-cpp/Resources/Shaders/example_Twist.vsh diff --git a/samples/Cpp/TestCpp/Resources/TileMaps/hexa-tiles.png.REMOVED.git-id b/tests/test-cpp/Resources/TileMaps/hexa-tiles.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/TileMaps/hexa-tiles.png.REMOVED.git-id rename to tests/test-cpp/Resources/TileMaps/hexa-tiles.png.REMOVED.git-id diff --git a/tests/test-cpp/Resources/TileMaps/map/slcj.png.REMOVED.git-id b/tests/test-cpp/Resources/TileMaps/map/slcj.png.REMOVED.git-id new file mode 100644 index 0000000000..c7ca23a772 --- /dev/null +++ b/tests/test-cpp/Resources/TileMaps/map/slcj.png.REMOVED.git-id @@ -0,0 +1 @@ +64ce8a88d0dee73cf5d9fbb8f3c80673c82b9575 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Resources/TileMaps/ortho-test1.png.REMOVED.git-id b/tests/test-cpp/Resources/TileMaps/ortho-test1.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/TileMaps/ortho-test1.png.REMOVED.git-id rename to tests/test-cpp/Resources/TileMaps/ortho-test1.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/TileMaps/ortho-test1_bw.png.REMOVED.git-id b/tests/test-cpp/Resources/TileMaps/ortho-test1_bw.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/TileMaps/ortho-test1_bw.png.REMOVED.git-id rename to tests/test-cpp/Resources/TileMaps/ortho-test1_bw.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/animations/grossini.plist.xml b/tests/test-cpp/Resources/animations/grossini.plist.xml similarity index 100% rename from samples/Cpp/TestCpp/Resources/animations/grossini.plist.xml rename to tests/test-cpp/Resources/animations/grossini.plist.xml diff --git a/samples/Cpp/TestCpp/Resources/armature/Cowboy.ExportJson.REMOVED.git-id b/tests/test-cpp/Resources/armature/Cowboy.ExportJson.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/armature/Cowboy.ExportJson.REMOVED.git-id rename to tests/test-cpp/Resources/armature/Cowboy.ExportJson.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/armature/Cowboy0.png.REMOVED.git-id b/tests/test-cpp/Resources/armature/Cowboy0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/armature/Cowboy0.png.REMOVED.git-id rename to tests/test-cpp/Resources/armature/Cowboy0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/armature/Dragon.xml b/tests/test-cpp/Resources/armature/Dragon.xml similarity index 100% rename from samples/Cpp/TestCpp/Resources/armature/Dragon.xml rename to tests/test-cpp/Resources/armature/Dragon.xml diff --git a/samples/Cpp/TestCpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id b/tests/test-cpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id rename to tests/test-cpp/Resources/armature/HeroAnimation.ExportJson.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/armature/cyborg.xml b/tests/test-cpp/Resources/armature/cyborg.xml similarity index 100% rename from samples/Cpp/TestCpp/Resources/armature/cyborg.xml rename to tests/test-cpp/Resources/armature/cyborg.xml diff --git a/samples/Cpp/TestCpp/Resources/armature/knight.xml b/tests/test-cpp/Resources/armature/knight.xml similarity index 100% rename from samples/Cpp/TestCpp/Resources/armature/knight.xml rename to tests/test-cpp/Resources/armature/knight.xml diff --git a/samples/Cpp/TestCpp/Resources/armature/robot.xml b/tests/test-cpp/Resources/armature/robot.xml similarity index 100% rename from samples/Cpp/TestCpp/Resources/armature/robot.xml rename to tests/test-cpp/Resources/armature/robot.xml diff --git a/samples/Cpp/TestCpp/Resources/armature/weapon.xml b/tests/test-cpp/Resources/armature/weapon.xml similarity index 100% rename from samples/Cpp/TestCpp/Resources/armature/weapon.xml rename to tests/test-cpp/Resources/armature/weapon.xml diff --git a/samples/Cpp/SimpleGame/Resources/background-music-aac.wav.REMOVED.git-id b/tests/test-cpp/Resources/background-music-aac.wav.REMOVED.git-id similarity index 100% rename from samples/Cpp/SimpleGame/Resources/background-music-aac.wav.REMOVED.git-id rename to tests/test-cpp/Resources/background-music-aac.wav.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/background.mp3.REMOVED.git-id b/tests/test-cpp/Resources/background.mp3.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/background.mp3.REMOVED.git-id rename to tests/test-cpp/Resources/background.mp3.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/ccb/flower.jpg.REMOVED.git-id b/tests/test-cpp/Resources/ccb/flower.jpg.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/ccb/flower.jpg.REMOVED.git-id rename to tests/test-cpp/Resources/ccb/flower.jpg.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/ccb/gem-0.wav.REMOVED.git-id b/tests/test-cpp/Resources/ccb/gem-0.wav.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/ccb/gem-0.wav.REMOVED.git-id rename to tests/test-cpp/Resources/ccb/gem-0.wav.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/ccb/gem-1.wav.REMOVED.git-id b/tests/test-cpp/Resources/ccb/gem-1.wav.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/ccb/gem-1.wav.REMOVED.git-id rename to tests/test-cpp/Resources/ccb/gem-1.wav.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/ccb/markerfelt24shadow.fnt.REMOVED.git-id b/tests/test-cpp/Resources/ccb/markerfelt24shadow.fnt.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/ccb/markerfelt24shadow.fnt.REMOVED.git-id rename to tests/test-cpp/Resources/ccb/markerfelt24shadow.fnt.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/cocosgui/Hello.png.REMOVED.git-id b/tests/test-cpp/Resources/cocosgui/Hello.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/cocosgui/Hello.png.REMOVED.git-id rename to tests/test-cpp/Resources/cocosgui/Hello.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/cocosgui/UITest/background.png.REMOVED.git-id b/tests/test-cpp/Resources/cocosgui/UITest/background.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/cocosgui/UITest/background.png.REMOVED.git-id rename to tests/test-cpp/Resources/cocosgui/UITest/background.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/cocosgui/b11.png.REMOVED.git-id b/tests/test-cpp/Resources/cocosgui/b11.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/cocosgui/b11.png.REMOVED.git-id rename to tests/test-cpp/Resources/cocosgui/b11.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/cocosgui/bitmapFontTest2.png.REMOVED.git-id b/tests/test-cpp/Resources/cocosgui/bitmapFontTest2.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/cocosgui/bitmapFontTest2.png.REMOVED.git-id rename to tests/test-cpp/Resources/cocosgui/bitmapFontTest2.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/cocosgui/examples/examples.json.REMOVED.git-id b/tests/test-cpp/Resources/cocosgui/examples/examples.json.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/cocosgui/examples/examples.json.REMOVED.git-id rename to tests/test-cpp/Resources/cocosgui/examples/examples.json.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/cocosgui/gui_examples/map_1/map_pve.png.REMOVED.git-id b/tests/test-cpp/Resources/cocosgui/gui_examples/map_1/map_pve.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/cocosgui/gui_examples/map_1/map_pve.png.REMOVED.git-id rename to tests/test-cpp/Resources/cocosgui/gui_examples/map_1/map_pve.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/cocosgui/gui_examples/page_1/background.png.REMOVED.git-id b/tests/test-cpp/Resources/cocosgui/gui_examples/page_1/background.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/cocosgui/gui_examples/page_1/background.png.REMOVED.git-id rename to tests/test-cpp/Resources/cocosgui/gui_examples/page_1/background.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/extensions/background.png.REMOVED.git-id b/tests/test-cpp/Resources/extensions/background.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/extensions/background.png.REMOVED.git-id rename to tests/test-cpp/Resources/extensions/background.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/Courier New.ttf.REMOVED.git-id b/tests/test-cpp/Resources/fonts/Courier New.ttf.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/Courier New.ttf.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/Courier New.ttf.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/Thonburi.ttf.REMOVED.git-id b/tests/test-cpp/Resources/fonts/Thonburi.ttf.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/Thonburi.ttf.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/Thonburi.ttf.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/ThonburiBold.ttf.REMOVED.git-id b/tests/test-cpp/Resources/fonts/ThonburiBold.ttf.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/ThonburiBold.ttf.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/ThonburiBold.ttf.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/arial-26-en-ru_0.png.REMOVED.git-id b/tests/test-cpp/Resources/fonts/arial-26-en-ru_0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/arial-26-en-ru_0.png.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/arial-26-en-ru_0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/arial-unicode-26.GlyphProject b/tests/test-cpp/Resources/fonts/arial-unicode-26.GlyphProject similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/arial-unicode-26.GlyphProject rename to tests/test-cpp/Resources/fonts/arial-unicode-26.GlyphProject diff --git a/samples/Cpp/TestCpp/Resources/fonts/arial-unicode-26.png.REMOVED.git-id b/tests/test-cpp/Resources/fonts/arial-unicode-26.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/arial-unicode-26.png.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/arial-unicode-26.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/arial.ttf.REMOVED.git-id b/tests/test-cpp/Resources/fonts/arial.ttf.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/arial.ttf.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/arial.ttf.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/bitmapFontChinese.png.REMOVED.git-id b/tests/test-cpp/Resources/fonts/bitmapFontChinese.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/bitmapFontChinese.png.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/bitmapFontChinese.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/bitmapFontTest.png.REMOVED.git-id b/tests/test-cpp/Resources/fonts/bitmapFontTest.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/bitmapFontTest.png.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/bitmapFontTest.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/bitmapFontTest2.bmp.REMOVED.git-id b/tests/test-cpp/Resources/fonts/bitmapFontTest2.bmp.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/bitmapFontTest2.bmp.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/bitmapFontTest2.bmp.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/bitmapFontTest2.png.REMOVED.git-id b/tests/test-cpp/Resources/fonts/bitmapFontTest2.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/bitmapFontTest2.png.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/bitmapFontTest2.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/boundsTestFont.png.REMOVED.git-id b/tests/test-cpp/Resources/fonts/boundsTestFont.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/boundsTestFont.png.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/boundsTestFont.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/font-issue1343-hd.png.REMOVED.git-id b/tests/test-cpp/Resources/fonts/font-issue1343-hd.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/font-issue1343-hd.png.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/font-issue1343-hd.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/futura-48.png.REMOVED.git-id b/tests/test-cpp/Resources/fonts/futura-48.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/futura-48.png.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/futura-48.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/helvetica-geneva-32.png.REMOVED.git-id b/tests/test-cpp/Resources/fonts/helvetica-geneva-32.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/helvetica-geneva-32.png.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/helvetica-geneva-32.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/markerFelt.fnt.REMOVED.git-id b/tests/test-cpp/Resources/fonts/markerFelt.fnt.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/markerFelt.fnt.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/markerFelt.fnt.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/strings.xml b/tests/test-cpp/Resources/fonts/strings.xml similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/strings.xml rename to tests/test-cpp/Resources/fonts/strings.xml diff --git a/samples/Cpp/TestCpp/Resources/fonts/tahoma.ttf.REMOVED.git-id b/tests/test-cpp/Resources/fonts/tahoma.ttf.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/tahoma.ttf.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/tahoma.ttf.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/fonts/wt021.ttf.REMOVED.git-id b/tests/test-cpp/Resources/fonts/wt021.ttf.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/fonts/wt021.ttf.REMOVED.git-id rename to tests/test-cpp/Resources/fonts/wt021.ttf.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/Images/background1.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/Images/background1.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/Images/background1.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/Images/background1.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/Images/background2.jpg.REMOVED.git-id b/tests/test-cpp/Resources/hd/Images/background2.jpg.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/Images/background2.jpg.REMOVED.git-id rename to tests/test-cpp/Resources/hd/Images/background2.jpg.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/Images/background2.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/Images/background2.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/Images/background2.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/Images/background2.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/armature/Cowboy0.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/armature/Cowboy0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/armature/Cowboy0.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/armature/Cowboy0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/armature/Dragon.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/armature/Dragon.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/armature/Dragon.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/armature/Dragon.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/armature/HeroAnimation0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/armature/weapon.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/armature/weapon.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/armature/weapon.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/armature/weapon.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/ccb/burst.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/ccb/burst.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/ccb/burst.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/ccb/burst.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/cocosgui/Hello.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/cocosgui/Hello.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/cocosgui/Hello.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/cocosgui/Hello.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/cocosgui/UITest/background.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/cocosgui/UITest/background.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/cocosgui/UITest/background.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/cocosgui/UITest/background.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/cocosgui/b11.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/cocosgui/b11.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/cocosgui/b11.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/cocosgui/b11.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/cocosgui/bitmapFontTest2.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/cocosgui/bitmapFontTest2.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/cocosgui/bitmapFontTest2.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/cocosgui/bitmapFontTest2.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/cocosgui/examples/examples.json.REMOVED.git-id b/tests/test-cpp/Resources/hd/cocosgui/examples/examples.json.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/cocosgui/examples/examples.json.REMOVED.git-id rename to tests/test-cpp/Resources/hd/cocosgui/examples/examples.json.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/cocosgui/gui_examples/map_1/map_pve.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/cocosgui/gui_examples/map_1/map_pve.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/cocosgui/gui_examples/map_1/map_pve.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/cocosgui/gui_examples/map_1/map_pve.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/cocosgui/gui_examples/page_1/background.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/cocosgui/gui_examples/page_1/background.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/cocosgui/gui_examples/page_1/background.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/cocosgui/gui_examples/page_1/background.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/extensions/background.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/extensions/background.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/extensions/background.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/extensions/background.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/fonts/font-issue1343.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/fonts/font-issue1343.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/fonts/font-issue1343.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/fonts/font-issue1343.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/fonts/markerFelt.fnt.REMOVED.git-id b/tests/test-cpp/Resources/hd/fonts/markerFelt.fnt.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/fonts/markerFelt.fnt.REMOVED.git-id rename to tests/test-cpp/Resources/hd/fonts/markerFelt.fnt.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/fonts/markerFelt.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/fonts/markerFelt.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/fonts/markerFelt.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/fonts/markerFelt.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/fonts/tuffy_bold_italic-charmap.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/fonts/tuffy_bold_italic-charmap.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/fonts/tuffy_bold_italic-charmap.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/fonts/tuffy_bold_italic-charmap.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/ArmatureComponentTest/Images/startMenuBG.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/ArmatureComponentTest/Images/startMenuBG.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/ArmatureComponentTest/Images/startMenuBG.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/ArmatureComponentTest/Images/startMenuBG.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/BackgroundComponentTest/Images/startMenuBG.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/BackgroundComponentTest/Images/startMenuBG.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/BackgroundComponentTest/Images/startMenuBG.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/BackgroundComponentTest/Images/startMenuBG.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/BackgroundComponentTest/Misc/music_logo.mp3.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/BackgroundComponentTest/Misc/music_logo.mp3.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/BackgroundComponentTest/Misc/music_logo.mp3.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/BackgroundComponentTest/Misc/music_logo.mp3.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/BackgroundComponentTest/Misc/music_logo.wav.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/BackgroundComponentTest/Misc/music_logo.wav.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/BackgroundComponentTest/Misc/music_logo.wav.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/BackgroundComponentTest/Misc/music_logo.wav.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/BackgroundComponentTest/startMenu/Fish_UI/starMenuButton01.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/BackgroundComponentTest/startMenu/Fish_UI/starMenuButton01.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/BackgroundComponentTest/startMenu/Fish_UI/starMenuButton01.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/BackgroundComponentTest/startMenu/Fish_UI/starMenuButton01.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/BackgroundComponentTest/startMenu/Fish_UI/starMenuButton02.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/BackgroundComponentTest/startMenu/Fish_UI/starMenuButton02.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/BackgroundComponentTest/startMenu/Fish_UI/starMenuButton02.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/BackgroundComponentTest/startMenu/Fish_UI/starMenuButton02.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/BackgroundComponentTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/BackgroundComponentTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/BackgroundComponentTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/BackgroundComponentTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/EffectComponentTest/CowBoy/Cowboy.ExportJson.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/EffectComponentTest/CowBoy/Cowboy.ExportJson.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/EffectComponentTest/CowBoy/Cowboy.ExportJson.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/EffectComponentTest/CowBoy/Cowboy.ExportJson.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/EffectComponentTest/CowBoy/Cowboy0.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/EffectComponentTest/CowBoy/Cowboy0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/EffectComponentTest/CowBoy/Cowboy0.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/EffectComponentTest/CowBoy/Cowboy0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/Images/startMenuBG.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/Images/startMenuBG.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/Images/startMenuBG.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/Images/startMenuBG.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.mp3.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.mp3.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.mp3.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.mp3.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.wav.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.wav.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.wav.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.wav.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/starMenuButton01.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/starMenuButton01.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/starMenuButton01.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/starMenuButton01.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/starMenuButton02.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/starMenuButton02.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/starMenuButton02.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/starMenuButton02.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/TriggerTest/Images/startMenuBG.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/TriggerTest/Images/startMenuBG.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/TriggerTest/Images/startMenuBG.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/TriggerTest/Images/startMenuBG.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/TriggerTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/TriggerTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/TriggerTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/TriggerTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/UIComponentTest/Images/startMenuBG.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/UIComponentTest/Images/startMenuBG.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/UIComponentTest/Images/startMenuBG.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/UIComponentTest/Images/startMenuBG.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/scenetest/UIComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/scenetest/UIComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/scenetest/UIComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/scenetest/UIComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/spine/goblins.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/spine/goblins.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/spine/goblins.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/spine/goblins.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/hd/spine/spineboy.png.REMOVED.git-id b/tests/test-cpp/Resources/hd/spine/spineboy.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/hd/spine/spineboy.png.REMOVED.git-id rename to tests/test-cpp/Resources/hd/spine/spineboy.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/ipad/ccb/burst.png.REMOVED.git-id b/tests/test-cpp/Resources/ipad/ccb/burst.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/ipad/ccb/burst.png.REMOVED.git-id rename to tests/test-cpp/Resources/ipad/ccb/burst.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/ipad/extensions/background.png.REMOVED.git-id b/tests/test-cpp/Resources/ipad/extensions/background.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/ipad/extensions/background.png.REMOVED.git-id rename to tests/test-cpp/Resources/ipad/extensions/background.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/ArmatureComponentTest/Images/startMenuBG.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/ArmatureComponentTest/Images/startMenuBG.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/ArmatureComponentTest/Images/startMenuBG.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/ArmatureComponentTest/Images/startMenuBG.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/BackgroundComponentTest/Images/startMenuBG.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/BackgroundComponentTest/Images/startMenuBG.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/BackgroundComponentTest/Images/startMenuBG.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/BackgroundComponentTest/Images/startMenuBG.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/BackgroundComponentTest/Misc/music_logo.mp3.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/BackgroundComponentTest/Misc/music_logo.mp3.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/BackgroundComponentTest/Misc/music_logo.mp3.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/BackgroundComponentTest/Misc/music_logo.mp3.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/BackgroundComponentTest/Misc/music_logo.wav.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/BackgroundComponentTest/Misc/music_logo.wav.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/BackgroundComponentTest/Misc/music_logo.wav.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/BackgroundComponentTest/Misc/music_logo.wav.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/BackgroundComponentTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/BackgroundComponentTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/BackgroundComponentTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/BackgroundComponentTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/EffectComponentTest/CowBoy/Cowboy.ExportJson.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/EffectComponentTest/CowBoy/Cowboy.ExportJson.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/EffectComponentTest/CowBoy/Cowboy.ExportJson.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/EffectComponentTest/CowBoy/Cowboy.ExportJson.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/EffectComponentTest/CowBoy/Cowboy0.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/EffectComponentTest/CowBoy/Cowboy0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/EffectComponentTest/CowBoy/Cowboy0.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/EffectComponentTest/CowBoy/Cowboy0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/LoadSceneEdtiorFileTest/Images/startMenuBG.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/LoadSceneEdtiorFileTest/Images/startMenuBG.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/LoadSceneEdtiorFileTest/Images/startMenuBG.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/LoadSceneEdtiorFileTest/Images/startMenuBG.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.mp3.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.mp3.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.mp3.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.mp3.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.wav.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.wav.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.wav.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.wav.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/ui_logo_001-hd.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/TriggerTest/Images/startMenuBG.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/TriggerTest/Images/startMenuBG.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/TriggerTest/Images/startMenuBG.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/TriggerTest/Images/startMenuBG.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/TriggerTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/TriggerTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/TriggerTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/TriggerTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/UIComponentTest/Images/startMenuBG.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/UIComponentTest/Images/startMenuBG.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/UIComponentTest/Images/startMenuBG.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/UIComponentTest/Images/startMenuBG.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/scenetest/UIComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id b/tests/test-cpp/Resources/scenetest/UIComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/scenetest/UIComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id rename to tests/test-cpp/Resources/scenetest/UIComponentTest/fishes/blowFish/Blowfish0.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/Resources/spine/goblins.png.REMOVED.git-id b/tests/test-cpp/Resources/spine/goblins.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/Resources/spine/goblins.png.REMOVED.git-id rename to tests/test-cpp/Resources/spine/goblins.png.REMOVED.git-id diff --git a/samples/Cpp/HelloCpp/proj.android/.classpath b/tests/test-cpp/proj.android/.classpath similarity index 100% rename from samples/Cpp/HelloCpp/proj.android/.classpath rename to tests/test-cpp/proj.android/.classpath diff --git a/samples/Lua/HelloLua/proj.android/.project b/tests/test-cpp/proj.android/.project similarity index 86% rename from samples/Lua/HelloLua/proj.android/.project rename to tests/test-cpp/proj.android/.project index 2a61577d0c..3993dc62b8 100644 --- a/samples/Lua/HelloLua/proj.android/.project +++ b/tests/test-cpp/proj.android/.project @@ -1,6 +1,6 @@ - HelloLua + TestCpp @@ -40,11 +40,4 @@ org.eclipse.cdt.managedbuilder.core.managedBuildNature org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - - Resources - 2 - PARENT-1-PROJECT_LOC/Resources - - diff --git a/samples/Cpp/TestCpp/proj.android/AndroidManifest.xml b/tests/test-cpp/proj.android/AndroidManifest.xml similarity index 94% rename from samples/Cpp/TestCpp/proj.android/AndroidManifest.xml rename to tests/test-cpp/proj.android/AndroidManifest.xml index 48c245c963..2d00af9411 100644 --- a/samples/Cpp/TestCpp/proj.android/AndroidManifest.xml +++ b/tests/test-cpp/proj.android/AndroidManifest.xml @@ -14,7 +14,7 @@ android:label="@string/app_name" android:screenOrientation="landscape" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" - android:configChanges="orientation|screenSize|smallestScreenSize"> + android:configChanges="orientation"> + @class RootViewController; -@interface AppController : NSObject { +@interface AppController : NSObject { UIWindow *window; RootViewController *viewController; } diff --git a/samples/Lua/HelloLua/proj.ios/AppController.mm b/tests/test-cpp/proj.ios/Classes/testsAppDelegate.mm similarity index 79% rename from samples/Lua/HelloLua/proj.ios/AppController.mm rename to tests/test-cpp/proj.ios/Classes/testsAppDelegate.mm index e87a13dbc9..43bedbcabb 100644 --- a/samples/Lua/HelloLua/proj.ios/AppController.mm +++ b/tests/test-cpp/proj.ios/Classes/testsAppDelegate.mm @@ -1,18 +1,19 @@ /**************************************************************************** - Copyright (c) 2010 cocos2d-x.org - + Copyright (c) 2013 cocos2d-x.org + Copyright (c) 2013-2014 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 @@ -21,12 +22,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#import -#import "AppController.h" -#import "cocos2d.h" -#import "EAGLView.h" -#import "AppDelegate.h" +#import "testsAppDelegate.h" + +#import "CCEAGLView.h" +#import "cocos2d.h" +#import "AppDelegate.h" #import "RootViewController.h" @implementation AppController @@ -37,24 +38,31 @@ // cocos2d application instance static AppDelegate s_sharedApplication; -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ + + cocos2d::Application *app = cocos2d::Application::getInstance(); + // Override point for customization after application launch. // Add the view controller's view to the window and display. window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; - CCEAGLView *__glView = [CCEAGLView viewWithFrame: [window bounds] - pixelFormat: kEAGLColorFormatRGBA8 - depthFormat: GL_DEPTH_COMPONENT16 - preserveBackbuffer: NO - sharegroup: nil - multiSampling: NO - numberOfSamples: 0 ]; + // Init the CCEAGLView + CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds] + pixelFormat: kEAGLColorFormatRGBA8 + depthFormat: GL_DEPTH24_STENCIL8_OES + preserveBackbuffer: NO + sharegroup: nil + multiSampling: NO + numberOfSamples: 0 ]; + + [eaglView setMultipleTouchEnabled:YES]; + // Use RootViewController manage CCEAGLView viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; viewController.wantsFullScreenLayout = YES; - viewController.view = __glView; + viewController.view = eaglView; // Set RootViewController to window if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) @@ -69,10 +77,15 @@ static AppDelegate s_sharedApplication; } [window makeKeyAndVisible]; - - [[UIApplication sharedApplication] setStatusBarHidden: YES]; - cocos2d::Application::getInstance()->run(); + [[UIApplication sharedApplication] setStatusBarHidden:true]; + + // IMPORTANT: Setting the GLView should be done after creating the RootViewController + cocos2d::GLView *glview = cocos2d::GLView::createWithEAGLView(eaglView); + cocos2d::Director::getInstance()->setOpenGLView(glview); + + app->run(); + return YES; } @@ -126,9 +139,9 @@ static AppDelegate s_sharedApplication; - (void)dealloc { + [window release]; [super dealloc]; } @end - diff --git a/samples/Cpp/HelloCpp/proj.ios/Default-568h@2x.png.REMOVED.git-id b/tests/test-cpp/proj.ios/Default-568h@2x.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/HelloCpp/proj.ios/Default-568h@2x.png.REMOVED.git-id rename to tests/test-cpp/proj.ios/Default-568h@2x.png.REMOVED.git-id diff --git a/samples/Cpp/HelloCpp/proj.ios/Default@2x.png.REMOVED.git-id b/tests/test-cpp/proj.ios/Default@2x.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/HelloCpp/proj.ios/Default@2x.png.REMOVED.git-id rename to tests/test-cpp/proj.ios/Default@2x.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/proj.ios/iphone_Prefix.pch b/tests/test-cpp/proj.ios/iphone_Prefix.pch similarity index 100% rename from samples/Cpp/TestCpp/proj.ios/iphone_Prefix.pch rename to tests/test-cpp/proj.ios/iphone_Prefix.pch diff --git a/samples/Cpp/TestCpp/proj.ios/main.m b/tests/test-cpp/proj.ios/main.m similarity index 100% rename from samples/Cpp/TestCpp/proj.ios/main.m rename to tests/test-cpp/proj.ios/main.m diff --git a/samples/Lua/HelloLua/proj.linux/main.cpp b/tests/test-cpp/proj.linux/main.cpp similarity index 83% rename from samples/Lua/HelloLua/proj.linux/main.cpp rename to tests/test-cpp/proj.linux/main.cpp index fee36d74ed..e420889600 100644 --- a/samples/Lua/HelloLua/proj.linux/main.cpp +++ b/tests/test-cpp/proj.linux/main.cpp @@ -12,7 +12,5 @@ int main(int argc, char **argv) { // create the application instance AppDelegate app; - EGLView eglView; - eglView.init("HelloLua",900,640); return Application::getInstance()->run(); } diff --git a/samples/Cpp/HelloCpp/proj.mac/Icon.icns.REMOVED.git-id b/tests/test-cpp/proj.mac/Icon.icns.REMOVED.git-id similarity index 100% rename from samples/Cpp/HelloCpp/proj.mac/Icon.icns.REMOVED.git-id rename to tests/test-cpp/proj.mac/Icon.icns.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/proj.mac/Test_Prefix.pch b/tests/test-cpp/proj.mac/Test_Prefix.pch similarity index 100% rename from samples/Cpp/TestCpp/proj.mac/Test_Prefix.pch rename to tests/test-cpp/proj.mac/Test_Prefix.pch diff --git a/samples/Cpp/HelloCpp/proj.mac/en.lproj/InfoPlist.strings b/tests/test-cpp/proj.mac/en.lproj/InfoPlist.strings similarity index 100% rename from samples/Cpp/HelloCpp/proj.mac/en.lproj/InfoPlist.strings rename to tests/test-cpp/proj.mac/en.lproj/InfoPlist.strings diff --git a/samples/Cpp/TestCpp/proj.mac/en.lproj/MainMenu.xib b/tests/test-cpp/proj.mac/en.lproj/MainMenu.xib similarity index 100% rename from samples/Cpp/TestCpp/proj.mac/en.lproj/MainMenu.xib rename to tests/test-cpp/proj.mac/en.lproj/MainMenu.xib diff --git a/samples/Cpp/TestCpp/proj.mac/main.cpp b/tests/test-cpp/proj.mac/main.cpp similarity index 94% rename from samples/Cpp/TestCpp/proj.mac/main.cpp rename to tests/test-cpp/proj.mac/main.cpp index 061f7b6874..1814d16c15 100644 --- a/samples/Cpp/TestCpp/proj.mac/main.cpp +++ b/tests/test-cpp/proj.mac/main.cpp @@ -23,14 +23,11 @@ ****************************************************************************/ #include "AppDelegate.h" -#include "CCEGLView.h" USING_NS_CC; int main(int argc, char *argv[]) { AppDelegate app; - EGLView eglView; - eglView.init("TestCPP",900,640); return Application::getInstance()->run(); } diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj b/tests/test-cpp/proj.win32/TestCpp.vcxproj similarity index 94% rename from samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj rename to tests/test-cpp/proj.win32/TestCpp.vcxproj index 2815c3c7f3..df8f3b6dc7 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj +++ b/tests/test-cpp/proj.win32/TestCpp.vcxproj @@ -36,13 +36,13 @@ - - + + - - + + @@ -94,7 +94,7 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" @@ -130,7 +130,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" @@ -186,8 +186,12 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ + + + + @@ -331,8 +335,13 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ + + + + + @@ -476,41 +485,41 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} false - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} false - + {811c0dab-7b96-4bd3-a154-b7572b58e4ab} - + {b57cf53f-2e49-4031-9822-047cc0e6bde2} - + {b7c2a162-dec9-4418-972e-240ab3cbfcae} - + {7e06e92c-537a-442b-9e4a-4761c84f8a1a} - + {df2638c0-8128-4847-867c-6eafe3dee7b5} - + {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} - + {21b2c324-891f-48ea-ad1a-5ae13de12e28} false - + {929480e7-23c0-4df6-8456-096d71547116} false - + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} false diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters b/tests/test-cpp/proj.win32/TestCpp.vcxproj.filters similarity index 97% rename from samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters rename to tests/test-cpp/proj.win32/TestCpp.vcxproj.filters index a6990872b6..2600ec0428 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters +++ b/tests/test-cpp/proj.win32/TestCpp.vcxproj.filters @@ -307,6 +307,9 @@ {5ff3af4e-0610-480b-b297-8f407e12f369} + + {f71fab28-32be-45c9-a941-9a22b5a59e51} + @@ -715,6 +718,18 @@ Classes\ExtensionsTest\CocoStudioSceneTest\TriggerCode + + Classes\PerformanceTest + + + Classes\PerformanceTest + + + Classes\ReleasePoolTest + + + Classes\PerformanceTest + @@ -1318,5 +1333,20 @@ Classes\ExtensionsTest\CocoStudioSceneTest\TriggerCode + + Classes\PerformanceTest + + + Classes\PerformanceTest + + + Classes\PerformanceTest + + + Classes\ReleasePoolTest + + + Classes\PerformanceTest + \ No newline at end of file diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.user b/tests/test-cpp/proj.win32/TestCpp.vcxproj.user similarity index 100% rename from samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.user rename to tests/test-cpp/proj.win32/TestCpp.vcxproj.user diff --git a/samples/Cpp/TestCpp/proj.win32/main.cpp b/tests/test-cpp/proj.win32/main.cpp similarity index 84% rename from samples/Cpp/TestCpp/proj.win32/main.cpp rename to tests/test-cpp/proj.win32/main.cpp index 8411246122..46ce5bf290 100644 --- a/samples/Cpp/TestCpp/proj.win32/main.cpp +++ b/tests/test-cpp/proj.win32/main.cpp @@ -1,6 +1,5 @@ #include "main.h" #include "AppDelegate.h" -#include "CCEGLView.h" USING_NS_CC; @@ -14,7 +13,5 @@ int APIENTRY _tWinMain(HINSTANCE hInstance, // create the application instance AppDelegate app; - EGLView eglView; - eglView.init("TestCPP",960,640); return Application::getInstance()->run(); } diff --git a/samples/Cpp/HelloCpp/proj.win32/main.h b/tests/test-cpp/proj.win32/main.h similarity index 100% rename from samples/Cpp/HelloCpp/proj.win32/main.h rename to tests/test-cpp/proj.win32/main.h diff --git a/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp b/tests/test-javascript/Classes/AppDelegate.cpp similarity index 84% rename from samples/Javascript/TestJavascript/Classes/AppDelegate.cpp rename to tests/test-javascript/Classes/AppDelegate.cpp index d5d37f513a..ffe11134d4 100644 --- a/samples/Javascript/TestJavascript/Classes/AppDelegate.cpp +++ b/tests/test-javascript/Classes/AppDelegate.cpp @@ -37,16 +37,20 @@ AppDelegate::~AppDelegate() bool AppDelegate::applicationDidFinishLaunching() { // initialize director - auto pDirector = Director::getInstance(); - pDirector->setOpenGLView(EGLView::getInstance()); + auto director = Director::getInstance(); + auto glview = director->getOpenGLView(); + if(!glview) { + glview = GLView::createWithRect("Test JavaScript", Rect(0,0,900,640)); + director->setOpenGLView(glview); + } // JS-Test in Html5 uses 800x450 as design resolution - EGLView::getInstance()->setDesignResolutionSize(800, 450, ResolutionPolicy::FIXED_HEIGHT); + glview->setDesignResolutionSize(800, 450, ResolutionPolicy::FIXED_HEIGHT); // turn on display FPS - pDirector->setDisplayStats(true); + director->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this - pDirector->setAnimationInterval(1.0 / 60); + director->setAnimationInterval(1.0 / 60); auto fileUtils = FileUtils::getInstance(); std::vector searchPaths; @@ -121,26 +125,6 @@ bool AppDelegate::applicationDidFinishLaunching() return true; } -void handle_signal(int signal) { - static int internal_state = 0; - ScriptingCore* sc = ScriptingCore::getInstance(); - // should start everything back - auto director = Director::getInstance(); - if (director->getRunningScene()) { - director->popToRootScene(); - } else { - PoolManager::sharedPoolManager()->finalize(); - if (internal_state == 0) { - //sc->dumpRoot(NULL, 0, NULL); - sc->start(); - internal_state = 1; - } else { - sc->runScript("hello.js"); - internal_state = 0; - } - } -} - // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { diff --git a/samples/Javascript/CocosDragonJS/Classes/AppDelegate.h b/tests/test-javascript/Classes/AppDelegate.h similarity index 100% rename from samples/Javascript/CocosDragonJS/Classes/AppDelegate.h rename to tests/test-javascript/Classes/AppDelegate.h diff --git a/samples/Cpp/AssetsManagerTest/proj.android/.classpath b/tests/test-javascript/proj.android/.classpath similarity index 100% rename from samples/Cpp/AssetsManagerTest/proj.android/.classpath rename to tests/test-javascript/proj.android/.classpath diff --git a/samples/Cpp/HelloCpp/proj.android/.project b/tests/test-javascript/proj.android/.project similarity index 79% rename from samples/Cpp/HelloCpp/proj.android/.project rename to tests/test-javascript/proj.android/.project index 908b979a53..f7677dbac4 100644 --- a/samples/Cpp/HelloCpp/proj.android/.project +++ b/tests/test-javascript/proj.android/.project @@ -1,10 +1,15 @@ - HelloCpp + TestJavascript + + org.eclipse.wst.jsdt.core.javascriptValidator + + + com.android.ide.eclipse.adt.ResourceManagerBuilder @@ -39,22 +44,13 @@ org.eclipse.cdt.core.ccnature org.eclipse.cdt.managedbuilder.core.managedBuildNature org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + org.eclipse.wst.jsdt.core.jsNature - Classes + scripting 2 - COCOS2DX/samples/Cpp/HelloCpp/Classes - - - cocos2dx - 2 - COCOS2DX/cocos2dx - - - extensions - 2 - COCOS2DX/extensions + COCOS2DX/scripting diff --git a/samples/Javascript/TestJavascript/proj.android/AndroidManifest.xml b/tests/test-javascript/proj.android/AndroidManifest.xml similarity index 94% rename from samples/Javascript/TestJavascript/proj.android/AndroidManifest.xml rename to tests/test-javascript/proj.android/AndroidManifest.xml index 4949d888fd..32906c96bf 100644 --- a/samples/Javascript/TestJavascript/proj.android/AndroidManifest.xml +++ b/tests/test-javascript/proj.android/AndroidManifest.xml @@ -16,7 +16,7 @@ android:label="@string/app_name" android:screenOrientation="landscape" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" - android:configChanges="orientation|screenSize|smallestScreenSize"> + android:configChanges="orientation"> { +@interface AppController : NSObject +{ UIWindow *window; RootViewController *viewController; } diff --git a/samples/Lua/TestLua/proj.ios/AppController.mm b/tests/test-javascript/proj.ios/AppController.mm similarity index 90% rename from samples/Lua/TestLua/proj.ios/AppController.mm rename to tests/test-javascript/proj.ios/AppController.mm index 7ba8b26843..6e1d42e9c0 100644 --- a/samples/Lua/TestLua/proj.ios/AppController.mm +++ b/tests/test-javascript/proj.ios/AppController.mm @@ -1,5 +1,6 @@ /**************************************************************************** - Copyright (c) 2010 cocos2d-x.org + Copyright (c) 2010-2013 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -21,13 +22,14 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#import -#import "AppController.h" -#import "cocos2d.h" -#import "EAGLView.h" -#import "AppDelegate.h" +#import +#import "cocos2d.h" + +#import "AppController.h" +#import "AppDelegate.h" #import "RootViewController.h" +#import "CCEAGLView.h" @implementation AppController @@ -37,13 +39,14 @@ // cocos2d application instance static AppDelegate s_sharedApplication; -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ // Override point for customization after application launch. // Add the view controller's view to the window and display. window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; - CCEAGLView *__glView = [CCEAGLView viewWithFrame: [window bounds] + CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds] pixelFormat: kEAGLColorFormatRGBA8 depthFormat: GL_DEPTH24_STENCIL8_OES preserveBackbuffer: NO @@ -51,10 +54,12 @@ static AppDelegate s_sharedApplication; multiSampling: NO numberOfSamples: 0 ]; + [eaglView setMultipleTouchEnabled:YES]; + // Use RootViewController manage CCEAGLView viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; viewController.wantsFullScreenLayout = YES; - viewController.view = __glView; + viewController.view = eaglView; // Set RootViewController to window if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) @@ -72,6 +77,10 @@ static AppDelegate s_sharedApplication; [[UIApplication sharedApplication] setStatusBarHidden: YES]; + // IMPORTANT: Setting the GLView should be done after creating the RootViewController + cocos2d::GLView *glview = cocos2d::GLView::createWithEAGLView(eaglView); + cocos2d::Director::getInstance()->setOpenGLView(glview); + cocos2d::Application::getInstance()->run(); return YES; } diff --git a/samples/Cpp/SimpleGame/proj.ios/Default-568h@2x.png.REMOVED.git-id b/tests/test-javascript/proj.ios/Default-568h@2x.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/SimpleGame/proj.ios/Default-568h@2x.png.REMOVED.git-id rename to tests/test-javascript/proj.ios/Default-568h@2x.png.REMOVED.git-id diff --git a/samples/Cpp/SimpleGame/proj.ios/Default@2x.png.REMOVED.git-id b/tests/test-javascript/proj.ios/Default@2x.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/SimpleGame/proj.ios/Default@2x.png.REMOVED.git-id rename to tests/test-javascript/proj.ios/Default@2x.png.REMOVED.git-id diff --git a/samples/Javascript/CocosDragonJS/proj.ios/Prefix.pch b/tests/test-javascript/proj.ios/Prefix.pch similarity index 100% rename from samples/Javascript/CocosDragonJS/proj.ios/Prefix.pch rename to tests/test-javascript/proj.ios/Prefix.pch diff --git a/samples/Cpp/HelloCpp/proj.ios/RootViewController.h b/tests/test-javascript/proj.ios/RootViewController.h similarity index 100% rename from samples/Cpp/HelloCpp/proj.ios/RootViewController.h rename to tests/test-javascript/proj.ios/RootViewController.h diff --git a/samples/Javascript/CocosDragonJS/proj.ios/RootViewController.mm b/tests/test-javascript/proj.ios/RootViewController.mm similarity index 100% rename from samples/Javascript/CocosDragonJS/proj.ios/RootViewController.mm rename to tests/test-javascript/proj.ios/RootViewController.mm diff --git a/samples/Javascript/CocosDragonJS/proj.ios/main.m b/tests/test-javascript/proj.ios/main.m similarity index 100% rename from samples/Javascript/CocosDragonJS/proj.ios/main.m rename to tests/test-javascript/proj.ios/main.m diff --git a/samples/Cpp/SimpleGame/proj.mac/Icon.icns.REMOVED.git-id b/tests/test-javascript/proj.mac/Icon.icns.REMOVED.git-id similarity index 100% rename from samples/Cpp/SimpleGame/proj.mac/Icon.icns.REMOVED.git-id rename to tests/test-javascript/proj.mac/Icon.icns.REMOVED.git-id diff --git a/samples/Javascript/TestJavascript/proj.mac/Test_Prefix.pch b/tests/test-javascript/proj.mac/Test_Prefix.pch similarity index 100% rename from samples/Javascript/TestJavascript/proj.mac/Test_Prefix.pch rename to tests/test-javascript/proj.mac/Test_Prefix.pch diff --git a/samples/Cpp/SimpleGame/proj.mac/en.lproj/InfoPlist.strings b/tests/test-javascript/proj.mac/en.lproj/InfoPlist.strings similarity index 100% rename from samples/Cpp/SimpleGame/proj.mac/en.lproj/InfoPlist.strings rename to tests/test-javascript/proj.mac/en.lproj/InfoPlist.strings diff --git a/samples/Javascript/CocosDragonJS/proj.mac/en.lproj/MainMenu.xib b/tests/test-javascript/proj.mac/en.lproj/MainMenu.xib similarity index 100% rename from samples/Javascript/CocosDragonJS/proj.mac/en.lproj/MainMenu.xib rename to tests/test-javascript/proj.mac/en.lproj/MainMenu.xib diff --git a/samples/Lua/TestLua/proj.mac/main.cpp b/tests/test-javascript/proj.mac/main.cpp similarity index 94% rename from samples/Lua/TestLua/proj.mac/main.cpp rename to tests/test-javascript/proj.mac/main.cpp index 45f24c946a..4b6a1e9021 100644 --- a/samples/Lua/TestLua/proj.mac/main.cpp +++ b/tests/test-javascript/proj.mac/main.cpp @@ -23,14 +23,13 @@ ****************************************************************************/ #include "AppDelegate.h" -#include "CCEGLView.h" +#include "cocos2d.h" USING_NS_CC; int main(int argc, char *argv[]) { AppDelegate app; - EGLView eglView; - eglView.init("TestLua",900,640); return Application::getInstance()->run(); } + diff --git a/samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj b/tests/test-javascript/proj.win32/TestJavascript.vcxproj similarity index 77% rename from samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj rename to tests/test-javascript/proj.win32/TestJavascript.vcxproj index e3be6f4245..bd3083eca2 100644 --- a/samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj +++ b/tests/test-javascript/proj.win32/TestJavascript.vcxproj @@ -34,13 +34,13 @@ - - + + - - + + @@ -80,7 +80,7 @@ Disabled $(ProjectDir)..\Classes;$(EngineRoot);$(EngineRoot)cocos;$(EngineRoot)cocos\storage;$(EngineRoot)cocos\editor-support;$(EngineRoot)cocos\scripting\auto-generated\js-bindings;$(EngineRoot)cocos\scripting\javascript\bindings;$(EngineRoot)cocos\audio\include;$(EngineRoot)external\spidermonkey\include\win32;$(EngineRoot)external\chipmunk\include\chipmunk;$(EngineRoot)extensions;%(AdditionalIncludeDirectories) - WIN32;_WINDOWS;STRICT;DEBUG;_DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + WIN32;_WINDOWS;STRICT;_DEBUG;XP_WIN;JS_HAVE___INTN;JS_INTPTR_TYPE=int;COCOS2D_DEBUG=1;COCOS2D_JAVASCRIPT=1;CC_ENABLE_CHIPMUNK_INTEGRATION=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false EnableFastChecks MultiThreadedDebugDLL @@ -98,12 +98,12 @@ if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" - libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-27.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true Windows @@ -113,8 +113,8 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\TestJavascriptRes" rd /s /q "$(OutDir)\TestJavascriptRes" mkdir "$(OutDir)\TestJavascriptRes" -xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\TestJavascriptRes\" /e /Y -xcopy "$(ProjectDir)..\..\Shared\tests" "$(OutDir)\TestJavascriptRes\" /e /Y +xcopy "$(ProjectDir)..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\TestJavascriptRes\" /e /Y +xcopy "$(ProjectDir)..\tests" "$(OutDir)\TestJavascriptRes\" /e /Y Copy js and resource files. @@ -154,12 +154,12 @@ xcopy "$(ProjectDir)..\..\Shared\tests" "$(OutDir)\TestJavascriptRes\" /e /Y if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\external\spidermonkey\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" - libcurl_imp.lib;mozjs-25.0.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) + libcurl_imp.lib;mozjs-27.lib;ws2_32.lib;sqlite3.lib;websockets.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) Windows MachineX86 @@ -169,8 +169,8 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ if not exist "$(OutDir)" mkdir "$(OutDir)" if exist "$(OutDir)\TestJavascriptRes" rd /s /q "$(OutDir)\TestJavascriptRes" mkdir "$(OutDir)\TestJavascriptRes" -xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\TestJavascriptRes\" /e /Y -xcopy "$(ProjectDir)..\..\Shared\tests" "$(OutDir)\TestJavascriptRes\" /e /Y +xcopy "$(ProjectDir)..\..\..\cocos\scripting\javascript\script\*.js" "$(OutDir)\TestJavascriptRes\" /e /Y +xcopy "$(ProjectDir)..\tests" "$(OutDir)\TestJavascriptRes\" /e /Y Copy js and resource files. @@ -190,66 +190,66 @@ xcopy "$(ProjectDir)..\..\Shared\tests" "$(OutDir)\TestJavascriptRes\" /e /Y - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} false - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} false - + {811c0dab-7b96-4bd3-a154-b7572b58e4ab} - + {b57cf53f-2e49-4031-9822-047cc0e6bde2} - + {b7c2a162-dec9-4418-972e-240ab3cbfcae} - + {7e06e92c-537a-442b-9e4a-4761c84f8a1a} - + {df2638c0-8128-4847-867c-6eafe3dee7b5} - + {21070e58-eec6-4e16-8b4f-6d083df55790} - + {f9da0fc1-651b-457b-962e-a4d61cebf5fd} - + {79d34511-e54e-410a-8bba-ef175ad6c695} - + {625f7391-9a91-48a1-8cfc-79508c822637} - + {9a844c88-97e8-4e2d-b09a-e138c67d338b} - + {68f5f371-bd7b-4c30-ae5b-0b08f22e0cde} - + {3bec13f5-e227-4d80-bc77-1c857f83bcfc} - + {39379840-825a-45a0-b363-c09ffef864bd} - + {e78cdc6b-f37d-48d2-ad91-1db549497e32} - + {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} - + {21b2c324-891f-48ea-ad1a-5ae13de12e28} - + {929480e7-23c0-4df6-8456-096d71547116} - + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} diff --git a/samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj.filters b/tests/test-javascript/proj.win32/TestJavascript.vcxproj.filters similarity index 100% rename from samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj.filters rename to tests/test-javascript/proj.win32/TestJavascript.vcxproj.filters diff --git a/samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj.user b/tests/test-javascript/proj.win32/TestJavascript.vcxproj.user similarity index 100% rename from samples/Javascript/TestJavascript/proj.win32/TestJavascript.vcxproj.user rename to tests/test-javascript/proj.win32/TestJavascript.vcxproj.user diff --git a/samples/Javascript/MoonWarriors/proj.win32/main.cpp b/tests/test-javascript/proj.win32/main.cpp similarity index 89% rename from samples/Javascript/MoonWarriors/proj.win32/main.cpp rename to tests/test-javascript/proj.win32/main.cpp index 42d84925be..f5ce0656ed 100644 --- a/samples/Javascript/MoonWarriors/proj.win32/main.cpp +++ b/tests/test-javascript/proj.win32/main.cpp @@ -1,6 +1,5 @@ #include "main.h" #include "AppDelegate.h" -#include "CCEGLView.h" USING_NS_CC; @@ -24,8 +23,6 @@ int APIENTRY _tWinMain(HINSTANCE hInstance, // create the application instance AppDelegate app; - EGLView eglView; - eglView.init("MoonWarriors", 480, 720); int ret = Application::getInstance()->run(); diff --git a/samples/Cpp/AssetsManagerTest/proj.win32/main.h b/tests/test-javascript/proj.win32/main.h similarity index 100% rename from samples/Cpp/AssetsManagerTest/proj.win32/main.h rename to tests/test-javascript/proj.win32/main.h diff --git a/samples/Javascript/CocosDragonJS/proj.win32/res/testjs.ico b/tests/test-javascript/proj.win32/res/testjs.ico similarity index 100% rename from samples/Javascript/CocosDragonJS/proj.win32/res/testjs.ico rename to tests/test-javascript/proj.win32/res/testjs.ico diff --git a/samples/Cpp/AssetsManagerTest/proj.win32/resource.h b/tests/test-javascript/proj.win32/resource.h similarity index 100% rename from samples/Cpp/AssetsManagerTest/proj.win32/resource.h rename to tests/test-javascript/proj.win32/resource.h diff --git a/samples/Javascript/CocosDragonJS/proj.win32/testjs.rc b/tests/test-javascript/proj.win32/testjs.rc similarity index 100% rename from samples/Javascript/CocosDragonJS/proj.win32/testjs.rc rename to tests/test-javascript/proj.win32/testjs.rc diff --git a/tests/test-javascript/tests b/tests/test-javascript/tests new file mode 160000 index 0000000000..7a9a69a414 --- /dev/null +++ b/tests/test-javascript/tests @@ -0,0 +1 @@ +Subproject commit 7a9a69a41480127a1572a4983eb9b5f1cbf2e186 diff --git a/samples/Lua/TestLua/.gitignore b/tests/test-lua/.gitignore similarity index 100% rename from samples/Lua/TestLua/.gitignore rename to tests/test-lua/.gitignore diff --git a/samples/Lua/TestLua/CMakeLists.txt b/tests/test-lua/CMakeLists.txt similarity index 84% rename from samples/Lua/TestLua/CMakeLists.txt rename to tests/test-lua/CMakeLists.txt index bc9427168f..b13ff6e4f1 100644 --- a/samples/Lua/TestLua/CMakeLists.txt +++ b/tests/test-lua/CMakeLists.txt @@ -7,9 +7,9 @@ set(SAMPLE_SRC include_directories( Classes - ../../../cocos/scripting/lua/bindings - ../../../external/lua/lua - ../../../external/lua/tolua + ../../cocos/scripting/lua/bindings + ../../external/lua/lua + ../../external/lua/tolua ) # add the executable @@ -37,6 +37,6 @@ pre_build(${APP_NAME} COMMAND ${CMAKE_COMMAND} -E remove_directory ${APP_BIN_DIR}/Resources COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/Resources ${APP_BIN_DIR}/Resources COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/cocos/scripting/lua/script ${APP_BIN_DIR}/Resources - COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/samples/Cpp/TestCpp/Resources ${APP_BIN_DIR}/Resources + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/tests/test-cpp/Resources ${APP_BIN_DIR}/Resources ) diff --git a/samples/Lua/TestLua/Classes/AppDelegate.cpp b/tests/test-lua/Classes/AppDelegate.cpp similarity index 81% rename from samples/Lua/TestLua/Classes/AppDelegate.cpp rename to tests/test-lua/Classes/AppDelegate.cpp index 98f5922eec..259171741c 100644 --- a/samples/Lua/TestLua/Classes/AppDelegate.cpp +++ b/tests/test-lua/Classes/AppDelegate.cpp @@ -1,5 +1,4 @@ #include "cocos2d.h" -#include "CCEGLView.h" #include "AppDelegate.h" #include "CCLuaEngine.h" #include "SimpleAudioEngine.h" @@ -20,17 +19,20 @@ AppDelegate::~AppDelegate() bool AppDelegate::applicationDidFinishLaunching() { - // initialize director - auto pDirector = Director::getInstance(); - pDirector->setOpenGLView(EGLView::getInstance()); + auto director = Director::getInstance(); + auto glview = director->getOpenGLView(); + if(!glview) { + glview = GLView::createWithRect("Test Lua", Rect(0,0,900,640)); + director->setOpenGLView(glview); + } // turn on display FPS - pDirector->setDisplayStats(true); + director->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this - pDirector->setAnimationInterval(1.0 / 60); + director->setAnimationInterval(1.0 / 60); - auto screenSize = EGLView::getInstance()->getFrameSize(); + auto screenSize = glview->getFrameSize(); auto designSize = Size(480, 320); @@ -42,10 +44,10 @@ bool AppDelegate::applicationDidFinishLaunching() std::vector searchPaths; searchPaths.push_back("hd"); pFileUtils->setSearchPaths(searchPaths); - pDirector->setContentScaleFactor(resourceSize.height/designSize.height); + director->setContentScaleFactor(resourceSize.height/designSize.height); } - EGLView::getInstance()->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::FIXED_HEIGHT); + glview->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::FIXED_HEIGHT); // register lua engine LuaEngine* pEngine = LuaEngine::getInstance(); diff --git a/samples/Lua/TestLua/Classes/AppDelegate.h b/tests/test-lua/Classes/AppDelegate.h similarity index 100% rename from samples/Lua/TestLua/Classes/AppDelegate.h rename to tests/test-lua/Classes/AppDelegate.h diff --git a/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp b/tests/test-lua/Classes/lua_assetsmanager_test_sample.cpp similarity index 100% rename from samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.cpp rename to tests/test-lua/Classes/lua_assetsmanager_test_sample.cpp diff --git a/samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.h b/tests/test-lua/Classes/lua_assetsmanager_test_sample.h similarity index 100% rename from samples/Lua/TestLua/Classes/lua_assetsmanager_test_sample.h rename to tests/test-lua/Classes/lua_assetsmanager_test_sample.h diff --git a/samples/Lua/TestLua/Resources/cocosbuilderRes/ccb/flower.jpg.REMOVED.git-id b/tests/test-lua/Resources/cocosbuilderRes/ccb/flower.jpg.REMOVED.git-id similarity index 100% rename from samples/Lua/TestLua/Resources/cocosbuilderRes/ccb/flower.jpg.REMOVED.git-id rename to tests/test-lua/Resources/cocosbuilderRes/ccb/flower.jpg.REMOVED.git-id diff --git a/samples/Lua/TestLua/Resources/cocosbuilderRes/ccb/gem-0.wav.REMOVED.git-id b/tests/test-lua/Resources/cocosbuilderRes/ccb/gem-0.wav.REMOVED.git-id similarity index 100% rename from samples/Lua/TestLua/Resources/cocosbuilderRes/ccb/gem-0.wav.REMOVED.git-id rename to tests/test-lua/Resources/cocosbuilderRes/ccb/gem-0.wav.REMOVED.git-id diff --git a/samples/Lua/TestLua/Resources/cocosbuilderRes/ccb/gem-1.wav.REMOVED.git-id b/tests/test-lua/Resources/cocosbuilderRes/ccb/gem-1.wav.REMOVED.git-id similarity index 100% rename from samples/Lua/TestLua/Resources/cocosbuilderRes/ccb/gem-1.wav.REMOVED.git-id rename to tests/test-lua/Resources/cocosbuilderRes/ccb/gem-1.wav.REMOVED.git-id diff --git a/samples/Lua/TestLua/Resources/cocosbuilderRes/ccb/markerfelt24shadow.fnt.REMOVED.git-id b/tests/test-lua/Resources/cocosbuilderRes/ccb/markerfelt24shadow.fnt.REMOVED.git-id similarity index 100% rename from samples/Lua/TestLua/Resources/cocosbuilderRes/ccb/markerfelt24shadow.fnt.REMOVED.git-id rename to tests/test-lua/Resources/cocosbuilderRes/ccb/markerfelt24shadow.fnt.REMOVED.git-id diff --git a/tests/test-lua/Resources/luaScript/AccelerometerTest/AccelerometerTest.lua b/tests/test-lua/Resources/luaScript/AccelerometerTest/AccelerometerTest.lua new file mode 100644 index 0000000000..76aeb3a008 --- /dev/null +++ b/tests/test-lua/Resources/luaScript/AccelerometerTest/AccelerometerTest.lua @@ -0,0 +1,73 @@ +local function AccelerometerMainLayer() + + local function title() + return "AccelerometerTest" + end + local layer = cc.Layer:create() + + local function onEnter() + layer:setAccelerometerEnabled(true) + + local label = cc.LabelTTF:create(title(), "Arial", 32) + layer:addChild(label, 1) + label:setPosition( cc.p(VisibleRect:center().x, VisibleRect:top().y - 50) ) + + local ball = cc.Sprite:create("Images/ball.png") + ball:setPosition(cc.p(VisibleRect:center().x, VisibleRect:center().y)) + layer:addChild(ball) + + local function accelerometerListener(event,x,y,z,timestamp) + local target = event:getCurrentTarget() + local ballSize = target:getContentSize() + local ptNowX,ptNowY = target:getPosition() + ptNowX = ptNowX + x * 9.81 + ptNowY = ptNowY + y * 9.81 + + local minX = math.floor(VisibleRect:left().x + ballSize.width / 2.0) + local maxX = math.floor(VisibleRect:right().x - ballSize.width / 2.0) + if ptNowX < minX then + ptNowX = minX + elseif ptNowX > maxX then + ptNowX = maxX + end + + local minY = math.floor(VisibleRect:bottom().y + ballSize.height / 2.0) + local maxY = math.floor(VisibleRect:top().y - ballSize.height / 2.0) + if ptNowY < minY then + ptNowY = minY + elseif ptNowY > maxY then + ptNowY = maxY + end + + target:setPosition(cc.p(ptNowX , ptNowY)) + end + + local listerner = cc.EventListenerAcceleration:create(accelerometerListener) + layer:getEventDispatcher():addEventListenerWithSceneGraphPriority(listerner,ball) + end + + local function onExit() + layer:setAccelerometerEnabled(false) + end + + local function onNodeEvent(event) + if "enter" == event then + onEnter() + elseif "exit" == event then + onExit() + end + end + + layer:registerScriptHandler(onNodeEvent) + + return layer +end + + +function AccelerometerMain() + cclog("AccelerometerMain") + local scene = cc.Scene:create() + scene:addChild(AccelerometerMainLayer()) + scene:addChild(CreateBackMenuItem()) + return scene +end diff --git a/samples/Lua/TestLua/Resources/luaScript/ActionManagerTest/ActionManagerTest.lua b/tests/test-lua/Resources/luaScript/ActionManagerTest/ActionManagerTest.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/ActionManagerTest/ActionManagerTest.lua rename to tests/test-lua/Resources/luaScript/ActionManagerTest/ActionManagerTest.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/ActionsEaseTest/ActionsEaseTest.lua b/tests/test-lua/Resources/luaScript/ActionsEaseTest/ActionsEaseTest.lua similarity index 99% rename from samples/Lua/TestLua/Resources/luaScript/ActionsEaseTest/ActionsEaseTest.lua rename to tests/test-lua/Resources/luaScript/ActionsEaseTest/ActionsEaseTest.lua index ae0da8b3bb..7ceb78c0e7 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ActionsEaseTest/ActionsEaseTest.lua +++ b/tests/test-lua/Resources/luaScript/ActionsEaseTest/ActionsEaseTest.lua @@ -425,10 +425,10 @@ local function SpeedTest() local spawn = cc.Spawn:create(seq3_1, seq3_2) SpeedTest_action1 = cc.Speed:create(cc.RepeatForever:create(spawn), 1.0) - local spawn2 = tolua.cast(spawn:clone(), "Spawn") + local spawn2 = tolua.cast(spawn:clone(), "cc.Spawn") SpeedTest_action2 = cc.Speed:create(cc.RepeatForever:create(spawn2), 1.0) - local spawn3 = tolua.cast(spawn:clone(), "Spawn") + local spawn3 = tolua.cast(spawn:clone(), "cc.Spawn") SpeedTest_action3 = cc.Speed:create(cc.RepeatForever:create(spawn3), 1.0) grossini:runAction(SpeedTest_action2) diff --git a/samples/Lua/TestLua/Resources/luaScript/ActionsProgressTest/ActionsProgressTest.lua b/tests/test-lua/Resources/luaScript/ActionsProgressTest/ActionsProgressTest.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/ActionsProgressTest/ActionsProgressTest.lua rename to tests/test-lua/Resources/luaScript/ActionsProgressTest/ActionsProgressTest.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/ActionsTest/ActionsTest.lua b/tests/test-lua/Resources/luaScript/ActionsTest/ActionsTest.lua similarity index 99% rename from samples/Lua/TestLua/Resources/luaScript/ActionsTest/ActionsTest.lua rename to tests/test-lua/Resources/luaScript/ActionsTest/ActionsTest.lua index 7a26897d9b..9b70078388 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ActionsTest/ActionsTest.lua +++ b/tests/test-lua/Resources/luaScript/ActionsTest/ActionsTest.lua @@ -551,7 +551,7 @@ local function ActionAnimate() local animation3 = animation2:clone() -- problem - tolua.cast(animation3,"Animation"):setLoops(4) + tolua.cast(animation3,"cc.Animation"):setLoops(4) local action3 = cc.Animate:create(animation3) kathia:runAction(action3) @@ -740,7 +740,7 @@ local function ActionRotateToRepeat() local act2 = cc.RotateTo:create(1, 0) local seq = cc.Sequence:create(act1, act2) local rep1 = cc.RepeatForever:create(seq) - local rep2 = cc.Repeat:create(tolua.cast(seq:clone(), "Sequence"), 10) + local rep2 = cc.Repeat:create(tolua.cast(seq:clone(), "cc.Sequence"), 10) tamara:runAction(rep1) kathia:runAction(rep2) @@ -931,8 +931,8 @@ local function ActionOrbit() local seq = cc.Sequence:create(move, move_back) local rfe = cc.RepeatForever:create(seq) kathia:runAction(rfe) - tamara:runAction(tolua.cast(rfe:clone(), "ActionInterval")) - grossini:runAction(tolua.cast(rfe:clone(), "ActionInterval")) + tamara:runAction(tolua.cast(rfe:clone(), "cc.ActionInterval")) + grossini:runAction(tolua.cast(rfe:clone(), "cc.ActionInterval")) Helper.subtitleLabel:setString("OrbitCamera action") diff --git a/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerModule.lua b/tests/test-lua/Resources/luaScript/AssetsManagerTest/AssetsManagerModule.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerModule.lua rename to tests/test-lua/Resources/luaScript/AssetsManagerTest/AssetsManagerModule.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua b/tests/test-lua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua similarity index 98% rename from samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua rename to tests/test-lua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua index bd09f69e8a..39d4a63e89 100644 --- a/samples/Lua/TestLua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua +++ b/tests/test-lua/Resources/luaScript/AssetsManagerTest/AssetsManagerTest.lua @@ -116,7 +116,7 @@ local function updateLayer() local function menuCallback(tag, menuItem) local scene = nil - local nIdx = menuItem:getZOrder() - itemTagBasic + local nIdx = menuItem:getLocalZOrder() - itemTagBasic local ExtensionsTestScene = CreateExtensionsTestScene(nIdx) if nil ~= ExtensionsTestScene then cc.Director:getInstance():replaceScene(ExtensionsTestScene) diff --git a/samples/Lua/TestLua/Resources/luaScript/BugsTest/BugsTest.lua b/tests/test-lua/Resources/luaScript/BugsTest/BugsTest.lua similarity index 74% rename from samples/Lua/TestLua/Resources/luaScript/BugsTest/BugsTest.lua rename to tests/test-lua/Resources/luaScript/BugsTest/BugsTest.lua index e935a44a44..822f7be3ad 100644 --- a/samples/Lua/TestLua/Resources/luaScript/BugsTest/BugsTest.lua +++ b/tests/test-lua/Resources/luaScript/BugsTest/BugsTest.lua @@ -1,8 +1,8 @@ -local MAX_COUNT = 9; -local LINE_SPACE = 40; -local kItemTagBasic = 5432; +local MAX_COUNT = 9 +local LINE_SPACE = 40 +local kItemTagBasic = 5432 -local Winsize = cc.Director:getInstance():getWinSize(); +local Winsize = cc.Director:getInstance():getWinSize() local testNames = { "Bug-350", @@ -18,8 +18,8 @@ local testNames = { local function CreateBugsTestBackMenuItem(pLayer) cc.MenuItemFont:setFontName("Arial") - cc.MenuItemFont:setFontSize(24); - local pMenuItemFont = cc.MenuItemFont:create("Back"); + cc.MenuItemFont:setFontSize(24) + local pMenuItemFont = cc.MenuItemFont:create("Back") pMenuItemFont:setPosition(cc.p(VisibleRect:rightBottom().x - 50, VisibleRect:rightBottom().y + 25)) local function menuCallback() local pScene = BugsTestMain() @@ -37,9 +37,9 @@ end --BugTest350 local function BugTest350() local pLayer = cc.Layer:create() - local pBackground = cc.Sprite:create("Hello.png"); - pBackground:setPosition(cc.p(Winsize.width/2, Winsize.height/2)); - pLayer:addChild(pBackground); + local pBackground = cc.Sprite:create("Hello.png") + pBackground:setPosition(cc.p(Winsize.width/2, Winsize.height/2)) + pLayer:addChild(pBackground) return pLayer end @@ -55,7 +55,7 @@ local function BugTest422() print(strLog) end - pResetLayer:removeChild(pNode, false); + pResetLayer:removeChild(pNode, false) local function menuCallback(tag,pMenuItem) if nil ~= pMenuItem then @@ -64,7 +64,7 @@ local function BugTest422() end end cc.MenuItemFont:setFontName("Arial") - cc.MenuItemFont:setFontSize(24); + cc.MenuItemFont:setFontSize(24) local pMenuItem1 = cc.MenuItemFont:create("One") pMenuItem1:registerScriptTapHandler(menuCallback) local pMenuItem2 = cc.MenuItemFont:create("Two") @@ -90,15 +90,15 @@ local function BugTest458() local function InitQuestionContainerSprite(pSprite) --Add label - local pLabel = cc.LabelTTF:create("Answer 1", "Arial", 12); - pLabel:setTag(100); + local pLabel = cc.LabelTTF:create("Answer 1", "Arial", 12) + pLabel:setTag(100) --Add the background - local pCorner = cc.Sprite:create("Images/bugs/corner.png"); - local nWidth = Winsize.width * 0.9 - (pCorner:getContentSize().width * 2); - local nHeight = Winsize.height * 0.15 - (pCorner:getContentSize().height * 2); - local pColorLayer = cc.LayerColor:create(cc.c4b(255, 255, 255, 255 * .75), nWidth, nHeight); - pColorLayer:setPosition(cc.p(-nWidth / 2, -nHeight / 2)); + local pCorner = cc.Sprite:create("Images/bugs/corner.png") + local nWidth = Winsize.width * 0.9 - (pCorner:getContentSize().width * 2) + local nHeight = Winsize.height * 0.15 - (pCorner:getContentSize().height * 2) + local pColorLayer = cc.LayerColor:create(cc.c4b(255, 255, 255, 255 * .75), nWidth, nHeight) + pColorLayer:setPosition(cc.p(-nWidth / 2, -nHeight / 2)) --First button is blue,Second is red,Used for testing - change later if (0 == nColorFlag) then pLabel:setColor(cc.c3b(0,0,255)) @@ -106,53 +106,53 @@ local function BugTest458() print("Color changed") pLabel:setColor(cc.c3b(255,0,0)) end - nColorFlag = nColorFlag + 1; - pSprite:addChild(pColorLayer); + nColorFlag = nColorFlag + 1 + pSprite:addChild(pColorLayer) - pCorner:setPosition(cc.p(-(nWidth / 2 + pCorner:getContentSize().width / 2), -(nHeight / 2 + pCorner:getContentSize().height / 2))); - pSprite:addChild(pCorner); + pCorner:setPosition(cc.p(-(nWidth / 2 + pCorner:getContentSize().width / 2), -(nHeight / 2 + pCorner:getContentSize().height / 2))) + pSprite:addChild(pCorner) local nX,nY = pCorner:getPosition() - local pCorner2 = cc.Sprite:create("Images/bugs/corner.png"); - pCorner2:setPosition(cc.p(-nX, nY)); - pCorner2:setFlipX(true); - pSprite:addChild(pCorner2); + local pCorner2 = cc.Sprite:create("Images/bugs/corner.png") + pCorner2:setPosition(cc.p(-nX, nY)) + pCorner2:setFlipX(true) + pSprite:addChild(pCorner2) - local pCorner3 = cc.Sprite:create("Images/bugs/corner.png"); - pCorner3:setPosition(cc.p(nX, -nY)); - pCorner3:setFlipY(true); - pSprite:addChild(pCorner3); + local pCorner3 = cc.Sprite:create("Images/bugs/corner.png") + pCorner3:setPosition(cc.p(nX, -nY)) + pCorner3:setFlipY(true) + pSprite:addChild(pCorner3) - local pCorner4 = cc.Sprite:create("Images/bugs/corner.png"); - pCorner4:setPosition(cc.p(-nX, -nY)); - pCorner4:setFlipX(true); - pCorner4:setFlipY(true); - pSprite:addChild(pCorner4); + local pCorner4 = cc.Sprite:create("Images/bugs/corner.png") + pCorner4:setPosition(cc.p(-nX, -nY)) + pCorner4:setFlipX(true) + pCorner4:setFlipY(true) + pSprite:addChild(pCorner4) - local pEdge = cc.Sprite:create("Images/bugs/edge.png"); - pEdge:setScaleX(nWidth); - pEdge:setPosition(cc.p(nX + (pCorner:getContentSize().width / 2) + (nWidth / 2), nY)); - pSprite:addChild(pEdge); + local pEdge = cc.Sprite:create("Images/bugs/edge.png") + pEdge:setScaleX(nWidth) + pEdge:setPosition(cc.p(nX + (pCorner:getContentSize().width / 2) + (nWidth / 2), nY)) + pSprite:addChild(pEdge) - local pEdge2 = cc.Sprite:create("Images/bugs/edge.png"); - pEdge2:setScaleX(nWidth); - pEdge2:setPosition(cc.p(nX + (pCorner:getContentSize().width / 2) + (nWidth / 2), -nY)); - pEdge2:setFlipY(true); - pSprite:addChild(pEdge2); + local pEdge2 = cc.Sprite:create("Images/bugs/edge.png") + pEdge2:setScaleX(nWidth) + pEdge2:setPosition(cc.p(nX + (pCorner:getContentSize().width / 2) + (nWidth / 2), -nY)) + pEdge2:setFlipY(true) + pSprite:addChild(pEdge2) - local pEdge3 = cc.Sprite:create("Images/bugs/edge.png"); - pEdge3:setRotation(90); - pEdge3:setScaleX(nHeight); - pEdge3:setPosition(cc.p(nX, nY + (pCorner:getContentSize().height / 2) + (nHeight / 2))); - pSprite:addChild(pEdge3); + local pEdge3 = cc.Sprite:create("Images/bugs/edge.png") + pEdge3:setRotation(90) + pEdge3:setScaleX(nHeight) + pEdge3:setPosition(cc.p(nX, nY + (pCorner:getContentSize().height / 2) + (nHeight / 2))) + pSprite:addChild(pEdge3) - local pEdge4 = cc.Sprite:create("Images/bugs/edge.png"); - pEdge4:setRotation(270); - pEdge4:setScaleX(nHeight); - pEdge4:setPosition(cc.p(-nX, nY + (pCorner:getContentSize().height / 2) + (nHeight / 2))); - pSprite:addChild(pEdge4); + local pEdge4 = cc.Sprite:create("Images/bugs/edge.png") + pEdge4:setRotation(270) + pEdge4:setScaleX(nHeight) + pEdge4:setPosition(cc.p(-nX, nY + (pCorner:getContentSize().height / 2) + (nHeight / 2))) + pSprite:addChild(pEdge4) - pSprite:addChild(pLabel); + pSprite:addChild(pLabel) end local pQuestion1 = cc.Sprite:create() @@ -165,19 +165,19 @@ local function BugTest458() end local pMenuItemSprite = cc.MenuItemSprite:create(pQuestion1,pQuestion2) pMenuItemSprite:registerScriptTapHandler(menuCallback) - local pLayerColor1 = cc.LayerColor:create(cc.c4b(0,0,255,255), 100, 100); --- question->release(); --- question2->release(); + local pLayerColor1 = cc.LayerColor:create(cc.c4b(0,0,255,255), 100, 100) +-- question->release() +-- question2->release() - local pLayerColor2 = cc.LayerColor:create(cc.c4b(255,0,0,255), 100, 100); - local pMenuItemSprite2 = cc.MenuItemSprite:create(pLayerColor1, pLayerColor2); + local pLayerColor2 = cc.LayerColor:create(cc.c4b(255,0,0,255), 100, 100) + local pMenuItemSprite2 = cc.MenuItemSprite:create(pLayerColor1, pLayerColor2) pMenuItemSprite2:registerScriptTapHandler(menuCallback) local pMenu = cc.Menu:create(pMenuItemSprite, pMenuItemSprite2) - pMenu:alignItemsVerticallyWithPadding(100); - pMenu:setPosition(cc.p(Winsize.width / 2, Winsize.height / 2)); + pMenu:alignItemsVerticallyWithPadding(100) + pMenu:setPosition(cc.p(Winsize.width / 2, Winsize.height / 2)) -- add the label as a child to this Layer - pLayer:addChild(pMenu); + pLayer:addChild(pMenu) return pLayer end @@ -189,21 +189,21 @@ local BugTest624_2_entry = nil local function BugTest624() local pLayer = cc.Layer:create() - local pLabel = cc.LabelTTF:create("Layer1", "Marker Felt", 36); - pLabel:setPosition(cc.p(Winsize.width / 2, Winsize.height / 2)); - pLayer:addChild(pLabel); - pLayer:setAccelerometerEnabled(true); --- schedule(schedule_selector(Bug624Layer::switchLayer), 5.0f); + local pLabel = cc.LabelTTF:create("Layer1", "Marker Felt", 36) + pLabel:setPosition(cc.p(Winsize.width / 2, Winsize.height / 2)) + pLayer:addChild(pLabel) + pLayer:setAccelerometerEnabled(true) +-- schedule(schedule_selector(Bug624Layer::switchLayer), 5.0f) local function BugTest624_SwitchLayer() local scheduler = cc.Director:getInstance():getScheduler() scheduler:unscheduleScriptEntry(BugTest624_entry) - local pScene = cc.Scene:create(); + local pScene = cc.Scene:create() local pNewPlayer = BugTest624_2() CreateBugsTestBackMenuItem(pNewPlayer) - pScene:addChild(pNewPlayer); - cc.Director:getInstance():replaceScene(cc.TransitionFade:create(2.0, pScene, cc.c3b(255,255,255))); + pScene:addChild(pNewPlayer) + cc.Director:getInstance():replaceScene(cc.TransitionFade:create(2.0, pScene, cc.c3b(255,255,255))) end @@ -228,20 +228,20 @@ end function BugTest624_2() local pLayer = cc.Layer:create() - local pLabel = cc.LabelTTF:create("Layer2", "Marker Felt", 36); - pLabel:setPosition(cc.p(Winsize.width / 2, Winsize.height / 2)); - pLayer:addChild(pLabel); - pLayer:setAccelerometerEnabled(true); + local pLabel = cc.LabelTTF:create("Layer2", "Marker Felt", 36) + pLabel:setPosition(cc.p(Winsize.width / 2, Winsize.height / 2)) + pLayer:addChild(pLabel) + pLayer:setAccelerometerEnabled(true) local function BugTest624_2_SwitchLayer() local scheduler = cc.Director:getInstance():getScheduler() scheduler:unscheduleScriptEntry(BugTest624_2_entry) - local pScene = cc.Scene:create(); + local pScene = cc.Scene:create() local pNewPlayer = BugTest624() CreateBugsTestBackMenuItem(pNewPlayer) - pScene:addChild(pNewPlayer); - cc.Director:getInstance():replaceScene(cc.TransitionFade:create(2.0, pScene, cc.c3b(255,0,0))); + pScene:addChild(pNewPlayer) + cc.Director:getInstance():replaceScene(cc.TransitionFade:create(2.0, pScene, cc.c3b(255,0,0))) end local function BugTest624_2_OnEnterOrExit(tag) @@ -294,65 +294,58 @@ end --BugTest914 local function BugTest914() - local pLayer = cc.Layer:create() + local layer = cc.Layer:create() - pLayer:setTouchEnabled(true); - - local pLayerColor = nil + local layerColor = nil for i = 0, 4 do - pLayerColor = cc.LayerColor:create(cc.c4b(i*20, i*20, i*20,255)) - pLayerColor:setContentSize(cc.size(i*100, i*100)); - pLayerColor:setPosition(cc.p(Winsize.width/2, Winsize.height/2)) - pLayerColor:setAnchorPoint(cc.p(0.5, 0.5)); - pLayerColor:ignoreAnchorPointForPosition(false); - pLayer:addChild(pLayerColor, -1-i); + layerColor = cc.LayerColor:create(cc.c4b(i*20, i*20, i*20,255)) + layerColor:setContentSize(cc.size(i*100, i*100)) + layerColor:setPosition(cc.p(Winsize.width/2, Winsize.height/2)) + layerColor:setAnchorPoint(cc.p(0.5, 0.5)) + layerColor:ignoreAnchorPointForPosition(false) + layer:addChild(layerColor, -1-i) end --create and initialize a Label local function restart() - local pScene = cc.Scene:create() - local pLayer = BugTest914() - CreateBugsTestBackMenuItem(pLayer) - pScene:addChild(pLayer); - cc.Director:getInstance():replaceScene(pScene) + local scene = cc.Scene:create() + local newLayer = BugTest914() + CreateBugsTestBackMenuItem(newLayer) + scene:addChild(newLayer) + cc.Director:getInstance():replaceScene(scene) end local label = cc.LabelTTF:create("Hello World", "Marker Felt", 64) --position the label on the center of the screen - label:setPosition(cc.p( Winsize.width /2 , Winsize.height/2 )); - pLayer:addChild(label); + label:setPosition(cc.p( Winsize.width /2 , Winsize.height/2 )) + layer:addChild(label) local item1 = cc.MenuItemFont:create("restart") item1:registerScriptTapHandler(restart) - --Bug914Layer::restart)); local menu = cc.Menu:create() menu:addChild(item1) menu:alignItemsVertically() menu:setPosition(cc.p(Winsize.width/2, 100)) - pLayer:addChild(menu) + layer:addChild(menu) -- handling touch events - local function onTouchMoved(tableArray) - local nCount = table.getn(tableArray) - nCount = math.floor(nCount / 3) - print(nCount) + local function onTouchMoved(touches, event) + local count = table.getn(touches) + print("Number of touches: ",count) end - local function onTouchBegan(tableArray) - onTouchMoved(tableArray) + local function onTouchBegan(touches, event) + onTouchMoved(touches, event) end - + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCHES_BEGAN ) + listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCHES_MOVED ) - local function onTouch(eventType,tableArray) - if eventType == "began" then - return onTouchBegan(tableArray) - elseif eventType == "moved" then - return onTouchMoved(tableArray) - end - end - pLayer:registerScriptTouchHandler(onTouch,true) - return pLayer + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) + + return layer end --BugTest1159 @@ -372,25 +365,25 @@ local function BugTest1159() local seq = cc.Sequence:create(cc.MoveTo:create(1.0, cc.p(1024.0, 384.0)), cc.MoveTo:create(1.0, cc.p(0.0, 384.0))) sprite_a:runAction(cc.RepeatForever:create(seq)) - local sprite_b = cc.LayerColor:create(cc.c4b(0, 0, 255, 255), 400, 400); + local sprite_b = cc.LayerColor:create(cc.c4b(0, 0, 255, 255), 400, 400) sprite_b:setAnchorPoint(cc.p(0.5, 0.5)) - sprite_b:ignoreAnchorPointForPosition(false); - sprite_b:setPosition(cc.p(Winsize.width/2, Winsize.height/2)); - pLayer:addChild(sprite_b); + sprite_b:ignoreAnchorPointForPosition(false) + sprite_b:setPosition(cc.p(Winsize.width/2, Winsize.height/2)) + pLayer:addChild(sprite_b) local function menuCallback() local pScene = cc.Scene:create() local pLayer = BugTest1159() CreateBugsTestBackMenuItem(pLayer) - pScene:addChild(pLayer); + pScene:addChild(pLayer) cc.Director:getInstance():replaceScene(cc.TransitionPageTurn:create(1.0, pScene, false)) end - local label = cc.MenuItemLabel:create(cc.LabelTTF:create("Flip Me", "Helvetica", 24)); + local label = cc.MenuItemLabel:create(cc.LabelTTF:create("Flip Me", "Helvetica", 24)) label:registerScriptTapHandler(menuCallback) - local menu = cc.Menu:create(); + local menu = cc.Menu:create() menu:addChild(label) - menu:setPosition(cc.p(Winsize.width - 200.0, 50.0)); - pLayer:addChild(menu); + menu:setPosition(cc.p(Winsize.width - 200.0, 50.0)) + pLayer:addChild(menu) local function onNodeEvent(event) if event == "exit" then @@ -436,7 +429,7 @@ local function BugTest1174() local bRet = false print("Test1 - Start") - local i = 0; + local i = 0 for i = 0, 9999 do --[[ A|b @@ -490,12 +483,12 @@ local function BugTest1174() -------- print("Test2 - Start") - p1 = cc.p(220,480); - p2 = cc.p(304,325); - p3 = cc.p(264,416); - p4 = cc.p(186,416); - s = 0.0; - t = 0.0; + p1 = cc.p(220,480) + p2 = cc.p(304,325) + p3 = cc.p(264,416) + p4 = cc.p(186,416) + s = 0.0 + t = 0.0 bRet,s,t = cc.pIsLineIntersect( p1, p2, p3, p4, s, t) if true == bRet then check_for_error(p1, p2, p3, p4, s, t) @@ -515,7 +508,7 @@ local function BugTest1174() -- c | d local ax = math.random() * -500 local ay = math.random() * 500 - p1 = cc.p(ax,ay); + p1 = cc.p(ax,ay) -- a | b -- ----- -- c | D @@ -579,11 +572,11 @@ end local function BugsTestMainLayer() - local ret = cc.Layer:create(); + local ret = cc.Layer:create() --menu callback local function menuCallback(tag, pMenuItem) - local nIdx = pMenuItem:getZOrder() - kItemTagBasic + local nIdx = pMenuItem:getLocalZOrder() - kItemTagBasic local BugTestScene = CreateBugsTestScene(nIdx) if nil ~= testScene then cc.Director:getInstance():replaceScene(testScene) @@ -591,8 +584,8 @@ local function BugsTestMainLayer() end -- add menu items for tests - local pItemMenu = cc.Menu:create(); - local nTestCount = table.getn(testNames); + local pItemMenu = cc.Menu:create() + local nTestCount = table.getn(testNames) local i = 1 for i = 1, nTestCount do @@ -605,19 +598,15 @@ local function BugsTestMainLayer() pItemMenu:setPosition(cc.p(0, 0)) ret:addChild(pItemMenu) - ret:setTouchEnabled(true) -- handling touch events local ptBeginPos = {x = 0, y = 0} local ptCurPos = {x = 0, y = 0} - local function onTouchBegan(x, y) - ptBeginPos = {x = x, y = y} - -- cc.TOUCHBEGAN event must return true - return true - end - - local function onTouchMoved(x, y) - local nMoveY = y - ptBeginPos.y + + -- handling touch events + local function onTouchMoved(touches, event) + local touchLocation = touches[1]:getLocation() + local nMoveY = touchLocation.y - ptBeginPos.y local curPosx, curPosy = pItemMenu:getPosition() local nextPosy = curPosy + nMoveY if nextPosy < 0 then @@ -631,26 +620,25 @@ local function BugsTestMainLayer() end pItemMenu:setPosition(curPosx, nextPosy) - ptBeginPos = {x = x, y = y} + ptBeginPos = touchLocation ptCurPos = {x = curPosx, y = nextPosy} end - - local function onTouch(eventType, x, y) - if eventType == "began" then - return onTouchBegan(x, y) - elseif eventType == "moved" then - return onTouchMoved(x, y) - end + local function onTouchBegan(touches, event) + ptBeginPos = touches[1]:getLocation() end + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCHES_BEGAN ) + listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCHES_MOVED ) - ret:registerScriptTouchHandler(onTouch) + local eventDispatcher = ret:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, ret) return ret end function BugsTestMain() - cclog("BugsTestMain"); - local scene = cc.Scene:create(); - scene:addChild(BugsTestMainLayer()); - scene:addChild(CreateBackMenuItem()); - return scene; + cclog("BugsTestMain") + local scene = cc.Scene:create() + scene:addChild(BugsTestMainLayer()) + scene:addChild(CreateBackMenuItem()) + return scene end diff --git a/samples/Lua/TestLua/Resources/luaScript/ClickAndMoveTest/ClickAndMoveTest.lua b/tests/test-lua/Resources/luaScript/ClickAndMoveTest/ClickAndMoveTest.lua similarity index 67% rename from samples/Lua/TestLua/Resources/luaScript/ClickAndMoveTest/ClickAndMoveTest.lua rename to tests/test-lua/Resources/luaScript/ClickAndMoveTest/ClickAndMoveTest.lua index ee13a9c390..87f49208b7 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ClickAndMoveTest/ClickAndMoveTest.lua +++ b/tests/test-lua/Resources/luaScript/ClickAndMoveTest/ClickAndMoveTest.lua @@ -17,13 +17,20 @@ local function initWithLayer() cc.FadeIn:create(1), cc.FadeOut:create(1)))) - local function onTouchEnded(x, y) + local function onTouchBegan(touch, event) + return true + end + + local function onTouchEnded(touch, event) + + local location = touch:getLocation() + local s = layer:getChildByTag(kTagSprite) s:stopAllActions() - s:runAction(cc.MoveTo:create(1, cc.p(x, y))) + s:runAction(cc.MoveTo:create(1, cc.p(location.x, location.y))) local posX, posY = s:getPosition() - local o = x - posX - local a = y - posY + local o = location.x - posX + local a = location.y - posY local at = math.atan(o / a) / math.pi * 180.0 if a < 0 then @@ -36,16 +43,11 @@ local function initWithLayer() s:runAction(cc.RotateTo:create(1, at)) end - local function onTouch(eventType, x, y) - if eventType == "began" then - return true - elseif eventType == "ended" then - return onTouchEnded(x, y) - end - end - - layer:setTouchEnabled(true) - layer:registerScriptTouchHandler(onTouch) + local listener = cc.EventListenerTouchOneByOne:create() + listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN ) + listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED ) + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) return layer end diff --git a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua b/tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua similarity index 95% rename from samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua rename to tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua index d47b24034e..adca6996a5 100644 --- a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua +++ b/tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua @@ -428,7 +428,7 @@ end function TestPerformance:refreshTitle() local subTitleInfo = ArmatureTestLayer.subTitle(5) .. self._armatureCount - local label = tolua.cast(self:getChildByTag(10001),"LabelTTF") + local label = tolua.cast(self:getChildByTag(10001),"cc.LabelTTF") label:setString(subTitleInfo) end @@ -633,7 +633,7 @@ function TestChangeZorder:onEnter() local function changeZorder(dt) local node = self:getChildByTag(self.currentTag) - node:setZOrder(math.random(0,1) * 3) + node:setLocalZOrder(math.random(0,1) * 3) self.currentTag = (self.currentTag + 1) % 3 end @@ -812,7 +812,6 @@ function TestParticleDisplay.extend(target) end function TestParticleDisplay:onEnter() - self:setTouchEnabled(true) self.animationID = 0 self.armature = ccs.Armature:create("robot") @@ -828,7 +827,7 @@ function TestParticleDisplay:onEnter() bone:addDisplay(p1, 0) bone:changeDisplayWithIndex(0, true) bone:setIgnoreMovementBoneData(true) - bone:setZOrder(100) + bone:setLocalZOrder(100) bone:setScale(1.2) self.armature:addBone(bone, "bady-a3") @@ -836,23 +835,21 @@ function TestParticleDisplay:onEnter() bone:addDisplay(p2, 0) bone:changeDisplayWithIndex(0, true) bone:setIgnoreMovementBoneData(true) - bone:setZOrder(100) + bone:setLocalZOrder(100) bone:setScale(1.2) self.armature:addBone(bone, "bady-a30") - local function onTouchBegan(x, y) + -- handling touch events + local function onTouchEnded(touches, event) self.animationID = (self.animationID + 1) % self.armature:getAnimation():getMovementCount() self.armature:getAnimation():playWithIndex(self.animationID) - return false end - local function onTouch(eventType, x, y) - if eventType == "began" then - return onTouchBegan(x,y) - end - end + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCHES_ENDED ) - self:registerScriptTouchHandler(onTouch) + local eventDispatcher = self:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self) end function TestParticleDisplay.create() @@ -889,7 +886,6 @@ function TestUseMutiplePicture.extend(target) end function TestUseMutiplePicture:onEnter() - self:setTouchEnabled(true) self.displayIndex = 1 self.armature = ccs.Armature:create("Knight_f/Knight") @@ -915,19 +911,17 @@ function TestUseMutiplePicture:onEnter() self.armature:getBone("weapon"):addDisplay(skin, i - 1) end - local function onTouchBegan(x, y) + -- handling touch events + local function onTouchEnded(touches, event) self.displayIndex = (self.displayIndex + 1) % (table.getn(weapon) - 1) self.armature:getBone("weapon"):changeDisplayWithIndex(self.displayIndex, true) - return false end - local function onTouch(eventType, x, y) - if eventType == "began" then - return onTouchBegan(x,y) - end - end + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCHES_ENDED ) - self:registerScriptTouchHandler(onTouch) + local eventDispatcher = self:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self) end function TestUseMutiplePicture.create() @@ -1012,7 +1006,6 @@ function TestArmatureNesting.extend(target) end function TestArmatureNesting:onEnter() - self:setTouchEnabled(true) self.weaponIndex = 0 self.armature = ccs.Armature:create("cyborg") @@ -1022,20 +1015,18 @@ function TestArmatureNesting:onEnter() self.armature:getAnimation():setSpeedScale(0.4) self:addChild(self.armature) - local function onTouchBegan(x, y) + -- handling touch events + local function onTouchEnded(touches, event) self.weaponIndex = (self.weaponIndex + 1) % 4 self.armature:getBone("armInside"):getChildArmature():getAnimation():playWithIndex(self.weaponIndex) self.armature:getBone("armOutside"):getChildArmature():getAnimation():playWithIndex(self.weaponIndex) - return false end - local function onTouch(eventType, x, y) - if eventType == "began" then - return onTouchBegan(x,y) - end - end + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCHES_ENDED ) - self:registerScriptTouchHandler(onTouch) + local eventDispatcher = self:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self) end function TestArmatureNesting.create() @@ -1131,30 +1122,26 @@ function TestArmatureNesting2.extend(target) end function TestArmatureNesting2:onEnter() - - self:setTouchEnabled(true) - - local function onTouchesEnded(tableArray) - local x,y = tableArray[1],tableArray[2] + -- handling touch events + local function onTouchEnded(touches, event) + local location = touches[1]:getLocation() local armature = self._hero._mount and self._hero._mount or self._hero - if x < armature:getPositionX() then + if location.x < armature:getPositionX() then armature:setScaleX(-1) else armature:setScaleX(1) end - local move = cc.MoveTo:create(2, cc.p(x,y)) + local move = cc.MoveTo:create(2, location) armature:stopAllActions() armature:runAction(cc.Sequence:create(move)) end - local function onTouch(eventType, tableArray) - if eventType == "ended" then - return onTouchesEnded(tableArray) - end - end + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCHES_ENDED ) - self:registerScriptTouchHandler(onTouch,true) + local eventDispatcher = self:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self) local function changeMountCallback(sender) self._hero:stopAllActions() diff --git a/tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioGUITest/CocoStudioGUITest.lua.REMOVED.git-id b/tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioGUITest/CocoStudioGUITest.lua.REMOVED.git-id new file mode 100644 index 0000000000..0279040f69 --- /dev/null +++ b/tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioGUITest/CocoStudioGUITest.lua.REMOVED.git-id @@ -0,0 +1 @@ +09ed3c488f6d182685c416c291f8f325fb5cc2d2 \ No newline at end of file diff --git a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/CocoStudioSceneTest.lua b/tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/CocoStudioSceneTest.lua similarity index 99% rename from samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/CocoStudioSceneTest.lua rename to tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/CocoStudioSceneTest.lua index 3c453756a4..fb8f52a742 100644 --- a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/CocoStudioSceneTest.lua +++ b/tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/CocoStudioSceneTest.lua @@ -40,7 +40,7 @@ function SceneEditorTestLayer:createGameScene() itemBack:registerScriptTapHandler(menuCloseCallback) local menuBack = cc.Menu:create() menuBack:setPosition(cc.p(0.0, 0.0)) - menuBack:setZOrder(4) + menuBack:setLocalZOrder(4) menuBack:addChild(itemBack) node:addChild(menuBack) diff --git a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/TriggerCode/acts.lua b/tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/TriggerCode/acts.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/TriggerCode/acts.lua rename to tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/TriggerCode/acts.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/TriggerCode/cons.lua b/tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/TriggerCode/cons.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/TriggerCode/cons.lua rename to tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/TriggerCode/cons.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/TriggerCode/eventDef.lua b/tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/TriggerCode/eventDef.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/TriggerCode/eventDef.lua rename to tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioSceneTest/TriggerCode/eventDef.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioTest.lua b/tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioTest.lua similarity index 98% rename from samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioTest.lua rename to tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioTest.lua index f830bc194e..8a9bf8fa5a 100644 --- a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioTest.lua +++ b/tests/test-lua/Resources/luaScript/CocoStudioTest/CocoStudioTest.lua @@ -67,7 +67,7 @@ function CocoStudioTestLayer.extend(target) end function CocoStudioTestLayer.onMenuCallback(tag,sender) - local index = sender:getZOrder() - ITEM_TAG_BASIC + local index = sender:getLocalZOrder() - ITEM_TAG_BASIC cocoStudioTestItemNames[index].testScene() end diff --git a/samples/Lua/TestLua/Resources/luaScript/CocosDenshionTest/CocosDenshionTest.lua b/tests/test-lua/Resources/luaScript/CocosDenshionTest/CocosDenshionTest.lua similarity index 78% rename from samples/Lua/TestLua/Resources/luaScript/CocosDenshionTest/CocosDenshionTest.lua rename to tests/test-lua/Resources/luaScript/CocosDenshionTest/CocosDenshionTest.lua index 62aef54479..5cc281471a 100644 --- a/samples/Lua/TestLua/Resources/luaScript/CocosDenshionTest/CocosDenshionTest.lua +++ b/tests/test-lua/Resources/luaScript/CocosDenshionTest/CocosDenshionTest.lua @@ -33,7 +33,7 @@ local function CocosDenshionTest() } local function menuCallback(tag, pMenuItem) - local nIdx = pMenuItem:getZOrder() - 10000 + local nIdx = pMenuItem:getLocalZOrder() - 10000 -- play background music if nIdx == 0 then AudioEngine.playMusic(MUSIC_FILE, true) @@ -108,7 +108,6 @@ local function CocosDenshionTest() m_pItmeMenu:setContentSize(cc.size(VisibleRect:getVisibleRect().width, (m_nTestCount + 1) * LINE_SPACE)) m_pItmeMenu:setPosition(cc.p(0, 0)) ret:addChild(m_pItmeMenu) - ret:setTouchEnabled(true) -- preload background music and effect AudioEngine.preloadMusic( MUSIC_FILE ) @@ -159,7 +158,46 @@ local function CocosDenshionTest() end end - ret:registerScriptTouchHandler(onTouchEvent) + local function onTouchBegan(touch, event) + local location = touch:getLocation() + prev.x = location.x + prev.y = location.y + m_tBeginPos = location + return true + end + + local function onTouchMoved(touch, event) + local location = touch:getLocation() + local touchLocation = location + local nMoveY = touchLocation.y - m_tBeginPos.y + local curPosX, curPosY = m_pItmeMenu:getPosition() + local curPos = cc.p(curPosX, curPosY) + local nextPos = cc.p(curPos.x, curPos.y + nMoveY) + + if nextPos.y < 0.0 then + m_pItmeMenu:setPosition(cc.p(0, 0)) + end + + if nextPos.y > ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height) then + m_pItmeMenu:setPosition(cc.p(0, ((m_nTestCount + 1)* LINE_SPACE - VisibleRect:getVisibleRect().height))) + end + + m_pItmeMenu:setPosition(nextPos) + m_tBeginPos.x = touchLocation.x + m_tBeginPos.y = touchLocation.y + + prev.x = location.x + prev.y = location.y + end + + local listener = cc.EventListenerTouchOneByOne:create() + listener:setSwallowTouches(true) + + listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN ) + listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED ) + local eventDispatcher = ret:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, ret) + return ret end diff --git a/samples/Lua/TestLua/Resources/luaScript/CurrentLanguageTest/CurrentLanguageTest.lua b/tests/test-lua/Resources/luaScript/CurrentLanguageTest/CurrentLanguageTest.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/CurrentLanguageTest/CurrentLanguageTest.lua rename to tests/test-lua/Resources/luaScript/CurrentLanguageTest/CurrentLanguageTest.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/DrawPrimitivesTest/DrawPrimitivesTest.lua b/tests/test-lua/Resources/luaScript/DrawPrimitivesTest/DrawPrimitivesTest.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/DrawPrimitivesTest/DrawPrimitivesTest.lua rename to tests/test-lua/Resources/luaScript/DrawPrimitivesTest/DrawPrimitivesTest.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/EffectsAdvancedTest/EffectsAdvancedTest.lua b/tests/test-lua/Resources/luaScript/EffectsAdvancedTest/EffectsAdvancedTest.lua similarity index 99% rename from samples/Lua/TestLua/Resources/luaScript/EffectsAdvancedTest/EffectsAdvancedTest.lua rename to tests/test-lua/Resources/luaScript/EffectsAdvancedTest/EffectsAdvancedTest.lua index 705ef3fac0..863044cd94 100644 --- a/samples/Lua/TestLua/Resources/luaScript/EffectsAdvancedTest/EffectsAdvancedTest.lua +++ b/tests/test-lua/Resources/luaScript/EffectsAdvancedTest/EffectsAdvancedTest.lua @@ -95,7 +95,7 @@ local function Effect2() local delay = cc.DelayTime:create(1) - target:runAction(cc.Sequence:create(shaky, delay ,reuse, shuffle, tolua.cast(delay:clone(), "Action"), turnoff, turnon)) + target:runAction(cc.Sequence:create(shaky, delay ,reuse, shuffle, tolua.cast(delay:clone(), "cc.Action"), turnoff, turnon)) return ret end diff --git a/samples/Lua/TestLua/Resources/luaScript/EffectsTest/EffectsName.lua b/tests/test-lua/Resources/luaScript/EffectsTest/EffectsName.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/EffectsTest/EffectsName.lua rename to tests/test-lua/Resources/luaScript/EffectsTest/EffectsName.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/EffectsTest/EffectsTest.lua b/tests/test-lua/Resources/luaScript/EffectsTest/EffectsTest.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/EffectsTest/EffectsTest.lua rename to tests/test-lua/Resources/luaScript/EffectsTest/EffectsTest.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/CocosBuilderTest.lua b/tests/test-lua/Resources/luaScript/ExtensionTest/CocosBuilderTest.lua similarity index 92% rename from samples/Lua/TestLua/Resources/luaScript/ExtensionTest/CocosBuilderTest.lua rename to tests/test-lua/Resources/luaScript/ExtensionTest/CocosBuilderTest.lua index a379690f84..590ae907b6 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/CocosBuilderTest.lua +++ b/tests/test-lua/Resources/luaScript/ExtensionTest/CocosBuilderTest.lua @@ -30,7 +30,7 @@ ccb["TestScrollViewsLayer"] = TestScrollViewsLayer local function onMenuItemAClicked() if nil ~= TestMenusLayer["mMenuItemStatusLabelBMFont"] then - local labelBmFt = tolua.cast(TestMenusLayer["mMenuItemStatusLabelBMFont"],"LabelBMFont") + local labelBmFt = tolua.cast(TestMenusLayer["mMenuItemStatusLabelBMFont"],"cc.LabelBMFont") if nil ~= labelBmFt then labelBmFt:setString("Menu Item A clicked."); end @@ -39,7 +39,7 @@ end local function onMenuItemBClicked() if nil ~= TestMenusLayer["mMenuItemStatusLabelBMFont"] then - local labelBmFt = tolua.cast(TestMenusLayer["mMenuItemStatusLabelBMFont"],"LabelBMFont") + local labelBmFt = tolua.cast(TestMenusLayer["mMenuItemStatusLabelBMFont"],"cc.LabelBMFont") if nil ~= labelBmFt then labelBmFt:setString("Menu Item B clicked."); end @@ -48,7 +48,7 @@ end local function pressedC( ... ) if nil ~= TestMenusLayer["mMenuItemStatusLabelBMFont"] then - local labelBmFt = tolua.cast(TestMenusLayer["mMenuItemStatusLabelBMFont"],"LabelBMFont") + local labelBmFt = tolua.cast(TestMenusLayer["mMenuItemStatusLabelBMFont"],"cc.LabelBMFont") if nil ~= labelBmFt then labelBmFt:setString("Menu Item C clicked."); end @@ -59,9 +59,9 @@ local function onMenuTestClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestMenus.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestMenus.ccbi") end @@ -88,9 +88,9 @@ local function onSpriteTestClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestSprites.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestSprites.ccbi") end @@ -107,9 +107,9 @@ local function onButtonTestClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestButtons.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestButtons.ccbi") end @@ -122,7 +122,7 @@ local function onButtonTestClicked() end local function onCCControlButtonClicked(sender,controlEvent) - local labelTTF = tolua.cast(TestButtonsLayer["mCCControlEventLabel"],"LabelBMFont") + local labelTTF = tolua.cast(TestButtonsLayer["mCCControlEventLabel"],"cc.LabelBMFont") if nil == labelTTF then return @@ -158,9 +158,9 @@ local function onAnimationsTestClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestAnimations.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestAnimations.ccbi") end @@ -177,9 +177,9 @@ local function onParticleSystemTestClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestParticleSystems.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestParticleSystems.ccbi") end @@ -193,7 +193,7 @@ end local function onCCControlButtonIdleClicked() if nil ~= TestAnimationsLayer["mAnimationManager"] then - local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"CCBAnimationManager") + local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"cc.CCBAnimationManager") if nil ~= animationMgr then animationMgr:runAnimationsForSequenceNamedTweenDuration("Idle", 0.3) end @@ -202,7 +202,7 @@ end local function onCCControlButtonWaveClicked() if nil ~= TestAnimationsLayer["mAnimationManager"] then - local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"CCBAnimationManager") + local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"cc.CCBAnimationManager") if nil ~= animationMgr then animationMgr:runAnimationsForSequenceNamedTweenDuration("Wave", 0.3) end @@ -211,7 +211,7 @@ end local function onCCControlButtonJumpClicked() if nil ~= TestAnimationsLayer["mAnimationManager"] then - local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"CCBAnimationManager") + local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"cc.CCBAnimationManager") if nil ~= animationMgr then animationMgr:runAnimationsForSequenceNamedTweenDuration("Jump", 0.3) end @@ -220,7 +220,7 @@ end local function onCCControlButtonFunkyClicked() if nil ~= TestAnimationsLayer["mAnimationManager"] then - local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"CCBAnimationManager") + local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"cc.CCBAnimationManager") if nil ~= animationMgr then animationMgr:runAnimationsForSequenceNamedTweenDuration("Funky", 0.3) end @@ -237,9 +237,9 @@ local function onScrollViewTestClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestScrollViews.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestScrollViews.ccbi") end @@ -256,9 +256,9 @@ local function onTimelineCallbackSoundClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestTimelineCallback.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestTimelineCallback.ccbi") end @@ -272,7 +272,7 @@ end function onCallback1() if nil ~= TestTimelineLayer["helloLabel"] then - local ccLabelTTF = tolua.cast(TestTimelineLayer["helloLabel"],"LabelTTF") + local ccLabelTTF = tolua.cast(TestTimelineLayer["helloLabel"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:runAction(cc.RotateBy:create(1, 360)) ccLabelTTF:setString("Callback 1"); @@ -282,7 +282,7 @@ end function onCallback2() if nil ~= TestTimelineLayer["helloLabel"] then - local ccLabelTTF = tolua.cast(TestTimelineLayer["helloLabel"],"LabelTTF") + local ccLabelTTF = tolua.cast(TestTimelineLayer["helloLabel"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:runAction(cc.RotateBy:create(2, 360)) ccLabelTTF:setString("Callback 2"); @@ -306,7 +306,7 @@ local function HelloCCBTestMainLayer() print(type(cc.Scene)) local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/HelloCocosBuilder.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") return layer end diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua b/tests/test-lua/Resources/luaScript/ExtensionTest/ExtensionTest.lua similarity index 82% rename from samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua rename to tests/test-lua/Resources/luaScript/ExtensionTest/ExtensionTest.lua index b831962568..8283c71e99 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua +++ b/tests/test-lua/Resources/luaScript/ExtensionTest/ExtensionTest.lua @@ -11,7 +11,9 @@ local ExtensionTestEnum = TEST_COCOSBUILDER = 2, TEST_WEBSOCKET = 3, TEST_EDITBOX = 4, - TEST_MAX_COUNT = 5, + TEST_TABLEVIEW = 5, + TEST_SCROLLVIEW = 6, + TEST_MAX_COUNT = 7, } local testsName = @@ -21,6 +23,8 @@ local testsName = "CocosBuilderTest", "WebSocketTest", "EditBoxTest", + "TableViewTest", + "ScrollViewTest", } @@ -65,7 +69,7 @@ local function runNotificationCenterTest() local s = cc.Director:getInstance():getWinSize() local function toggleSwitch(tag,menuItem) - local toggleItem = tolua.cast(menuItem,"MenuItemToggle") + local toggleItem = tolua.cast(menuItem,"cc.MenuItemToggle") local nIndex = toggleItem:getSelectedIndex() local selectedItem = toggleItem:getSelectedItem() if 0 == nIndex then @@ -151,7 +155,7 @@ local function runNotificationCenterTest() connectitem:setTag(NotificationCenterParam.kTagConnect+i) local function connectToSwitch(tag,menuItem) - local connectMenuitem = tolua.cast(menuItem,"MenuItemToggle") + local connectMenuitem = tolua.cast(menuItem,"cc.MenuItemToggle") local bConnected = true if connectMenuitem:getSelectedIndex() == 0 then bConnected = false @@ -372,7 +376,7 @@ local function runCCControlTest() if nil == pSender or nil == pDisplayValueLabel then return end - local pControl = tolua.cast(pSender,"ControlSlider") + local pControl = tolua.cast(pSender,"cc.ControlSlider") local strFmt = nil if pControl:getTag() == 1 then strFmt = string.format("Upper slider value = %.02f",pControl:getValue()) @@ -430,7 +434,7 @@ local function runCCControlTest() return end - local pPicker = tolua.cast(pSender,"ControlColourPicker") + local pPicker = tolua.cast(pSender,"cc.ControlColourPicker") local strFmt = string.format("#%02X%02X%02X",pPicker:getColor().r, pPicker:getColor().g, pPicker:getColor().b) pColorLabel:setString(strFmt) end @@ -495,7 +499,7 @@ local function runCCControlTest() return end - local pControl = tolua.cast(pSender,"ControlSwitch") + local pControl = tolua.cast(pSender,"cc.ControlSwitch") if pControl:isOn() then pDisplayValueLabel:setString("On") else @@ -770,7 +774,7 @@ local function runCCControlTest() return end - local pControl = tolua.cast(pSender,"ControlPotentiometer") + local pControl = tolua.cast(pSender,"cc.ControlPotentiometer") local strFmt = string.format("%0.2f",pControl:getValue()) pDisplayValueLabel:setString(strFmt ) end @@ -827,7 +831,7 @@ local function runCCControlTest() return end - local pControl = tolua.cast(pSender,"ControlStepper") + local pControl = tolua.cast(pSender,"cc.ControlStepper") local strFmt = string.format("%0.02f",pControl:getValue() ) pDisplayValueLabel:setString(strFmt ) end @@ -913,7 +917,7 @@ local function runEditBoxTest() local EditEmail = nil local function editBoxTextEventHandle(strEventName,pSender) - local edit = tolua.cast(pSender,"EditBox") + local edit = tolua.cast(pSender,"cc.EditBox") local strFmt if strEventName == "began" then strFmt = string.format("editBox %p DidBegin !", edit) @@ -988,6 +992,192 @@ local function runEditBoxTest() return newScene end +local TableViewTestLayer = class("TableViewTestLayer") +TableViewTestLayer.__index = TableViewTestLayer + +function TableViewTestLayer.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TableViewTestLayer) + return target +end + +function TableViewTestLayer.scrollViewDidScroll(view) + print("scrollViewDidScroll") +end + +function TableViewTestLayer.scrollViewDidZoom(view) + print("scrollViewDidZoom") +end + +function TableViewTestLayer.tableCellTouched(table,cell) + print("cell touched at index: " .. cell:getIdx()) +end + +function TableViewTestLayer.cellSizeForTable(table,idx) + return 60,60 +end + +function TableViewTestLayer.tableCellAtIndex(table, idx) + local strValue = string.format("%d",idx) + local cell = table:dequeueCell() + local label = nil + if nil == cell then + cell = cc.TableViewCell:new() + local sprite = cc.Sprite:create("Images/Icon.png") + sprite:setAnchorPoint(cc.p(0,0)) + sprite:setPosition(cc.p(0, 0)) + cell:addChild(sprite) + + label = cc.LabelTTF:create(strValue, "Helvetica", 20.0) + label:setPosition(cc.p(0,0)) + label:setAnchorPoint(cc.p(0,0)) + label:setTag(123) + cell:addChild(label) + else + label = tolua.cast(cell:getChildByTag(123),"cc.LabelTTF") + if nil ~= label then + label:setString(strValue) + end + end + + return cell +end + +function TableViewTestLayer.numberOfCellsInTableView(table) + return 25 +end + +function TableViewTestLayer:init() + + local winSize = cc.Director:getInstance():getWinSize() + + local tableView = cc.TableView:create(cc.size(600,60)) + tableView:setDirection(cc.SCROLLVIEW_DIRECTION_HORIZONTAL) + tableView:setPosition(cc.p(20, winSize.height / 2 - 150)) + tableView:setDelegate() + self:addChild(tableView) + --registerScriptHandler functions must be before the reloadData funtion + tableView:registerScriptHandler(TableViewTestLayer.numberOfCellsInTableView,cc.NUMBER_OF_CELLS_IN_TABLEVIEW) + tableView:registerScriptHandler(TableViewTestLayer.scrollViewDidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL) + tableView:registerScriptHandler(TableViewTestLayer.scrollViewDidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM) + tableView:registerScriptHandler(TableViewTestLayer.tableCellTouched,cc.TABLECELL_TOUCHED) + tableView:registerScriptHandler(TableViewTestLayer.cellSizeForTable,cc.TABLECELL_SIZE_FOR_INDEX) + tableView:registerScriptHandler(TableViewTestLayer.tableCellAtIndex,cc.TABLECELL_SIZE_AT_INDEX) + tableView:reloadData() + + tableView = cc.TableView:create(cc.size(60, 350)) + tableView:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL) + tableView:setPosition(cc.p(winSize.width - 150, winSize.height / 2 - 150)) + tableView:setDelegate() + tableView:setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN) + self:addChild(tableView) + tableView:registerScriptHandler(TableViewTestLayer.scrollViewDidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL) + tableView:registerScriptHandler(TableViewTestLayer.scrollViewDidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM) + tableView:registerScriptHandler(TableViewTestLayer.tableCellTouched,cc.TABLECELL_TOUCHED) + tableView:registerScriptHandler(TableViewTestLayer.cellSizeForTable,cc.TABLECELL_SIZE_FOR_INDEX) + tableView:registerScriptHandler(TableViewTestLayer.tableCellAtIndex,cc.TABLECELL_SIZE_AT_INDEX) + tableView:registerScriptHandler(TableViewTestLayer.numberOfCellsInTableView,cc.NUMBER_OF_CELLS_IN_TABLEVIEW) + tableView:reloadData() + + -- Back Menu + local pToMainMenu = cc.Menu:create() + CreateExtensionsBasicLayerMenu(pToMainMenu) + pToMainMenu:setPosition(cc.p(0, 0)) + self:addChild(pToMainMenu,10) + + return true +end + +function TableViewTestLayer.create() + local layer = TableViewTestLayer.extend(cc.Layer:create()) + if nil ~= layer then + layer:init() + end + + return layer +end + +local function runTableViewTest() + local newScene = cc.Scene:create() + local newLayer = TableViewTestLayer.create() + newScene:addChild(newLayer) + return newScene +end + +local function runScrollViewTest() + local newScene = cc.Scene:create() + local newLayer = cc.Layer:create() + + -- Back Menu + local pToMainMenu = cc.Menu:create() + CreateExtensionsBasicLayerMenu(pToMainMenu) + pToMainMenu:setPosition(cc.p(0, 0)) + newLayer:addChild(pToMainMenu,10) + + local layerColor = cc.LayerColor:create(cc.c4b(128,64,0,255)) + newLayer:addChild(layerColor) + + local scrollView1 = cc.ScrollView:create() + local screenSize = cc.Director:getInstance():getWinSize() + local function scrollView1DidScroll() + print("scrollView1DidScroll") + end + local function scrollView1DidZoom() + print("scrollView1DidZoom") + end + if nil ~= scrollView1 then + scrollView1:setViewSize(cc.size(screenSize.width / 2,screenSize.height)) + scrollView1:setPosition(cc.p(0,0)) + scrollView1:setScale(1.0) + scrollView1:ignoreAnchorPointForPosition(true) + local flowersprite1 = cc.Sprite:create("ccb/flower.jpg") + if nil ~= flowersprite1 then + scrollView1:setContainer(flowersprite1) + scrollView1:updateInset() + end + scrollView1:setDirection(cc.SCROLLVIEW_DIRECTION_BOTH ) + scrollView1:setClippingToBounds(true) + scrollView1:setBounceable(true) + scrollView1:setDelegate() + scrollView1:registerScriptHandler(scrollView1DidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL) + scrollView1:registerScriptHandler(scrollView1DidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM) + end + newLayer:addChild(scrollView1) + + local scrollView2 = cc.ScrollView:create() + local function scrollView2DidScroll() + print("scrollView2DidScroll") + end + local function scrollView2DidZoom() + print("scrollView2DidZoom") + end + if nil ~= scrollView2 then + scrollView2:setViewSize(cc.size(screenSize.width / 2,screenSize.height)) + scrollView2:setPosition(cc.p(screenSize.width / 2,0)) + scrollView2:setScale(1.0) + scrollView2:ignoreAnchorPointForPosition(true) + local flowersprite2 = cc.Sprite:create("ccb/flower.jpg") + if nil ~= flowersprite2 then + scrollView2:setContainer(flowersprite2) + scrollView2:updateInset() + end + scrollView2:setDirection(cc.SCROLLVIEW_DIRECTION_BOTH ) + scrollView2:setClippingToBounds(true) + scrollView2:setBounceable(true) + scrollView2:setDelegate() + scrollView2:registerScriptHandler(scrollView2DidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL) + scrollView2:registerScriptHandler(scrollView2DidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM) + end + newLayer:addChild(scrollView2) + + newScene:addChild(newLayer) + return newScene +end + local CreateExtensionsTestTable = { runNotificationCenterTest, @@ -995,6 +1185,8 @@ local CreateExtensionsTestTable = runCocosBuilder, runWebSocketTest, runEditBoxTest, + runTableViewTest, + runScrollViewTest, } @@ -1009,7 +1201,7 @@ local function ExtensionsMainLayer() local function menuCallback(tag, pMenuItem) local scene = nil - local nIdx = pMenuItem:getZOrder() - kItemTagBasic + local nIdx = pMenuItem:getLocalZOrder() - kItemTagBasic local ExtensionsTestScene = CreateExtensionsTestScene(nIdx) if nil ~= ExtensionsTestScene then cc.Director:getInstance():replaceScene(ExtensionsTestScene) @@ -1047,14 +1239,15 @@ local function ExtensionsMainLayer() layer:addChild(menu) -- handling touch events - local beginPos = {x = 0, y = 0} - local function onTouchBegan(x, y) - beginPos = {x = x, y = y} - return true + local beginPos = {x = 0, y = 0} + local function onTouchesBegan(touches, event) + beginPos = touches[1]:getLocation() end - local function onTouchMoved(x, y) - local nMoveY = y - beginPos.y + local function onTouchesMoved(touches, event) + local location = touches[1]:getLocation() + + local nMoveY = location.y - beginPos.y local curPosx, curPosy = menu:getPosition() local nextPosy = curPosy + nMoveY local winSize = cc.Director:getInstance():getWinSize() @@ -1069,20 +1262,15 @@ local function ExtensionsMainLayer() end menu:setPosition(curPosx, nextPosy) - beginPos = {x = x, y = y} + beginPos = {x = location.x, y = location.y} end - local function onTouch(eventType, x, y) - if eventType == "began" then - return onTouchBegan(x, y) - elseif eventType == "moved" then - return onTouchMoved(x, y) - end - end + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchesBegan,cc.Handler.EVENT_TOUCHES_BEGAN ) + listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCH_MOVED ) - layer:setTouchEnabled(true) - - layer:registerScriptTouchHandler(onTouch) + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) return layer end diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/WebProxyTest.lua b/tests/test-lua/Resources/luaScript/ExtensionTest/WebProxyTest.lua similarity index 97% rename from samples/Lua/TestLua/Resources/luaScript/ExtensionTest/WebProxyTest.lua rename to tests/test-lua/Resources/luaScript/ExtensionTest/WebProxyTest.lua index e27a321cb5..9a2c203ffd 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/WebProxyTest.lua +++ b/tests/test-lua/Resources/luaScript/ExtensionTest/WebProxyTest.lua @@ -83,9 +83,9 @@ toMainMenu:setPosition(cc.p(0, 0)) layer:addChild(toMainMenu,10) - wsSendText = WebSocket:create("ws://echo.websocket.org") - wsSendBinary = WebSocket:create("ws://echo.websocket.org") - wsError = WebSocket:create("ws://invalid.url.com") + wsSendText = cc.WebSocket:create("ws://echo.websocket.org") + wsSendBinary = cc.WebSocket:create("ws://echo.websocket.org") + wsError = cc.WebSocket:create("ws://invalid.url.com") local function wsSendTextOpen(strData) sendTextStatus:setString("Send Text WS was opened.") diff --git a/samples/Lua/TestLua/Resources/luaScript/FontTest/FontTest.lua b/tests/test-lua/Resources/luaScript/FontTest/FontTest.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/FontTest/FontTest.lua rename to tests/test-lua/Resources/luaScript/FontTest/FontTest.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/IntervalTest/IntervalTest.lua b/tests/test-lua/Resources/luaScript/IntervalTest/IntervalTest.lua similarity index 97% rename from samples/Lua/TestLua/Resources/luaScript/IntervalTest/IntervalTest.lua rename to tests/test-lua/Resources/luaScript/IntervalTest/IntervalTest.lua index 37fa74c9f3..3f09c0bf0e 100644 --- a/samples/Lua/TestLua/Resources/luaScript/IntervalTest/IntervalTest.lua +++ b/tests/test-lua/Resources/luaScript/IntervalTest/IntervalTest.lua @@ -15,7 +15,7 @@ local function IntervalLayer() local s = cc.Director:getInstance():getWinSize() -- sun local sun = cc.ParticleSun:create() - sun:setTexture(cc.TextureCache:getInstance():addImage("Images/fire.png")) + sun:setTexture(cc.Director:getInstance():getTextureCache():addImage("Images/fire.png")) sun:setPosition( cc.p(VisibleRect:rightTop().x-32,VisibleRect:rightTop().y-32) ) sun:setTotalParticles(130) diff --git a/tests/test-lua/Resources/luaScript/KeypadTest/KeypadTest.lua b/tests/test-lua/Resources/luaScript/KeypadTest/KeypadTest.lua new file mode 100644 index 0000000000..850a908225 --- /dev/null +++ b/tests/test-lua/Resources/luaScript/KeypadTest/KeypadTest.lua @@ -0,0 +1,49 @@ +local function KeypadMainLayer() + local layer = cc.Layer:create() + + local function onEnter() + print("come in") + local s = cc.Director:getInstance():getWinSize() + local label = cc.LabelTTF:create("Keypad Test", "Arial", 28) + layer:addChild(label, 0) + label:setPosition(cc.p(s.width/2, s.height-50)) + + local labelTip = cc.LabelTTF:create("Please press any key...", "Arial", 22) + labelTip:setPosition(cc.p(s.width / 2, s.height / 2)) + layer:addChild(labelTip, 0) + + local function onKeyReleased(keyCode, event) + local label = event:getCurrentTarget() + if keyCode == cc.KeyCode.KEY_BACKSPACE then + label:setString("BACK clicked!") + elseif keyCode == cc.KeyCode.KEY_MENU then + label:setString("MENU clicked!") + end + end + + local listener = cc.EventListenerKeyboard:create() + listener:registerScriptHandler(onKeyReleased, cc.Handler.EVENT_KEYBOARD_RELEASED ) + + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, labelTip) + end + + local function onNodeEvent(event) + if event == "enter" then + onEnter() + end + end + + layer:registerScriptHandler(onNodeEvent) + + return layer +end + + +function KeypadTestMain() + cclog("KeypadTestMain") + local scene = cc.Scene:create() + scene:addChild(KeypadMainLayer()) + scene:addChild(CreateBackMenuItem()) + return scene +end diff --git a/samples/Lua/TestLua/Resources/luaScript/LabelTest/LabelTest.lua b/tests/test-lua/Resources/luaScript/LabelTest/LabelTest.lua similarity index 96% rename from samples/Lua/TestLua/Resources/luaScript/LabelTest/LabelTest.lua rename to tests/test-lua/Resources/luaScript/LabelTest/LabelTest.lua index 32649cbdba..c92d347fcb 100644 --- a/samples/Lua/TestLua/Resources/luaScript/LabelTest/LabelTest.lua +++ b/tests/test-lua/Resources/luaScript/LabelTest/LabelTest.lua @@ -32,11 +32,11 @@ function LabelAtlasTest.step(dt) local string = string.format("%2.2f Test", m_time) local label1_origin = LabelAtlasTest.layer:getChildByTag(kTagSprite1) - local label1 = tolua.cast(label1_origin, "LabelAtlas") + local label1 = tolua.cast(label1_origin, "cc.LabelAtlas") label1:setString(string) -- local label2_origin = LabelAtlasTest.layer:getChildByTag(kTagSprite2) - local label2 = tolua.cast(label2_origin, "LabelAtlas") + local label2 = tolua.cast(label2_origin, "cc.LabelAtlas") string = string.format("%d", m_time) label2:setString(string) @@ -88,11 +88,11 @@ function LabelAtlasColorTest.step(dt) m_time = m_time + dt local string = string.format("%2.2f Test", m_time) local label1_origin = LabelAtlasColorTest.layer:getChildByTag(kTagSprite1) - local label1 = tolua.cast(label1_origin, "LabelAtlas") + local label1 = tolua.cast(label1_origin, "cc.LabelAtlas") label1:setString(string) local label2_origin = LabelAtlasColorTest.layer:getChildByTag(kTagSprite2) - local label2 = tolua.cast(label2_origin, "LabelAtlas") + local label2 = tolua.cast(label2_origin, "cc.LabelAtlas") string = string.format("%d", m_time) label2:setString(string) @@ -199,7 +199,7 @@ function Atlas3.create() label2:setColor(cc.c3b(255, 0, 0 )) layer:addChild(label2, 0, kTagBitmapAtlas2) - label2:runAction( tolua.cast(repeatAction:clone(), "Action") ) + label2:runAction( tolua.cast(repeatAction:clone(), "cc.Action") ) local label3 = cc.LabelBMFont:create("Test", "fonts/bitmapFontTest2.fnt") -- testing anchors @@ -223,13 +223,13 @@ function Atlas3.step(dt) m_time = m_time + dt local string = string.format("%2.2f Test j", m_time) - local label1 = tolua.cast(Atlas3.layer:getChildByTag(kTagBitmapAtlas1), "LabelBMFont") + local label1 = tolua.cast(Atlas3.layer:getChildByTag(kTagBitmapAtlas1), "cc.LabelBMFont") label1:setString(string) - local label2 = tolua.cast(Atlas3.layer:getChildByTag(kTagBitmapAtlas2), "LabelBMFont") + local label2 = tolua.cast(Atlas3.layer:getChildByTag(kTagBitmapAtlas2), "cc.LabelBMFont") label2:setString(string) - local label3 = tolua.cast(Atlas3.layer:getChildByTag(kTagBitmapAtlas3), "LabelBMFont") + local label3 = tolua.cast(Atlas3.layer:getChildByTag(kTagBitmapAtlas3), "cc.LabelBMFont") label3:setString(string) end @@ -309,7 +309,7 @@ function Atlas4.create() label2:setPosition( cc.p(s.width/2.0, 80) ) local lastChar = label2:getChildByTag(3) - lastChar:runAction(tolua.cast( rot_4ever:clone(), "Action" )) + lastChar:runAction(tolua.cast( rot_4ever:clone(), "cc.Action" )) layer:registerScriptHandler(Atlas4.onNodeEvent) @@ -329,7 +329,7 @@ function Atlas4.step(dt) local string = string.format("%04.1f", m_time) - local label1 = tolua.cast(Atlas4.layer:getChildByTag(kTagBitmapAtlas2), "LabelBMFont") + local label1 = tolua.cast(Atlas4.layer:getChildByTag(kTagBitmapAtlas2), "cc.LabelBMFont") label1:setString(string) end @@ -592,9 +592,9 @@ function LabelsEmpty.create() end function LabelsEmpty.updateStrings(dt) - local label1 = tolua.cast(LabelsEmpty.layer:getChildByTag(kTagBitmapAtlas1), "LabelBMFont") - local label2 = tolua.cast(LabelsEmpty.layer:getChildByTag(kTagBitmapAtlas2), "LabelTTF") - local label3 = tolua.cast(LabelsEmpty.layer:getChildByTag(kTagBitmapAtlas3), "LabelAtlas") + local label1 = tolua.cast(LabelsEmpty.layer:getChildByTag(kTagBitmapAtlas1), "cc.LabelBMFont") + local label2 = tolua.cast(LabelsEmpty.layer:getChildByTag(kTagBitmapAtlas2), "cc.LabelTTF") + local label3 = tolua.cast(LabelsEmpty.layer:getChildByTag(kTagBitmapAtlas3), "cc.LabelAtlas") if( LabelsEmpty.setEmpty == false) then label1:setString("not empty") @@ -992,8 +992,6 @@ function BitmapFontMultiLineAlignment.create() local layer = cc.Layer:create() Helper.initWithLayer(layer) - layer:setTouchEnabled(true) - -- ask director the the window size local size = cc.Director:getInstance():getWinSize() @@ -1068,7 +1066,44 @@ function BitmapFontMultiLineAlignment.create() layer:addChild(stringMenu) layer:addChild(alignmentMenu) layer:registerScriptHandler(BitmapFontMultiLineAlignment.onNodeEvent) - layer:registerScriptTouchHandler(BitmapFontMultiLineAlignment.onTouchEvent) + + local function onTouchesBegan(touches, event) + local location = touches[1]:getLocationInView() + if cc.rectContainsPoint(BitmapFontMultiLineAlignment._pArrowsShouldRetain:getBoundingBox(), location) then + BitmapFontMultiLineAlignment._drag = true + BitmapFontMultiLineAlignment._pArrowsBarShouldRetain:setVisible(true) + end + end + + local function onTouchesMoved(touches, event) + if BitmapFontMultiLine._drag == false then + return + end + local location = touches[1]:getLocationInView() + local winSize = cc.Director:getInstance():getWinSize() + BitmapFontMultiLineAlignment._pArrowsShouldRetain:setPosition( + math.max(math.min(location.x, ArrowsMax*winSize.width), ArrowsMin*winSize.width), + BitmapFontMultiLineAlignment._pArrowsShouldRetain:getPositionY()) + + local labelWidth = math.abs(BitmapFontMultiLineAlignment._pArrowsShouldRetain:getPositionX() - BitmapFontMultiLineAlignment._pLabelShouldRetain:getPositionX()) * 2 + + BitmapFontMultiLineAlignment._pLabelShouldRetain:setWidth(labelWidth) + end + + local function onTouchesEnded(touch, event) + BitmapFontMultiLineAlignment._drag = false + BitmapFontMultiLineAlignment.snapArrowsToEdge() + BitmapFontMultiLineAlignment._pArrowsBarShouldRetain:setVisible(false) + end + + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchesBegan,cc.Handler.EVENT_TOUCHES_BEGAN ) + listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCHES_MOVED ) + listener:registerScriptHandler(onTouchesEnded,cc.Handler.EVENT_TOUCHES_ENDED ) + + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) + return layer end @@ -1083,7 +1118,7 @@ end function BitmapFontMultiLineAlignment.stringChanged(tag, sender) - local item = tolua.cast(sender, "MenuItemFont") + local item = tolua.cast(sender, "cc.MenuItemFont") item:setColor(cc.c3b(255, 0, 0)) BitmapFontMultiLineAlignment._pLastAlignmentItem:setColor(cc.c3b(255, 255, 255)) BitmapFontMultiLineAlignment._pLastAlignmentItem = item @@ -1101,7 +1136,7 @@ end function BitmapFontMultiLineAlignment.alignmentChanged(tag, sender) -- cclog("BitmapFontMultiLineAlignment.alignmentChanged, tag:"..tag) - local item = tolua.cast(sender, "MenuItemFont") + local item = tolua.cast(sender, "cc.MenuItemFont") item:setColor(cc.c3b(255, 0, 0)) BitmapFontMultiLineAlignment._pLastAlignmentItem:setColor(cc.c3b(255, 255, 255)) BitmapFontMultiLineAlignment._pLastAlignmentItem = item @@ -1118,35 +1153,6 @@ function BitmapFontMultiLineAlignment.alignmentChanged(tag, sender) BitmapFontMultiLineAlignment.snapArrowsToEdge() end -function BitmapFontMultiLineAlignment.onTouchEvent(eventType, x, y) - -- cclog("type:"..eventType.."["..x..","..y.."]") - if eventType == "began" then - if cc.rectContainsPoint(BitmapFontMultiLineAlignment._pArrowsShouldRetain:getBoundingBox(), cc.p(x, y)) then - BitmapFontMultiLineAlignment._drag = true - BitmapFontMultiLineAlignment._pArrowsBarShouldRetain:setVisible(true) - return true - end - elseif eventType == "ended" then - BitmapFontMultiLineAlignment._drag = false - BitmapFontMultiLineAlignment.snapArrowsToEdge() - BitmapFontMultiLineAlignment._pArrowsBarShouldRetain:setVisible(false) - elseif eventType == "moved" then - if BitmapFontMultiLine._drag == false then - return - end - - local winSize = cc.Director:getInstance():getWinSize() - BitmapFontMultiLineAlignment._pArrowsShouldRetain:setPosition( - math.max(math.min(x, ArrowsMax*winSize.width), ArrowsMin*winSize.width), - BitmapFontMultiLineAlignment._pArrowsShouldRetain:getPositionY()) - - local labelWidth = math.abs(BitmapFontMultiLineAlignment._pArrowsShouldRetain:getPositionX() - BitmapFontMultiLineAlignment._pLabelShouldRetain:getPositionX()) * 2 - - BitmapFontMultiLineAlignment._pLabelShouldRetain:setWidth(labelWidth) - - end -end - function BitmapFontMultiLineAlignment.snapArrowsToEdge() BitmapFontMultiLineAlignment._pArrowsShouldRetain:setPosition( BitmapFontMultiLineAlignment._pLabelShouldRetain:getPositionX() + BitmapFontMultiLineAlignment._pLabelShouldRetain:getContentSize().width/2, BitmapFontMultiLineAlignment._pLabelShouldRetain:getPositionY() diff --git a/samples/Lua/TestLua/Resources/luaScript/LabelTestNew/LabelTestNew.lua b/tests/test-lua/Resources/luaScript/LabelTestNew/LabelTestNew.lua similarity index 72% rename from samples/Lua/TestLua/Resources/luaScript/LabelTestNew/LabelTestNew.lua rename to tests/test-lua/Resources/luaScript/LabelTestNew/LabelTestNew.lua index 375f710ddd..0bcdadd979 100644 --- a/samples/Lua/TestLua/Resources/luaScript/LabelTestNew/LabelTestNew.lua +++ b/tests/test-lua/Resources/luaScript/LabelTestNew/LabelTestNew.lua @@ -42,7 +42,7 @@ function LabelFNTColorAndOpacity.create() local col = cc.LayerColor:create( cc.c4b(128,128,128,255) ) layer:addChild(col, -10) - local label1 = cc.Label:createWithBMFont("Test", "fonts/bitmapFontTest2.fnt") + local label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest2.fnt", "Test") -- testing anchors label1:setAnchorPoint( cc.p(0,0) ) @@ -55,15 +55,15 @@ function LabelFNTColorAndOpacity.create() local repeatAction = cc.RepeatForever:create(seq) label1:runAction(repeatAction) - local label2 = cc.Label:createWithBMFont("Test", "fonts/bitmapFontTest2.fnt") + local label2 = cc.Label:createWithBMFont("fonts/bitmapFontTest2.fnt", "Test") -- testing anchors label2:setAnchorPoint( cc.p(0.5, 0.5) ) label2:setColor(cc.c3b(255, 0, 0 )) layer:addChild(label2, 0, kTagBitmapAtlas2) - label2:runAction( tolua.cast(repeatAction:clone(), "Action") ) + label2:runAction( tolua.cast(repeatAction:clone(), "cc.Action") ) - local label3 = cc.Label:createWithBMFont("Test", "fonts/bitmapFontTest2.fnt") + local label3 = cc.Label:createWithBMFont("fonts/bitmapFontTest2.fnt", "Test") -- testing anchors label3:setAnchorPoint( cc.p(1,1) ) layer:addChild(label3, 0, kTagBitmapAtlas3) @@ -85,13 +85,13 @@ function LabelFNTColorAndOpacity.step(dt) m_time = m_time + dt local string = string.format("%2.2f Test j", m_time) - local label1 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas1), "Label") + local label1 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas1), "cc.Label") label1:setString(string) - local label2 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas2), "Label") + local label2 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas2), "cc.Label") label2:setString(string) - local label3 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas3), "Label") + local label3 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas3), "cc.Label") label3:setString(string) end @@ -121,7 +121,7 @@ function LabelFNTSpriteActions.create() LabelFNTSpriteActions.layer = layer -- Upper Label - local label = cc.Label:createWithBMFont("Bitmap Font Atlas", "fonts/bitmapFontTest.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest.fnt", "Bitmap Font Atlas") layer:addChild(label) local s = cc.Director:getInstance():getWinSize() @@ -160,12 +160,12 @@ function LabelFNTSpriteActions.create() -- Bottom Label - local label2 = cc.Label:createWithBMFont("00.0", "fonts/bitmapFontTest.fnt") + local label2 = cc.Label:createWithBMFont("fonts/bitmapFontTest.fnt", "00.0") layer:addChild(label2, 0, kTagBitmapAtlas2) label2:setPosition( cc.p(s.width/2.0, 80) ) local lastChar = label2:getLetter(3) - lastChar:runAction(tolua.cast( rot_4ever:clone(), "Action" )) + lastChar:runAction(tolua.cast( rot_4ever:clone(), "cc.Action" )) layer:registerScriptHandler(LabelFNTSpriteActions.onNodeEvent) @@ -203,7 +203,7 @@ function LabelFNTPadding:create() Helper.initWithLayer(layer) LabelFNTPadding.layer = layer - local label = cc.Label:createWithBMFont("abcdefg", "fonts/bitmapFontTest4.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest4.fnt", "abcdefg") layer:addChild(label) local s = cc.Director:getInstance():getWinSize() @@ -231,17 +231,17 @@ function LabelFNTOffset:create() LabelFNTOffset.layer = layer local s = cc.Director:getInstance():getWinSize() - local label = cc.Label:createWithBMFont("FaFeFiFoFu", "fonts/bitmapFontTest5.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "FaFeFiFoFu") layer:addChild(label) label:setPosition( cc.p(s.width/2, s.height/2+50) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) - label = cc.Label:createWithBMFont("fafefifofu", "fonts/bitmapFontTest5.fnt") + label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "fafefifofu") layer:addChild(label) label:setPosition( cc.p(s.width/2, s.height/2) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) - label = cc.Label:createWithBMFont("aeiou", "fonts/bitmapFontTest5.fnt") + label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "aeiou") layer:addChild(label) label:setPosition( cc.p(s.width/2, s.height/2-50) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) @@ -264,19 +264,19 @@ function LabelFNTColor:create() local s = cc.Director:getInstance():getWinSize() - local label = cc.Label:createWithBMFont("Blue", "fonts/bitmapFontTest5.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "Blue") label:setColor( cc.c3b(0, 0, 255 )) layer:addChild(label) label:setPosition( cc.p(s.width/2, s.height/4) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) - label = cc.Label:createWithBMFont("Red", "fonts/bitmapFontTest5.fnt") + label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "Red") layer:addChild(label) label:setPosition( cc.p(s.width/2, 2*s.height/4) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) label:setColor( cc.c3b(255, 0, 0) ) - label = cc.Label:createWithBMFont("G", "fonts/bitmapFontTest5.fnt") + label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "Green") layer:addChild(label) label:setPosition( cc.p(s.width/2, 3*s.height/4) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) @@ -301,20 +301,23 @@ function LabelTTFColor:create() Helper.initWithLayer(layer) local s = cc.Director:getInstance():getWinSize() + local ttfConfig = {} + ttfConfig.fontFilePath="fonts/arial.ttf" + ttfConfig.fontSize=35 - local label1 = cc.Label:createWithTTF("Green", "fonts/arial.ttf", 35, s.width, cc.VERTICAL_TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + local label1 = cc.Label:createWithTTF(ttfConfig,"Green", cc.VERTICAL_TEXT_ALIGNMENT_CENTER, s.width) label1:setColor( cc.c3b(0, 255, 0 )) layer:addChild(label1) label1:setPosition( cc.p(s.width/2, s.height/5 * 1.5) ) label1:setAnchorPoint( cc.p(0.5, 0.5) ) - local label2 = cc.Label:createWithTTF("Red", "fonts/arial.ttf", 35, s.width, cc.VERTICAL_TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + local label2 = cc.Label:createWithTTF(ttfConfig, "Red", cc.VERTICAL_TEXT_ALIGNMENT_CENTER, s.width) layer:addChild(label2) label2:setPosition( cc.p(s.width/2, s.height/5 * 2.0) ) label2:setAnchorPoint( cc.p(0.5, 0.5) ) label2:setColor( cc.c3b(255, 0, 0) ) - local label3 = cc.Label:createWithTTF("Blue", "fonts/arial.ttf", 35, s.width, cc.VERTICAL_TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + local label3 = cc.Label:createWithTTF(ttfConfig, "Blue", cc.VERTICAL_TEXT_ALIGNMENT_CENTER, s.width) layer:addChild(label3) label3:setPosition( cc.p(s.width/2, s.height/5 * 2.5) ) label3:setAnchorPoint( cc.p(0.5, 0.5) ) @@ -342,7 +345,7 @@ function LabelFNTHundredLabels:create() local i = 0 for i = 0, 100, 1 do local str = string.format("-%d-", i) - local label = cc.Label:createWithBMFont(str, "fonts/bitmapFontTest.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest.fnt", str) layer:addChild(label) local s = cc.Director:getInstance():getWinSize() @@ -353,7 +356,7 @@ function LabelFNTHundredLabels:create() end Helper.titleLabel:setString("New Label + .FNT file") - Helper.subtitleLabel:setString("Creating several Labels using the same FNT file; should be fast") + Helper.subtitleLabel:setString("Creating several Labels using the same FNT file should be fast") return layer end @@ -371,7 +374,7 @@ function LabelFNTMultiLine:create() local s = nil -- Left - local label1 = cc.Label:createWithBMFont(" Multi line\nLeft", "fonts/bitmapFontTest3.fnt") + local label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", " Multi line\nLeft") label1:setAnchorPoint(cc.p(0,0)) layer:addChild(label1, 0, kTagBitmapAtlas1) @@ -380,7 +383,7 @@ function LabelFNTMultiLine:create() -- Center - local label2 = cc.Label:createWithBMFont("Multi line\nCenter", "fonts/bitmapFontTest3.fnt") + local label2 = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", "Multi line\nCenter") label2:setAnchorPoint(cc.p(0.5, 0.5)) layer:addChild(label2, 0, kTagBitmapAtlas2) @@ -388,7 +391,7 @@ function LabelFNTMultiLine:create() cclog("content size: %.2fx%.2f", s.width, s.height) -- right - local label3 = cc.Label:createWithBMFont("Multi line\nRight\nThree lines Three", "fonts/bitmapFontTest3.fnt") + local label3 = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", "Multi line\nRight\nThree lines Three") label3:setAnchorPoint(cc.p(1, 1)) layer:addChild(label3, 0, kTagBitmapAtlas3) @@ -433,13 +436,17 @@ function LabelFNTandTTFEmpty.create() local s = cc.Director:getInstance():getWinSize() -- cc.LabelBMFont - local label1 = cc.Label:createWithBMFont("", "fonts/bitmapFontTest3.fnt",cc.TEXT_ALIGNMENT_CENTER,s.width) + local label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", "", cc.TEXT_ALIGNMENT_CENTER,s.width) layer:addChild(label1, 0, kTagBitmapAtlas1) label1:setPosition(cc.p(s.width/2, s.height-100)) -- cc.LabelTTF - local label2 = cc.Label:createWithTTF("", "fonts/arial.ttf", 48, s.width, cc.TEXT_ALIGNMENT_CENTER,cc.GLYPHCOLLECTION_NEHE) + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 48 + local label2 = cc.Label:createWithTTF(ttfConfig, "", cc.TEXT_ALIGNMENT_CENTER, s.width) layer:addChild(label2, 0, kTagBitmapAtlas2) + label2:setAnchorPoint(cc.p(0.5, 0.5)) label2:setPosition(cc.p(s.width/2, s.height/2)) layer:registerScriptHandler(LabelFNTandTTFEmpty.onNodeEvent) @@ -481,7 +488,7 @@ function LabelFNTRetina.create() local s = cc.Director:getInstance():getWinSize() -- cc.LabelBMFont - local label1 = cc.Label:createWithBMFont("TESTING RETINA DISPLAY", "fonts/konqa32.fnt") + local label1 = cc.Label:createWithBMFont("fonts/konqa32.fnt", "TESTING RETINA DISPLAY") label1:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label1) label1:setPosition(cc.p(s.width/2, s.height/2)) @@ -503,7 +510,7 @@ function LabelFNTGlyphDesigner.create() local s = cc.Director:getInstance():getWinSize() - local label1 = cc.Label:createWithBMFont("TESTING RETINA DISPLAY", "fonts/futura-48.fnt") + local label1 = cc.Label:createWithBMFont("fonts/futura-48.fnt", "TESTING RETINA DISPLAY") label1:setAnchorPoint(cc.p(0.5, 0.5)) layer:addChild(label1) @@ -523,8 +530,13 @@ function LabelTTFUnicodeChinese.create() Helper.subtitleLabel:setString("Testing new Label + TTF with Chinese character") local s = cc.Director:getInstance():getWinSize() - - local label1 = cc.Label:createWithTTF("美好的一天啊", "fonts/wt021.ttf", 55, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_CUSTOM, "美好的一天啊") + local ttfConfig = {} + ttfConfig.fontFilePath="fonts/wt021.ttf" + ttfConfig.fontSize=55 + ttfConfig.glyphs=cc.GLYPHCOLLECTION_CUSTOM + ttfConfig.customGlyphs="美好的一天啊" + + local label1 = cc.Label:createWithTTF(ttfConfig,"美好的一天啊", cc.TEXT_ALIGNMENT_CENTER, s.width) label1:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label1) label1:setPosition(cc.p(s.width/2, s.height/2)) @@ -542,7 +554,7 @@ function LabelFNTUnicodeChinese.create() Helper.initWithLayer(layer) local size = cc.Director:getInstance():getWinSize() - local lable = cc.Label:createWithBMFont("中国", "fonts/bitmapFontChinese.fnt") + local lable = cc.Label:createWithBMFont("fonts/bitmapFontChinese.fnt", "中国") lable:setAnchorPoint(cc.p(0.5,0.5)) lable:setPosition(cc.p(size.width / 2, size.height /2)) layer:addChild(lable) @@ -584,14 +596,11 @@ local LabelFNTMultiLineAlignment = { function LabelFNTMultiLineAlignment.create() local layer = cc.Layer:create() Helper.initWithLayer(layer) - - layer:setTouchEnabled(true) - -- ask director the the window size local size = cc.Director:getInstance():getWinSize() -- create and initialize a Label - LabelFNTMultiLineAlignment._pLabelShouldRetain = cc.Label:createWithBMFont(LongSentencesExample, "fonts/markerFelt.fnt", cc.TEXT_ALIGNMENT_CENTER, size.width/1.5) + LabelFNTMultiLineAlignment._pLabelShouldRetain = cc.Label:createWithBMFont("fonts/markerFelt.fnt", LongSentencesExample, cc.TEXT_ALIGNMENT_CENTER, size.width/1.5) LabelFNTMultiLineAlignment._pLabelShouldRetain:setAnchorPoint(cc.p(0.5, 0.5)) LabelFNTMultiLineAlignment._pLabelShouldRetain:retain() @@ -662,7 +671,46 @@ function LabelFNTMultiLineAlignment.create() layer:addChild(stringMenu) layer:addChild(alignmentMenu) layer:registerScriptHandler(LabelFNTMultiLineAlignment.onNodeEvent) - layer:registerScriptTouchHandler(LabelFNTMultiLineAlignment.onTouchEvent) + + local function onTouchesBegan(touches, event) + local location = touches[1]:getLocationInView() + if cc.rectContainsPoint(LabelFNTMultiLineAlignment._pArrowsShouldRetain:getBoundingBox(), cc.p(location.x, location.y)) then + LabelFNTMultiLineAlignment._drag = true + LabelFNTMultiLineAlignment._pArrowsBarShouldRetain:setVisible(true) + end + end + + local function onTouchesMoved(touches, event) + if LabelFNTMultiLineAlignment._drag == false then + return + end + + local winSize = cc.Director:getInstance():getWinSize() + local location = touches[1]:getLocationInView() + + LabelFNTMultiLineAlignment._pArrowsShouldRetain:setPosition( + math.max(math.min(location.x, ArrowsMax*winSize.width), ArrowsMin*winSize.width), + LabelFNTMultiLineAlignment._pArrowsShouldRetain:getPositionY()) + + local labelWidth = math.abs(LabelFNTMultiLineAlignment._pArrowsShouldRetain:getPositionX() - LabelFNTMultiLineAlignment._pLabelShouldRetain:getPositionX()) * 2 + + LabelFNTMultiLineAlignment._pLabelShouldRetain:setWidth(labelWidth) + end + + local function onTouchesEnded(touch, event) + LabelFNTMultiLineAlignment._drag = false + LabelFNTMultiLineAlignment.snapArrowsToEdge() + LabelFNTMultiLineAlignment._pArrowsBarShouldRetain:setVisible(false) + end + + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchesBegan,cc.Handler.EVENT_TOUCHES_BEGAN ) + listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCHES_MOVED ) + listener:registerScriptHandler(onTouchesEnded,cc.Handler.EVENT_TOUCHES_ENDED ) + + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) + return layer end @@ -677,7 +725,7 @@ end function LabelFNTMultiLineAlignment.stringChanged(tag, sender) - local item = tolua.cast(sender, "MenuItemFont") + local item = tolua.cast(sender, "cc.MenuItemFont") item:setColor(cc.c3b(255, 0, 0)) LabelFNTMultiLineAlignment._pLastAlignmentItem:setColor(cc.c3b(255, 255, 255)) LabelFNTMultiLineAlignment._pLastAlignmentItem = item @@ -695,7 +743,7 @@ end function LabelFNTMultiLineAlignment.alignmentChanged(tag, sender) -- cclog("LabelFNTMultiLineAlignment.alignmentChanged, tag:"..tag) - local item = tolua.cast(sender, "MenuItemFont") + local item = tolua.cast(sender, "cc.MenuItemFont") item:setColor(cc.c3b(255, 0, 0)) LabelFNTMultiLineAlignment._pLastAlignmentItem:setColor(cc.c3b(255, 255, 255)) LabelFNTMultiLineAlignment._pLastAlignmentItem = item @@ -712,35 +760,6 @@ function LabelFNTMultiLineAlignment.alignmentChanged(tag, sender) LabelFNTMultiLineAlignment.snapArrowsToEdge() end -function LabelFNTMultiLineAlignment.onTouchEvent(eventType, x, y) - -- cclog("type:"..eventType.."["..x..","..y.."]") - if eventType == "began" then - if cc.rectContainsPoint(LabelFNTMultiLineAlignment._pArrowsShouldRetain:getBoundingBox(), cc.p(x, y)) then - LabelFNTMultiLineAlignment._drag = true - LabelFNTMultiLineAlignment._pArrowsBarShouldRetain:setVisible(true) - return true - end - elseif eventType == "ended" then - LabelFNTMultiLineAlignment._drag = false - LabelFNTMultiLineAlignment.snapArrowsToEdge() - LabelFNTMultiLineAlignment._pArrowsBarShouldRetain:setVisible(false) - elseif eventType == "moved" then - if LabelFNTMultiLineAlignment._drag == false then - return - end - - local winSize = cc.Director:getInstance():getWinSize() - LabelFNTMultiLineAlignment._pArrowsShouldRetain:setPosition( - math.max(math.min(x, ArrowsMax*winSize.width), ArrowsMin*winSize.width), - LabelFNTMultiLineAlignment._pArrowsShouldRetain:getPositionY()) - - local labelWidth = math.abs(LabelFNTMultiLineAlignment._pArrowsShouldRetain:getPositionX() - LabelFNTMultiLineAlignment._pLabelShouldRetain:getPositionX()) * 2 - - LabelFNTMultiLineAlignment._pLabelShouldRetain:setWidth(labelWidth) - - end -end - function LabelFNTMultiLineAlignment.snapArrowsToEdge() LabelFNTMultiLineAlignment._pArrowsShouldRetain:setPosition( LabelFNTMultiLineAlignment._pLabelShouldRetain:getPositionX() + LabelFNTMultiLineAlignment._pLabelShouldRetain:getContentSize().width/2, LabelFNTMultiLineAlignment._pLabelShouldRetain:getPositionY() @@ -759,17 +778,17 @@ function LabelFNTUNICODELanguages.create() local s = cc.Director:getInstance():getWinSize() - local label1 = cc.Label:createWithBMFont("Buen día", "fonts/arial-unicode-26.fnt", 200, cc.TEXT_ALIGNMENT_LEFT) + local label1 = cc.Label:createWithBMFont("fonts/arial-unicode-26.fnt", "Buen día", cc.TEXT_ALIGNMENT_CENTER, 200) label1:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label1) label1:setPosition(cc.p(s.width/2, s.height/4*3)) - local label2 = cc.Label:createWithBMFont("美好的一天", "fonts/arial-unicode-26.fnt") + local label2 = cc.Label:createWithBMFont("fonts/arial-unicode-26.fnt", "美好的一天") label2:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label2) label2:setPosition(cc.p(s.width/2, s.height/4*2)) - local label3 = cc.Label:createWithBMFont("良い一日を", "fonts/arial-unicode-26.fnt") + local label3 = cc.Label:createWithBMFont("fonts/arial-unicode-26.fnt", "良い一日を") label3:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label3) label3:setPosition(cc.p(s.width/2, s.height/4*1)) @@ -788,21 +807,20 @@ function LabelTTFAlignmentNew.create() Helper.subtitleLabel:setString("Tests alignment values") local s = cc.Director:getInstance():getWinSize() - - local ttf0 = cc.Label:createWithTTF("Alignment 0\nnew line", "fonts/tahoma.ttf", 32) - ttf0:setAlignment(cc.TEXT_ALIGNMENT_LEFT) + local ttfConfig = {} + ttfConfig.fontFilePath="fonts/tahoma.ttf" + ttfConfig.fontSize=32 + local ttf0 = cc.Label:createWithTTF(ttfConfig, "Alignment 0\nnew line", cc.TEXT_ALIGNMENT_LEFT) ttf0:setPosition(cc.p(s.width/2,(s.height/6)*2 - 30)) ttf0:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(ttf0) - local ttf1 = cc.Label:createWithTTF("Alignment 1\nnew line", "fonts/tahoma.ttf", 32) - ttf1:setAlignment(cc.TEXT_ALIGNMENT_CENTER) + local ttf1 = cc.Label:createWithTTF(ttfConfig, "Alignment 1\nnew line", cc.TEXT_ALIGNMENT_CENTER) ttf1:setPosition(cc.p(s.width/2,(s.height/6)*3 - 30)) ttf1:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(ttf1) - local ttf2 = cc.Label:createWithTTF("Alignment 2\nnew line", "fonts/tahoma.ttf", 32) - ttf2:setAlignment(cc.TEXT_ALIGNMENT_RIGHT) + local ttf2 = cc.Label:createWithTTF(ttfConfig, "Alignment 2\nnew line", cc.TEXT_ALIGNMENT_RIGHT) ttf2:setPosition(cc.p(s.width/2,(s.height/6)*4 - 30)) ttf2:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(ttf2) @@ -824,18 +842,26 @@ function LabelTTFUnicodeNew.create() local s = cc.Director:getInstance():getWinSize() local vStep = s.height/9 local vSize = s.height + + local ttfConfig = {} + ttfConfig.fontFilePath="fonts/arial.ttf" + ttfConfig.fontSize=45 + ttfConfig.glyphs=cc.GLYPHCOLLECTION_ASCII - local label1 = cc.Label:createWithTTF("Buen día, ¿cómo te llamas?", "fonts/arial.ttf", 45, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_ASCII) + local label1 = cc.Label:createWithTTF(ttfConfig,"Buen día, ¿cómo te llamas?", cc.TEXT_ALIGNMENT_CENTER, s.width) label1:setAnchorPoint(cc.p(0.5,0.5)) label1:setPosition(cc.p(s.width/2, vSize - vStep * 4.5)) layer:addChild(label1) - local label2 = cc.Label:createWithTTF("In welcher Straße haben Sie gelebt?", "fonts/arial.ttf", 45, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_ASCII) + local label2 = cc.Label:createWithTTF(ttfConfig, "In welcher Straße haben Sie gelebt?", cc.TEXT_ALIGNMENT_CENTER, s.width) label2:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label2) label2:setPosition(cc.p(s.width/2, vSize - vStep * 5.5)) - local label3 = cc.Label:createWithTTF("美好的一天", "fonts/wt021.ttf", 45, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_CUSTOM, "美好的一天") + ttfConfig.fontFilePath = "fonts/wt021.ttf" + ttfConfig.glyphs = cc.GLYPHCOLLECTION_CUSTOM + ttfConfig.customGlyphs = "美好的一天" + local label3 = cc.Label:createWithTTF(ttfConfig, "美好的一天", cc.TEXT_ALIGNMENT_CENTER, s.width) label3:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label3) label3:setPosition(cc.p(s.width/2, vSize - vStep * 6.5)) @@ -862,7 +888,7 @@ function LabelFNTBounds.create() layer:addChild(colorlayer, -10) -- cc.LabelBMFont - local label1 = cc.Label:createWithBMFont("Testing Glyph Designer", "fonts/boundsTestFont.fnt", cc.TEXT_ALIGNMENT_CENTER, s.width) + local label1 = cc.Label:createWithBMFont("fonts/boundsTestFont.fnt", "Testing Glyph Designer", cc.TEXT_ALIGNMENT_CENTER, s.width) label1:setAnchorPoint(cc.p(0.5, 0.5)) layer:addChild(label1) @@ -899,8 +925,10 @@ function LabelTTFLongLineWrapping.create() Helper.subtitleLabel:setString("Uses the new Label with TTF. Testing auto-wrapping") local s = cc.Director:getInstance():getWinSize() - - local label1 = cc.Label:createWithTTF(LongSentencesExample, "fonts/arial.ttf", 28, s.width,cc.TEXT_ALIGNMENT_LEFT, cc.GLYPHCOLLECTION_NEHE) + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 28 + local label1 = cc.Label:createWithTTF(ttfConfig, LongSentencesExample, cc.TEXT_ALIGNMENT_LEFT, s.width) label1:setAnchorPoint(cc.p(0.5,1.0)) label1:setPosition(cc.p(s.width/2, s.height/2)) layer:addChild(label1) @@ -927,8 +955,10 @@ function LabelTTFDynamicAlignment.create() LabelTTFDynamicAlignment._eHorizAlign = cc.TEXT_ALIGNMENT_LEFT local s = cc.Director:getInstance():getWinSize() - - LabelTTFDynamicAlignment._label = cc.Label:createWithTTF(LongSentencesExample, "fonts/arial.ttf", 45, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 45 + LabelTTFDynamicAlignment._label = cc.Label:createWithTTF(ttfConfig, LongSentencesExample, cc.TEXT_ALIGNMENT_CENTER, s.width) LabelTTFDynamicAlignment._label:setPosition( cc.p(s.width/2, s.height/2) ) LabelTTFDynamicAlignment._label:setAnchorPoint(cc.p(0.5, 0.5)) layer:addChild(LabelTTFDynamicAlignment._label) @@ -1000,9 +1030,12 @@ function LabelTTFFontsTestNew.create() "fonts/Schwarzwald Regular.ttf", "fonts/Scissor Cuts.ttf", } - + local ttfConfig = {} + ttfConfig.fontFilePath = ttfPaths[0] + ttfConfig.fontSize = 40 for i=1, table.getn(ttfPaths) do - local label = cc.Label:createWithTTF( ttfPaths[i], ttfPaths[i], 40, 0, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + ttfConfig.fontFilePath = ttfPaths[i] + local label = cc.Label:createWithTTF( ttfConfig, ttfPaths[i], cc.TEXT_ALIGNMENT_CENTER, 0) if nil ~= label then label:setPosition( cc.p(s.width/2, ((s.height * 0.6)/table.getn(ttfPaths) * (i -1)) + (s.height/5))) layer:addChild(label) @@ -1029,13 +1062,180 @@ function LabelBMFontTestNew.create() local s = cc.Director:getInstance():getWinSize() - local label1 = cc.Label:createWithBMFont("Hello World, this is testing the new Label using fnt file", "fonts/bitmapFontTest2.fnt", cc.TEXT_ALIGNMENT_CENTER, s.width) + local label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest2.fnt", "Hello World, this is testing the new Label using fnt file", cc.TEXT_ALIGNMENT_CENTER, s.width) label1:setAnchorPoint(cc.p(0.5,0.5)) label1:setPosition(cc.p(s.width/2, s.height/2)) layer:addChild(label1) return layer end + +-------------------------------------------------------- +----- LabelTTFDistanceField +-------------------------------------------------------- +local LabelTTFDistanceField = {} +function LabelTTFDistanceField.create() + local layer = cc.Layer:create() + Helper.initWithLayer(layer) + Helper.titleLabel:setString("New Label + .TTF") + Helper.subtitleLabel:setString("Testing rendering base on DistanceField") + + local s = cc.Director:getInstance():getWinSize() + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 80 + ttfConfig.glyphs = cc.GLYPHCOLLECTION_DYNAMIC + ttfConfig.customGlyphs = nil + ttfConfig.distanceFieldEnabled = true + + local label1 = cc.Label:createWithTTF(ttfConfig,"Distance Field",cc.TEXT_ALIGNMENT_CENTER,s.width) + label1:setAnchorPoint(cc.p(0.5,0.5)) + label1:setPosition(cc.p(s.width/2, s.height/2)) + label1:setColor( cc.c3b(0, 255, 0) ) + local action = cc.Sequence:create(cc.DelayTime:create(1.0), + cc.ScaleTo:create(6.0,5.0,5.0), + cc.ScaleTo:create(6.0,1.0,1.0)) + label1:runAction(cc.RepeatForever:create(action)) + layer:addChild(label1) + + local label2 = cc.Label:createWithTTF(ttfConfig,"Distance Field",cc.TEXT_ALIGNMENT_CENTER,s.width) + label2:setPosition( cc.p(s.width/2, s.height/5) ) + label2:setColor( cc.c3b(255, 0, 0)) + label2:setAnchorPoint(cc.p(0.5, 0.5)) + layer:addChild(label2) + + return layer +end + +-------------------------------------------------------- +----- LabelTTFDistanceFieldEffect +-------------------------------------------------------- +local LabelTTFDistanceFieldEffect = {} +function LabelTTFDistanceFieldEffect.create() + local layer = cc.Layer:create() + Helper.initWithLayer(layer) + Helper.titleLabel:setString("New Label + .TTF") + Helper.subtitleLabel:setString("Testing effect base on DistanceField") + + local s = cc.Director:getInstance():getWinSize() + + local col = cc.LayerColor:create( cc.c4b(200, 191, 231, 255)) + layer:addChild(col) + + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 80 + ttfConfig.glyphs = cc.GLYPHCOLLECTION_DYNAMIC + ttfConfig.customGlyphs = nil + ttfConfig.distanceFieldEnabled = true + + local label1 = cc.Label:createWithTTF(ttfConfig,"Glow",cc.TEXT_ALIGNMENT_CENTER,s.width) + label1:setAnchorPoint(cc.p(0.5,0.5)) + label1:setPosition(cc.p(s.width/2, s.height/2)) + label1:setColor( cc.c3b(0, 255, 0) ) + label1:setLabelEffect(cc.LabelEffect.GLOW, cc.c3b(255, 255, 0)) + layer:addChild(label1) + + local label2 = cc.Label:createWithTTF(ttfConfig,"Outline",cc.TEXT_ALIGNMENT_CENTER,s.width) + label2:setPosition( cc.p(s.width/2, s.height * 0.375)) + label2:setColor( cc.c3b(255, 0, 0)) + label2:setAnchorPoint(cc.p(0.5, 0.5)) + label2:setLabelEffect(cc.LabelEffect.OUTLINE, cc.c3b(0, 0, 255)) + layer:addChild(label2) + + local label3 = cc.Label:createWithTTF(ttfConfig,"Shadow",cc.TEXT_ALIGNMENT_CENTER,s.width) + label3:setPosition( cc.p(s.width/2, s.height * 0.25)) + label3:setColor( cc.c3b(255, 0, 0)) + label3:setAnchorPoint(cc.p(0.5, 0.5)) + label3:setLabelEffect(cc.LabelEffect.SHADOW, cc.c3b(0, 0, 0)) + layer:addChild(label3) + + return layer +end + + +-------------------------------------------------------------------- +-- +-- LabelCharMapTest +-- +-------------------------------------------------------------------- +local LabelCharMapTest = {} + +function LabelCharMapTest.create() + local layer = cc.Layer:create() + Helper.initWithLayer(layer) + Helper.titleLabel:setString("New Label + char map file") + Helper.subtitleLabel:setString("Updating label should be fast.") + + time = 0 + + local label1 = cc.Label:createWithCharMap("fonts/tuffy_bold_italic-charmap.plist") + layer:addChild(label1, 0, kTagSprite1) + label1:setPosition( cc.p(10,100) ) + label1:setOpacity( 200 ) + + local label2 = cc.Label:createWithCharMap("fonts/tuffy_bold_italic-charmap.plist") + layer:addChild(label2, 0, kTagSprite2) + label2:setPosition( cc.p(10,160) ) + label2:setOpacity( 32 ) + + local label3 = cc.Label:createWithCharMap("fonts/tuffy_bold_italic-charmap.png", 48, 64, 32)--32 means Space key + label3:setString("123 Test") + layer:addChild(label3, 0, kTagSprite3) + label3:setPosition(cc.p(10,220)) + + local function step(dt) + time = time + dt + local info = string.format("%2.2f Test", time) + + local label1 = layer:getChildByTag(kTagSprite1) + label1:setString(info) + + local label2 = layer:getChildByTag(kTagSprite2) + info = string.format("%d",time) + label2:setString(info) + end + + layer:scheduleUpdateWithPriorityLua(step, 0) + + function onNodeEvent(tag) + if tag == "exit" then + layer:unscheduleUpdate() + end + end + + layer:registerScriptHandler(onNodeEvent) + + return layer +end + + +-------------------------------------------------------- +----- LabelCrashTest +-------------------------------------------------------- +local LabelCrashTest = {} +function LabelCrashTest.create() + local layer = cc.Layer:create() + Helper.initWithLayer(layer) + Helper.titleLabel:setString("New Label + .TTF") + Helper.subtitleLabel:setString("Testing rendering base on DistanceField") + + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 80 + ttfConfig.glyphs = cc.GLYPHCOLLECTION_DYNAMIC + ttfConfig.customGlyphs = nil + ttfConfig.distanceFieldEnabled = true + local s = cc.Director:getInstance():getWinSize() + local label1 = cc.Label:createWithTTF(ttfConfig,"Test崩溃123", cc.TEXT_ALIGNMENT_CENTER, s.width) + label1:setPosition( cc.p(s.width/2, s.height/2) ) + label1:setAnchorPoint(cc.p(0.5, 0.5)) + layer:addChild(label1) + + return layer +end + +------------ function LabelTestNew() cclog("LabelTestNew") m_time = 0 @@ -1064,6 +1264,10 @@ function LabelTestNew() LabelTTFDynamicAlignment.create, LabelTTFFontsTestNew.create, LabelBMFontTestNew.create, + LabelTTFDistanceField.create, + LabelTTFDistanceFieldEffect.create, + LabelCharMapTest.create, + LabelCrashTest.create, } scene:addChild(LabelFNTColorAndOpacity.create()) scene:addChild(CreateBackMenuItem()) diff --git a/samples/Lua/TestLua/Resources/luaScript/LayerTest/LayerTest.lua b/tests/test-lua/Resources/luaScript/LayerTest/LayerTest.lua similarity index 93% rename from samples/Lua/TestLua/Resources/luaScript/LayerTest/LayerTest.lua rename to tests/test-lua/Resources/luaScript/LayerTest/LayerTest.lua index 991ad016fd..7fce8fdc99 100644 --- a/samples/Lua/TestLua/Resources/luaScript/LayerTest/LayerTest.lua +++ b/tests/test-lua/Resources/luaScript/LayerTest/LayerTest.lua @@ -302,8 +302,6 @@ end local function LayerTest1() local ret = createLayerDemoLayer("ColorLayer resize (tap & move)") - ret:setTouchEnabled(true) - local s = cc.Director:getInstance():getWinSize() local layer = cc.LayerColor:create( cc.c4b(0xFF, 0x00, 0x00, 0x80), 200, 200) @@ -316,20 +314,28 @@ local function LayerTest1() local newSize = cc.size( math.abs(x - s.width/2)*2, math.abs(y - s.height/2)*2) - local l = tolua.cast(ret:getChildByTag(kTagLayer), "LayerColor") + local l = tolua.cast(ret:getChildByTag(kTagLayer), "cc.LayerColor") l:setContentSize( newSize ) end - local function onTouchEvent(eventType, x, y) - if eventType == "began" then - updateSize(x, y) - return true - else - updateSize(x, y) - end + local function onTouchesMoved(touches, event) + local touchLocation = touches[1]:getLocation() + + updateSize(touchLocation.x, touchLocation.y) end - ret:registerScriptTouchHandler(onTouchEvent) + + local function onTouchesBegan(touches, event) + onTouchesMoved(touches, event) + end + + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchesBegan,cc.Handler.EVENT_TOUCHES_BEGAN ) + listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCHES_MOVED ) + + local eventDispatcher = ret:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, ret) + return ret end @@ -389,7 +395,7 @@ local function LayerTestBlend() local blend = true local function newBlend(dt) - local layer = tolua.cast(ret:getChildByTag(kTagLayer), "LayerColor") + local layer = tolua.cast(ret:getChildByTag(kTagLayer), "cc.LayerColor") local src = 0 local dst = 0 @@ -430,8 +436,6 @@ local function LayerGradient() local layer1 = cc.LayerGradient:create(cc.c4b(255,0,0,255), cc.c4b(0,255,0,255), cc.p(0.9, 0.9)) ret:addChild(layer1, 0, kTagLayer) - ret:setTouchEnabled(true) - local label1 = cc.LabelTTF:create("Compressed Interpolation: Enabled", "Marker Felt", 26) local label2 = cc.LabelTTF:create("Compressed Interpolation: Disabled", "Marker Felt", 26) local item1 = cc.MenuItemLabel:create(label1) @@ -441,7 +445,7 @@ local function LayerGradient() local function toggleItem(sender) -- cclog("toggleItem") - local gradient = tolua.cast(ret:getChildByTag(kTagLayer), "LayerGradient") + local gradient = tolua.cast(ret:getChildByTag(kTagLayer), "cc.LayerGradient") gradient:setCompressedInterpolation(not gradient:isCompressedInterpolation()) end @@ -452,22 +456,23 @@ local function LayerGradient() local s = cc.Director:getInstance():getWinSize() menu:setPosition(cc.p(s.width / 2, 100)) - local function onTouchEvent(eventType, x, y) - if eventType == "began" then - return true - elseif eventType == "moved" then - local s = cc.Director:getInstance():getWinSize() - local start = cc.p(x, y) - local movingPos = cc.p(s.width/2,s.height/2) - local diff = cc.p(movingPos.x - start.x, movingPos.y - start.y) - diff = cc.pNormalize(diff) + local function onTouchesMoved(touches, event) + local s = cc.Director:getInstance():getWinSize() + local start = touches[1]:getLocation() + local movingPos = cc.p(s.width/2,s.height/2) + local diff = cc.p(movingPos.x - start.x, movingPos.y - start.y) + diff = cc.pNormalize(diff) - local gradient = tolua.cast(ret:getChildByTag(1), "LayerGradient") - gradient:setVector(diff) - end + local gradient = tolua.cast(ret:getChildByTag(1), "cc.LayerGradient") + gradient:setVector(diff) end - ret:registerScriptTouchHandler(onTouchEvent) + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCHES_MOVED ) + + local eventDispatcher = ret:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, ret) + return ret end @@ -487,7 +492,7 @@ local function LayerIgnoreAnchorPointPos() l:setPosition(cc.p( s.width/2, s.height/2)) local move = cc.MoveBy:create(2, cc.p(100,2)) - local back = tolua.cast(move:reverse(), "MoveBy") + local back = tolua.cast(move:reverse(), "cc.MoveBy") local seq = cc.Sequence:create(move, back) l:runAction(cc.RepeatForever:create(seq)) ret:addChild(l, 0, kLayerIgnoreAnchorPoint) @@ -564,7 +569,7 @@ local function LayerIgnoreAnchorPointScale() local scale = cc.ScaleBy:create(2, 2) - local back = tolua.cast(scale:reverse(), "ScaleBy") + local back = tolua.cast(scale:reverse(), "cc.ScaleBy") local seq = cc.Sequence:create(scale, back) l:runAction(cc.RepeatForever:create(seq)) diff --git a/samples/Lua/TestLua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua b/tests/test-lua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua similarity index 98% rename from samples/Lua/TestLua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua rename to tests/test-lua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua index dd149a00d5..6fea800fee 100644 --- a/samples/Lua/TestLua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua +++ b/tests/test-lua/Resources/luaScript/LuaBridgeTest/LuaBridgeTest.lua @@ -127,7 +127,7 @@ local function LuaBridgeLayer() local function menuCallback(tag, pMenuItem) local scene = nil - local nIdx = pMenuItem:getZOrder() - itemTagBasic + local nIdx = pMenuItem:getLocalZOrder() - itemTagBasic local newScene = newLuaBridgeScene(nIdx) if nil ~= newScene then newScene:addChild(createMenuToBridgeScene(),10) diff --git a/samples/Lua/TestLua/Resources/luaScript/MenuTest/MenuTest.lua b/tests/test-lua/Resources/luaScript/MenuTest/MenuTest.lua similarity index 89% rename from samples/Lua/TestLua/Resources/luaScript/MenuTest/MenuTest.lua rename to tests/test-lua/Resources/luaScript/MenuTest/MenuTest.lua index d2593602e0..5c1c78c42a 100644 --- a/samples/Lua/TestLua/Resources/luaScript/MenuTest/MenuTest.lua +++ b/tests/test-lua/Resources/luaScript/MenuTest/MenuTest.lua @@ -22,8 +22,6 @@ local function MenuLayerMainMenu() local m_disabledItem = nil local ret = cc.Layer:create() - ret:setTouchEnabled(true) - ret:setTouchMode(cc.TOUCHES_ONE_BY_ONE ) -- Font Item local spriteNormal = cc.Sprite:create(s_MenuItem, cc.rect(0,23*2,115,23)) @@ -34,13 +32,13 @@ local function MenuLayerMainMenu() local function menuCallback(sender) cclog("menuCallback...") - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(1) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(1) end item1:registerScriptTapHandler(menuCallback) -- Image Item local function menuCallback2(sender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(2) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(2) end local item2 = cc.MenuItemImage:create(s_SendScore, s_PressSendScore) @@ -87,7 +85,7 @@ local function MenuLayerMainMenu() cc.MenuItemFont:setFontName("Marker Felt") local function menuCallbackConfig(sender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(3) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(3) end -- Label Item (cc.LabelBMFont) @@ -101,7 +99,7 @@ local function MenuLayerMainMenu() -- Events cc.MenuItemFont:setFontName("Marker Felt") local function menuCallbackBugsTest(pSender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(4) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(4) end -- Bugs Item @@ -117,7 +115,7 @@ local function MenuLayerMainMenu() item7:registerScriptTapHandler(onQuit) local function menuMovingCallback(pSender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(5) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(5) end local item8 = cc.MenuItemFont:create("Remove menu item when moving") @@ -154,7 +152,7 @@ local function MenuLayerMainMenu() if pObject == nil then break end - child = tolua.cast(pObject, "Node") + child = tolua.cast(pObject, "cc.Node") local dstPointX, dstPointY = child:getPosition() local offset = s.width/2 + 50 if i % 2 == 0 then @@ -202,7 +200,7 @@ local function MenuLayer2() local function alignMenusH() local i = 0 for i=0, 1 do - local menu = tolua.cast(ret:getChildByTag(100+i), "Menu") + local menu = tolua.cast(ret:getChildByTag(100+i), "cc.Menu") menu:setPosition( m_centeredMenu ) if i==0 then -- TIP: if no padding, padding = 5 @@ -221,7 +219,7 @@ local function MenuLayer2() local function alignMenusV() local i = 0 for i=0, 1 do - local menu = tolua.cast(ret:getChildByTag(100+i), "Menu") + local menu = tolua.cast(ret:getChildByTag(100+i), "cc.Menu") menu:setPosition( m_centeredMenu ) if i==0 then -- TIP: if no padding, padding = 5 @@ -238,11 +236,11 @@ local function MenuLayer2() end local function menuCallback(sender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(0) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(0) end local function menuCallbackOpacity(tag, sender) - local menu = tolua.cast(sender:getParent(), "Menu") + local menu = tolua.cast(sender:getParent(), "cc.Menu") local opacity = menu:getOpacity() if opacity == 128 then menu:setOpacity(255) @@ -307,7 +305,7 @@ local function MenuLayer3() local m_disabledItem = nil local ret = cc.Layer:create() local function menuCallback(sender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(0) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(0) end local function menuCallback2(sender) @@ -359,8 +357,8 @@ local function MenuLayer3() item2:runAction( cc.RepeatForever:create(cc.Sequence:create( jump, jump:reverse()))) local spin1 = cc.RotateBy:create(3, 360) - local spin2 = tolua.cast(spin1:clone(), "ActionInterval") - local spin3 = tolua.cast(spin1:clone(), "ActionInterval") + local spin2 = tolua.cast(spin1:clone(), "cc.ActionInterval") + local spin3 = tolua.cast(spin1:clone(), "cc.ActionInterval") item1:runAction( cc.RepeatForever:create(spin1) ) item2:runAction( cc.RepeatForever:create(spin2) ) @@ -400,11 +398,11 @@ local function MenuLayer4() local item1 = cc.MenuItemToggle:create(cc.MenuItemFont:create( "On" )) local function menuCallback(tag, sender) - cclog("selected item: tag: %d, index:%d", tag, tolua.cast(sender, "MenuItemToggle"):getSelectedIndex() ) + cclog("selected item: tag: %d, index:%d", tag, tolua.cast(sender, "cc.MenuItemToggle"):getSelectedIndex() ) end local function backCallback(tag, sender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(0) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(0) end item1:registerScriptTapHandler(menuCallback) @@ -477,21 +475,21 @@ end local function BugsTest() local ret = cc.Layer:create() local function issue1410MenuCallback(tag, pSender) - local menu = tolua.cast(pSender:getParent(), "Menu") + local menu = tolua.cast(pSender:getParent(), "cc.Menu") menu:setEnabled(false) menu:setEnabled(true) cclog("NO CRASHES") end local function issue1410v2MenuCallback(tag, pSender) - local menu = tolua.cast(pSender:getParent(), "Menu") + local menu = tolua.cast(pSender:getParent(), "cc.Menu") menu:setEnabled(true) menu:setEnabled(false) cclog("NO CRASHES. AND MENU SHOULD STOP WORKING") end local function backMenuCallback(tag, pSender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(0) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(0) end @@ -528,7 +526,7 @@ local function RemoveMenuItemWhenMove() local back = cc.MenuItemFont:create("go back") local function goBack(tag, pSender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(0) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(0) end back:registerScriptTapHandler(goBack) @@ -542,32 +540,32 @@ local function RemoveMenuItemWhenMove() menu:setPosition(cc.p(s.width/2, s.height/2)) - ret:setTouchEnabled(true) ---[[ + local function onTouchBegan(touch, event) + return true + end + + local function onTouchMoved(touch, event) + if item ~= nil then + item:removeFromParent(true) + --item:release() + --item = nil + end + end + + local listener = cc.EventListenerTouchOneByOne:create() + listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN ) + listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED ) + local eventDispatcher = ret:getEventDispatcher() + eventDispatcher:addEventListenerWithFixedPriority(listener, -129) + local function onNodeEvent(event) - if event == "enter" then - cc.Director:getInstance():getTouchDispatcher():addTargetedDelegate(ret, -129, false) - elseif event == "exit" then - -- item:release() + if event == "exit" then + ret:getEventDispatcher():removeEventListener(listener) end end ret:registerScriptHandler(onNodeEvent) - ]]-- - local function onTouchEvent(eventType, x, y) - if eventType == "began" then - return true - elseif eventType == "moved" then - if item ~= nil then - item:removeFromParent(true) - --item:release() - --item = nil - end - end - end - - ret:registerScriptTouchHandler(onTouchEvent,false,-129,false) return ret end diff --git a/samples/Lua/TestLua/Resources/luaScript/MotionStreakTest/MotionStreakTest.lua b/tests/test-lua/Resources/luaScript/MotionStreakTest/MotionStreakTest.lua similarity index 91% rename from samples/Lua/TestLua/Resources/luaScript/MotionStreakTest/MotionStreakTest.lua rename to tests/test-lua/Resources/luaScript/MotionStreakTest/MotionStreakTest.lua index 60cd559053..79db81c8c7 100644 --- a/samples/Lua/TestLua/Resources/luaScript/MotionStreakTest/MotionStreakTest.lua +++ b/tests/test-lua/Resources/luaScript/MotionStreakTest/MotionStreakTest.lua @@ -106,28 +106,17 @@ local function MotionStreakTest2() streak:setPosition(cc.p(s.width / 2, s.height / 2)) - local function onTouchMoved(x, y) - if firstTick == true then - firstTick = false - return - end - - streak:setPosition(cc.p(x, y)) + local function onTouchesMoved(touches, event) + streak:setPosition( touches[1]:getLocation() ) end - local function onTouch(eventType, x, y) - if eventType == "began" then - return true - elseif eventType == "moved" then - return onTouchMoved(x, y) - end - end - - firstTick = true - layer:setTouchEnabled(true) - layer:registerScriptTouchHandler(onTouch) + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCHES_MOVED ) + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) Helper.titleLabel:setString("MotionStreak test") + return layer end diff --git a/samples/Lua/TestLua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua b/tests/test-lua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua similarity index 99% rename from samples/Lua/TestLua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua rename to tests/test-lua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua index e363ae3141..959950d73e 100644 --- a/samples/Lua/TestLua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua +++ b/tests/test-lua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua @@ -184,7 +184,7 @@ function TouchableSpriteTest:onEnter() sprite2:addChild(sprite3, 1) local function onTouchBegan(touch, event) - local target = tolua.cast(event:getCurrentTarget(),"Sprite") + local target = tolua.cast(event:getCurrentTarget(),"cc.Sprite") local locationInNode = target:convertToNodeSpace(touch:getLocation()) local s = target:getContentSize() @@ -199,20 +199,20 @@ function TouchableSpriteTest:onEnter() end local function onTouchMoved(touch, event) - local target = tolua.cast(event:getCurrentTarget(), "Sprite") + local target = tolua.cast(event:getCurrentTarget(), "cc.Sprite") local posX,posY = target:getPosition() local delta = touch:getDelta() target:setPosition(cc.p(posX + delta.x, posY + delta.y)) end local function onTouchEnded(touch, event) - local target = tolua.cast(event:getCurrentTarget(), "Sprite") + local target = tolua.cast(event:getCurrentTarget(), "cc.Sprite") print("sprite onTouchesEnded..") target:setOpacity(255) if target == sprite2 then - sprite1:setZOrder(100) + sprite1:setLocalZOrder(100) elseif target == sprite1 then - sprite1:setZOrder(0) + sprite1:setLocalZOrder(0) end end diff --git a/samples/Lua/TestLua/Resources/luaScript/NodeTest/NodeTest.lua b/tests/test-lua/Resources/luaScript/NodeTest/NodeTest.lua similarity index 86% rename from samples/Lua/TestLua/Resources/luaScript/NodeTest/NodeTest.lua rename to tests/test-lua/Resources/luaScript/NodeTest/NodeTest.lua index 47e4d0103e..6cf01b65e6 100644 --- a/samples/Lua/TestLua/Resources/luaScript/NodeTest/NodeTest.lua +++ b/tests/test-lua/Resources/luaScript/NodeTest/NodeTest.lua @@ -261,10 +261,10 @@ local function Test6() local rot = cc.RotateBy:create(2, 360) local rot_back = rot:reverse() local forever1 = cc.RepeatForever:create(cc.Sequence:create(rot, rot_back)) - local forever11 = tolua.cast(forever1:clone(), "RepeatForever") + local forever11 = tolua.cast(forever1:clone(), "cc.RepeatForever") - local forever2 = tolua.cast(forever1:clone(), "RepeatForever") - local forever21 = tolua.cast(forever1:clone(), "RepeatForever") + local forever2 = tolua.cast(forever1:clone(), "cc.RepeatForever") + local forever21 = tolua.cast(forever1:clone(), "cc.RepeatForever") Test6_layer:addChild(sp1, 0, kTagSprite1) sp1:addChild(sp11) @@ -299,7 +299,7 @@ local function shouldNotCrash(dt) -- if the node has timers, it crashes local explosion = cc.ParticleSun:create() - explosion:setTexture(cc.TextureCache:getInstance():addImage("Images/fire.png")) + explosion:setTexture(cc.Director:getInstance():getTextureCache():addImage("Images/fire.png")) explosion:setPosition(s.width / 2, s.height / 2) @@ -369,11 +369,11 @@ local function StressTest2() sublayer:addChild(sp1, 1) local fire = cc.ParticleFire:create() - fire:setTexture(cc.TextureCache:getInstance():addImage("Images/fire.png")) - fire = tolua.cast(fire, "Node") + fire:setTexture(cc.Director:getInstance():getTextureCache():addImage("Images/fire.png")) + fire = tolua.cast(fire, "cc.Node") fire:setPosition(80, s.height / 2 - 50) - local copy_seq3 = tolua.cast(seq3:clone(), "Sequence") + local copy_seq3 = tolua.cast(seq3:clone(), "cc.Sequence") fire:runAction(cc.RepeatForever:create(copy_seq3)) sublayer:addChild(fire, 2) @@ -564,32 +564,30 @@ local function ConvertToNode() point:setPosition(sprite:getPosition()) - local copy = tolua.cast(action:clone(), "RepeatForever") + local copy = tolua.cast(action:clone(), "cc.RepeatForever") sprite:runAction(copy) ConvertToNode_layer:addChild(sprite, i) end - local function onTouchEnded(x, y) - for i = 0, 2 do - local node = ConvertToNode_layer:getChildByTag(100 + i) - local p1, p2 - p1 = node:convertToNodeSpaceAR(cc.p(x, y)) - p2 = node:convertToNodeSpace(cc.p(x, y)) + local function onTouchesEnded(touches, event) + local count = table.getn(touches) + for i = 1, count do + local location = touches[i]:getLocation() + for j = 1,3 do + local node = ConvertToNode_layer:getChildByTag(100 + i - 1) + local p1, p2 + p1 = node:convertToNodeSpaceAR(location) + p2 = node:convertToNodeSpace(location) - cclog("AR: x=" .. p1.x .. ", y=" .. p1.y .. " -- Not AR: x=" .. p2.x .. ", y=" .. p2.y) + cclog("AR: x=" .. p1.x .. ", y=" .. p1.y .. " -- Not AR: x=" .. p2.x .. ", y=" .. p2.y) + end end end - local function onTouch(eventType, x, y) - if eventType == "began" then - return true - elseif eventType == "ended" then - return onTouchEnded(x, y) - end - end - - ConvertToNode_layer:setTouchEnabled(true) - ConvertToNode_layer:registerScriptTouchHandler(onTouch) + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchesEnded,cc.Handler.EVENT_TOUCHES_ENDED ) + local eventDispatcher = ConvertToNode_layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, ConvertToNode_layer) Helper.titleLabel:setString("Convert To Node Space") Helper.subtitleLabel:setString("testing convertToNodeSpace / AR. Touch and see console") @@ -631,6 +629,58 @@ local function NodeNonOpaqueTest() return layer end +----------------------------------- +-- NodeGlobalZValueTest +----------------------------------- +local function NodeGlobalZValueTest() + local layer = getBaseLayer() + Helper.titleLabel:setString("Global Z Value") + Helper.subtitleLabel:setString("Center Sprite should change go from foreground to background") + + + local s = cc.Director:getInstance():getWinSize() + local zOrderSprite = nil + for i = 1,9 do + local parent = cc.Node:create() + local sprite = nil + if i == 5 then + sprite = cc.Sprite:create("Images/grossinis_sister2.png") + sprite:setGlobalZOrder(-1) + zOrderSprite = sprite + else + sprite = cc.Sprite:create("Images/grossinis_sister1.png") + end + parent:addChild(sprite) + layer:addChild(parent) + + local w = sprite:getContentSize().width + sprite:setPosition(s.width/2 - w*0.7*(i - 6),s.height / 2) + end + + local accum = 0 + + local function update(dt) + accum = accum + dt + if accum > 1 then + local z = zOrderSprite:getGlobalZOrder() + zOrderSprite:setGlobalZOrder(-z) + accum = 0 + end + end + + local function onNodeEvent(tag) + if tag == "exit" then + layer:unscheduleUpdate() + end + end + layer:scheduleUpdateWithPriorityLua(update,0) + layer:registerScriptHandler(onNodeEvent) + + return layer +end + + + function CocosNodeTest() local scene = cc.Scene:create() @@ -647,7 +697,8 @@ function CocosNodeTest() CameraZoomTest, ConvertToNode, NodeOpaqueTest, - NodeNonOpaqueTest + NodeNonOpaqueTest, + NodeGlobalZValueTest, } scene:addChild(CameraCenterTest()) diff --git a/samples/Lua/TestLua/Resources/luaScript/OpenGLTest/OpenGLTest.lua b/tests/test-lua/Resources/luaScript/OpenGLTest/OpenGLTest.lua similarity index 99% rename from samples/Lua/TestLua/Resources/luaScript/OpenGLTest/OpenGLTest.lua rename to tests/test-lua/Resources/luaScript/OpenGLTest/OpenGLTest.lua index 91ac6844e4..e34f399e07 100644 --- a/samples/Lua/TestLua/Resources/luaScript/OpenGLTest/OpenGLTest.lua +++ b/tests/test-lua/Resources/luaScript/OpenGLTest/OpenGLTest.lua @@ -147,7 +147,7 @@ local function OpenGLTestMainLayer() local i = 0 local len = table.getn(children) for i= 0 ,len - 1 do - local child = tolua.cast(children[i + 1], "Sprite") + local child = tolua.cast(children[i + 1], "cc.Sprite") local oldPosX,oldPosY = child:getPosition() child:setPosition(oldPosX,math.sin(accum * 2 + i / 2.0) * 20) local scaleY = math.sin(accum * 2 + i / 2.0 + 0.707) @@ -558,7 +558,7 @@ local function OpenGLTestMainLayer() local function getCurrentResult() local var = {} - local glProgam = tolua.cast(sprite:getShaderProgram(),"GLProgram") + local glProgam = tolua.cast(sprite:getShaderProgram(),"cc.GLProgram") if nil ~= glProgam then local p = glProgam:getProgram() local aaSize,aaType,aaName = gl.getActiveAttrib(p,0) diff --git a/samples/Lua/TestLua/Resources/luaScript/ParallaxTest/ParallaxTest.lua b/tests/test-lua/Resources/luaScript/ParallaxTest/ParallaxTest.lua similarity index 86% rename from samples/Lua/TestLua/Resources/luaScript/ParallaxTest/ParallaxTest.lua rename to tests/test-lua/Resources/luaScript/ParallaxTest/ParallaxTest.lua index 24f5405368..af6d1c160f 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ParallaxTest/ParallaxTest.lua +++ b/tests/test-lua/Resources/luaScript/ParallaxTest/ParallaxTest.lua @@ -83,7 +83,6 @@ end local function Parallax2() local ret = createParallaxLayer("Parallax: drag screen") - ret:setTouchEnabled( true ) -- Top Layer, a simple image local cocosImage = cc.Sprite:create(s_Power) @@ -126,25 +125,19 @@ local function Parallax2() -- top image is moved at a ratio of 3.0x, 2.5y voidNode:addChild( cocosImage, 2, cc.p(3.0,2.5), cc.p(200,1000) ) ret:addChild(voidNode, 0, kTagNode) - local prev = {x = 0, y = 0} - local function onTouchEvent(eventType, x, y) - if eventType == "began" then - prev.x = x - prev.y = y - return true - elseif eventType == "moved" then - local node = ret:getChildByTag(kTagNode) - local newX = node:getPositionX() - local newY = node:getPositionY() - local diffX = x - prev.x - local diffY = y - prev.y - node:setPosition( cc.pAdd(cc.p(newX, newY), cc.p(diffX, diffY)) ) - prev.x = x - prev.y = y - end + local function onTouchesMoved(touches, event) + local diff = touches[1]:getDelta() + + local node = ret:getChildByTag(kTagNode) + local currentPosX, currentPosY = node:getPosition() + node:setPosition(cc.p(currentPosX + diff.x, currentPosY + diff.y)) end - ret:registerScriptTouchHandler(onTouchEvent) + + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCHES_MOVED ) + local eventDispatcher = ret:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, ret) return ret end diff --git a/samples/Lua/TestLua/Resources/luaScript/ParticleTest/ParticleTest.lua b/tests/test-lua/Resources/luaScript/ParticleTest/ParticleTest.lua similarity index 92% rename from samples/Lua/TestLua/Resources/luaScript/ParticleTest/ParticleTest.lua rename to tests/test-lua/Resources/luaScript/ParticleTest/ParticleTest.lua index f0a9c1ae7c..2b4848251b 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ParticleTest/ParticleTest.lua +++ b/tests/test-lua/Resources/luaScript/ParticleTest/ParticleTest.lua @@ -147,28 +147,34 @@ local function getBaseLayer() local seq = cc.Sequence:create(move, move_back) background:runAction(cc.RepeatForever:create(seq)) - local function onTouchEnded(x, y) - local pos = cc.p(0, 0) - if background ~= nil then - pos = background:convertToWorldSpace(cc.p(0, 0)) - end + local function onTouchesEnded(touches, event) + local location = touches[1]:getLocation() + local pos = cc.p(0, 0) + if background ~= nil then + pos = background:convertToWorldSpace(cc.p(0, 0)) + end - if emitter ~= nil then - local newPos = cc.pSub(cc.p(x, y), pos) - emitter:setPosition(newPos.x, newPos.y) - end - end - - local function onTouch(eventType, x, y) - if eventType == "began" then - return true - else - return onTouchEnded(x, y) + if emitter ~= nil then + local newPos = cc.pSub(location, pos) + emitter:setPosition(newPos.x, newPos.y) end end - layer:setTouchEnabled(true) - layer:registerScriptTouchHandler(onTouch) + local function onTouchesBegan(touches, event) + onTouchesEnded(touches, event); + end + + local function onTouchesMoved(touches, event) + onTouchesEnded(touches, event); + end + + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchesBegan,cc.Handler.EVENT_TOUCHES_BEGAN ) + listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCHES_MOVED ) + listener:registerScriptHandler(onTouchesEnded,cc.Handler.EVENT_TOUCHES_ENDED ) + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) + layer:registerScriptHandler(baseLayer_onEnterOrExit) return layer @@ -378,7 +384,7 @@ local function DemoFlower() emitter = cc.ParticleFlower:create() -- emitter:retain() background:addChild(emitter, 10) - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_stars1)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_stars1)) setEmitterPosition() @@ -396,7 +402,7 @@ local function DemoGalaxy() -- emitter:retain() background:addChild(emitter, 10) - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_fire)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire)) setEmitterPosition() @@ -414,7 +420,7 @@ local function DemoFirework() -- emitter:retain() background:addChild(emitter, 10) - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_stars1)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_stars1)) setEmitterPosition() @@ -432,7 +438,7 @@ local function DemoSpiral() -- emitter:retain() background:addChild(emitter, 10) - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_fire)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire)) setEmitterPosition() @@ -450,7 +456,7 @@ local function DemoSun() -- emitter:retain() background:addChild(emitter, 10) - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_fire)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire)) setEmitterPosition() @@ -468,7 +474,7 @@ local function DemoMeteor() -- emitter:retain() background:addChild(emitter, 10) - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_fire)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire)) setEmitterPosition() @@ -486,7 +492,7 @@ local function DemoFire() -- emitter:retain() background:addChild(emitter, 10) - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_fire)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire)) local pos_x, pos_y = emitter:getPosition() emitter:setPosition(pos_x, 100) @@ -503,7 +509,7 @@ local function DemoSmoke() emitter = cc.ParticleSmoke:create() -- emitter:retain() background:addChild(emitter, 10) - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_fire)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire)) local pos_x, pos_y = emitter:getPosition() emitter:setPosition(pos_x, 100) @@ -523,7 +529,7 @@ local function DemoExplosion() -- emitter:retain() background:addChild(emitter, 10) - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_stars1)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_stars1)) emitter:setAutoRemoveOnFinish(true) @@ -566,7 +572,7 @@ local function DemoSnow() emitter:setEmissionRate(emitter:getTotalParticles() / emitter:getLife()) - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_snow)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_snow)) setEmitterPosition() @@ -587,7 +593,7 @@ local function DemoRain() emitter:setPosition(pos_x, pos_y - 100) emitter:setLife(4) - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_fire)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire)) setEmitterPosition() @@ -605,7 +611,7 @@ local function DemoBigFlower() background:addChild(emitter, 10) ----emitter:release() -- win32 : use this line or remove this line and use autorelease() - emitter:setTexture( cc.TextureCache:getInstance():addImage(s_stars1) ) + emitter:setTexture( cc.Director:getInstance():getTextureCache():addImage(s_stars1) ) emitter:setDuration(-1) -- gravity @@ -674,7 +680,7 @@ local function DemoRotFlower() background:addChild(emitter, 10) ----emitter:release() -- win32 : Remove this line - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_stars2)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_stars2)) -- duration emitter:setDuration(-1) @@ -792,7 +798,7 @@ local function DemoModernArt() emitter:setEndSizeVar(8.0) -- texture - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_fire)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire)) -- additive emitter:setBlendAdditive(false) @@ -814,7 +820,7 @@ local function DemoRing() background:addChild(emitter, 10) - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_stars1)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_stars1)) emitter:setLifeVar(0) emitter:setLife(10) emitter:setSpeed(100) @@ -847,14 +853,14 @@ local function ParallaxParticle() emitter = cc.ParticleFlower:create() -- emitter:retain() - emitter:setTexture(cc.TextureCache:getInstance():addImage(s_fire)) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire)) p1:addChild(emitter, 10) emitter:setPosition(250, 200) local par = cc.ParticleSun:create() p2:addChild(par, 10) - par:setTexture(cc.TextureCache:getInstance():addImage(s_fire)) + par:setTexture(cc.Director:getInstance():getTextureCache():addImage(s_fire)) local move = cc.MoveBy:create(4, cc.p(300,0)) local move_back = move:reverse() @@ -897,7 +903,7 @@ local function RadiusMode1() emitter = cc.ParticleSystemQuad:createWithTotalParticles(200) layer:addChild(emitter, 10) - emitter:setTexture(cc.TextureCache:getInstance():addImage("Images/stars-grayscale.png")) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage("Images/stars-grayscale.png")) -- duration emitter:setDuration(cc.PARTICLE_DURATION_INFINITY) @@ -967,7 +973,7 @@ local function RadiusMode2() emitter = cc.ParticleSystemQuad:createWithTotalParticles(200) layer:addChild(emitter, 10) - emitter:setTexture(cc.TextureCache:getInstance():addImage("Images/stars-grayscale.png")) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage("Images/stars-grayscale.png")) -- duration emitter:setDuration(cc.PARTICLE_DURATION_INFINITY ) @@ -1036,7 +1042,7 @@ local function Issue704() emitter = cc.ParticleSystemQuad:createWithTotalParticles(100) layer:addChild(emitter, 10) - emitter:setTexture(cc.TextureCache:getInstance():addImage("Images/fire.png")) + emitter:setTexture(cc.Director:getInstance():getTextureCache():addImage("Images/fire.png")) -- duration emitter:setDuration(cc.PARTICLE_DURATION_INFINITY) @@ -1129,7 +1135,7 @@ local function Issue870() background = nil local system = cc.ParticleSystemQuad:create("Particles/SpinningPeas.plist") - system:setTextureWithRect(cc.TextureCache:getInstance():addImage("Images/particles.png"), cc.rect(0,0,32,32)) + system:setTextureWithRect(cc.Director:getInstance():getTextureCache():addImage("Images/particles.png"), cc.rect(0,0,32,32)) layer:addChild(system, 10) emitter = system @@ -1151,7 +1157,7 @@ local function MultipleParticleSystems() layer:removeChild(background, true) background = nil - cc.TextureCache:getInstance():addImage("Images/particles.png") + cc.Director:getInstance():getTextureCache():addImage("Images/particles.png") for i = 0, 4 do local particleSystem = cc.ParticleSystemQuad:create("Particles/SpinningPeas.plist") @@ -1278,8 +1284,8 @@ local function reorderSystem(dt) local childArray = ReorderParticleSystems_batchNode:getChildren() local random = math.random(1,table.getn(childArray)) local child = childArray[random] - -- problem: there's no getZOrder() for cc.Object - -- ReorderParticleSystems_batchNode:reorderChild(child, child:getZOrder() - 1) + -- problem: there's no getLocalZOrder() for cc.Object + -- ReorderParticleSystems_batchNode:reorderChild(child, child:getLocalZOrder() - 1) ReorderParticleSystems_batchNode:reorderChild(child, math.random(0, 99999)) end diff --git a/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceSpriteTest.lua b/tests/test-lua/Resources/luaScript/PerformanceTest/PerformanceSpriteTest.lua similarity index 99% rename from samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceSpriteTest.lua rename to tests/test-lua/Resources/luaScript/PerformanceTest/PerformanceSpriteTest.lua index acf5a59927..a2707f5a51 100644 --- a/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceSpriteTest.lua +++ b/tests/test-lua/Resources/luaScript/PerformanceTest/PerformanceSpriteTest.lua @@ -80,7 +80,7 @@ local function initWithSubTest(nSubTest, p) parent = p batchNode = nil - local mgr = cc.TextureCache:getInstance() + local mgr = cc.Director:getInstance():getTextureCache() -- remove all texture mgr:removeTexture(mgr:addImage("Images/grossinis_sister1.png")) mgr:removeTexture(mgr:addImage("Images/grossini_dance_atlas.png")) diff --git a/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua b/tests/test-lua/Resources/luaScript/PerformanceTest/PerformanceTest.lua similarity index 93% rename from samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua rename to tests/test-lua/Resources/luaScript/PerformanceTest/PerformanceTest.lua index 0267dd0eb0..9e2ef7adc9 100644 --- a/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua +++ b/tests/test-lua/Resources/luaScript/PerformanceTest/PerformanceTest.lua @@ -147,7 +147,7 @@ local function runNodeChildrenTest() local function updateQuantityLabel() if nQuantityOfNodes ~= nLastRenderedCount then -- local pInfoLabel = pNewscene:getChildByTag(NodeChildrenTestParam.kTagInfoLayer) - local pInfoLabel = tolua.cast(pNewscene:getChildByTag(NodeChildrenTestParam.kTagInfoLayer), "LabelTTF") + local pInfoLabel = tolua.cast(pNewscene:getChildByTag(NodeChildrenTestParam.kTagInfoLayer), "cc.LabelTTF") local strNode = nQuantityOfNodes.." nodes" pInfoLabel:setString(strNode) nLastRenderedCount = nQuantityOfNodes @@ -166,7 +166,7 @@ local function runNodeChildrenTest() local i = 0 local len = table.getn(pChildren) for i = 0, len - 1, 1 do - local child = tolua.cast(pChildren[i + 1], "Sprite") + local child = tolua.cast(pChildren[i + 1], "cc.Sprite") child:setVisible(false) end end @@ -189,7 +189,7 @@ local function runNodeChildrenTest() end for i = 0 , nTotalToAdd - 1 do - local pChild = tolua.cast(pSprites[i + 1],"Node") + local pChild = tolua.cast(pSprites[i + 1],"cc.Node") pBatchNode:addChild(pChild, zs[i], NodeChildrenTestParam.kTagBase + i) end @@ -216,7 +216,7 @@ local function runNodeChildrenTest() end -- add them with random Z (very important!) for i=0, nTotalToAdd - 1 do - local pChild = tolua.cast(pSprites[i + 1],"Node") + local pChild = tolua.cast(pSprites[i + 1],"cc.Node") pBatchNode:addChild(pChild, math.random(-1,1) * 50, NodeChildrenTestParam.kTagBase + i) end @@ -244,7 +244,7 @@ local function runNodeChildrenTest() --dd them with random Z (very important!) for i = 0, nTotalToAdd - 1 do - local pChild = tolua.cast(pSprites[i + 1] ,"Node") + local pChild = tolua.cast(pSprites[i + 1] ,"cc.Node") pBatchNode:addChild(pChild, math.random(-1,1) * 50, NodeChildrenTestParam.kTagBase + i) end @@ -252,7 +252,7 @@ local function runNodeChildrenTest() -- reorder them for i = 0, nTotalToAdd - 1 do - local pNode = tolua.cast(pSprites[i + 1],"Node") + local pNode = tolua.cast(pSprites[i + 1],"cc.Node") pBatchNode:reorderChild(pNode, math.random(-1,1) * 50) end pBatchNode:sortAllChildren() @@ -501,14 +501,14 @@ local function runParticleTest() end local function TestNCallback(tag,pMenuItem) - local nIndex = pMenuItem:getZOrder() - ParticleTestParam.kSubMenuBasicZOrder + local nIndex = pMenuItem:getLocalZOrder() - ParticleTestParam.kSubMenuBasicZOrder nSubtestNumber = nIndex ShowCurrentTest() end local function UpdateQuantityLabel() if nQuantityParticles ~= nLastRenderedCount then - local pInfoLabel = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagInfoLayer), "LabelTTF") + local pInfoLabel = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagInfoLayer), "cc.LabelTTF") local strInfo = string.format("%u particles", nQuantityParticles) pInfoLabel:setString(strInfo) @@ -518,7 +518,7 @@ local function runParticleTest() local function doTest() local s = cc.Director:getInstance():getWinSize() - local pParticleSystem = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagParticleSystem),"ParticleSystem") + local pParticleSystem = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagParticleSystem),"cc.ParticleSystem") if nil == pParticleSystem then return end @@ -731,8 +731,8 @@ local function runParticleTest() pNewScene:removeChildByTag(ParticleTestParam.kTagParticleSystem, true) --remove the "fire.png" from the TextureCache cache. - local pTexture = cc.TextureCache:getInstance():addImage("Images/fire.png") - cc.TextureCache:getInstance():removeTexture(pTexture) + local pTexture = cc.Director:getInstance():getTextureCache():addImage("Images/fire.png") + cc.Director:getInstance():getTextureCache():removeTexture(pTexture) local pParticleSystem = cc.ParticleSystemQuad:createWithTotalParticles(nQuantityParticles) if 1 == nSubtestNumber then cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888) @@ -752,7 +752,7 @@ local function runParticleTest() end if nil ~= pParticleSystem then - pParticleSystem:setTexture(cc.TextureCache:getInstance():addImage("Images/fire.png")) + pParticleSystem:setTexture(cc.Director:getInstance():getTextureCache():addImage("Images/fire.png")) end pNewScene:addChild(pParticleSystem, 0, ParticleTestParam.kTagParticleSystem) @@ -763,8 +763,8 @@ local function runParticleTest() end local function step(t) - local pAtlas = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagLabelAtlas),"LabelAtlas") - local pEmitter = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagParticleSystem),"ParticleSystem") + local pAtlas = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagLabelAtlas),"cc.LabelAtlas") + local pEmitter = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagParticleSystem),"cc.ParticleSystem") local strInfo = string.format("%4d",pEmitter:getParticleCount()) pAtlas:setString(strInfo) end @@ -989,7 +989,7 @@ local function runSpriteTest() local function UpdateNodes() if nQuantityNodes ~= nLastRenderedCount then - local pInfoLabel = tolua.cast(pNewScene:getChildByTag(SpriteTestParam.kTagInfoLayer), "LabelTTF") + local pInfoLabel = tolua.cast(pNewScene:getChildByTag(SpriteTestParam.kTagInfoLayer), "cc.LabelTTF") local strInfo = string.format("%u nodes", nQuantityNodes) pInfoLabel:setString(strInfo) nLastRenderedCount = nQuantityNodes @@ -1178,7 +1178,7 @@ local function runSpriteTest() end local function TestNCallback(tag,pMenuItem) - local nIndex = pMenuItem:getZOrder() - SpriteTestParam.kSubMenuBasicZOrder + local nIndex = pMenuItem:getLocalZOrder() - SpriteTestParam.kSubMenuBasicZOrder nSubtestNumber = nIndex ShowCurrentTest() end @@ -1203,7 +1203,7 @@ local function runSpriteTest() *12: 64 (4-bit) PVRTC Batch Node of 32 x 32 each ]]-- --purge textures - local pMgr = cc.TextureCache:getInstance() + local pMgr = cc.Director:getInstance():getTextureCache() --[mgr removeAllTextures] pMgr:removeTexture(pMgr:addImage("Images/grossinis_sister1.png")) pMgr:removeTexture(pMgr:addImage("Images/grossini_dance_atlas.png")) @@ -1352,7 +1352,10 @@ local function runTextureTest() local function PerformTestsPNG(strFileName) local time local pTexture = nil - local pCache = cc.TextureCache:getInstance() + local pCache = cc.Director:getInstance():getTextureCache() + + local pDefaultFormat = cc.Texture2D:getDefaultAlphaPixelFormat(); + print("RGBA 8888") cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888) pTexture = pCache:addImage(strFileName) @@ -1397,6 +1400,8 @@ local function runTextureTest() print(" ERROR") end pCache:removeTexture(pTexture) + + cc.Texture2D:setDefaultAlphaPixelFormat(pDefaultFormat) end local function PerformTests() print("--------") @@ -1548,48 +1553,37 @@ local function runTouchesTest() end -- handling touch events - local function onTouchBegan(tableArray) - if 0 == nCurCase then - nNumberOfTouchesB = nNumberOfTouchesB + 1 - elseif 1 == nCurCase then - nNumberOfTouchesB = nNumberOfTouchesB + table.getn(tableArray) - end - end - - local function onTouchMoved(tableArray) - if 0 == nCurCase then - nNumberOfTouchesM = nNumberOfTouchesM + 1 - elseif 1 == nCurCase then - nNumberOfTouchesM = nNumberOfTouchesM + table.getn(tableArray) - end - end - - local function onTouchEnded(tableArray) - if 0 == nCurCase then - nNumberOfTouchesE = nNumberOfTouchesE + 1 - elseif 1 == nCurCase then - nNumberOfTouchesE = nNumberOfTouchesE + table.getn(tableArray) - end - end - - local function onTouchCancelled(tableArray) - if 0 == nCurCase then - nNumberOfTouchesC = nNumberOfTouchesC + 1 - elseif 1 == nCurCase then - nNumberOfTouchesC = nNumberOfTouchesC + table.getn(tableArray) - end + local function onTouchEnded(touch, event) + nNumberOfTouchesE = nNumberOfTouchesE + 1 end - local function onTouch(eventType,tableArray) - if eventType == "began" then - return onTouchBegan(tableArray) - elseif eventType == "moved" then - return onTouchMoved(tableArray) - elseif eventType == "ended" then - return onTouchEnded(tableArray) - elseif eventType == "cancelled" then - return onTouchCancelled(tableArray) - end + local function onTouchBegan(touch, event) + nNumberOfTouchesB = nNumberOfTouchesB + 1 + end + + local function onTouchMoved(touch, event) + nNumberOfTouchesM = nNumberOfTouchesM + 1 + end + + local function onTouchCancelled(touch, event) + nNumberOfTouchesC = nNumberOfTouchesC + 1 + end + + + local function onTouchesEnded(touches, event) + nNumberOfTouchesE = nNumberOfTouchesE + table.getn(touches) + end + + local function onTouchesBegan(touches, event) + nNumberOfTouchesB = nNumberOfTouchesB + table.getn(touches) + end + + local function onTouchesMoved(touches, event) + nNumberOfTouchesM = nNumberOfTouchesM + table.getn(touches) + end + + local function onTouchesCancelled(touches, event) + nNumberOfTouchesC= nNumberOfTouchesC + table.getn(touches) end local function InitLayer() @@ -1617,9 +1611,24 @@ local function runTouchesTest() nNumberOfTouchesM = 0 nNumberOfTouchesE = 0 nNumberOfTouchesC = 0 - pLayer:setTouchEnabled(true) - - pLayer:registerScriptTouchHandler(onTouch,true) + + if 0 == nCurCase then + local listener = cc.EventListenerTouchOneByOne:create() + listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN ) + listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED ) + listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED ) + listener:registerScriptHandler(onTouchCancelled,cc.Handler.EVENT_TOUCH_CANCELLED ) + local eventDispatcher = pLayer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, pLayer) + elseif 1 == nCurCase then + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchesBegan,cc.Handler.EVENT_TOUCHES_BEGAN ) + listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCHES_MOVED ) + listener:registerScriptHandler(onTouchesEnded,cc.Handler.EVENT_TOUCHES_ENDED ) + listener:registerScriptHandler(onTouchesCancelled,cc.Handler.EVENT_TOUCHES_CANCELLED ) + local eventDispatcher = pLayer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, pLayer) + end end function ShowCurrentTest() @@ -1661,7 +1670,7 @@ local function CreatePerformancesTestScene(nPerformanceNo) end local function menuCallback(tag, pMenuItem) local scene = nil - local nIdx = pMenuItem:getZOrder() - kItemTagBasic + local nIdx = pMenuItem:getLocalZOrder() - kItemTagBasic local PerformanceTestScene = CreatePerformancesTestScene(nIdx) if nil ~= PerformanceTestScene then cc.Director:getInstance():replaceScene(PerformanceTestScene) diff --git a/samples/Lua/TestLua/Resources/luaScript/PhysicsTest/PhysicsTest.lua b/tests/test-lua/Resources/luaScript/PhysicsTest/PhysicsTest.lua similarity index 63% rename from samples/Lua/TestLua/Resources/luaScript/PhysicsTest/PhysicsTest.lua rename to tests/test-lua/Resources/luaScript/PhysicsTest/PhysicsTest.lua index 0434b0a3c4..0cff427b7f 100644 --- a/samples/Lua/TestLua/Resources/luaScript/PhysicsTest/PhysicsTest.lua +++ b/tests/test-lua/Resources/luaScript/PhysicsTest/PhysicsTest.lua @@ -16,6 +16,89 @@ local function range(from, to, step) end, nil, from - step end +-- bit operation + +bit = bit or {} +bit.data32 = {} +for i=1,32 do + bit.data32[i]=2^(32-i) +end + +function bit._b2d(arg) + local nr=0 + for i=1,32 do + if arg[i] ==1 then + nr=nr+bit.data32[i] + end + end + return nr +end + +function bit._d2b(arg) + arg = arg >= 0 and arg or (0xFFFFFFFF + arg + 1) + local tr={} + for i=1,32 do + if arg >= bit.data32[i] then + tr[i]=1 + arg=arg-bit.data32[i] + else + tr[i]=0 + end + end + return tr +end + +function bit._and(a,b) + local op1=bit._d2b(a) + local op2=bit._d2b(b) + local r={} + + for i=1,32 do + if op1[i]==1 and op2[i]==1 then + r[i]=1 + else + r[i]=0 + end + end + return bit._b2d(r) + +end + +function bit._rshift(a,n) + local op1=bit._d2b(a) + n = n <= 32 and n or 32 + n = n >= 0 and n or 0 + + for i=32, n+1, -1 do + op1[i] = op1[i-n] + end + for i=1, n do + op1[i] = 0 + end + + return bit._b2d(op1) +end + +function bit._not(a) + local op1=bit._d2b(a) + local r={} + + for i=1,32 do + if op1[i]==1 then + r[i]=0 + else + r[i]=1 + end + end + return bit._b2d(r) +end + +bit.band = bit.band or bit._and +bit.rshift = bit.rshift or bit._rshift +bit.bnot = bit.bnot or bit._not + +-- bit operation end + local function initWithLayer(layer, callback) curLayer = layer layer.spriteTexture = cc.SpriteBatchNode:create("Images/grossini_dance_atlas.png", 100):getTexture() @@ -26,7 +109,7 @@ local function initWithLayer(layer, callback) cc.Director:getInstance():getRunningScene():getPhysicsWorld():setDebugDrawMask(debug and cc.PhysicsWorld.DEBUGDRAW_ALL or cc.PhysicsWorld.DEBUGDRAW_NONE) end - layer.toggleDebug = toggleDebugCallback; + layer.toggleDebug = function(self) toggleDebugCallback(nil) end; cc.MenuItemFont:setFontSize(18) local item = cc.MenuItemFont:create("Toogle debug") item:registerScriptTapHandler(toggleDebugCallback) @@ -291,9 +374,6 @@ local function PhysicsDemoJoints() for j in range(0, 3) do local offset = cc.p(VisibleRect:leftBottom().x + 5 + j * width + width/2, VisibleRect:leftBottom().y + 50 + i * height + height/2); box:addShape(cc.PhysicsShapeEdgeBox:create(cc.size(width, height), cc.PHYSICSSHAPE_MATERIAL_DEFAULT, 1, offset)); - print("i,j") - print(i) - print(j) local index = i*4 + j if index == 0 then local sp1 = makeBall(layer, cc.p(offset.x - 30, offset.y), 10); @@ -597,13 +677,339 @@ local function PhysicsDemoRayCast() return layer end -local function registerOnEnter() - layer:registerOn(PhysicsDemoLogoSmash) +local function PhysicsDemoOneWayPlatform() + local layer = cc.Layer:create() + local function onEnter() + + local touchListener = cc.EventListenerTouchOneByOne:create(); + touchListener:registerScriptHandler(onTouchBegan, cc.Handler.EVENT_TOUCH_BEGAN); + touchListener:registerScriptHandler(onTouchMoved, cc.Handler.EVENT_TOUCH_MOVED); + touchListener:registerScriptHandler(onTouchEnded, cc.Handler.EVENT_TOUCH_ENDED); + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer); + + local ground = cc.Node:create(); + ground:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x, VisibleRect:leftBottom().y + 50), cc.p(VisibleRect:rightBottom().x, VisibleRect:rightBottom().y + 50))); + layer:addChild(ground); + + local platform = makeBox(VisibleRect:center(), cc.size(200, 50)); + platform:getPhysicsBody():setDynamic(false); + layer:addChild(platform); + + local ball = makeBall(layer, cc.p(VisibleRect:center().x, VisibleRect:center().y - 50), 20); + ball:getPhysicsBody():setVelocity(cc.p(0, 150)); + ball:getPhysicsBody():setTag(DRAG_BODYS_TAG); + ball:getPhysicsBody():setMass(1.0); + layer:addChild(ball); + + local function onContactBegin(event, contact) + return contact:getContactData().normal.y < 0; + end + local contactListener = cc.EventListenerPhysicsContactWithBodies:create(platform:getPhysicsBody(), ball:getPhysicsBody()); + contactListener:registerScriptHandler(onContactBegin, cc.Handler.EVENT_PHYSICS_CONTACT_BEGIN); + eventDispatcher:addEventListenerWithSceneGraphPriority(contactListener, layer); + end + + initWithLayer(layer, onEnter) + Helper.titleLabel:setString("One Way Platform") + + return layer +end + +local function PhysicsDemoActions() + local layer = cc.Layer:create() + local function onEnter() + local touchListener = cc.EventListenerTouchOneByOne:create() + touchListener:registerScriptHandler(onTouchBegan, cc.Handler.EVENT_TOUCH_BEGAN) + touchListener:registerScriptHandler(onTouchMoved, cc.Handler.EVENT_TOUCH_MOVED) + touchListener:registerScriptHandler(onTouchEnded, cc.Handler.EVENT_TOUCH_ENDED) + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) + + local node = cc.Node:create(); + node:setPhysicsBody(cc.PhysicsBody:createEdgeBox(cc.size(VisibleRect:getVisibleRect().width, VisibleRect:getVisibleRect().height))); + node:setPosition(VisibleRect:center()); + layer:addChild(node); + + local sp1 = addGrossiniAtPosition(layer, VisibleRect:center()); + local sp2 = addGrossiniAtPosition(layer, cc.p(VisibleRect:left().x + 50, VisibleRect:left().y)); + local sp3 = addGrossiniAtPosition(layer, cc.p(VisibleRect:right().x - 20, VisibleRect:right().y)); + local sp4 = addGrossiniAtPosition(layer, cc.p(VisibleRect:leftTop().x + 50, VisibleRect:leftTop().y-50)); + sp4:getPhysicsBody():setGravityEnable(false); + + + local actionTo = cc.JumpTo:create(2, cc.p(100,100), 50, 4); + local actionBy = cc.JumpBy:create(2, cc.p(300,0), 50, 4); + local actionUp = cc.JumpBy:create(2, cc.p(0,50), 80, 4); + local actionByBack = actionBy:reverse(); + + sp1:runAction(cc.RepeatForever:create(actionUp)); + sp2:runAction(cc.RepeatForever:create(cc.Sequence:create(actionBy, actionByBack))); + sp3:runAction(actionTo); + sp4:runAction(cc.RepeatForever:create(cc.Sequence:create(actionBy:clone(), actionByBack:clone()))); + end + + initWithLayer(layer, onEnter) + Helper.titleLabel:setString("Actions") + + return layer +end + +local function PhysicsDemoPump() + local layer = cc.Layer:create() + local function onEnter() + layer:toggleDebug(); + + local distance = 0.0; + local rotationV = 0.0; + local function onTouchBeganEx(touch, event) + onTouchBegan(touch, event) + distance = touch:getLocation().x - VisibleRect:center().x; + return true; + end + + local function onTouchMovedEx(touch, event) + onTouchMoved(touch, event); + distance = touch:getLocation().x - VisibleRect:center().x; + end + + local function onTouchEndedEx(touch, event) + onTouchEnded(touch, event) + distance = 0; + end + + local touchListener = cc.EventListenerTouchOneByOne:create() + touchListener:registerScriptHandler(onTouchBeganEx, cc.Handler.EVENT_TOUCH_BEGAN) + touchListener:registerScriptHandler(onTouchMovedEx, cc.Handler.EVENT_TOUCH_MOVED) + touchListener:registerScriptHandler(onTouchEndedEx, cc.Handler.EVENT_TOUCH_ENDED) + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer) + + local function update() + for _, body in ipairs(cc.Director:getInstance():getRunningScene():getPhysicsWorld():getAllBodies()) do + if body:getTag() == DRAG_BODYS_TAG and body:getPosition().y < 0.0 then + body:getNode():setPosition(cc.p(VisibleRect:leftTop().x + 75, VisibleRect:leftTop().y + math.random() * 90, 0)); + body:setVelocity(cc.p(0, 0)); + end + end + + local gear = cc.Director:getInstance():getRunningScene():getPhysicsWorld():getBody(1); + if gear then + if distance ~= 0.0 then + rotationV = rotationV + distance/2500.0; + end + if rotationV > 30 then rotationV = 30.0 end + if rotationV < -30 then rotationV = -30.0 end + + gear:setAngularVelocity(rotationV); + rotationV = rotationV*0.995; + end + end + + layer:scheduleUpdateWithPriorityLua(update, 0); + + local node = cc.Node:create(); + local body = cc.PhysicsBody:create(); + body:setDynamic(false); + + local staticMaterial = cc.PhysicsMaterial(cc.PHYSICS_INFINITY, 0, 0.5); + body:addShape(cc.PhysicsShapeEdgeSegment:create( + cc.p(VisibleRect:leftTop().x + 50, VisibleRect:leftTop().y), + cc.p(VisibleRect:leftTop().x + 50, VisibleRect:leftTop().y-130), staticMaterial, 2.0)); + body:addShape(cc.PhysicsShapeEdgeSegment:create( + cc.p(VisibleRect:leftTop().x + 190, VisibleRect:leftTop().y), + cc.p(VisibleRect:leftTop().x + 100, VisibleRect:leftTop().y-50), staticMaterial, 2.0)); + body:addShape(cc.PhysicsShapeEdgeSegment:create( + cc.p(VisibleRect:leftTop().x + 100, VisibleRect:leftTop().y-50), + cc.p(VisibleRect:leftTop().x + 100, VisibleRect:leftTop().y-90), staticMaterial, 2.0)); + body:addShape(cc.PhysicsShapeEdgeSegment:create( + cc.p(VisibleRect:leftTop().x + 50, VisibleRect:leftTop().y-130), + cc.p(VisibleRect:leftTop().x + 100, VisibleRect:leftTop().y-145), staticMaterial, 2.0)); + body:addShape(cc.PhysicsShapeEdgeSegment:create( + cc.p(VisibleRect:leftTop().x + 100, VisibleRect:leftTop().y-145), + cc.p(VisibleRect:leftBottom().x + 100, VisibleRect:leftBottom().y + 80), staticMaterial, 2.0)); + body:addShape(cc.PhysicsShapeEdgeSegment:create( + cc.p(VisibleRect:leftTop().x + 150, VisibleRect:leftTop().y-80), + cc.p(VisibleRect:leftBottom().x + 150, VisibleRect:leftBottom().y + 80), staticMaterial, 2.0)); + body:addShape(cc.PhysicsShapeEdgeSegment:create( + cc.p(VisibleRect:leftTop().x + 150, VisibleRect:leftTop().y-80), + cc.p(VisibleRect:rightTop().x -100, VisibleRect:rightTop().y-150), staticMaterial, 2.0)); + + body:setCategoryBitmask(1); + + for _ in range(1, 6) do + local ball = makeBall(layer, cc.p(VisibleRect:leftTop().x + 75 + math.random() * 90, VisibleRect:leftTop().y), 22, cc.PhysicsMaterial(0.05, 0.0, 0.1)); + ball:getPhysicsBody():setTag(DRAG_BODYS_TAG); + layer:addChild(ball); + end + + node:setPhysicsBody(body); + layer:addChild(node); + + local vec = + { + cc.p(VisibleRect:leftTop().x + 102, VisibleRect:leftTop().y-148), + cc.p(VisibleRect:leftTop().x + 148, VisibleRect:leftTop().y-161), + cc.p(VisibleRect:leftBottom().x + 148, VisibleRect:leftBottom().y + 20), + cc.p(VisibleRect:leftBottom().x + 102, VisibleRect:leftBottom().y + 20) + }; + + local world = cc.Director:getInstance():getRunningScene():getPhysicsWorld(); + + -- small gear + local sgear = cc.Node:create(); + local sgearB = cc.PhysicsBody:createCircle(44); + sgear:setPhysicsBody(sgearB); + sgear:setPosition(cc.p(VisibleRect:leftBottom().x + 125, VisibleRect:leftBottom().y)); + layer:addChild(sgear); + sgearB:setCategoryBitmask(4); + sgearB:setCollisionBitmask(4); + sgearB:setTag(1); + world:addJoint(cc.PhysicsJointPin:construct(body, sgearB, sgearB:getPosition())); + + + -- big gear + local bgear = cc.Node:create(); + local bgearB = cc.PhysicsBody:createCircle(100); + bgear:setPhysicsBody(bgearB); + bgear:setPosition(cc.p(VisibleRect:leftBottom().x + 275, VisibleRect:leftBottom().y)); + layer:addChild(bgear); + bgearB:setCategoryBitmask(4); + world:addJoint(cc.PhysicsJointPin:construct(body, bgearB, bgearB:getPosition())); + + + -- pump + local pump = cc.Node:create(); + local center = cc.PhysicsShape:getPolyonCenter(vec); + pump:setPosition(center); + local pumpB = cc.PhysicsBody:createPolygon(vec, cc.PHYSICSBODY_MATERIAL_DEFAULT, cc.p(-center.x, -center.y)); + pump:setPhysicsBody(pumpB); + layer:addChild(pump); + pumpB:setCategoryBitmask(2); + pumpB:setGravityEnable(false); + world:addJoint(cc.PhysicsJointDistance:construct(pumpB, sgearB, cc.p(0, 0), cc.p(0, -44))); + + -- plugger + local seg = {cc.p(VisibleRect:leftTop().x + 75, VisibleRect:leftTop().y-120), cc.p(VisibleRect:leftBottom().x + 75, VisibleRect:leftBottom().y-100)}; + local segCenter = cc.p((seg[2].x + seg[1].x)/2, (seg[2].y + seg[1].y)/2); + seg[2] = cc.p(seg[2].x - segCenter.x, seg[2].y - segCenter.y); + seg[1] = cc.p(seg[1].x - segCenter.x, seg[1].y - segCenter.y); + local plugger = cc.Node:create(); + local pluggerB = cc.PhysicsBody:createEdgeSegment(seg[1], seg[2], cc.PhysicsMaterial(0.01, 0.0, 0.5), 20); + pluggerB:setDynamic(true); + pluggerB:setMass(30); + pluggerB:setMoment(100000); + plugger:setPhysicsBody(pluggerB); + plugger:setPosition(segCenter); + layer:addChild(plugger); + pluggerB:setCategoryBitmask(2); + sgearB:setCollisionBitmask(5); + world:addJoint(cc.PhysicsJointPin:construct(body, pluggerB, cc.p(VisibleRect:leftBottom().x + 75, VisibleRect:leftBottom().y-90))); + world:addJoint(cc.PhysicsJointDistance:construct(pluggerB, sgearB, + pluggerB:world2Local(cc.p(VisibleRect:leftBottom().x + 75, VisibleRect:leftBottom().y)), cc.p(44, 0))); + end + + initWithLayer(layer, onEnter) + Helper.titleLabel:setString("Pump") + Helper.subtitleLabel:setString("touch screen on left or right") + + return layer +end + +local function PhysicsDemoSlice() + local layer = cc.Layer:create() + local function onEnter() + layer:toggleDebug() + local sliceTag = 1; + + local function clipPoly(shape, normal, distance) + local body = shape:getBody(); + local count = shape:getPointsCount(); + local points = {} + + local j = count - 1 + for i in range(0, count-1) do + local a = body:local2World(shape:getPoint(j)); + local aDist = cc.pDot(a, normal) - distance; + + if aDist < 0.0 then + points[#points + 1] = a; + end + + local b = body:local2World(shape:getPoint(i)); + local bDist = cc.pDot(b, normal) - distance; + + if aDist*bDist < 0.0 then + local t = math.abs(aDist)/(math.abs(aDist) + math.abs(bDist)); + points[#points + 1] = cc.pLerp(a, b, t); + end + j = i + end + + local center = cc.PhysicsShape:getPolyonCenter(points); + local node = cc.Node:create(); + local polyon = cc.PhysicsBody:createPolygon(points, cc.PHYSICSBODY_MATERIAL_DEFAULT, cc.p(-center.x, -center.y)); + node:setPosition(center); + node:setPhysicsBody(polyon); + polyon:setVelocity(body:getVelocityAtWorldPoint(center)); + polyon:setAngularVelocity(body:getAngularVelocity()); + polyon.tag = sliceTag; + layer:addChild(node); + end + + + local function slice(world, info) + if info.shape:getBody().tag ~= sliceTag then + return true; + end + + if not info.shape:containsPoint(info.start) and not info.shape:containsPoint(info.ended) then + local normal = cc.p(info.ended.x - info.start.x, info.ended.y - info.start.y); + normal = cc.pNormalize(cc.pPerp(normal)); + local dist = cc.pDot(info.start, normal); + + clipPoly(info.shape, normal, dist); + clipPoly(info.shape, cc.p(-normal.x, -normal.y), -dist); + + info.shape:getBody():removeFromWorld(); + end + return true; + end + + local function onTouchEnded(touch, event) + cc.Director:getInstance():getRunningScene():getPhysicsWorld():rayCast(slice, touch:getStartLocation(), touch:getLocation()); + end + + local touchListener = cc.EventListenerTouchOneByOne:create(); + touchListener:registerScriptHandler(function() return true end, cc.Handler.EVENT_TOUCH_BEGAN); + touchListener:registerScriptHandler(onTouchEnded, cc.Handler.EVENT_TOUCH_ENDED); + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(touchListener, layer); + + local ground = cc.Node:create(); + ground:setPhysicsBody(cc.PhysicsBody:createEdgeSegment(cc.p(VisibleRect:leftBottom().x, VisibleRect:leftBottom().y + 50), + cc.p(VisibleRect:rightBottom().x, VisibleRect:rightBottom().y + 50))); + layer:addChild(ground); + + local box = cc.Node:create(); + local points = {cc.p(-100, -100), cc.p(-100, 100), cc.p(100, 100), cc.p(100, -100)}; + box:setPhysicsBody(cc.PhysicsBody:createPolygon(points)); + box:setPosition(VisibleRect:center()); + box:getPhysicsBody().tag = sliceTag; + layer:addChild(box); + end + + initWithLayer(layer, onEnter) + Helper.titleLabel:setString("Slice") + Helper.subtitleLabel:setString("click and drag to slice up the block") + + return layer end function PhysicsTest() - cclog("PhysicsTest") - local scene = cc.Scene:createWithPhysics() + cclog("PhysicsTest") + local scene = cc.Scene:createWithPhysics() + Helper.usePhysics = true Helper.createFunctionTable = { @@ -612,6 +1018,10 @@ function PhysicsTest() PhysicsDemoClickAdd, PhysicsDemoRayCast, PhysicsDemoJoints, + PhysicsDemoActions, + PhysicsDemoPump, + PhysicsDemoOneWayPlatform, + PhysicsDemoSlice, } scene:addChild(Helper.createFunctionTable[1]()) diff --git a/samples/Lua/TestLua/Resources/luaScript/RenderTextureTest/RenderTextureTest.lua b/tests/test-lua/Resources/luaScript/RenderTextureTest/RenderTextureTest.lua similarity index 85% rename from samples/Lua/TestLua/Resources/luaScript/RenderTextureTest/RenderTextureTest.lua rename to tests/test-lua/Resources/luaScript/RenderTextureTest/RenderTextureTest.lua index d398b87f34..d44a4a677a 100644 --- a/samples/Lua/TestLua/Resources/luaScript/RenderTextureTest/RenderTextureTest.lua +++ b/tests/test-lua/Resources/luaScript/RenderTextureTest/RenderTextureTest.lua @@ -8,24 +8,23 @@ local function RenderTextureSave() local ret = createTestLayer("Touch the screen", "Press 'Save Image' to create an snapshot of the render texture") local s = cc.Director:getInstance():getWinSize() - local m_pTarget = nil - local m_pBrush = nil - local m_pTarget = nil + local target = nil local counter = 0 + local brushes = {} local function clearImage(tag, pSender) - m_pTarget:clear(math.random(), math.random(), math.random(), math.random()) + target:clear(math.random(), math.random(), math.random(), math.random()) end local function saveImage(tag, pSender) local png = string.format("image-%d.png", counter) local jpg = string.format("image-%d.jpg", counter) - m_pTarget:saveToFile(png, cc.IMAGE_FORMAT_PNG) - m_pTarget:saveToFile(jpg, cc.IMAGE_FORMAT_JPEG) + target:saveToFile(png, cc.IMAGE_FORMAT_PNG) + target:saveToFile(jpg, cc.IMAGE_FORMAT_JPEG) - local pImage = m_pTarget:newImage() + local pImage = target:newImage() - local tex = cc.TextureCache:getInstance():addUIImage(pImage, png) + local tex = cc.Director:getInstance():getTextureCache():addUIImage(pImage, png) pImage:release() @@ -42,78 +41,66 @@ local function RenderTextureSave() local function onNodeEvent(event) if event == "exit" then - m_pBrush:release() - m_pTarget:release() - cc.TextureCache:getInstance():removeUnusedTextures() + target:release() + cc.Director:getInstance():getTextureCache():removeUnusedTextures() end end ret:registerScriptHandler(onNodeEvent) -- create a render texture, this is what we are going to draw into - m_pTarget = cc.RenderTexture:create(s.width, s.height, cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888) - m_pTarget:retain() - m_pTarget:setPosition(cc.p(s.width / 2, s.height / 2)) + target = cc.RenderTexture:create(s.width, s.height, cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888) + target:retain() + target:setPosition(cc.p(s.width / 2, s.height / 2)) -- note that the render texture is a cc.Node, and contains a sprite of its texture for convience, -- so we can just parent it to the scene like any other cc.Node - ret:addChild(m_pTarget, -1) + ret:addChild(target, -1) - -- create a brush image to draw into the texture with - m_pBrush = cc.Sprite:create("Images/fire.png") - m_pBrush:retain() - m_pBrush:setColor(cc.c3b(255, 0, 0)) - m_pBrush:setOpacity(20) + local function onTouchesMoved(touches, event) + local start = touches[1]:getLocation() + local ended = touches[1]:getPreviousLocation() + target:begin() - local prev = {x = 0, y = 0} - local function onTouchEvent(eventType, x, y) - if eventType == "began" then - prev.x = x - prev.y = y - return true - elseif eventType == "moved" then - local diffX = x - prev.x - local diffY = y - prev.y + local distance = cc.pGetDistance(start, ended) + if distance > 1 then + brushes = {} + local d = distance + local i = 0 - local startP = cc.p(x, y) - local endP = cc.p(prev.x, prev.y) - - -- begin drawing to the render texture - m_pTarget:begin() - - -- for extra points, we'll draw this smoothly from the last position and vary the sprite's - -- scale/rotation/offset - local distance = cc.pGetDistance(startP, endP) - if distance > 1 then - local d = distance - local i = 0 - for i = 0, d-1 do - local difx = endP.x - startP.x - local dify = endP.y - startP.y - local delta = i / distance - m_pBrush:setPosition(cc.p(startP.x + (difx * delta), startP.y + (dify * delta))) - m_pBrush:setRotation(math.random(0, 359)) - local r = math.random(0, 49) / 50.0 + 0.25 - m_pBrush:setScale(r) - - -- Use cc.RANDOM_0_1() will cause error when loading libtests.so on android, I don't know why. - m_pBrush:setColor(cc.c3b(math.random(0, 126) + 128, 255, 255)) - -- Call visit to draw the brush, don't call draw.. - m_pBrush:visit() - end + for i = 0,d -1 do + -- create a brush image to draw into the texture with + local sprite = cc.Sprite:create("Images/fire.png") + sprite:setColor(cc.c3b(255, 0, 0)) + sprite:setOpacity(20) + brushes[i + 1] = sprite end - -- finish drawing and return context back to the screen - m_pTarget:endToLua() + for i = 0,d -1 do + local difx = ended.x - start.x + local dify = ended.y - start.y + local delta = i / distance + brushes[i + 1]:setPosition(cc.p(start.x + (difx * delta), start.y + (dify * delta))) + brushes[i + 1]:setRotation(math.random(0, 359)) + local r = math.random(0, 49) / 50.0 + 0.25 + brushes[i + 1]:setScale(r) + + -- Use cc.RANDOM_0_1() will cause error when loading libtests.so on android, I don't know why. + brushes[i + 1]:setColor(cc.c3b(math.random(0, 126) + 128, 255, 255)) + -- Call visit to draw the brush, don't call draw.. + brushes[i + 1]:visit() + end end - prev.x = x - prev.y = y + -- finish drawing and return context back to the screen + target:endToLua() end - ret:setTouchEnabled(true) - ret:registerScriptTouchHandler(onTouchEvent) + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCHES_MOVED ) + local eventDispatcher = ret:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, ret) -- Save Image menu cc.MenuItemFont:setFontSize(16) local item1 = cc.MenuItemFont:create("Save Image") diff --git a/samples/Lua/TestLua/Resources/luaScript/RotateWorldTest/RotateWorldTest.lua b/tests/test-lua/Resources/luaScript/RotateWorldTest/RotateWorldTest.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/RotateWorldTest/RotateWorldTest.lua rename to tests/test-lua/Resources/luaScript/RotateWorldTest/RotateWorldTest.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/SceneTest/SceneTest.lua b/tests/test-lua/Resources/luaScript/SceneTest/SceneTest.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/SceneTest/SceneTest.lua rename to tests/test-lua/Resources/luaScript/SceneTest/SceneTest.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/SpineTest/SpineTest.lua b/tests/test-lua/Resources/luaScript/SpineTest/SpineTest.lua similarity index 98% rename from samples/Lua/TestLua/Resources/luaScript/SpineTest/SpineTest.lua rename to tests/test-lua/Resources/luaScript/SpineTest/SpineTest.lua index f537ece2df..3e93a7c975 100644 --- a/samples/Lua/TestLua/Resources/luaScript/SpineTest/SpineTest.lua +++ b/tests/test-lua/Resources/luaScript/SpineTest/SpineTest.lua @@ -26,7 +26,7 @@ SpineTestLayer1 = function() spineboy:addAnimation(0, 'walk', true) spineboy:addAnimation(0, 'jump', true, 4) - spineboy:registerScriptHandler(function(event) + spineboy:registerSpineEventHandler(function(event) if event.type == 'start' then print(string.format("[spine] %d start: %s", event.trackIndex, diff --git a/samples/Lua/TestLua/Resources/luaScript/SpriteTest/SpriteTest.lua b/tests/test-lua/Resources/luaScript/SpriteTest/SpriteTest.lua similarity index 98% rename from samples/Lua/TestLua/Resources/luaScript/SpriteTest/SpriteTest.lua rename to tests/test-lua/Resources/luaScript/SpriteTest/SpriteTest.lua index c6e9c6dd7b..29c4dae6aa 100644 --- a/samples/Lua/TestLua/Resources/luaScript/SpriteTest/SpriteTest.lua +++ b/tests/test-lua/Resources/luaScript/SpriteTest/SpriteTest.lua @@ -55,12 +55,10 @@ function Sprite1.addNewSpriteWithCoords(layer, point) sprite:runAction( cc.RepeatForever:create(seq) ) end -function Sprite1.onTouch(event, x, y) - if event == "began" then - return true - elseif event == "ended" then - Sprite1.addNewSpriteWithCoords(Helper.currentLayer, cc.p(x,y)) - return true +function Sprite1.onTouchesEnd(touches, event) + for i = 1,table.getn(touches) do + local location = touches[i]:getLocation() + Sprite1.addNewSpriteWithCoords(Helper.currentLayer, location) end end @@ -69,8 +67,11 @@ function Sprite1.create() local layer = cc.Layer:create() Helper.initWithLayer(layer) Sprite1.addNewSpriteWithCoords(layer, cc.p(size.width/2, size.height/2)) - layer:setTouchEnabled(true) - layer:registerScriptTouchHandler(Sprite1.onTouch) + + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(Sprite1.onTouchesEnd,cc.Handler.EVENT_TOUCHES_ENDED ) + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) Helper.titleLabel:setString("Sprite (tap screen)") @@ -115,12 +116,10 @@ function SpriteBatchNode1.addNewSpriteWithCoords(layer, point) sprite:runAction( cc.RepeatForever:create(seq) ) end -function SpriteBatchNode1.onTouch(event, x, y) - if event == "began" then - return true - elseif event == "ended" then - SpriteBatchNode1.addNewSpriteWithCoords(Helper.currentLayer, cc.p(x,y)) - return true +function SpriteBatchNode1.onTouchesEnd(touches,event) + for i = 1,table.getn(touches) do + local location = touches[i]:getLocation() + SpriteBatchNode1.addNewSpriteWithCoords(Helper.currentLayer, location) end end @@ -132,8 +131,10 @@ function SpriteBatchNode1.create() SpriteBatchNode1.addNewSpriteWithCoords(layer, cc.p(size.width/2, size.height/2)) - layer:setTouchEnabled(true) - layer:registerScriptTouchHandler(SpriteBatchNode1.onTouch) + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(Sprite1.onTouchesEnd,cc.Handler.EVENT_TOUCHES_ENDED ) + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) Helper.titleLabel:setString("SpriteBatchNode (tap screen)") @@ -445,7 +446,7 @@ function SpriteAnchorPoint.initLayer(layer) end point:setPosition( sprite:getPosition() ) - local copy = tolua.cast(action:clone(), "Action") + local copy = tolua.cast(action:clone(), "cc.Action") sprite:runAction(copy) layer:addChild(sprite, i) end @@ -498,7 +499,7 @@ function SpriteBatchNodeAnchorPoint.initLayer(layer) point:setPosition( cc.p(sprite:getPosition()) ) - local copy = tolua.cast(action:clone(), "Action") + local copy = tolua.cast(action:clone(), "cc.Action") sprite:runAction(copy) batch:addChild(sprite, i) end diff --git a/samples/Lua/TestLua/Resources/luaScript/Texture2dTest/Texture2dTest.lua b/tests/test-lua/Resources/luaScript/Texture2dTest/Texture2dTest.lua similarity index 86% rename from samples/Lua/TestLua/Resources/luaScript/Texture2dTest/Texture2dTest.lua rename to tests/test-lua/Resources/luaScript/Texture2dTest/Texture2dTest.lua index ec191438b1..66a31b7988 100644 --- a/samples/Lua/TestLua/Resources/luaScript/Texture2dTest/Texture2dTest.lua +++ b/tests/test-lua/Resources/luaScript/Texture2dTest/Texture2dTest.lua @@ -7,10 +7,10 @@ local originCreateLayer = createTestLayer local function createTestLayer(title, subtitle) local ret = originCreateLayer(title, subtitle) Helper.titleLabel:setTag(kTagLabel) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) local col = cc.LayerColor:create(cc.c4b(128,128,128,255)) ret:addChild(col, -10) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end -------------------------------------------------------------------- @@ -26,7 +26,7 @@ local function TextureTIFF() local img = cc.Sprite:create("Images/test_image.tiff") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -43,7 +43,7 @@ local function TexturePNG() local img = cc.Sprite:create("Images/test_image.png") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -59,7 +59,7 @@ local function TextureJPEG() local img = cc.Sprite:create("Images/test_image.jpeg") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -75,7 +75,7 @@ local function TextureWEBP() local img = cc.Sprite:create("Images/test_image.webp") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -89,12 +89,12 @@ local function TextureMipMap() "Left image uses mipmap. Right image doesn't") local s = cc.Director:getInstance():getWinSize() - local texture0 = cc.TextureCache:getInstance():addImage( + local texture0 = cc.Director:getInstance():getTextureCache():addImage( "Images/grossini_dance_atlas.png") texture0:generateMipmap() texture0:setTexParameters(gl.LINEAR_MIPMAP_LINEAR, gl.LINEAR, gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE) - local texture1 = cc.TextureCache:getInstance():addImage( + local texture1 = cc.Director:getInstance():getTextureCache():addImage( "Images/grossini_dance_atlas_nomipmap.png") local img0 = cc.Sprite:createWithTexture(texture0) @@ -110,12 +110,12 @@ local function TextureMipMap() local scale1 = cc.EaseOut:create(cc.ScaleBy:create(4, 0.01), 3) local sc_back = scale1:reverse() - local scale2 = tolua.cast(scale1:clone(), "EaseOut") + local scale2 = tolua.cast(scale1:clone(), "cc.EaseOut") local sc_back2 = scale2:reverse() img0:runAction(cc.RepeatForever:create(cc.Sequence:create(scale1, sc_back))) img1:runAction(cc.RepeatForever:create(cc.Sequence:create(scale2, sc_back2))) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -148,13 +148,13 @@ local function TexturePVRMipMap() local scale1 = cc.EaseOut:create(cc.ScaleBy:create(4, 0.01), 3) local sc_back = scale1:reverse() - local scale2 = tolua.cast(scale1:clone(), "EaseOut") + local scale2 = tolua.cast(scale1:clone(), "cc.EaseOut") local sc_back2 = scale2:reverse() imgMipMap:runAction(cc.RepeatForever:create(cc.Sequence:create(scale1, sc_back))) img:runAction(cc.RepeatForever:create(cc.Sequence:create(scale2, sc_back2))) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -182,13 +182,13 @@ local function TexturePVRMipMap2() local scale1 = cc.EaseOut:create(cc.ScaleBy:create(4, 0.01), 3) local sc_back = scale1:reverse() - local scale2 = tolua.cast(scale1:clone(), "EaseOut") + local scale2 = tolua.cast(scale1:clone(), "cc.EaseOut") local sc_back2 = scale2:reverse() imgMipMap:runAction(cc.RepeatForever:create(cc.Sequence:create(scale1, sc_back))) img:runAction(cc.RepeatForever:create(cc.Sequence:create(scale2, sc_back2))) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -211,7 +211,7 @@ local function TexturePVR2BPP() ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -234,7 +234,7 @@ local function TexturePVR() else cclog("This test is not supported.") end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -258,7 +258,7 @@ local function TexturePVR4BPP() else cclog("This test is not supported in cocos2d-mac") end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -277,7 +277,7 @@ local function TexturePVRRGBA8888() local img = cc.Sprite:create("Images/test_image_rgba8888.pvr") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -300,7 +300,7 @@ local function TexturePVRBGRA8888() else cclog("BGRA8888 images are not supported") end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -318,7 +318,7 @@ local function TexturePVRRGBA5551() local img = cc.Sprite:create("Images/test_image_rgba5551.pvr") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -336,7 +336,7 @@ local function TexturePVRRGBA4444() local img = cc.Sprite:create("Images/test_image_rgba4444.pvr") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -355,7 +355,7 @@ local function TexturePVRRGBA4444GZ() local img = cc.Sprite:create("Images/test_image_rgba4444.pvr") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -374,7 +374,7 @@ local function TexturePVRRGBA4444CCZ() local img = cc.Sprite:create("Images/test_image_rgba4444.pvr.ccz") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -392,7 +392,7 @@ local function TexturePVRRGB565() local img = cc.Sprite:create("Images/test_image_rgb565.pvr") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -408,7 +408,7 @@ local function TexturePVRRGB888() img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -426,7 +426,7 @@ local function TexturePVRA8() local img = cc.Sprite:create("Images/test_image_a8.pvr") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -444,7 +444,7 @@ local function TexturePVRI8() local img = cc.Sprite:create("Images/test_image_i8.pvr") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -463,7 +463,7 @@ local function TexturePVRAI88() local img = cc.Sprite:create("Images/test_image_ai88.pvr") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -478,7 +478,7 @@ local function TexturePVR2BPPv3() img:setPosition(cc.p(s.width/2.0, s.height/2.0)) ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -494,7 +494,7 @@ local function TexturePVRII2BPPv3() ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -512,7 +512,7 @@ local function TexturePVR4BPPv3() cclog("This test is not supported") end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -534,7 +534,7 @@ local function TexturePVRII4BPPv3() else cclog("This test is not supported") end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -551,7 +551,7 @@ local function TexturePVRRGBA8888v3() ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -571,7 +571,7 @@ local function TexturePVRBGRA8888v3() cclog("BGRA images are not supported") end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -587,7 +587,7 @@ local function TexturePVRRGBA5551v3() ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -604,7 +604,7 @@ local function TexturePVRRGBA4444v3() ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -621,7 +621,7 @@ local function TexturePVRRGB565v3() ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -638,7 +638,7 @@ local function TexturePVRRGB888v3() ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -655,7 +655,7 @@ local function TexturePVRA8v3() ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -672,7 +672,7 @@ local function TexturePVRI8v3() ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -689,7 +689,7 @@ local function TexturePVRAI88v3() ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -726,7 +726,7 @@ local function TexturePVRNonSquare() local img = cc.Sprite:create("Images/grossini_128x256_mipmap.pvr") img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -745,7 +745,7 @@ local function TexturePVRNPOT4444() img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -764,7 +764,7 @@ local function TexturePVRNPOT8888() img:setPosition(cc.p( s.width/2.0, s.height/2.0)) ret:addChild(img) end - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -803,13 +803,13 @@ local function TextureAlias() -- scale them to show local sc = cc.ScaleBy:create(3, 8.0) - local sc_back = tolua.cast(sc:reverse(), "ScaleBy") + local sc_back = tolua.cast(sc:reverse(), "cc.ScaleBy") local scaleforever = cc.RepeatForever:create(cc.Sequence:create(sc, sc_back)) - local scaleToo = tolua.cast(scaleforever:clone(), "RepeatForever") + local scaleToo = tolua.cast(scaleforever:clone(), "cc.RepeatForever") sprite2:runAction(scaleforever) sprite:runAction(scaleToo) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -829,7 +829,7 @@ local function TexturePixelFormat() -- 3- 16-bit RGB5A1 -- 4- 16-bit RGB565 - local label = tolua.cast(ret:getChildByTag(kTagLabel), "LabelTTF") + local label = tolua.cast(ret:getChildByTag(kTagLabel), "cc.LabelTTF") label:setColor(cc.c3b(16,16,255)) local s = cc.Director:getInstance():getWinSize() @@ -844,7 +844,7 @@ local function TexturePixelFormat() ret:addChild(sprite1, 0) -- remove texture from texture manager - cc.TextureCache:getInstance():removeTexture(sprite1:getTexture()) + cc.Director:getInstance():getTextureCache():removeTexture(sprite1:getTexture()) -- RGBA 4444 image (16-bit) cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A4444) @@ -853,7 +853,7 @@ local function TexturePixelFormat() ret:addChild(sprite2, 0) -- remove texture from texture manager - cc.TextureCache:getInstance():removeTexture(sprite2:getTexture()) + cc.Director:getInstance():getTextureCache():removeTexture(sprite2:getTexture()) -- RGB5A1 image (16-bit) cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB5_A1) @@ -862,7 +862,7 @@ local function TexturePixelFormat() ret:addChild(sprite3, 0) -- remove texture from texture manager - cc.TextureCache:getInstance():removeTexture(sprite3:getTexture()) + cc.Director:getInstance():getTextureCache():removeTexture(sprite3:getTexture()) -- RGB888 image cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RG_B888 ) @@ -871,7 +871,7 @@ local function TexturePixelFormat() ret:addChild(sprite4, 0) -- remove texture from texture manager - cc.TextureCache:getInstance():removeTexture(sprite4:getTexture()) + cc.Director:getInstance():getTextureCache():removeTexture(sprite4:getTexture()) -- RGB565 image (16-bit) cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RG_B565) @@ -880,7 +880,7 @@ local function TexturePixelFormat() ret:addChild(sprite5, 0) -- remove texture from texture manager - cc.TextureCache:getInstance():removeTexture(sprite5:getTexture()) + cc.Director:getInstance():getTextureCache():removeTexture(sprite5:getTexture()) -- A8 image (8-bit) cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_A8 ) @@ -889,16 +889,16 @@ local function TexturePixelFormat() ret:addChild(sprite6, 0) -- remove texture from texture manager - cc.TextureCache:getInstance():removeTexture(sprite6:getTexture()) + cc.Director:getInstance():getTextureCache():removeTexture(sprite6:getTexture()) local fadeout = cc.FadeOut:create(2) local fadein = cc.FadeIn:create(2) local seq = cc.Sequence:create(cc.DelayTime:create(2), fadeout, fadein) local seq_4ever = cc.RepeatForever:create(seq) - local seq_4ever2 = tolua.cast(seq_4ever:clone(), "RepeatForever") - local seq_4ever3 = tolua.cast(seq_4ever:clone(), "RepeatForever") - local seq_4ever4 = tolua.cast(seq_4ever:clone(), "RepeatForever") - local seq_4ever5 = tolua.cast(seq_4ever:clone(), "RepeatForever") + local seq_4ever2 = tolua.cast(seq_4ever:clone(), "cc.RepeatForever") + local seq_4ever3 = tolua.cast(seq_4ever:clone(), "cc.RepeatForever") + local seq_4ever4 = tolua.cast(seq_4ever:clone(), "cc.RepeatForever") + local seq_4ever5 = tolua.cast(seq_4ever:clone(), "cc.RepeatForever") sprite1:runAction(seq_4ever) sprite2:runAction(seq_4ever2) @@ -908,7 +908,7 @@ local function TexturePixelFormat() -- restore default cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_DEFAULT) - cc.TextureCache:getInstance():dumpCachedTextureInfo() + print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo()) return ret end @@ -964,12 +964,12 @@ local function TextureAsync() ret:addChild(label, 10) local scale = cc.ScaleBy:create(0.3, 2) - local scale_back = tolua.cast(scale:reverse(), "ScaleBy") + local scale_back = tolua.cast(scale:reverse(), "cc.ScaleBy") local seq = cc.Sequence:create(scale, scale_back) label:runAction(cc.RepeatForever:create(seq)) local function imageLoaded(pObj) - local tex = tolua.cast(pObj, "Texture2D") + local tex = tolua.cast(pObj, "cc.Texture2D") local director = cc.Director:getInstance() --cc.ASSERT( [NSThread currentThread] == [director runningThread], @"FAIL. Callback should be on cocos2d thread") @@ -997,16 +997,16 @@ local function TextureAsync() for j=0, 7 do local szSpriteName = string.format( "Images/sprites_test/sprite-%d-%d.png", i, j) - cc.TextureCache:getInstance():addImageAsync( + cc.Director:getInstance():getTextureCache():addImageAsync( szSpriteName, imageLoaded) end end - cc.TextureCache:getInstance():addImageAsync("Images/background1.jpg", imageLoaded) - cc.TextureCache:getInstance():addImageAsync("Images/background2.jpg", imageLoaded) - cc.TextureCache:getInstance():addImageAsync("Images/background.png", imageLoaded) - cc.TextureCache:getInstance():addImageAsync("Images/atlastest.png", imageLoaded) - cc.TextureCache:getInstance():addImageAsync("Images/grossini_dance_atlas.png",imageLoaded) + cc.Director:getInstance():getTextureCache():addImageAsync("Images/background1.jpg", imageLoaded) + cc.Director:getInstance():getTextureCache():addImageAsync("Images/background2.jpg", imageLoaded) + cc.Director:getInstance():getTextureCache():addImageAsync("Images/background.png", imageLoaded) + cc.Director:getInstance():getTextureCache():addImageAsync("Images/atlastest.png", imageLoaded) + cc.Director:getInstance():getTextureCache():addImageAsync("Images/grossini_dance_atlas.png",imageLoaded) end local schedulerEntry = nil @@ -1015,7 +1015,7 @@ local function TextureAsync() schedulerEntry = scheduler:scheduleScriptFunc(loadImages, 1.0, false) elseif event == "exit" then scheduler:unscheduleScriptEntry(schedulerEntry) - cc.TextureCache:getInstance():removeAllTextures() + cc.Director:getInstance():getTextureCache():removeAllTextures() end end @@ -1043,12 +1043,12 @@ local function TextureGlClamp() local rotate = cc.RotateBy:create(4, 360) sprite:runAction(rotate) local scale = cc.ScaleBy:create(2, 0.04) - local scaleBack = tolua.cast(scale:reverse(), "ScaleBy") + local scaleBack = tolua.cast(scale:reverse(), "cc.ScaleBy") local seq = cc.Sequence:create(scale, scaleBack) sprite:runAction(seq) local function onNodeEvent(event) if event == "exit" then - cc.TextureCache:getInstance():removeUnusedTextures() + cc.Director:getInstance():getTextureCache():removeUnusedTextures() end end @@ -1077,12 +1077,12 @@ local function TextureGlRepeat() local rotate = cc.RotateBy:create(4, 360) sprite:runAction(rotate) local scale = cc.ScaleBy:create(2, 0.04) - local scaleBack = tolua.cast(scale:reverse(), "ScaleBy") + local scaleBack = tolua.cast(scale:reverse(), "cc.ScaleBy") local seq = cc.Sequence:create(scale, scaleBack) sprite:runAction(seq) local function onNodeEvent(event) if event == "exit" then - cc.TextureCache:getInstance():removeUnusedTextures() + cc.Director:getInstance():getTextureCache():removeUnusedTextures() end end @@ -1150,7 +1150,7 @@ local function TextureCache1() sprite:setScale(2) ret:addChild(sprite) - cc.TextureCache:getInstance():removeTexture(sprite:getTexture()) + cc.Director:getInstance():getTextureCache():removeTexture(sprite:getTexture()) sprite = cc.Sprite:create("Images/grossinis_sister1.png") sprite:setPosition(cc.p(s.width/5*2, s.height/2)) @@ -1166,7 +1166,7 @@ local function TextureCache1() sprite:setScale(2) ret:addChild(sprite) - cc.TextureCache:getInstance():removeTextureForKey("Images/grossinis_sister2.png") + cc.Director:getInstance():getTextureCache():removeTextureForKey("Images/grossinis_sister2.png") sprite = cc.Sprite:create("Images/grossinis_sister2.png") sprite:setPosition(cc.p(s.width/5*4, s.height/2)) @@ -1192,8 +1192,8 @@ local function TextureDrawAtPoint() m_pTex2F:drawAtPoint(cc.p(s.width/2+50, s.height/2 - 50)) end - m_pTex1 = cc.TextureCache:getInstance():addImage("Images/grossinis_sister1.png") - m_pTex2F = cc.TextureCache:getInstance():addImage("Images/grossinis_sister2.png") + m_pTex1 = cc.Director:getInstance():getTextureCache():addImage("Images/grossinis_sister1.png") + m_pTex2F = cc.Director:getInstance():getTextureCache():addImage("Images/grossinis_sister2.png") m_pTex1:retain() m_pTex2F:retain() @@ -1226,8 +1226,8 @@ local function TextureDrawInRect() m_pTex2F:drawInRect(rect2) end - local m_pTex1 = cc.TextureCache:getInstance():addImage("Images/grossinis_sister1.png") - local m_pTex2F = cc.TextureCache:getInstance():addImage("Images/grossinis_sister2.png") + local m_pTex1 = cc.Director:getInstance():getTextureCache():addImage("Images/grossinis_sister1.png") + local m_pTex2F = cc.Director:getInstance():getTextureCache():addImage("Images/grossinis_sister2.png") m_pTex1:retain() m_pTex2F:retain() @@ -1260,7 +1260,7 @@ local function TextureMemoryAlloc() cclog("updateImage"..tag) m_pBackground:removeFromParent(true) end - cc.TextureCache:getInstance():removeUnusedTextures() + cc.Director:getInstance():getTextureCache():removeUnusedTextures() local file = "" if tag == 0 then @@ -1338,7 +1338,7 @@ local function TexturePVRv3Premult() local function transformSprite(sprite) local fade = cc.FadeOut:create(2) local dl = cc.DelayTime:create(2) - local fadein = tolua.cast(fade:reverse(), "FadeOut") + local fadein = tolua.cast(fade:reverse(), "cc.FadeOut") local seq = cc.Sequence:create(fade, fadein, dl) local repeatAction = cc.RepeatForever:create(seq) sprite:runAction(repeatAction) @@ -1364,7 +1364,7 @@ local function TexturePVRv3Premult() -- PNG cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888) - cc.TextureCache:getInstance():removeTextureForKey("Images/grossinis_sister1-testalpha.png") + cc.Director:getInstance():getTextureCache():removeTextureForKey("Images/grossinis_sister1-testalpha.png") local png = cc.Sprite:create("Images/grossinis_sister1-testalpha.png") ret:addChild(png, 0) png:setPosition(cc.p(size.width/4*3, size.height/2)) diff --git a/samples/Lua/TestLua/Resources/luaScript/TileMapTest/TileMapTest.lua b/tests/test-lua/Resources/luaScript/TileMapTest/TileMapTest.lua similarity index 93% rename from samples/Lua/TestLua/Resources/luaScript/TileMapTest/TileMapTest.lua rename to tests/test-lua/Resources/luaScript/TileMapTest/TileMapTest.lua index c2326ca230..69d394373a 100644 --- a/samples/Lua/TestLua/Resources/luaScript/TileMapTest/TileMapTest.lua +++ b/tests/test-lua/Resources/luaScript/TileMapTest/TileMapTest.lua @@ -12,26 +12,18 @@ local function createTileDemoLayer(title, subtitle) Helper.titleLabel:setString(titleStr) Helper.subtitleLabel:setString(subTitleStr) - local prev = {x = 0, y = 0} - local function onTouchEvent(eventType, x, y) - if eventType == "began" then - prev.x = x - prev.y = y - return true - elseif eventType == "moved" then - local node = layer:getChildByTag(kTagTileMap) - local newX = node:getPositionX() - local newY = node:getPositionY() - local diffX = x - prev.x - local diffY = y - prev.y - - node:setPosition( cc.pAdd(cc.p(newX, newY), cc.p(diffX, diffY)) ) - prev.x = x - prev.y = y - end + local function onTouchesMoved(touches, event ) + local diff = touches[1]:getDelta() + local node = layer:getChildByTag(kTagTileMap) + local currentPosX, currentPosY= node:getPosition() + node:setPosition(cc.p(currentPosX + diff.x, currentPosY + diff.y)) end - layer:setTouchEnabled(true) - layer:registerScriptTouchHandler(onTouchEvent) + + local listener = cc.EventListenerTouchAllAtOnce:create() + listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCHES_MOVED ) + local eventDispatcher = layer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) + return layer end -------------------------------------------------------------------- @@ -90,7 +82,7 @@ local function TileMapEditTest() -- The only limitation is that you cannot change an empty, or assign an empty tile to a tile -- The value 0 not rendered so don't assign or change a tile with value 0 - local tilemap = tolua.cast(layer:getChildByTag(kTagTileMap), "TileMapAtlas") + local tilemap = tolua.cast(layer:getChildByTag(kTagTileMap), "cc.TileMapAtlas") -- -- For example you can iterate over all the tiles @@ -165,7 +157,7 @@ local function TMXOrthoTest() local len = table.getn(pChildrenArray) for i = 0, len-1, 1 do pObject = pChildrenArray[i + 1] - child = tolua.cast(pObject, "SpriteBatchNode") + child = tolua.cast(pObject, "cc.SpriteBatchNode") if child == nil then break @@ -219,7 +211,7 @@ local function TMXOrthoTest2() local len = table.getn(pChildrenArray) for i = 0, len-1, 1 do - child = tolua.cast(pChildrenArray[i + 1], "SpriteBatchNode") + child = tolua.cast(pChildrenArray[i + 1], "cc.SpriteBatchNode") if child == nil then break @@ -251,7 +243,7 @@ local function TMXOrthoTest3() local len = table.getn(pChildrenArray) for i = 0, len-1, 1 do - child = tolua.cast(pChildrenArray[i + 1], "SpriteBatchNode") + child = tolua.cast(pChildrenArray[i + 1], "cc.SpriteBatchNode") if child == nil then break @@ -285,7 +277,7 @@ local function TMXOrthoTest4() local len = table.getn(pChildrenArray) for i = 0, len-1, 1 do - child = tolua.cast(pChildrenArray[i + 1], "SpriteBatchNode") + child = tolua.cast(pChildrenArray[i + 1], "cc.SpriteBatchNode") if child == nil then break @@ -312,7 +304,7 @@ local function TMXOrthoTest4() local function removeSprite(dt) scheduler:unscheduleScriptEntry(schedulerEntry) schedulerEntry = nil - local map = tolua.cast(ret:getChildByTag(kTagTileMap), "TMXTiledMap") + local map = tolua.cast(ret:getChildByTag(kTagTileMap), "cc.TMXTiledMap") local layer0 = map:getLayer("Layer 0") local s = layer0:getLayerSize() @@ -376,7 +368,7 @@ local function TMXReadWriteTest() local function removeSprite(sender) --------cclog("removing tile: %x", sender) - local node = tolua.cast(sender, "Node") + local node = tolua.cast(sender, "cc.Node") if nil == node then print("Errro node is nil") end @@ -390,9 +382,9 @@ local function TMXReadWriteTest() local finish = cc.CallFunc:create(removeSprite) local seq0 = cc.Sequence:create(move, rotate, scale, opacity, fadein, scaleback, finish) - local seq1 = tolua.cast(seq0:clone(), "Action") - local seq2 = tolua.cast(seq0:clone(), "Action") - local seq3 = tolua.cast(seq0:clone(), "Action") + local seq1 = tolua.cast(seq0:clone(), "cc.Action") + local seq2 = tolua.cast(seq0:clone(), "cc.Action") + local seq3 = tolua.cast(seq0:clone(), "cc.Action") tile0:runAction(seq0) tile1:runAction(seq1) @@ -408,8 +400,8 @@ local function TMXReadWriteTest() local function updateCol(dt) - local map = tolua.cast(ret:getChildByTag(kTagTileMap), "TMXTiledMap") - local layer = tolua.cast(map:getChildByTag(0), "TMXLayer") + local map = tolua.cast(ret:getChildByTag(kTagTileMap), "cc.TMXTiledMap") + local layer = tolua.cast(map:getChildByTag(0), "cc.TMXLayer") --------cclog("++++atlas quantity: %d", layer:textureAtlas():getTotalQuads()) --------cclog("++++children: %d", layer:getChildren():count() ) @@ -426,8 +418,8 @@ local function TMXReadWriteTest() local function repaintWithGID(dt) -- unschedule:_cmd) - local map = tolua.cast(ret:getChildByTag(kTagTileMap), "TMXTiledMap") - local layer = tolua.cast(map:getChildByTag(0), "TMXLayer") + local map = tolua.cast(ret:getChildByTag(kTagTileMap), "cc.TMXTiledMap") + local layer = tolua.cast(map:getChildByTag(0), "cc.TMXLayer") local s = layer:getLayerSize() local x = 0 @@ -441,8 +433,8 @@ local function TMXReadWriteTest() local function removeTiles(dt) scheduler:unscheduleScriptEntry(removeTilesScheduler) removeTilesScheduler = nil - local map = tolua.cast(ret:getChildByTag(kTagTileMap), "TMXTiledMap") - local layer = tolua.cast(map:getChildByTag(0), "TMXLayer") + local map = tolua.cast(ret:getChildByTag(kTagTileMap), "cc.TMXTiledMap") + local layer = tolua.cast(map:getChildByTag(0), "cc.TMXLayer") local s = layer:getLayerSize() local y = 0 for y=0, s.height-1, 1 do @@ -588,7 +580,7 @@ local function TMXUncompressedTest() local i = 0 local len = table.getn(pChildrenArray) for i = 0, len-1, 1 do - layer = tolua.cast(pChildrenArray[i + 1], "TMXLayer") + layer = tolua.cast(pChildrenArray[i + 1], "cc.TMXLayer") if layer == nil then break end @@ -659,7 +651,7 @@ end local function draw() - local map = tolua.cast(getChildByTag(kTagTileMap), "TMXTiledMap") + local map = tolua.cast(getChildByTag(kTagTileMap), "cc.TMXTiledMap") local group = map:getObjectGroup("Object Group 1") local objects = group:getObjects() @@ -716,7 +708,7 @@ local function TMXIsoObjectsTest() local i = 0 local len = table.getn(objects) for i = 0, len-1, 1 do - dict = tolua.cast(objects[i + 1], "Dictionary") + dict = tolua.cast(objects[i + 1], "cc.Dictionary") if dict == nil then break @@ -728,7 +720,7 @@ end local function draw() - local map = tolua.cast(getChildByTag(kTagTileMap), "TMXTiledMap") + local map = tolua.cast(getChildByTag(kTagTileMap), "cc.TMXTiledMap") local group = map:getObjectGroup("Object Group 1") local objects = group:getObjects() @@ -736,20 +728,20 @@ local function draw() local i = 0 local len = table.getn(objects) for i = 0, len-1, 1 do - dict = tolua.cast(objects[i + 1], "Dictionary") + dict = tolua.cast(objects[i + 1], "cc.Dictionary") if dict == nil then break end local key = "x" - local x = (tolua.cast(dict:objectForKey(key), "String")):intValue()--dynamic_cast(dict:objectForKey("x")):getNumber() + local x = (tolua.cast(dict:objectForKey(key), "cc.String")):intValue()--dynamic_cast(dict:objectForKey("x")):getNumber() key = "y" - local y = (tolua.cast(dict:objectForKey(key), "String")):intValue()--dynamic_cast(dict:objectForKey("y")):getNumber() + local y = (tolua.cast(dict:objectForKey(key), "cc.String")):intValue()--dynamic_cast(dict:objectForKey("y")):getNumber() key = "width" - local width = (tolua.cast(dict:objectForKey(key), "String")):intValue()--dynamic_cast(dict:objectForKey("width")):getNumber() + local width = (tolua.cast(dict:objectForKey(key), "cc.String")):intValue()--dynamic_cast(dict:objectForKey("width")):getNumber() key = "height" - local height = (tolua.cast(dict:objectForKey(key), "String")):intValue()--dynamic_cast(dict:objectForKey("height")):getNumber() + local height = (tolua.cast(dict:objectForKey(key), "cc.String")):intValue()--dynamic_cast(dict:objectForKey("height")):getNumber() glLineWidth(3) @@ -1081,7 +1073,7 @@ local function TMXOrthoFlipTest() local i = 0 for i = 0, table.getn(map:getChildren())-1, 1 do - local child = tolua.cast(map:getChildren()[i + 1], "SpriteBatchNode") + local child = tolua.cast(map:getChildren()[i + 1], "cc.SpriteBatchNode") child:getTexture():setAntiAliasTexParameters() end @@ -1106,7 +1098,7 @@ local function TMXOrthoFlipRunTimeTest() local i = 0 for i = 0, table.getn(map:getChildren())-1, 1 do - local child = tolua.cast(map:getChildren()[i + 1], "SpriteBatchNode") + local child = tolua.cast(map:getChildren()[i + 1], "cc.SpriteBatchNode") child:getTexture():setAntiAliasTexParameters() end @@ -1186,7 +1178,7 @@ local function TMXOrthoFromXMLTest() local i = 0 local len = table.getn(map:getChildren()) for i = 0, len-1, 1 do - local child = tolua.cast(map:getChildren()[i + 1], "SpriteBatchNode") + local child = tolua.cast(map:getChildren()[i + 1], "cc.SpriteBatchNode") child:getTexture():setAntiAliasTexParameters() end @@ -1214,7 +1206,7 @@ local function TMXBug987() local len = table.getn(childs) local pNode = nil for i = 0, len-1, 1 do - pNode = tolua.cast(childs[i + 1], "TMXLayer") + pNode = tolua.cast(childs[i + 1], "cc.TMXLayer") if pNode == nil then break end diff --git a/samples/Lua/TestLua/Resources/luaScript/TouchesTest/Ball.lua b/tests/test-lua/Resources/luaScript/TouchesTest/Ball.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/TouchesTest/Ball.lua rename to tests/test-lua/Resources/luaScript/TouchesTest/Ball.lua diff --git a/tests/test-lua/Resources/luaScript/TouchesTest/Paddle.lua b/tests/test-lua/Resources/luaScript/TouchesTest/Paddle.lua new file mode 100644 index 0000000000..d0c20ab500 --- /dev/null +++ b/tests/test-lua/Resources/luaScript/TouchesTest/Paddle.lua @@ -0,0 +1,70 @@ +require "extern" +require "luaScript/VisibleRect" + +Paddle = class("Paddle", function(texture) + return cc.Sprite:createWithTexture(texture) +end) + +Paddle.__index = Paddle + +local kPaddleStateGrabbed = 0 +local kPaddleStateUngrabbed = 1 + +Paddle._state = kPaddleStateGrabbed + + +function Paddle:rect() + local s = self:getTexture():getContentSize() + return cc.rect(-s.width / 2, -s.height / 2, s.width, s.height) +end + +function Paddle:containsTouchLocation(x,y) + local position = cc.p(self:getPosition()) + local s = self:getTexture():getContentSize() + local touchRect = cc.rect(-s.width / 2 + position.x, -s.height / 2 + position.y, s.width, s.height) + local b = cc.rectContainsPoint(touchRect, cc.p(x,y)) + return b +end + +function Paddle:paddleWithTexture(aTexture) + local pPaddle = Paddle.new(aTexture) + pPaddle._state = kPaddleStateUngrabbed + pPaddle:registerScriptHandler(function(tag) + if "enter" == tag then + pPaddle:onEnter() + elseif "exit" == tag then + end +end) + return pPaddle +end + +function Paddle:onEnter() + local listenner = cc.EventListenerTouchOneByOne:create() + listenner:setSwallowTouches(true) + listenner:registerScriptHandler(function(touch, event) + print(string.format("Paddle::onTouchBegan id = %d, x = %f, y = %f", touch:getId(), touch:getLocation().x, touch:getLocation().y)) + if (self._state ~= kPaddleStateUngrabbed) then + return false + end + + if not self:containsTouchLocation(touch:getLocation().x,touch:getLocation().y) then + return false + end + + self._state = kPaddleStateGrabbed + return true + end,cc.Handler.EVENT_TOUCH_BEGAN ) + listenner:registerScriptHandler(function(touch, event) + print(string.format("Paddle::onTouchMoved id = %d, x = %f, y = %f", touch:getId(), touch:getLocation().x, touch:getLocation().y)) + assert(self._state == kPaddleStateGrabbed, "Paddle - Unexpected state!") + local touchPoint = touch:getLocation() + local curPosX,curPosY = self:getPosition() + self:setPosition(cc.p(touchPoint.x,curPosY)) + end,cc.Handler.EVENT_TOUCH_MOVED ) + listenner:registerScriptHandler(function(touch, event) + assert(self._state == kPaddleStateGrabbed, "Paddle - Unexpected state!") + self._state = kPaddleStateUngrabbed + end,cc.Handler.EVENT_TOUCH_ENDED ) + local eventDispatcher = self:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listenner, self) +end diff --git a/samples/Lua/TestLua/Resources/luaScript/TouchesTest/TouchesTest.lua b/tests/test-lua/Resources/luaScript/TouchesTest/TouchesTest.lua similarity index 87% rename from samples/Lua/TestLua/Resources/luaScript/TouchesTest/TouchesTest.lua rename to tests/test-lua/Resources/luaScript/TouchesTest/TouchesTest.lua index 085de21ebe..7532689f38 100644 --- a/samples/Lua/TestLua/Resources/luaScript/TouchesTest/TouchesTest.lua +++ b/tests/test-lua/Resources/luaScript/TouchesTest/TouchesTest.lua @@ -48,22 +48,11 @@ local function doStep(delta) m_ball:draw(); end -local function onTouch(event, x, y) - - for _,paddle in ipairs(m_paddles) do - if paddle:containsTouchLocation(x,y) == true then - return paddle:onTouch(event, x, y) - end - end - - return true -end - local function CreateTouchesLayer() layer = cc.Layer:create() m_ballStartingVelocity = cc.p(20.0, -100.0); - local mgr = cc.TextureCache:getInstance() + local mgr = cc.Director:getInstance():getTextureCache() local texture = mgr:addImage(s_Ball) m_ball = Ball.ballWithTexture(texture); @@ -72,7 +61,7 @@ local function CreateTouchesLayer() layer:addChild( m_ball ); m_ball:retain(); - local paddleTexture = cc.TextureCache:getInstance():addImage(s_Paddle); + local paddleTexture = cc.Director:getInstance():getTextureCache():addImage(s_Paddle); local paddlesM = {} @@ -106,9 +95,6 @@ local function CreateTouchesLayer() -- schedule layer:scheduleUpdateWithPriorityLua(doStep, 0) - layer:setTouchEnabled(true) - layer:registerScriptTouchHandler(onTouch) - return layer end diff --git a/samples/Lua/TestLua/Resources/luaScript/TransitionsTest/TransitionsName.lua b/tests/test-lua/Resources/luaScript/TransitionsTest/TransitionsName.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/TransitionsTest/TransitionsName.lua rename to tests/test-lua/Resources/luaScript/TransitionsTest/TransitionsName.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/TransitionsTest/TransitionsTest.lua b/tests/test-lua/Resources/luaScript/TransitionsTest/TransitionsTest.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/TransitionsTest/TransitionsTest.lua rename to tests/test-lua/Resources/luaScript/TransitionsTest/TransitionsTest.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/UserDefaultTest/UserDefaultTest.lua b/tests/test-lua/Resources/luaScript/UserDefaultTest/UserDefaultTest.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/UserDefaultTest/UserDefaultTest.lua rename to tests/test-lua/Resources/luaScript/UserDefaultTest/UserDefaultTest.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/VisibleRect.lua b/tests/test-lua/Resources/luaScript/VisibleRect.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/VisibleRect.lua rename to tests/test-lua/Resources/luaScript/VisibleRect.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua b/tests/test-lua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua similarity index 96% rename from samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua rename to tests/test-lua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua index 1cdffa035a..4bec50a734 100644 --- a/samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua +++ b/tests/test-lua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua @@ -22,7 +22,7 @@ local function XMLHttpRequestLayer() --Get local function onMenuGetClicked() - local xhr = XMLHttpRequest:new() + local xhr = cc.XMLHttpRequest:new() xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING xhr:open("GET", "http://httpbin.org/get") @@ -46,7 +46,7 @@ local function XMLHttpRequestLayer() --Post local function onMenuPostClicked() - local xhr = XMLHttpRequest:new() + local xhr = cc.XMLHttpRequest:new() xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING xhr:open("POST", "http://httpbin.org/post") local function onReadyStateChange() @@ -67,7 +67,7 @@ local function XMLHttpRequestLayer() --Post Binary local function onMenuPostBinaryClicked() - local xhr = XMLHttpRequest:new() + local xhr = cc.XMLHttpRequest:new() xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_ARRAY_BUFFER xhr:open("POST", "http://httpbin.org/post") @@ -102,7 +102,7 @@ local function XMLHttpRequestLayer() --Post Json local function onMenuPostJsonClicked() - local xhr = XMLHttpRequest:new() + local xhr = cc.XMLHttpRequest:new() xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON xhr:open("POST", "http://httpbin.org/post") diff --git a/samples/Lua/TestLua/Resources/luaScript/ZwoptexTest/ZwoptexTest.lua b/tests/test-lua/Resources/luaScript/ZwoptexTest/ZwoptexTest.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/ZwoptexTest/ZwoptexTest.lua rename to tests/test-lua/Resources/luaScript/ZwoptexTest/ZwoptexTest.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/controller.lua b/tests/test-lua/Resources/luaScript/controller.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/controller.lua rename to tests/test-lua/Resources/luaScript/controller.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/helper.lua b/tests/test-lua/Resources/luaScript/helper.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/helper.lua rename to tests/test-lua/Resources/luaScript/helper.lua diff --git a/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua b/tests/test-lua/Resources/luaScript/mainMenu.lua similarity index 94% rename from samples/Lua/TestLua/Resources/luaScript/mainMenu.lua rename to tests/test-lua/Resources/luaScript/mainMenu.lua index 17302973c2..4c47dc697f 100644 --- a/samples/Lua/TestLua/Resources/luaScript/mainMenu.lua +++ b/tests/test-lua/Resources/luaScript/mainMenu.lua @@ -170,14 +170,15 @@ function CreateTestMenu() menuLayer:addChild(MainMenu) -- handling touch events - local function onTouchBegan(x, y) - BeginPos = {x = x, y = y} + local function onTouchBegan(touch, event) + BeginPos = touch:getLocation() -- CCTOUCHBEGAN event must return true return true end - local function onTouchMoved(x, y) - local nMoveY = y - BeginPos.y + local function onTouchMoved(touch, event) + local location = touch:getLocation() + local nMoveY = location.y - BeginPos.y local curPosx, curPosy = MainMenu:getPosition() local nextPosy = curPosy + nMoveY local winSize = cc.Director:getInstance():getWinSize() @@ -192,20 +193,15 @@ function CreateTestMenu() end MainMenu:setPosition(curPosx, nextPosy) - BeginPos = {x = x, y = y} + BeginPos = {x = location.x, y = location.y} CurPos = {x = curPosx, y = nextPosy} end - local function onTouch(eventType, x, y) - if eventType == "began" then - return onTouchBegan(x, y) - elseif eventType == "moved" then - return onTouchMoved(x, y) - end - end - - menuLayer:setTouchEnabled(true) - menuLayer:registerScriptTouchHandler(onTouch) + local listener = cc.EventListenerTouchOneByOne:create() + listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN ) + listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED ) + local eventDispatcher = menuLayer:getEventDispatcher() + eventDispatcher:addEventListenerWithSceneGraphPriority(listener, menuLayer) return menuLayer end diff --git a/samples/Lua/TestLua/Resources/luaScript/testResource.lua b/tests/test-lua/Resources/luaScript/testResource.lua similarity index 100% rename from samples/Lua/TestLua/Resources/luaScript/testResource.lua rename to tests/test-lua/Resources/luaScript/testResource.lua diff --git a/samples/Javascript/CocosDragonJS/proj.android/.classpath b/tests/test-lua/proj.android/.classpath similarity index 100% rename from samples/Javascript/CocosDragonJS/proj.android/.classpath rename to tests/test-lua/proj.android/.classpath diff --git a/samples/Lua/TestLua/proj.android/.project b/tests/test-lua/proj.android/.project similarity index 100% rename from samples/Lua/TestLua/proj.android/.project rename to tests/test-lua/proj.android/.project diff --git a/samples/Lua/TestLua/proj.android/AndroidManifest.xml b/tests/test-lua/proj.android/AndroidManifest.xml similarity index 94% rename from samples/Lua/TestLua/proj.android/AndroidManifest.xml rename to tests/test-lua/proj.android/AndroidManifest.xml index 5eb27de989..430e935659 100644 --- a/samples/Lua/TestLua/proj.android/AndroidManifest.xml +++ b/tests/test-lua/proj.android/AndroidManifest.xml @@ -14,7 +14,7 @@ android:label="@string/app_name" android:screenOrientation="landscape" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" - android:configChanges="orientation|screenSize|smallestScreenSize"> + android:configChanges="orientation"> #import "AppController.h" #import "cocos2d.h" -#import "EAGLView.h" +#import "CCEAGLView.h" #import "AppDelegate.h" #import "RootViewController.h" @@ -37,24 +37,26 @@ // cocos2d application instance static AppDelegate s_sharedApplication; -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + // Override point for customization after application launch. // Add the view controller's view to the window and display. window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; - CCEAGLView *__glView = [CCEAGLView viewWithFrame: [window bounds] - pixelFormat: kEAGLColorFormatRGBA8 - depthFormat: GL_DEPTH_COMPONENT16 - preserveBackbuffer: NO - sharegroup:nil - multiSampling:NO - numberOfSamples:0]; - - // Use RootViewController manage CCEAGLView + CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds] + pixelFormat: kEAGLColorFormatRGBA8 + depthFormat: GL_DEPTH24_STENCIL8_OES + preserveBackbuffer: NO + sharegroup: nil + multiSampling: NO + numberOfSamples: 0 ]; + + [eaglView setMultipleTouchEnabled:YES]; + + // Use RootViewController manage CCEAGLView viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; viewController.wantsFullScreenLayout = YES; - viewController.view = __glView; + viewController.view = eaglView; // Set RootViewController to window if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) @@ -71,7 +73,12 @@ static AppDelegate s_sharedApplication; [window makeKeyAndVisible]; [[UIApplication sharedApplication] setStatusBarHidden: YES]; - + + + // IMPORTANT: Setting the GLView should be done after creating the RootViewController + cocos2d::GLView *glview = cocos2d::GLView::createWithEAGLView(eaglView); + cocos2d::Director::getInstance()->setOpenGLView(glview); + cocos2d::Application::getInstance()->run(); return YES; } @@ -94,7 +101,7 @@ static AppDelegate s_sharedApplication; - (void)applicationDidEnterBackground:(UIApplication *)application { /* - Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. If your application supports background execution, called instead of applicationWillTerminate: when the user quits. */ cocos2d::Application::getInstance()->applicationDidEnterBackground(); @@ -122,6 +129,7 @@ static AppDelegate s_sharedApplication; /* Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. */ + cocos2d::Director::getInstance()->purgeCachedData(); } diff --git a/samples/Cpp/TestCpp/proj.ios/Default-568h@2x.png.REMOVED.git-id b/tests/test-lua/proj.ios/Default-568h@2x.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/proj.ios/Default-568h@2x.png.REMOVED.git-id rename to tests/test-lua/proj.ios/Default-568h@2x.png.REMOVED.git-id diff --git a/samples/Cpp/TestCpp/proj.ios/Default@2x.png.REMOVED.git-id b/tests/test-lua/proj.ios/Default@2x.png.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/proj.ios/Default@2x.png.REMOVED.git-id rename to tests/test-lua/proj.ios/Default@2x.png.REMOVED.git-id diff --git a/samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.h b/tests/test-lua/proj.ios/LuaObjectCBridgeTest.h similarity index 100% rename from samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.h rename to tests/test-lua/proj.ios/LuaObjectCBridgeTest.h diff --git a/samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.mm b/tests/test-lua/proj.ios/LuaObjectCBridgeTest.mm similarity index 100% rename from samples/Lua/TestLua/proj.ios/LuaObjectCBridgeTest.mm rename to tests/test-lua/proj.ios/LuaObjectCBridgeTest.mm diff --git a/samples/Cpp/SimpleGame/proj.ios/RootViewController.h b/tests/test-lua/proj.ios/RootViewController.h similarity index 100% rename from samples/Cpp/SimpleGame/proj.ios/RootViewController.h rename to tests/test-lua/proj.ios/RootViewController.h diff --git a/samples/Cpp/SimpleGame/proj.ios/RootViewController.mm b/tests/test-lua/proj.ios/RootViewController.mm similarity index 100% rename from samples/Cpp/SimpleGame/proj.ios/RootViewController.mm rename to tests/test-lua/proj.ios/RootViewController.mm diff --git a/samples/Lua/TestLua/proj.ios/TestLua_Prefix.pch b/tests/test-lua/proj.ios/TestLua_Prefix.pch similarity index 100% rename from samples/Lua/TestLua/proj.ios/TestLua_Prefix.pch rename to tests/test-lua/proj.ios/TestLua_Prefix.pch diff --git a/samples/Lua/TestLua/proj.ios/main.m b/tests/test-lua/proj.ios/main.m similarity index 100% rename from samples/Lua/TestLua/proj.ios/main.m rename to tests/test-lua/proj.ios/main.m diff --git a/samples/Cpp/HelloCpp/proj.linux/main.cpp b/tests/test-lua/proj.linux/main.cpp similarity index 83% rename from samples/Cpp/HelloCpp/proj.linux/main.cpp rename to tests/test-lua/proj.linux/main.cpp index eaac21e713..e420889600 100644 --- a/samples/Cpp/HelloCpp/proj.linux/main.cpp +++ b/tests/test-lua/proj.linux/main.cpp @@ -12,7 +12,5 @@ int main(int argc, char **argv) { // create the application instance AppDelegate app; - EGLView eglView; - eglView.init("HelloCpp",900,640); return Application::getInstance()->run(); } diff --git a/samples/Cpp/TestCpp/proj.mac/Icon.icns.REMOVED.git-id b/tests/test-lua/proj.mac/Icon.icns.REMOVED.git-id similarity index 100% rename from samples/Cpp/TestCpp/proj.mac/Icon.icns.REMOVED.git-id rename to tests/test-lua/proj.mac/Icon.icns.REMOVED.git-id diff --git a/samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.h b/tests/test-lua/proj.mac/LuaObjectCBridgeTest.h similarity index 100% rename from samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.h rename to tests/test-lua/proj.mac/LuaObjectCBridgeTest.h diff --git a/samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.mm b/tests/test-lua/proj.mac/LuaObjectCBridgeTest.mm similarity index 100% rename from samples/Lua/TestLua/proj.mac/LuaObjectCBridgeTest.mm rename to tests/test-lua/proj.mac/LuaObjectCBridgeTest.mm diff --git a/samples/Lua/TestLua/proj.mac/TestLua_Prefix.pch b/tests/test-lua/proj.mac/TestLua_Prefix.pch similarity index 100% rename from samples/Lua/TestLua/proj.mac/TestLua_Prefix.pch rename to tests/test-lua/proj.mac/TestLua_Prefix.pch diff --git a/samples/Cpp/TestCpp/proj.mac/en.lproj/InfoPlist.strings b/tests/test-lua/proj.mac/en.lproj/InfoPlist.strings similarity index 100% rename from samples/Cpp/TestCpp/proj.mac/en.lproj/InfoPlist.strings rename to tests/test-lua/proj.mac/en.lproj/InfoPlist.strings diff --git a/samples/Cpp/HelloCpp/proj.mac/en.lproj/MainMenu.xib b/tests/test-lua/proj.mac/en.lproj/MainMenu.xib similarity index 100% rename from samples/Cpp/HelloCpp/proj.mac/en.lproj/MainMenu.xib rename to tests/test-lua/proj.mac/en.lproj/MainMenu.xib diff --git a/samples/Lua/HelloLua/proj.mac/main.cpp b/tests/test-lua/proj.mac/main.cpp similarity index 94% rename from samples/Lua/HelloLua/proj.mac/main.cpp rename to tests/test-lua/proj.mac/main.cpp index d3a6801ac6..1814d16c15 100644 --- a/samples/Lua/HelloLua/proj.mac/main.cpp +++ b/tests/test-lua/proj.mac/main.cpp @@ -23,14 +23,11 @@ ****************************************************************************/ #include "AppDelegate.h" -#include "CCEGLView.h" USING_NS_CC; int main(int argc, char *argv[]) { AppDelegate app; - EGLView eglView; - eglView.init("HelloLua",900,640); return Application::getInstance()->run(); } diff --git a/samples/Lua/TestLua/proj.win32/TestLua.rc b/tests/test-lua/proj.win32/TestLua.rc similarity index 100% rename from samples/Lua/TestLua/proj.win32/TestLua.rc rename to tests/test-lua/proj.win32/TestLua.rc diff --git a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj b/tests/test-lua/proj.win32/TestLua.win32.vcxproj similarity index 85% rename from samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj rename to tests/test-lua/proj.win32/TestLua.win32.vcxproj index 7d04e0f16c..799ae15647 100644 --- a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj +++ b/tests/test-lua/proj.win32/TestLua.win32.vcxproj @@ -36,13 +36,13 @@ - - + + - - + + @@ -104,8 +104,8 @@ - xcopy "$(ProjectDir)..\..\..\Cpp\TestCpp\Resources" "$(ProjectDir)..\..\TestLua\Resources" /e /Y -xcopy "$(EngineRoot)cocos\scripting\lua\script" "$(ProjectDir)..\..\TestLua\Resources" /e /Y + xcopy "$(ProjectDir)..\..\test-cpp\Resources" "$(ProjectDir)..\Resources" /e /Y +xcopy "$(EngineRoot)cocos\scripting\lua\script" "$(ProjectDir)..\Resources" /e /Y copy files from TestCpp to TestLua @@ -152,13 +152,13 @@ xcopy /Y /Q "$(EngineRoot)external\websockets\prebuilt\\win32\*.*" "$(OutDir)" - xcopy "$(ProjectDir)..\..\..\Cpp\TestCpp\Resources" "$(ProjectDir)..\..\TestLua\Resources" /e /Y -xcopy "$(ProjectDir)..\..\..\..\cocos\scripting\lua\script" "$(ProjectDir)..\..\TestLua\Resources" /e /Y + xcopy "$(ProjectDir)..\..\test-cpp\Resources" "$(ProjectDir)..\Resources" /e /Y +xcopy "$(EngineRoot)cocos\scripting\lua\script" "$(ProjectDir)..\Resources" /e /Y copy files from TestCpp to TestLua if not exist "$(OutDir)" mkdir "$(OutDir)" -xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" +xcopy /Y /Q "$(ProjectDir)..\..\..\external\websockets\prebuilt\win32\*.*" "$(OutDir)" @@ -172,37 +172,37 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ - + {98a51ba8-fc3a-415b-ac8f-8c7bd464e93e} - + {f8edd7fa-9a51-4e80-baeb-860825d2eac6} - + {811c0dab-7b96-4bd3-a154-b7572b58e4ab} - + {b57cf53f-2e49-4031-9822-047cc0e6bde2} - + {b7c2a162-dec9-4418-972e-240ab3cbfcae} - + {7e06e92c-537a-442b-9e4a-4761c84f8a1a} - + {df2638c0-8128-4847-867c-6eafe3dee7b5} - + {ddc3e27f-004d-4dd4-9dd3-931a013d2159} - + {632a8f38-d0f0-4d22-86b3-d69f5e6bf63a} - + {21b2c324-891f-48ea-ad1a-5ae13de12e28} - + {207bc7a9-ccf1-4f2f-a04d-45f72242ae25} diff --git a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters b/tests/test-lua/proj.win32/TestLua.win32.vcxproj.filters similarity index 100% rename from samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.filters rename to tests/test-lua/proj.win32/TestLua.win32.vcxproj.filters diff --git a/samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.user b/tests/test-lua/proj.win32/TestLua.win32.vcxproj.user similarity index 100% rename from samples/Lua/TestLua/proj.win32/TestLua.win32.vcxproj.user rename to tests/test-lua/proj.win32/TestLua.win32.vcxproj.user diff --git a/samples/Lua/TestLua/proj.win32/main.cpp b/tests/test-lua/proj.win32/main.cpp similarity index 92% rename from samples/Lua/TestLua/proj.win32/main.cpp rename to tests/test-lua/proj.win32/main.cpp index 2554f5981a..eb96bb538f 100644 --- a/samples/Lua/TestLua/proj.win32/main.cpp +++ b/tests/test-lua/proj.win32/main.cpp @@ -24,8 +24,6 @@ int APIENTRY _tWinMain(HINSTANCE hInstance, // create the application instance AppDelegate app; - EGLView eglView; - eglView.init("TestLua",900,640); int ret = Application::getInstance()->run(); diff --git a/samples/Lua/TestLua/proj.win32/main.h b/tests/test-lua/proj.win32/main.h similarity index 100% rename from samples/Lua/TestLua/proj.win32/main.h rename to tests/test-lua/proj.win32/main.h diff --git a/samples/Lua/TestLua/proj.win32/res/TestLua.ico b/tests/test-lua/proj.win32/res/TestLua.ico similarity index 100% rename from samples/Lua/TestLua/proj.win32/res/TestLua.ico rename to tests/test-lua/proj.win32/res/TestLua.ico diff --git a/samples/Lua/TestLua/proj.win32/resource.h b/tests/test-lua/proj.win32/resource.h similarity index 100% rename from samples/Lua/TestLua/proj.win32/resource.h rename to tests/test-lua/proj.win32/resource.h diff --git a/tools/bindings-generator b/tools/bindings-generator index 71a0aa4bc7..47343067f0 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 71a0aa4bc70743ae2078f4a43217987751ff17ec +Subproject commit 47343067f0d13240ea813cdb406de973ca5aa4e0 diff --git a/tools/closure-compiler/obfuscate.py b/tools/closure-compiler/obfuscate.py index 4979edc50e..9572576278 100755 --- a/tools/closure-compiler/obfuscate.py +++ b/tools/closure-compiler/obfuscate.py @@ -1,6 +1,6 @@ #!/usr/bin/python -# create_project.py -# Create cross-platform cocos2d-x project +# obfuscate.py +# Create Ant buildfile to obfuscate game source code # Copyright (c) 2012 cocos2d-x.org # Author: WangZhe @@ -16,9 +16,9 @@ import sys import os, os.path def dumpUsage(): - print "Usage: generate-config.py -input INPUT_PATH -output OUTPUT_PATH -cocos2d COCOS2D_ROOT_PATH" + print "Usage: %s -input INPUT_PATH -output OUTPUT_PATH -cocos2d COCOS2D_ROOT_PATH" % (os.path.basename(__file__)) print "Options:" - print " -intput INPUT_PATH The path to javscript files directory" + print " -input INPUT_PATH The path to javascript files directory" print " -output OUTPUT_PATH The path to the obfuscated javascript file" print " -cocos2d COCOS2D_ROOT_PATH The root path of cocos2d-x, e.g. /workspace/cocos2d-x" print "" @@ -123,7 +123,7 @@ checkParams() generateXmlForCompiler() # print "running ant to generate obfuscated main.js" # os.popen("ant -buildfile obfuscate.xml") -print "Successful! obfuscate.xml is generated." -print "Note: Please reoder the files sequence in obfuscate.xml, keep it the same order as javascript \"requrie\" instruction," -print "then call \"ant -buildfile obfuscate.xml\" to obfuscate your js codes." +print "Successful! obfuscate.xml generated." +print "Note: Please reorder the file's sequence in obfuscate.xml, keep it the same order as javascript \"require\" instruction," +print "then call \"ant -buildfile obfuscate.xml\" to obfuscate your js code." diff --git a/tools/cocos2d-console b/tools/cocos2d-console index 3556d41429..a6a36cab2e 160000 --- a/tools/cocos2d-console +++ b/tools/cocos2d-console @@ -1 +1 @@ -Subproject commit 3556d41429e487e88fbbd5222df95fdd4c2ddf7b +Subproject commit a6a36cab2ef6a1b2ce140c7ec2f0a4149ae0de24 diff --git a/tools/jenkins-scripts/create-job.py b/tools/jenkins-scripts/create-job.py index 1aac211cdf..fac13cc4df 100644 --- a/tools/jenkins-scripts/create-job.py +++ b/tools/jenkins-scripts/create-job.py @@ -9,11 +9,11 @@ import requests pr_num = sys.argv[1] #get github access token -access_token = os.environ['GITHUB_ACCESS_TOKEN'] + #get pr data via github api -api_get_pr = "https://api.github.com/repos/cocos2d/cocos2d-x/pulls/"+str(pr_num)+"?access_token="+access_token +api_get_pr = "https://api.github.com/repos/cocos2d/cocos2d-x/pulls/"+str(pr_num) r = requests.get(api_get_pr) pr = r.json() @@ -23,7 +23,7 @@ payload = {"action":"opened","number":"","pull_request":""} payload['number']=pr_num payload['pull_request']=pr -jenkins_trigger_url="http://ci.cocos2d-x.org:8000/job/cocos-2dx-pull-request-build/buildWithParameters?token="+access_token +jenkins_trigger_url="http://115.28.134.83:8000/job/cocos-2dx-pull-request-build/buildWithParameters?token=ced2014" #send trigger and payload post_data = {'payload':""} diff --git a/tools/jenkins-scripts/create-template-project.py b/tools/jenkins-scripts/create-template-project.py new file mode 100644 index 0000000000..e82af72c95 --- /dev/null +++ b/tools/jenkins-scripts/create-template-project.py @@ -0,0 +1,19 @@ +import os + +languages = ['cpp','lua','javascript'] +base_path = 'tools/project-creator/' +create_project = base_path + 'create_project.py' +template_root = base_path + 'templateTest' + +# create project +for item in languages: + ret = os.system('python ' + create_project + + ' -n ' + 'template' + item + + ' -k ' + 'com.test.template.' + item + + ' -l ' + item + + ' -p ' + template_root) + if(ret > 0): + ret = 1 + exit(ret) + +exit(0) diff --git a/tools/jenkins-scripts/gen_jsb_win32.bat b/tools/jenkins-scripts/gen_jsb_win32.bat new file mode 100644 index 0000000000..872ad9a4c4 --- /dev/null +++ b/tools/jenkins-scripts/gen_jsb_win32.bat @@ -0,0 +1,36 @@ +@echo off + +::!/bin/bash + +:: Generate JS and Lua bindings for Cocos2D-X +:: ... using Android NDK system headers +:: ... and automatically update submodule references +:: ... and push these changes to remote repos + +:: Dependencies +:: +:: For bindings generator: +:: (see ../../../tojs/genbindings.sh and ../../../tolua/genbindings-win32.bat +:: ... for the defaults used if the environment is not customized) +:: +:: * $PYTHON_BIN +:: * $CLANG_ROOT +:: * $NDK_ROOT +:: +echo "[test]start generate js binding..." +set COCOS2DX_ROOT=%cd%/../.. +set "COCOS2DX_ROOT=%COCOS2DX_ROOT:\=/%" +set TO_JS_ROOT=%COCOS2DX_ROOT%/tools/tojs +set TO_LUA_ROOT=%COCOS2DX_ROOT%/tools/tolua +set GENERATED_WORKTREE=%COCOS2DX_ROOT%/cocos/scripting/auto-generated +set "GENERATED_WORKTREE=%GENERATED_WORKTREE:/=\%" + +:: Run to_js genbindings +call %TO_JS_ROOT%/genbindings-win32.bat + +:: Run to_lua genbindings +call %TO_LUA_ROOT%/genbindings-win32.bat + +echo +echo Bindings generated successfully +echo \ No newline at end of file diff --git a/tools/jenkins-scripts/ios-build.sh b/tools/jenkins-scripts/ios-build.sh new file mode 100755 index 0000000000..60014ffe0e --- /dev/null +++ b/tools/jenkins-scripts/ios-build.sh @@ -0,0 +1,5 @@ +#put xctool.sh into your PATH +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +COCOS2DX_ROOT="$DIR"/../.. +xcodebuild -project "$COCOS2DX_ROOT"/build/cocos2d_tests.xcodeproj -scheme "build-all-tests iOS" -destination "platform=iOS Simulator,name=iPhone Retina (4-inch)" clean +xcodebuild -project "$COCOS2DX_ROOT"/build/cocos2d_tests.xcodeproj -scheme "build-all-tests iOS" -destination "platform=iOS Simulator,name=iPhone Retina (4-inch)" build diff --git a/tools/jenkins-scripts/job-trigger.py b/tools/jenkins-scripts/job-trigger.py new file mode 100755 index 0000000000..b344ca9dde --- /dev/null +++ b/tools/jenkins-scripts/job-trigger.py @@ -0,0 +1,83 @@ +#Github pull reqest builder for Jenkins + +import json +import re +import os +import requests +import sys +import traceback + +def main(): + #get payload from os env + payload_str = os.environ['payload'] + #parse to json obj + payload = json.loads(payload_str) + + #get pull number + pr_num = payload['number'] + print 'pr_num:' + str(pr_num) + payload_forword = {"number":pr_num} + + #build for pull request action 'open' and 'synchronize', skip 'close' + action = payload['action'] + print 'action: ' + action + payload_forword['action'] = action + + pr = payload['pull_request'] + url = pr['html_url'] + print "url:" + url + payload_forword['html_url'] = url + + #get statuses url + statuses_url = pr['statuses_url'] + payload_forword['statuses_url'] = statuses_url + + #get pr target branch + branch = pr['base']['ref'] + payload_forword['branch'] = branch + + #set commit status to pending + target_url = os.environ['BUILD_URL'] + + if(action == 'closed'): + print 'pull request #' + str(pr_num) + ' is '+action+', no build triggered' + return(0) + + r = requests.get(pr['url']+"/commits") + commits = r.json() + last_commit = commits[len(commits)-1] + message = last_commit['commit']['message'] + + pattern = re.compile("\[ci(\s+)skip\]", re.I) + result = pattern.search(message) + if result is not None: + print 'skip build for pull request #' + str(pr_num) + return(0) + + data = {"state":"pending", "target_url":target_url} + access_token = os.environ['GITHUB_ACCESS_TOKEN'] + Headers = {"Authorization":"token " + access_token} + + try: + requests.post(statuses_url, data=json.dumps(data), headers=Headers) + except: + traceback.print_exc() + + job_trigger_url = os.environ['JOB_TRIGGER_URL'] + #send trigger and payload + post_data = {'payload':""} + post_data['payload']= json.dumps(payload_forword) + requests.post(job_trigger_url, data=post_data) + + return(0) + +# -------------- main -------------- +if __name__ == '__main__': + sys_ret = 0 + try: + sys_ret = main() + except: + traceback.print_exc() + sys_ret = 1 + finally: + sys.exit(sys_ret) diff --git a/tools/jenkins-scripts/post-build.py b/tools/jenkins-scripts/post-build.py new file mode 100644 index 0000000000..1b59a2c599 --- /dev/null +++ b/tools/jenkins-scripts/post-build.py @@ -0,0 +1,32 @@ +import os +import json +import requests +import jenkinsapi +from jenkinsapi.jenkins import Jenkins +from jenkinsapi.constants import STATUS_SUCCESS + +payload_str = os.environ['payload'] +payload_str = payload_str.decode('utf-8','ignore') +#parse to json obj +payload = json.loads(payload_str) +#pr = payload['pull_request'] +url = payload['html_url'] +print "build pr:" + url +#get statuses url +statuses_url = payload['statuses_url'] + +J = Jenkins(os.environ['JENKINS_URL']) +target_url = os.environ['BUILD_URL'] +build_number = int(os.environ['BUILD_NUMBER']) +data = {"state":"pending", "target_url":target_url} +access_token = os.environ['GITHUB_ACCESS_TOKEN'] +Headers = {"Authorization":"token " + access_token} + +result = J[os.environ['JOB_NAME']].get_build(build_number).get_status() + +if(result == STATUS_SUCCESS): + data['state'] = "success" +else: + data['state'] = "failure" + +requests.post(statuses_url, data=json.dumps(data), headers=Headers) diff --git a/tools/jenkins-scripts/pull-request-builder.py b/tools/jenkins-scripts/pull-request-builder.py index 3f258e4401..a6fb9aa65c 100755 --- a/tools/jenkins-scripts/pull-request-builder.py +++ b/tools/jenkins-scripts/pull-request-builder.py @@ -10,6 +10,7 @@ import requests import sys import traceback import platform +import subprocess #set Jenkins build description using submitDescription to mock browser behavior #TODO: need to set parent build description @@ -27,6 +28,7 @@ def set_description(desc, url): def main(): #get payload from os env payload_str = os.environ['payload'] + payload_str = payload_str.decode('utf-8','ignore') #parse to json obj payload = json.loads(payload_str) @@ -38,39 +40,29 @@ def main(): action = payload['action'] print 'action: ' + action - pr = payload['pull_request'] + #pr = payload['pull_request'] - url = pr['html_url'] + url = payload['html_url'] print "url:" + url pr_desc = '

pr#' + str(pr_num) + ' is '+ action +'

' #get statuses url - statuses_url = pr['statuses_url'] + statuses_url = payload['statuses_url'] #get pr target branch - branch = pr['base']['ref'] + branch = payload['branch'] #set commit status to pending - target_url = os.environ['BUILD_URL'] + #target_url = os.environ['BUILD_URL'] + jenkins_url = os.environ['JENKINS_URL'] + job_name = os.environ['JOB_NAME'].split('/')[0] + build_number = os.environ['BUILD_NUMBER'] + target_url = jenkins_url + 'job/' + job_name + '/' + build_number + '/' set_description(pr_desc, target_url) - - if((action != 'opened') and (action != 'synchronize')): - print 'pull request #' + str(pr_num) + ' is '+action+', no build triggered' - return(0) - - r = requests.get(pr['url']+"/commits") - commits = r.json() - last_commit = commits[len(commits)-1] - message = last_commit['commit']['message'] - - pattern = re.compile("\[ci(\s+)skip\]", re.I) - result = pattern.search(message) - if result is not None: - print 'skip build for pull request #' + str(pr_num) - return(0) + data = {"state":"pending", "target_url":target_url} access_token = os.environ['GITHUB_ACCESS_TOKEN'] @@ -86,12 +78,10 @@ def main(): os.system("git checkout develop") os.system("git branch -D pull" + str(pr_num)) #clean workspace - print "git clean -xdf" + print "git clean -xdf" os.system("git clean -xdf") - - #fetch pull request to local repo - git_fetch_pr = "git fetch origin pull/" + str(pr_num) + "/head" + git_fetch_pr = "git fetch origin pull/" + str(pr_num) + "/merge" os.system(git_fetch_pr) #checkout @@ -103,58 +93,59 @@ def main(): os.system(git_update_submodule) # Generate binding glue codes - if(platform.system() == 'Darwin'): - os.system("tools/jenkins-scripts/gen_jsb.sh") + if(branch == 'develop'): + if(platform.system() == 'Darwin'): + os.system("tools/jenkins-scripts/gen_jsb.sh") + elif(platform.system() == 'Windows'): + os.chdir("tools/jenkins-scripts") + os.system("gen_jsb_win32.bat") + os.chdir("../..") #make temp dir print "current dir is" + os.environ['WORKSPACE'] os.system("cd " + os.environ['WORKSPACE']); os.mkdir("android_build_objs") #add symbol link - PROJECTS=["Cpp/HelloCpp","Cpp/TestCpp","Cpp/SimpleGame","Cpp/AssetsManagerTest", - "Javascript/TestJavascript","Javascript/CocosDragonJS","Javascript/CrystalCraze", - "Javascript/MoonWarriors","Javascript/WatermelonWithMe","Lua/HelloLua","Lua/TestLua"] + PROJECTS=["test_cpp", + "test-javascript","test-lua"] print platform.system() if(platform.system() == 'Darwin'): for item in PROJECTS: - cmd = "ln -s " + os.environ['WORKSPACE']+"/android_build_objs/ " + os.environ['WORKSPACE']+"/samples/"+item+"/proj.android/obj" + cmd = "ln -s " + os.environ['WORKSPACE']+"/android_build_objs/ " + os.environ['WORKSPACE']+"/tests/"+item+"/proj.android/obj" os.system(cmd) elif(platform.system() == 'Windows'): for item in PROJECTS: p = item.replace("/", os.sep) - cmd = "mklink /J "+os.environ['WORKSPACE']+os.sep+"samples"+os.sep +p+os.sep+"proj.android"+os.sep+"obj " + os.environ['WORKSPACE']+os.sep+"android_build_objs" + cmd = "mklink /J "+os.environ['WORKSPACE']+os.sep+"tests"+os.sep +p+os.sep+"proj.android"+os.sep+"obj " + os.environ['WORKSPACE']+os.sep+"android_build_objs" print cmd os.system(cmd) #build - #TODO: support android-mac build currently - #TODO: add android-windows7 build #TODO: add android-linux build - #TODO: add ios build #TODO: add mac build - #TODO: add win32 build + node_name = os.environ['NODE_NAME'] if(branch == 'develop'): - ret = os.system("python build/android-build.py -n -j10 all") + if(node_name == 'android_mac') or (node_name == 'android_win7'): + ret = os.system("python build/android-build.py -n -j10 all") + elif(node_name == 'win32_win7'): + ret = subprocess.call('"%VS110COMNTOOLS%..\IDE\devenv.com" "build\cocos2d-win32.vc2012.sln" /Build "Debug|Win32"', shell=True) + elif(node_name == 'ios_mac'): + ret = os.system("tools/jenkins-scripts/ios-build.sh") elif(branch == 'master'): - ret = os.system("samples/Cpp/TestCpp/proj.android/build_native.sh") + if(platform.system() == 'Darwin'): + ret = os.system("samples/Cpp/TestCpp/proj.android/build_native.sh") + else: + ret = 0 #get build result print "build finished and return " + str(ret) + exit_code = 1 if ret == 0: exit_code = 0 - data['state'] = "success" - else: exit_code = 1 - data['state'] = "failure" - - #set commit status - try: - requests.post(statuses_url, data=json.dumps(data), headers=Headers) - except: - traceback.print_exc() - + #clean workspace os.system("cd " + os.environ['WORKSPACE']); os.system("git checkout develop") diff --git a/tools/project-creator/README.md b/tools/project-creator/README.md index 7417a3ecdb..81122b9337 100644 --- a/tools/project-creator/README.md +++ b/tools/project-creator/README.md @@ -13,7 +13,7 @@ Notice: The best project path is an English path without spaces. To use this, open the terminal and type: ``` $ cd cocos2d-x/tools/project-creator - $ ./project-creator.py --help - $ ./project-creator.py -n mygame -k com.your_company.mygame -l cpp -p /home/mygame + $ ./create_project.py --help + $ ./create_project.py -n mygame -k com.your_company.mygame -l cpp -p /home/mygame $ cd /home/mygame ``` diff --git a/tools/project-creator/module/cocos_files.json.REMOVED.git-id b/tools/project-creator/module/cocos_files.json.REMOVED.git-id index 38b25afe6d..d9134402f7 100644 --- a/tools/project-creator/module/cocos_files.json.REMOVED.git-id +++ b/tools/project-creator/module/cocos_files.json.REMOVED.git-id @@ -1 +1 @@ -0a2d046187d7848172fadf6ee4a7e80897e6a75c \ No newline at end of file +badb55806c84be4b033ccebcf87094b30be56f97 \ No newline at end of file diff --git a/tools/project-creator/module/core.py b/tools/project-creator/module/core.py index f12ce71553..d5fab0da83 100644 --- a/tools/project-creator/module/core.py +++ b/tools/project-creator/module/core.py @@ -179,8 +179,7 @@ class CocosProject: self.step = 0 #begin copy engine - print("###begin copy engine") - print("waitting copy cocos2d ...") + print("> Copying cocos2d files...") dstPath = os.path.join(self.context["dst_project_path"],"cocos2d") for index in range(len(fileList)): srcfile = os.path.join(self.cocos_root,fileList[index]) @@ -201,14 +200,19 @@ class CocosProject: self.step = self.step + 1 if self.callbackfun and self.step%int(self.totalStep/50) == 0: self.callbackfun(self.step,self.totalStep,fileList[index]) - print("cocos2d\t\t: Done!") + print("< done") # call process_proj from each platform's script folder + + print ("") + print("> Creating project files...") for platform in self.platforms_list: self.__processPlatformProjects(platform) + print("< done") - print ("###New project has been created in this path: ") + print ("") + print ("A new project was created in:") print (self.context["dst_project_path"].replace("\\", "/")) - print ("Have Fun!") + return True def __processPlatformProjects(self, platform): @@ -262,7 +266,7 @@ class CocosProject: replaceString(os.path.join(proj_path, dst), self.context["src_project_name"], self.context["dst_project_name"]) # done! - showMsg = "proj.%s\t\t: Done!" % platform + showMsg = ">> Creating proj.%s... OK" % platform self.step += 1 if self.callbackfun: self.callbackfun(self.step,self.totalStep,showMsg) diff --git a/tools/project-creator/module/ui.py b/tools/project-creator/module/ui.py index 98d261cbf0..63209fe3e4 100644 --- a/tools/project-creator/module/ui.py +++ b/tools/project-creator/module/ui.py @@ -86,9 +86,9 @@ class ThreadedTask(threading.Thread): self.newProjectCallBack ) if breturn: - putMsg = "end@%d@%d@%s" %(100, 100, "create successful") + putMsg = "end@%d@%d@%s" %(100, 100, "Projected created successfully") else: - putMsg = "end@%d@%d@%s" %(100, 100, "create failure") + putMsg = "end@%d@%d@%s" %(100, 100, "Failed to create project") self.queue.put(putMsg) def newProjectCallBack(self, step, totalStep, showMsg): @@ -176,7 +176,7 @@ class TkCocosDialog(Frame): scnHeight = self.parent.winfo_screenheight() tmpcnf = '%dx%d+%d+%d'%(curWidth, curHeight, int((scnWidth-curWidth)/2), int((scnHeight-curHeight)/2)) self.parent.geometry(tmpcnf) - self.parent.title("Cocos Project Creator") + self.parent.title("Cocos2d Project Creator") #fix size #self.parent.maxsize(curWidth, curHeight) @@ -280,4 +280,4 @@ def createTkCocosDialog(): sys.stdout = old_stdout if __name__ =='__main__': - createTkCocosDialog() \ No newline at end of file + createTkCocosDialog() diff --git a/tools/tojs/README.mdown b/tools/tojs/README.mdown index d0897de1d5..ca2d722fa6 100644 --- a/tools/tojs/README.mdown +++ b/tools/tojs/README.mdown @@ -1,20 +1,19 @@ How to Use bindings-generator ================== -On Windows (Not available from 3.0-pre-alpha0, the reason is that Clang3.3 can't work perfectly on windows, therefore, disable windows support temporary.): +On Windows: ------------ -* Make sure that you have installed `android-ndk-r8d` or higher version. -* Download python2.7.3 from (http://www.python.org/ftp/python/2.7.3/python-2.7.3.msi). +* Make sure that you have installed `android-ndk-r9b`. +* Download python2.7.3 (32bit) from (http://www.python.org/ftp/python/2.7.3/python-2.7.3.msi). * Add the installed path of python (e.g. C:\Python27) to windows environment variable named 'PATH'. * Download pyyaml from http://pyyaml.org/download/pyyaml/PyYAML-3.10.win32-py2.7.exe and install it. * Download pyCheetah from https://raw.github.com/dumganhar/cocos2d-x/download/downloads/Cheetah.zip, unzip it to "C:\Python27\Lib\site-packages" -* Modify environment variables (`PYTHON_ROOT` and `NDK_ROOT`) in `genbindings-win32.bat`. -* Go to "cocos2d-x/tools/tojs" folder, and run "genbindings-win32.bat". The generated codes will be under "cocos2d-x\scripting\javascript\bindings\generated". +* Set environment variables (`PYTHON_ROOT` and `NDK_ROOT`) or just modify variables (`PYTHON_ROOT` and `NDK_ROOT`) in `genbindings-win32.bat`. +* Go to "cocos2d-x/tools/tojs" folder, and run "genbindings-win32.bat". The generated codes will be under "cocos\scripting\auto-generated\js-bindings". On MAC: ---------- -* Please refer to https://github.com/cocos2d/bindings-generator/blob/master/README.md - +* Please refer to https://github.com/cocos2d/bindings-generator/blob/develop/README.md diff --git a/tools/tojs/cocos2dx.ini b/tools/tojs/cocos2dx.ini index dfc3d0c576..32ed7f22ff 100644 --- a/tools/tojs/cocos2dx.ini +++ b/tools/tojs/cocos2dx.ini @@ -26,7 +26,7 @@ headers = %(cocosdir)s/cocos/2d/cocos2d.h %(cocosdir)s/cocos/audio/include/Simpl # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = New.* Sprite.* Scene Node.* Director Layer.* Menu.* Touch .*Action.* Move.* Rotate.* Blink.* Tint.* Sequence Repeat.* Fade.* Ease.* Scale.* Transition.* Spawn Animat.* Flip.* Delay.* Skew.* Jump.* Place.* Show.* Progress.* PointArray ToggleVisibility.* RemoveSelf Hide Particle.* Label.* Atlas.* TextureCache.* Texture2D Cardinal.* CatmullRom.* ParallaxNode TileMap.* TMX.* CallFunc RenderTexture GridAction Grid3DAction GridBase$ .+Grid Shaky3D Waves3D FlipX3D FlipY3D Speed ActionManager Set SimpleAudioEngine Scheduler Timer Orbit.* Follow.* Bezier.* CardinalSpline.* Camera.* DrawNode .*3D$ Liquid$ Waves$ ShuffleTiles$ TurnOffTiles$ Split.* Twirl$ FileUtils$ GLProgram ShaderCache Application ClippingNode MotionStreak TextFieldTTF EGLViewProtocol EGLView Component __NodeRGBA __LayerRGBA +classes = New.* Sprite.* Scene Node.* Director Layer.* Menu.* Touch .*Action.* Move.* Rotate.* Blink.* Tint.* Sequence Repeat.* Fade.* Ease.* Scale.* Transition.* Spawn Animat.* Flip.* Delay.* Skew.* Jump.* Place.* Show.* Progress.* PointArray ToggleVisibility.* RemoveSelf Hide Particle.* Label.* Atlas.* TextureCache.* Texture2D Cardinal.* CatmullRom.* ParallaxNode TileMap.* TMX.* CallFunc RenderTexture GridAction Grid3DAction GridBase$ .+Grid Shaky3D Waves3D FlipX3D FlipY3D Speed ActionManager Set SimpleAudioEngine Scheduler Timer Orbit.* Follow.* Bezier.* CardinalSpline.* Camera.* DrawNode .*3D$ Liquid$ Waves$ ShuffleTiles$ TurnOffTiles$ Split.* Twirl$ FileUtils$ GLProgram ShaderCache Application ClippingNode MotionStreak TextFieldTTF EGLViewProtocol EGLView Component __NodeRGBA __LayerRGBA SAXParser classes_need_extend = Node Layer.* Sprite MenuItemFont Scene DrawNode @@ -54,17 +54,17 @@ skip = Node::[^setPosition$ setGLServerState description getUserObject .*UserDat Copying::[*], LabelProtocol::[*], LabelTextFormatProtocol::[*], - Label::[getLettersInfo], + Label::[getLettersInfo createWithTTF setTTFConfig], .*Delegate::[*], PoolManager::[*], Texture2D::[initWithPVRTCData addPVRTCImage releaseData setTexParameters initWithData keepData getPixelFormatInfoMap], Set::[begin end acceptVisitor], IMEDispatcher::[*], - SAXParser::[*], Thread::[*], Profiler::[*], ProfilingTimer::[*], CallFunc::[create initWithFunction], + SAXParser::[(?!(init))], SAXDelegator::[*], Color3bObject::[*], TouchDispatcher::[*], @@ -105,14 +105,13 @@ skip = Node::[^setPosition$ setGLServerState description getUserObject .*UserDat TextureCache::[addPVRTCImage addImageAsync], Timer::[getSelector createWithScriptHandler], *::[copyWith.* onEnter.* onExit.* ^description$ getObjectType onTouch.* onAcc.* onKey.* onRegisterTouchListener], - FileUtils::[(g|s)etSearchResolutionsOrder$ (g|s)etSearchPaths$ getFileData getDataFromFile getFullPathCache], + FileUtils::[(g|s)etSearchResolutionsOrder$ (g|s)etSearchPaths$ getFileData getDataFromFile getWritablePath setPopupNotify destroyInstance getFullPathCache], Application::[^application.* ^run$], Camera::[getEyeXYZ getCenterXYZ getUpXYZ], ccFontDefinition::[*], NewTextureAtlas::[*], RenderTexture::[listenToBackground listenToForeground] - rename_functions = SpriteFrameCache::[addSpriteFramesWithFile=addSpriteFrames getSpriteFrameByName=getSpriteFrame], MenuItemFont::[setFontNameObj=setFontName setFontSizeObj=setFontSize getFontSizeObj=getFontSize getFontNameObj=getFontName], ProgressTimer::[setReverseProgress=setReverseDirection], @@ -120,7 +119,7 @@ rename_functions = SpriteFrameCache::[addSpriteFramesWithFile=addSpriteFrames ge LayerGradient::[initWithColor=init], LayerColor::[initWithColor=init], GLProgram::[initWithVertexShaderByteArray=initWithString initWithVertexShaderFilename=init programLog=getProgramLog setUniformLocationWith1i=setUniformLocationI32], - Node::[removeFromParentAndCleanup=removeFromParent removeAllChildrenWithCleanup=removeAllChildren], + Node::[removeFromParentAndCleanup=removeFromParent removeAllChildrenWithCleanup=removeAllChildren getLocalZOrder=getZOrder setLocalZOrder=setZOrder], LabelAtlas::[create=_create], Sprite::[initWithFile=init], SpriteBatchNode::[initWithFile=init removeAllChildrenWithCleanup=removeAllChildren], @@ -137,14 +136,14 @@ rename_classes = ParticleSystemQuad::ParticleSystem, remove_prefix = # classes for which there will be no "parent" lookup -classes_have_no_parents = Node Director SimpleAudioEngine FileUtils TMXMapInfo Application EGLViewProtocol +classes_have_no_parents = Node Director SimpleAudioEngine FileUtils TMXMapInfo Application EGLViewProtocol SAXParser # base classes which will be skipped when their sub-classes found them. base_classes_to_skip = Object Clonable # classes that create no constructor # Set is special and we will use a hand-written constructor -abstract_classes = Action FiniteTimeAction ActionInterval ActionEase EaseRateAction EaseElastic EaseBounce ActionInstant GridAction Grid3DAction TiledGrid3DAction Director SpriteFrameCache TransitionEaseScene Set SimpleAudioEngine FileUtils Application ClippingNode Label EGLViewProtocol EGLView Component +abstract_classes = Action FiniteTimeAction ActionInterval ActionEase EaseRateAction EaseElastic EaseBounce ActionInstant GridAction Grid3DAction TiledGrid3DAction Director SpriteFrameCache TransitionEaseScene Set SimpleAudioEngine FileUtils Application ClippingNode Label EGLViewProtocol EGLView Component SAXParser # Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. script_control_cpp = no diff --git a/tools/tojs/cocos2dx_studio.ini b/tools/tojs/cocos2dx_studio.ini index 64cd414f96..4d4e9e6e60 100644 --- a/tools/tojs/cocos2dx_studio.ini +++ b/tools/tojs/cocos2dx_studio.ini @@ -79,4 +79,4 @@ abstract_classes = ColliderDetector ColliderBody ArmatureDataManager ComAttribut # Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. script_control_cpp = no -classes_need_extend = Armature +classes_need_extend = Armature ComController diff --git a/tools/tojs/genbindings-win32.bat b/tools/tojs/genbindings-win32.bat new file mode 100644 index 0000000000..2eed6dd76e --- /dev/null +++ b/tools/tojs/genbindings-win32.bat @@ -0,0 +1,116 @@ +@echo off + +:: This script is used to generate jsbinding glue codes. +:: Android ndk version must be ndk-r9b. + +setlocal +:: You should modify PYTHON_ROOT and NDK_ROOT to work under your environment. +:: or just uncomment the follow 2 lines and set them. + +:: set PYTHON_ROOT=C:/Python27 +:: set NDK_ROOT=G:/android/android-ndk-r9b + +setlocal ENABLEEXTENSIONS +if %errorlevel% neq 0 ( + echo Unable to enable extensions + exit /b 1 + ) + +if defined PYTHON_ROOT (echo PYTHON_ROOT is defined.) else ( + echo PYTHON_ROOT is NOT defined! + exit /b 1 + ) + +if defined NDK_ROOT (echo NDK_ROOT is defined.) else ( + echo NDK_ROOT is NOT defined! + exit /b 1 + ) + +:: Check use 32-bit or 64-bit +:: Assume 64-bit +set TEMP=windows-x86_64 +if not exist "%NDK_ROOT%/toolchains/llvm-3.3/prebuilt/%TEMP%" set TEMP= +:: Otherwise fall back to 32-bit make +if "%TEMP%"=="" set TEMP=windows + +set NDK_LLVM_ROOT=%NDK_ROOT%/toolchains/llvm-3.3/prebuilt/%TEMP% + +set COCOS2DX_ROOT=%cd%/../.. +set "COCOS2DX_ROOT=%COCOS2DX_ROOT:\=/%" +set CXX_GENERATOR_ROOT=%COCOS2DX_ROOT%/tools/bindings-generator +set TO_JS_ROOT=%COCOS2DX_ROOT%/tools/tojs +set "CXX_GENERATOR_ROOT=%CXX_GENERATOR_ROOT:\=/%" +set OUTPUT_DIR=%COCOS2DX_ROOT%/cocos/scripting/auto-generated/js-bindings +set "OUTPUT_DIR=%OUTPUT_DIR:/=\%" + +set PATH=%PATH%;%CXX_GENERATOR_ROOT%/libclang;%CXX_GENERATOR_ROOT%/tools/win32;%PYTHON_ROOT% + +:: write userconf.ini + +set _CONF_INI_FILE=%cd%\userconf.ini +if exist %_CONF_INI_FILE% del /Q %_CONF_INI_FILE% + + +echo +echo generating userconf.ini... +echo --- +echo [DEFAULT] > %_CONF_INI_FILE% +echo androidndkdir=%NDK_ROOT% >> %_CONF_INI_FILE% +echo clangllvmdir=%NDK_LLVM_ROOT% >> %_CONF_INI_FILE% +echo cocosdir=%COCOS2DX_ROOT% >> %_CONF_INI_FILE% +echo cxxgeneratordir=%CXX_GENERATOR_ROOT% >> %_CONF_INI_FILE% +:: fixme: to fix parse error, we must difine __WCHAR_MAX__ and undefine __MINGW32__ . +echo extra_flags=-D__WCHAR_MAX__=0x7fffffff -U__MINGW32__ >> %_CONF_INI_FILE% +echo --- + + + +:: Generate bindings for cocos2dx +echo Generating bindings for cocos2dx... +python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx.ini -s cocos2d-x -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_auto +if %errorlevel% neq 0 goto ERROR + +echo "Generating bindings for cocos2dx_extension..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_extension.ini -s cocos2dx_extension -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_extension_auto +if %errorlevel% neq 0 goto ERROR + +echo "Generating bindings for cocos2dx_builder..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_builder.ini -s cocos2dx_builder -t spidermonkey -o %OUTPUT_DIR% -n jsb_cocos2dx_builder_auto +if %errorlevel% neq 0 goto ERROR + +echo "Generating bindings for cocos2dx_gui..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_gui.ini -s cocos2dx_gui -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_gui_auto +if %errorlevel% neq 0 goto ERROR + + +echo "Generating bindings for cocos2dx_studio..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_studio.ini -s cocos2dx_studio -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_studio_auto +if %errorlevel% neq 0 goto ERROR + + +echo "Generating bindings for cocos2dx_spine..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_JS_ROOT%/cocos2dx_spine.ini -s cocos2dx_spine -t spidermonkey -o %OUTPUT_DIR% -n js_cocos2dx_spine_auto +if %errorlevel% neq 0 goto ERROR + + +:: Change the generated file format from DOS to UNIX. +pushd "%OUTPUT_DIR%" +dos2unix * +popd + +goto PASS + +:PASS +echo --------------------------------- +echo Generating bindings succeeds. +echo --------------------------------- +endlocal +exit /b 0 + +:ERROR +echo --------------------------------- +echo Generating bindings fails. +echo --------------------------------- +endlocal +exit /b 1 + diff --git a/tools/tojs/genbindings.sh b/tools/tojs/genbindings.sh index 00d2d7a8c5..aa95a4e28b 100755 --- a/tools/tojs/genbindings.sh +++ b/tools/tojs/genbindings.sh @@ -1,4 +1,9 @@ #!/bin/bash +# +# Usage: +# export NDK_ROOT=/path/to/ndk-r9b +# ./genbindings.sh +# # exit this script if any commmand fails set -e @@ -6,10 +11,12 @@ set -e # read user.cfg if it exists and is readable _CFG_FILE=$(dirname "$0")"/user.cfg" -if [ -f "$_CFG_FILE" ] +if [ -f "$_CFG_FILE" ]; then - [ -r "$_CFG_FILE" ] || die "Fatal Error: $_CFG_FILE exists but is unreadable" - . "$_CFG_FILE" + if [ ! -r "$_CFG_FILE" ]; then + echo "Fatal Error: $_CFG_FILE exists but is unreadable" + exit 1 + fi fi # paths @@ -19,11 +26,6 @@ if [ -z "${NDK_ROOT+aaa}" ]; then NDK_ROOT="$HOME/bin/android-ndk" fi -if [ -z "${CLANG_ROOT+aaa}" ]; then -# ... if CLANG_ROOT is not set, use "$HOME/bin/clang+llvm-3.3" - CLANG_ROOT="$HOME/bin/clang+llvm-3.3" -fi - if [ -z "${PYTHON_BIN+aaa}" ]; then # ... if PYTHON_BIN is not set, use "/usr/bin/python2.7" PYTHON_BIN="/usr/bin/python2.7" @@ -35,7 +37,7 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # paths with defaults hardcoded to relative paths if [ -z "${COCOS2DX_ROOT+aaa}" ]; then - COCOS2DX_ROOT="$DIR/../../" + COCOS2DX_ROOT="$DIR/../.." fi if [ -z "${CXX_GENERATOR_ROOT+aaa}" ]; then @@ -43,16 +45,59 @@ if [ -z "${CXX_GENERATOR_ROOT+aaa}" ]; then fi if [ -z "${TOJS_ROOT+aaa}" ]; then - TO_JS_ROOT="$COCOS2DX_ROOT/tools/tojs" + TOJS_ROOT="$COCOS2DX_ROOT/tools/tojs" fi +# set output dir +OUTPUT_DIR=${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings + echo "Paths" echo " NDK_ROOT: $NDK_ROOT" -echo " CLANG_ROOT: $CLANG_ROOT" echo " PYTHON_BIN: $PYTHON_BIN" echo " COCOS2DX_ROOT: $COCOS2DX_ROOT" echo " CXX_GENERATOR_ROOT: $CXX_GENERATOR_ROOT" -echo " TO_JS_ROOT: $TO_JS_ROOT" +echo " TOJS_ROOT: $TOJS_ROOT" + +# check NDK version, must be r9b +if ! grep -q r9b $NDK_ROOT/RELEASE.TXT +then + echo " Fatal Error: NDK r9b must be required!" + exit 1 +fi + +# check clang include path +OS_NAME=$('uname') +NDK_LLVM_ROOT=$NDK_ROOT/toolchains/llvm-3.3/prebuilt +case "$OS_NAME" in + Darwin | darwin) + echo "in darwin" + if [ -d "$NDK_LLVM_ROOT/darwin-x86_64" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/darwin-x86_64 + elif [ -d "$NDK_LLVM_ROOT/darwin-x86" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/darwin-x86 + else + echo $NDK_LLVM_ROOT + echo " Fatal Error: $NDK_LLVM_ROOT doesn't contains prebuilt llvm 3.3" + exit 1 + fi + ;; + Linux | linux) + echo "in linux" + if [ -d "$NDK_LLVM_ROOT/linux-x86_64" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/linux-x86_64 + elif [ -d "$NDK_LLVM_ROOT/linux-x86" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/linux-x86 + else + echo " Fatal Error: $NDK_LLVM_ROOT doesn't contains prebuilt llvm 3.3" + exit 1 + fi + ;; + *) + echo " Fatal Error: Please run this script in linux or mac osx." + exit 1 + ;; +esac + # write userconf.ini @@ -65,7 +110,7 @@ fi _CONTENTS="" _CONTENTS+="[DEFAULT]"'\n' _CONTENTS+="androidndkdir=$NDK_ROOT"'\n' -_CONTENTS+="clangllvmdir=$CLANG_ROOT"'\n' +_CONTENTS+="clangllvmdir=$NDK_LLVM_ROOT"'\n' _CONTENTS+="cocosdir=$COCOS2DX_ROOT"'\n' _CONTENTS+="cxxgeneratordir=$CXX_GENERATOR_ROOT"'\n' _CONTENTS+="extra_flags="'\n' @@ -80,19 +125,20 @@ echo --- # Generate bindings for cocos2dx echo "Generating bindings for cocos2dx..." set -x -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx.ini -s cocos2d-x -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_auto echo "Generating bindings for cocos2dx_extension..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_extension_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_extension_auto echo "Generating bindings for cocos2dx_builder..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_builder.ini -s cocos2dx_builder -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_builder_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_builder.ini -s cocos2dx_builder -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_builder_auto echo "Generating bindings for cocos2dx_gui..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_gui.ini -s cocos2dx_gui -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_gui_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_gui.ini -s cocos2dx_gui -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_gui_auto echo "Generating bindings for cocos2dx_studio..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_studio_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_studio_auto echo "Generating bindings for cocos2dx_spine..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_spine.ini -s cocos2dx_spine -t spidermonkey -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/js-bindings -n jsb_cocos2dx_spine_auto \ No newline at end of file +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOJS_ROOT}/cocos2dx_spine.ini -s cocos2dx_spine -t spidermonkey -o ${OUTPUT_DIR} -n jsb_cocos2dx_spine_auto + diff --git a/tools/tolua/README.mdown b/tools/tolua/README.mdown index d0897de1d5..f6f34fddd4 100644 --- a/tools/tolua/README.mdown +++ b/tools/tolua/README.mdown @@ -1,20 +1,20 @@ How to Use bindings-generator ================== -On Windows (Not available from 3.0-pre-alpha0, the reason is that Clang3.3 can't work perfectly on windows, therefore, disable windows support temporary.): +On Windows: ------------ -* Make sure that you have installed `android-ndk-r8d` or higher version. -* Download python2.7.3 from (http://www.python.org/ftp/python/2.7.3/python-2.7.3.msi). +* Make sure that you have installed `android-ndk-r9b`. +* Download python2.7.3 (32bit) from (http://www.python.org/ftp/python/2.7.3/python-2.7.3.msi). * Add the installed path of python (e.g. C:\Python27) to windows environment variable named 'PATH'. * Download pyyaml from http://pyyaml.org/download/pyyaml/PyYAML-3.10.win32-py2.7.exe and install it. * Download pyCheetah from https://raw.github.com/dumganhar/cocos2d-x/download/downloads/Cheetah.zip, unzip it to "C:\Python27\Lib\site-packages" -* Modify environment variables (`PYTHON_ROOT` and `NDK_ROOT`) in `genbindings-win32.bat`. -* Go to "cocos2d-x/tools/tojs" folder, and run "genbindings-win32.bat". The generated codes will be under "cocos2d-x\scripting\javascript\bindings\generated". +* Set environment variables (`PYTHON_ROOT` and `NDK_ROOT`) or just modify variables (`PYTHON_ROOT` and `NDK_ROOT`) in `genbindings-win32.bat`. +* Go to "cocos2d-x/tools/tolua" folder, and run "genbindings-win32.bat". The generated codes will be under "cocos\scripting\auto-generated\lua-bindings". On MAC: ---------- -* Please refer to https://github.com/cocos2d/bindings-generator/blob/master/README.md +* Please refer to https://github.com/cocos2d/bindings-generator/blob/develop/README.md diff --git a/tools/tolua/cocos2dx.ini b/tools/tolua/cocos2dx.ini index e8d443afad..c3f448b595 100644 --- a/tools/tolua/cocos2dx.ini +++ b/tools/tolua/cocos2dx.ini @@ -26,7 +26,7 @@ headers = %(cocosdir)s/cocos/2d/cocos2d.h %(cocosdir)s/cocos/audio/include/Simpl # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = New.* Sprite.* Scene Node.* Director Layer.* Menu.* Touch .*Action.* Move.* Rotate.* Blink.* Tint.* Sequence Repeat.* Fade.* Ease.* Scale.* Transition.* Spawn Animat.* Flip.* Delay.* Skew.* Jump.* Place.* Show.* Progress.* PointArray ToggleVisibility.* RemoveSelf Hide Particle.* Label.* Atlas.* TextureCache.* Texture2D Cardinal.* CatmullRom.* ParallaxNode TileMap.* TMX.* CallFunc RenderTexture GridAction Grid3DAction GridBase$ .+Grid Shaky3D Waves3D FlipX3D FlipY3D Speed ActionManager Set SimpleAudioEngine Scheduler Timer Orbit.* Follow.* Bezier.* CardinalSpline.* Camera.* DrawNode .*3D$ Liquid$ Waves$ ShuffleTiles$ TurnOffTiles$ Split.* Twirl$ FileUtils$ GLProgram ShaderCache Application ClippingNode MotionStreak ^Object$ UserDefault EGLViewProtocol EGLView Image Event(?!.*(Physics).*).* +classes = New.* Sprite.* Scene Node.* Director Layer.* Menu.* Touch .*Action.* Move.* Rotate.* Blink.* Tint.* Sequence Repeat.* Fade.* Ease.* Scale.* Transition.* Spawn Animat.* Flip.* Delay.* Skew.* Jump.* Place.* Show.* Progress.* PointArray ToggleVisibility.* RemoveSelf Hide Particle.* Label.* Atlas.* TextureCache.* Texture2D Cardinal.* CatmullRom.* ParallaxNode TileMap.* TMX.* CallFunc RenderTexture GridAction Grid3DAction GridBase$ .+Grid Shaky3D Waves3D FlipX3D FlipY3D Speed ActionManager Set SimpleAudioEngine Scheduler Timer Orbit.* Follow.* Bezier.* CardinalSpline.* Camera.* DrawNode .*3D$ Liquid$ Waves$ ShuffleTiles$ TurnOffTiles$ Split.* Twirl$ FileUtils$ GLProgram ShaderCache Application ClippingNode MotionStreak ^Object$ UserDefault EGLViewProtocol EGLView Image Event(?!.*(Physics).*).* Component # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -48,7 +48,7 @@ skip = Node::[setGLServerState description getUserObject .*UserData getGLServerS Layer.*::[didAccelerate (g|s)etBlendFunc keyPressed keyReleased], Menu.*::[.*Target getSubItems create initWithItems alignItemsInRows alignItemsInColumns], MenuItem.*::[create setCallback initWithCallback], - Label::[getLettersInfo], + Label::[getLettersInfo createWithTTF setTTFConfig], Copying::[*], LabelProtocol::[*], LabelTextFormatProtocol::[*], @@ -108,7 +108,6 @@ skip = Node::[setGLServerState description getUserObject .*UserData getGLServerS ccFontDefinition::[*], Object::[autorelease isEqual acceptVisitor update], UserDefault::[getInstance (s|g)etDataForKey], - Label::[getLettersInfo], EGLViewProtocol::[setTouchDelegate], EGLView::[end swapBuffers], NewTextureAtlas::[*], @@ -144,7 +143,7 @@ base_classes_to_skip = Clonable # classes that create no constructor # Set is special and we will use a hand-written constructor -abstract_classes = Action FiniteTimeAction ActionInterval ActionEase EaseRateAction EaseElastic EaseBounce ActionInstant GridAction Grid3DAction TiledGrid3DAction Director SpriteFrameCache TransitionEaseScene Set SimpleAudioEngine FileUtils Application ClippingNode Label EGLViewProtocol EGLView EventAcceleration DisplayLinkDirector +abstract_classes = Action FiniteTimeAction ActionInterval ActionEase EaseRateAction EaseElastic EaseBounce ActionInstant GridAction Grid3DAction TiledGrid3DAction Director SpriteFrameCache TransitionEaseScene Set SimpleAudioEngine FileUtils Application ClippingNode Label EGLViewProtocol EGLView EventAcceleration DisplayLinkDirector Component # Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'. script_control_cpp = no diff --git a/tools/tolua/cocos2dx_extension.ini b/tools/tolua/cocos2dx_extension.ini index d75f375305..248894593e 100644 --- a/tools/tolua/cocos2dx_extension.ini +++ b/tools/tolua/cocos2dx_extension.ini @@ -27,7 +27,7 @@ headers = %(cocosdir)s/extensions/cocos-ext.h %(cocosdir)s/cocos/editor-support/ # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* EditBox$ +classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* EditBox$ ScrollView$ TableView$ TableViewCell$ # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -46,7 +46,9 @@ skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getC AssetsManagerDelegateProtocol::[*], Control::[removeHandleOfControlEvent addHandleOfControlEvent], ControlUtils::[*], - ControlSwitchSprite::[*] + ControlSwitchSprite::[*], + ScrollView::[(g|s)etDelegate$], + TableView::[create (g|s)etDataSource$ (g|s)etDelegate] rename_functions = CCBReader::[getAnimationManager=getActionManager setAnimationManager=setActionManager] diff --git a/tools/tolua/cocos2dx_physics.ini b/tools/tolua/cocos2dx_physics.ini index 7c6c3ed78f..84ca321e42 100644 --- a/tools/tolua/cocos2dx_physics.ini +++ b/tools/tolua/cocos2dx_physics.ini @@ -37,12 +37,13 @@ classes = Event(.*(Physics).*) Physics.* skip = PhysicsBody::[getJoints createPolygon createEdgeChain createEdgePolygon], PhysicsShape::[recenterPoints getPolyonCenter], - PhysicsShapeBox::[getPoints], - PhysicsShapeEdgeBox::[getPoints], - PhysicsShapePolygon::[getPoints], - PhysicsShapeEdgePolygon::[getPoints], - PhysicsShapeEdgeChain::[getPoints], - PhysicsWorld::[getScene queryPoint queryRect rayCast] + PhysicsShapeBox::[^getPoints$], + PhysicsShapeEdgeBox::[^getPoints$], + PhysicsShapePolygon::[^getPoints$], + PhysicsShapeEdgePolygon::[^getPoints$], + PhysicsShapeEdgeChain::[^getPoints$], + PhysicsWorld::[getScene queryPoint queryRect rayCast], + PhysicsContact::[getData setData] rename_functions = diff --git a/tools/tolua/genbindings-win32.bat b/tools/tolua/genbindings-win32.bat new file mode 100644 index 0000000000..672d63bd2f --- /dev/null +++ b/tools/tolua/genbindings-win32.bat @@ -0,0 +1,117 @@ +@echo off + +:: This script is used to generate jsbinding glue codes. +:: Android ndk version must be ndk-r9b. + +setlocal +:: You should modify PYTHON_ROOT and NDK_ROOT to work under your environment. +:: or just uncomment the follow 2 lines and set them. + +:: set PYTHON_ROOT=C:/Python27 +:: set NDK_ROOT=G:/android/android-ndk-r9b + +setlocal ENABLEEXTENSIONS +if %errorlevel% neq 0 ( + echo Unable to enable extensions + exit /b 1 + ) + +if defined PYTHON_ROOT (echo PYTHON_ROOT is defined.) else ( + echo PYTHON_ROOT is NOT defined! + exit /b 1 + ) + +if defined NDK_ROOT (echo NDK_ROOT is defined.) else ( + echo NDK_ROOT is NOT defined! + exit /b 1 + ) + +:: Check use 32-bit or 64-bit +:: Assume 64-bit +set TEMP=windows-x86_64 +if not exist "%NDK_ROOT%/toolchains/llvm-3.3/prebuilt/%TEMP%" set TEMP= +:: Otherwise fall back to 32-bit make +if "%TEMP%"=="" set TEMP=windows + +set NDK_LLVM_ROOT=%NDK_ROOT%/toolchains/llvm-3.3/prebuilt/%TEMP% + +set COCOS2DX_ROOT=%cd%/../.. +set "COCOS2DX_ROOT=%COCOS2DX_ROOT:\=/%" +set CXX_GENERATOR_ROOT=%COCOS2DX_ROOT%/tools/bindings-generator +set TO_LUA_ROOT=%COCOS2DX_ROOT%/tools/tolua +set "CXX_GENERATOR_ROOT=%CXX_GENERATOR_ROOT:\=/%" +set OUTPUT_DIR=%COCOS2DX_ROOT%/cocos/scripting/auto-generated/lua-bindings +set "OUTPUT_DIR=%OUTPUT_DIR:/=\%" + +set PATH=%PATH%;%CXX_GENERATOR_ROOT%/libclang;%CXX_GENERATOR_ROOT%/tools/win32;%PYTHON_ROOT% + +:: write userconf.ini + +set _CONF_INI_FILE=%cd%\userconf.ini +if exist %_CONF_INI_FILE% del /Q %_CONF_INI_FILE% + + +echo +echo generating userconf.ini... +echo --- +echo [DEFAULT] > %_CONF_INI_FILE% +echo androidndkdir=%NDK_ROOT% >> %_CONF_INI_FILE% +echo clangllvmdir=%NDK_LLVM_ROOT% >> %_CONF_INI_FILE% +echo cocosdir=%COCOS2DX_ROOT% >> %_CONF_INI_FILE% +echo cxxgeneratordir=%CXX_GENERATOR_ROOT% >> %_CONF_INI_FILE% +:: fixme: to fix parse error, we must difine __WCHAR_MAX__ and undefine __MINGW32__ . +echo extra_flags=-D__WCHAR_MAX__=0x7fffffff -U__MINGW32__ >> %_CONF_INI_FILE% +echo --- + + + +:: Generate bindings for cocos2dx +echo Generating bindings for cocos2dx... +python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx.ini -s cocos2d-x -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_auto +if %errorlevel% neq 0 goto ERROR + +echo "Generating bindings for cocos2dx_extension..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_extension_auto +if %errorlevel% neq 0 goto ERROR + +echo "Generating bindings for cocos2dx_gui..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_gui.ini -s cocos2dx_gui -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_gui_auto +if %errorlevel% neq 0 goto ERROR + + +echo "Generating bindings for cocos2dx_studio..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_studio_auto +if %errorlevel% neq 0 goto ERROR + + +echo "Generating bindings for cocos2dx_spine..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_spine.ini -s cocos2dx_spine -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_spine_auto +if %errorlevel% neq 0 goto ERROR + + +echo "Generating bindings for cocos2dx_physics..." +python %CXX_GENERATOR_ROOT%/generator.py %TO_LUA_ROOT%/cocos2dx_physics.ini -s cocos2dx_physics -t lua -o %OUTPUT_DIR% -n lua_cocos2dx_physics_auto +if %errorlevel% neq 0 goto ERROR + + +:: Change the generated file format from DOS to UNIX. +pushd "%OUTPUT_DIR%" +dos2unix * +popd + +goto PASS + +:PASS +echo --------------------------------- +echo Generating bindings succeeds. +echo --------------------------------- +endlocal +exit /b 0 + +:ERROR +echo --------------------------------- +echo Generating bindings fails. +echo --------------------------------- +endlocal +exit /b 1 + diff --git a/tools/tolua/genbindings.sh b/tools/tolua/genbindings.sh index eb463fcfa5..e15de46b1a 100755 --- a/tools/tolua/genbindings.sh +++ b/tools/tolua/genbindings.sh @@ -1,4 +1,9 @@ #!/bin/bash +# +# Usage: +# export NDK_ROOT=/path/to/ndk-r9b +# ./genbindings.sh +# # exit this script if any commmand fails set -e @@ -6,10 +11,12 @@ set -e # read user.cfg if it exists and is readable _CFG_FILE=$(dirname "$0")"/user.cfg" -if [ -f "$_CFG_FILE" ] +if [ -f "$_CFG_FILE" ]; then - [ -r "$_CFG_FILE" ] || die "Fatal Error: $_CFG_FILE exists but is unreadable" - . "$_CFG_FILE" + if [ ! -r "$_CFG_FILE" ]; then + echo "Fatal Error: $_CFG_FILE exists but is unreadable" + exit 1 + fi fi # paths @@ -19,11 +26,6 @@ if [ -z "${NDK_ROOT+aaa}" ]; then NDK_ROOT="$HOME/bin/android-ndk" fi -if [ -z "${CLANG_ROOT+aaa}" ]; then -# ... if CLANG_ROOT is not set, use "$HOME/bin/clang+llvm-3.3" - CLANG_ROOT="$HOME/bin/clang+llvm-3.3" -fi - if [ -z "${PYTHON_BIN+aaa}" ]; then # ... if PYTHON_BIN is not set, use "/usr/bin/python2.7" PYTHON_BIN="/usr/bin/python2.7" @@ -35,24 +37,67 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # paths with defaults hardcoded to relative paths if [ -z "${COCOS2DX_ROOT+aaa}" ]; then - COCOS2DX_ROOT="$DIR/../../" + COCOS2DX_ROOT="$DIR/../.." fi if [ -z "${CXX_GENERATOR_ROOT+aaa}" ]; then CXX_GENERATOR_ROOT="$COCOS2DX_ROOT/tools/bindings-generator" fi -if [ -z "${TOJS_ROOT+aaa}" ]; then - TO_JS_ROOT="$COCOS2DX_ROOT/tools/tolua" +if [ -z "${TOLUA_ROOT+aaa}" ]; then + TOLUA_ROOT="$COCOS2DX_ROOT/tools/tolua" fi +# set output dir +OUTPUT_DIR=${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings + echo "Paths" echo " NDK_ROOT: $NDK_ROOT" -echo " CLANG_ROOT: $CLANG_ROOT" echo " PYTHON_BIN: $PYTHON_BIN" echo " COCOS2DX_ROOT: $COCOS2DX_ROOT" echo " CXX_GENERATOR_ROOT: $CXX_GENERATOR_ROOT" -echo " TO_JS_ROOT: $TO_JS_ROOT" +echo " TOLUA_ROOT: $TOLUA_ROOT" + +# check NDK version, must be r9b +if ! grep -q r9b $NDK_ROOT/RELEASE.TXT +then + echo " Fatal Error: NDK r9b must be required!" + exit 1 +fi + +# check clang include path +OS_NAME=$('uname') +NDK_LLVM_ROOT=$NDK_ROOT/toolchains/llvm-3.3/prebuilt +case "$OS_NAME" in + Darwin | darwin) + echo "in darwin" + if [ -d "$NDK_LLVM_ROOT/darwin-x86_64" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/darwin-x86_64 + elif [ -d "$NDK_LLVM_ROOT/darwin-x86" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/darwin-x86 + else + echo $NDK_LLVM_ROOT + echo " Fatal Error: $NDK_LLVM_ROOT doesn't contains prebuilt llvm 3.3" + exit 1 + fi + ;; + Linux | linux) + echo "in linux" + if [ -d "$NDK_LLVM_ROOT/linux-x86_64" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/linux-x86_64 + elif [ -d "$NDK_LLVM_ROOT/linux-x86" ]; then + NDK_LLVM_ROOT=$NDK_LLVM_ROOT/linux-x86 + else + echo " Fatal Error: $NDK_LLVM_ROOT doesn't contains prebuilt llvm 3.3" + exit 1 + fi + ;; + *) + echo " Fatal Error: Please run this script in linux or mac osx." + exit 1 + ;; +esac + # write userconf.ini @@ -65,7 +110,7 @@ fi _CONTENTS="" _CONTENTS+="[DEFAULT]"'\n' _CONTENTS+="androidndkdir=$NDK_ROOT"'\n' -_CONTENTS+="clangllvmdir=$CLANG_ROOT"'\n' +_CONTENTS+="clangllvmdir=$NDK_LLVM_ROOT"'\n' _CONTENTS+="cocosdir=$COCOS2DX_ROOT"'\n' _CONTENTS+="cxxgeneratordir=$CXX_GENERATOR_ROOT"'\n' _CONTENTS+="extra_flags="'\n' @@ -80,19 +125,20 @@ echo --- # Generate bindings for cocos2dx echo "Generating bindings for cocos2dx..." set -x -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx.ini -s cocos2d-x -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx.ini -s cocos2d-x -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_auto echo "Generating bindings for cocos2dx_extension..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_extension_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_extension.ini -s cocos2dx_extension -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_extension_auto echo "Generating bindings for cocos2dx_gui..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_gui.ini -s cocos2dx_gui -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_gui_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_gui.ini -s cocos2dx_gui -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_gui_auto echo "Generating bindings for cocos2dx_studio..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_studio_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_studio.ini -s cocos2dx_studio -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_studio_auto echo "Generating bindings for cocos2dx_spine..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_spine.ini -s cocos2dx_spine -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_spine_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_spine.ini -s cocos2dx_spine -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_spine_auto echo "Generating bindings for cocos2dx_physics..." -LD_LIBRARY_PATH=${CLANG_ROOT}/lib $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TO_JS_ROOT}/cocos2dx_physics.ini -s cocos2dx_physics -t lua -o ${COCOS2DX_ROOT}/cocos/scripting/auto-generated/lua-bindings -n lua_cocos2dx_physics_auto +LD_LIBRARY_PATH=${CXX_GENERATOR_ROOT}/libclang $PYTHON_BIN ${CXX_GENERATOR_ROOT}/generator.py ${TOLUA_ROOT}/cocos2dx_physics.ini -s cocos2dx_physics -t lua -o ${OUTPUT_DIR} -n lua_cocos2dx_physics_auto + diff --git a/tools/travis-scripts/before-install.sh b/tools/travis-scripts/before-install.sh index acfdd36e12..d8eeb09ebe 100755 --- a/tools/travis-scripts/before-install.sh +++ b/tools/travis-scripts/before-install.sh @@ -6,9 +6,6 @@ set -e DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" COCOS2DX_ROOT="$DIR"/../.. HOST_NAME="" -LLVM_VERSION="" -LLVM_PACKAGE="" -LLVM_PACKAGE_SUFFIX="" mkdir -p $HOME/bin cd $HOME/bin @@ -29,47 +26,6 @@ install_android_ndk() mv android-ndk-r9b android-ndk } -install_llvm() -{ - LLVM_VERSION="3.3" - if [ "$PLATFORM"x = "ios"x ]; then - LLVM_PACKAGE="clang+llvm-3.3-x86_64-apple-darwin12" - LLVM_PACKAGE_SUFFIX=".tar.gz" - else - LLVM_PACKAGE="clang+llvm-3.3-Ubuntu-13.04-x86_64-linux-gnu" - LLVM_PACKAGE_SUFFIX=".tar.bz2" - fi - - # Download llvm - echo "Download ${LLVM_PACKAGE} ..." - curl -O http://llvm.org/releases/${LLVM_VERSION}/${LLVM_PACKAGE}${LLVM_PACKAGE_SUFFIX} - echo "Decompress ${LLVM_PACKAGE} ..." - if [ "$PLATFORM"x = "ios"x ]; then - tar xzf ${LLVM_PACKAGE}${LLVM_PACKAGE_SUFFIX} - else - tar xjf ${LLVM_PACKAGE}${LLVM_PACKAGE_SUFFIX} - fi - - # Rename llvm - mv ${LLVM_PACKAGE} clang+llvm-${LLVM_VERSION} -} - -install_llvm_3_2() -{ - if [ "$PLATFORM"x = "ios"x ]; then - HOST_NAME="apple-darwin11" - else - HOST_NAME="linux-ubuntu-12.04" - fi - # Download llvm3.2 - echo "Download clang+llvm-3.2-x86_64-${HOST_NAME}.tar.gz" - curl -O http://llvm.org/releases/3.2/clang+llvm-3.2-x86_64-${HOST_NAME}.tar.gz - echo "Decompress clang+llvm-3.2-x86_64-${HOST_NAME}.tar.gz ..." - tar xzf clang+llvm-3.2-x86_64-${HOST_NAME}.tar.gz - # Rename llvm - mv clang+llvm-3.2-x86_64-${HOST_NAME} clang+llvm-3.2 -} - install_nacl_sdk() { # NaCl compilers are built for 32-bit linux so we need to install @@ -92,11 +48,8 @@ if [ "$GEN_JSB"x = "YES"x ]; then exit 0 fi install_android_ndk - install_llvm elif [ "$PLATFORM"x = "linux"x ]; then sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test - # OpenMW team provides SDL2 package. - sudo apt-add-repository -y ppa:openmw/build sudo apt-get update sudo apt-get install gcc-4.7 g++-4.7 sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.6 @@ -104,19 +57,15 @@ elif [ "$PLATFORM"x = "linux"x ]; then g++ --version bash $COCOS2DX_ROOT/build/install-deps-linux.sh install_android_ndk - install_llvm elif [ "$PLATFORM"x = "nacl"x ]; then install_nacl_sdk elif [ "$PLATFORM"x = "android"x ]; then install_android_ndk - install_llvm elif [ "$PLATFORM"x = "emscripten"x ]; then sudo rm -rf /dev/shm && sudo ln -s /run/shm /dev/shm install_android_ndk - install_llvm_3_2 elif [ "$PLATFORM"x = "ios"x ]; then install_android_ndk - install_llvm pushd $COCOS2DX_ROOT git submodule add https://github.com/facebook/xctool.git ./xctool @@ -127,3 +76,4 @@ else echo "Unknown \$PLATFORM: '$PLATFORM'" exit 1 fi + diff --git a/tools/travis-scripts/install_glfw.sh b/tools/travis-scripts/install_glfw.sh index ff08914ff7..933c5b1ee1 100755 --- a/tools/travis-scripts/install_glfw.sh +++ b/tools/travis-scripts/install_glfw.sh @@ -1,6 +1,6 @@ #!/bin/bash -GLFW_VERSION="3.0.2" +GLFW_VERSION="3.0.4" GLFW_SOURCE="https://codeload.github.com/glfw/glfw/tar.gz/${GLFW_VERSION}" GLFW_ZIP="glfw${GLFW_VERSION}.tar.gz" GLFW_INSTALL="glfw_install" @@ -46,9 +46,6 @@ install_glfw() clean_tmp_file } -GLFW_INSTALLED=$(whereis libglfw |grep libglfw.so) -if [ "$GLFW_INSTALLED"x = ""x ]; then - install_glfw -else - echo "libglfw has been installed, skip..." -fi + +install_glfw + diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index aa9c47f5c6..d7c938d702 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -42,9 +42,9 @@ elif [ "$PLATFORM"x = "android"x ]; then # Create a directory for temporary objects mkdir android_build_objs - PROJECTS=("Cpp/HelloCpp" "Cpp/TestCpp" "Cpp/SimpleGame" "Cpp/AssetsManagerTest" "Javascript/TestJavascript" "Javascript/CocosDragonJS" "Javascript/CrystalCraze" "Javascript/MoonWarriors" "Javascript/WatermelonWithMe" "Lua/HelloLua" "Lua/TestLua") + PROJECTS=("test-cpp" "test-javascript" "test-lua") for i in ${PROJECTS[*]}; do - ln -s $COCOS2DX_ROOT/android_build_objs $COCOS2DX_ROOT/samples/$i/proj.android/obj + ln -s $COCOS2DX_ROOT/android_build_objs $COCOS2DX_ROOT/tests/$i/proj.android/obj done # Build all samples