code:
/****************************************************************************
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 "IMEJni.h"
#include "CCIMEDispatcher.h"
#include "JniHelper.h"

#include <android/log.h>
#include <string.h>
#include <jni.h>

#if 0
#define  LOG_TAG    "IMEJni"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#else
#define  LOGD(...)
#endif

using namespace cocos2d;

extern "C"
{
    //////////////////////////////////////////////////////////////////////////
    // handle IME message
    //////////////////////////////////////////////////////////////////////////

    void setKeyboardStateJNI(int bOpen)
    {
		JniMethodInfo t;

		if (JniHelper::getStaticMethodInfo(t,
			"org/cocos2dx/lib/Cocos2dxGLSurfaceView",
			(bOpen) ? "openIMEKeyboard" : "closeIMEKeyboard",
			"()V"))
		{
			t.env->CallStaticVoidMethod(t.classID, t.methodID);
			t.env->DeleteLocalRef(t.classID);
		}
    }

    void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInsertText(JNIEnv* env, jobject thiz, jstring text)
    {
        jboolean isCopy = 0;
        const char* pszText = env->GetStringUTFChars(text, &isCopy);
        if (isCopy)
        {
            cocos2d::CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(pszText, strlen(pszText));
            env->ReleaseStringUTFChars(text, pszText);
        }
    }

    void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeDeleteBackward(JNIEnv* env, jobject thiz)
    {
        cocos2d::CCIMEDispatcher::sharedDispatcher()->dispatchDeleteBackward();
    }

    jstring Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeGetContentText()
    {
        JNIEnv * env = 0;

        if (JniHelper::getJavaVM()->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK || ! env)
        {
            return 0;
        }
        const char * pszText = cocos2d::CCIMEDispatcher::sharedDispatcher()->getContentText();
        return env->NewStringUTF(pszText);
    }
}


code:
/****************************************************************************
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.
****************************************************************************/
#ifndef __ANDROID_IME_JNI_H__
#define __ANDROID_IME_JNI_H__

extern "C"

{
    extern void setKeyboardStateJNI(int bOpen);
}

#endif // __ANDROID_IME_JNI_H__

license: mit


code:
/****************************************************************************
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 "JniHelper.h"
#include <android/log.h>
#include <string.h>

#if 1
#define  LOG_TAG    "JniHelper"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#else
#define  LOGD(...)
#endif

#define JAVAVM	cocos2d::JniHelper::getJavaVM()

using namespace std;

extern "C"
{

    //////////////////////////////////////////////////////////////////////////
    // java vm helper function
    //////////////////////////////////////////////////////////////////////////

	static bool getEnv(JNIEnv **env)
	{
		bool bRet = false;

		do
		{
			if (JAVAVM->GetEnv((void**)env, JNI_VERSION_1_4) != JNI_OK)
			{
				LOGD("Failed to get the environment using GetEnv()");
				break;
			}

			if (JAVAVM->AttachCurrentThread(env, 0) < 0)
			{
				LOGD("Failed to get the environment using AttachCurrentThread()");
				break;
			}

			bRet = true;
		} while (0);

		return bRet;
	}

	static jclass getClassID_(const char *className, JNIEnv *env)
	{
		JNIEnv *pEnv = env;
		jclass ret = 0;

		do
		{
			if (! pEnv)
			{
				if (! getEnv(&pEnv))
				{
					break;
				}
			}

			ret = pEnv->FindClass(className);
			if (! ret)
			{
				 LOGD("Failed to find class of %s", className);
				break;
			}
		} while (0);

		return ret;
	}

	static bool getStaticMethodInfo_(cocos2d::JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode)
    {
		jmethodID methodID = 0;
		JNIEnv *pEnv = 0;
		bool bRet = false;

        do
        {
			if (! getEnv(&pEnv))
			{
				break;
			}

            jclass classID = getClassID_(className, pEnv);

            methodID = pEnv->GetStaticMethodID(classID, methodName, paramCode);
            if (! methodID)
            {
                LOGD("Failed to find static method id of %s", methodName);
                break;
            }

			methodinfo.classID = classID;
			methodinfo.env = pEnv;
			methodinfo.methodID = methodID;

			bRet = true;
        } while (0);

        return bRet;
    }

	static bool getMethodInfo_(cocos2d::JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode)
	{
		jmethodID methodID = 0;
		JNIEnv *pEnv = 0;
		bool bRet = false;

		do
		{
			if (! getEnv(&pEnv))
			{
				break;
			}

			jclass classID = getClassID_(className, pEnv);

			methodID = pEnv->GetMethodID(classID, methodName, paramCode);
			if (! methodID)
			{
				LOGD("Failed to find method id of %s", methodName);
				break;
			}

			methodinfo.classID = classID;
			methodinfo.env = pEnv;
			methodinfo.methodID = methodID;

			bRet = true;
		} while (0);

		return bRet;
	}

	static string jstring2string_(jstring jstr)
	{
		JNIEnv *env = 0;

		jboolean isCopy;
		if (! getEnv(&env))
		{
			return 0;
		}

		const char* chars = env->GetStringUTFChars(jstr, &isCopy);
		string ret(chars);
		if (isCopy)
		{
			env->ReleaseStringUTFChars(jstr, chars);
		}

		return ret;
	}
}

namespace cocos2d {

	JavaVM* JniHelper::m_psJavaVM = NULL;

	JavaVM* JniHelper::getJavaVM()
	{
		return m_psJavaVM;
	}

	void JniHelper::setJavaVM(JavaVM *javaVM)
	{
		m_psJavaVM = javaVM;
	}

	jclass JniHelper::getClassID(const char *className, JNIEnv *env)
	{
		return getClassID_(className, env);
	}

	bool JniHelper::getStaticMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode)
	{
		return getStaticMethodInfo_(methodinfo, className, methodName, paramCode);
	}

	bool JniHelper::getMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode)
	{
		return getMethodInfo_(methodinfo, className, methodName, paramCode);
	}

	string JniHelper::jstring2string(jstring str)
	{
		return jstring2string_(str);
	}
}


code:
/****************************************************************************
Copyright (c) 2010-2011 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.
****************************************************************************/
#ifndef __ANDROID_JNI_HELPER_H__
#define __ANDROID_JNI_HELPER_H__

#include <jni.h>
#include <string>
#include "CCPlatformMacros.h"

namespace cocos2d {

	typedef struct JniMethodInfo_
	{
		JNIEnv *    env;
		jclass      classID;
		jmethodID   methodID;
	} JniMethodInfo;

	class CC_DLL JniHelper
	{
	public:
		static JavaVM* getJavaVM();
		static void setJavaVM(JavaVM *javaVM);
		static jclass getClassID(const char *className, JNIEnv *env=0);
		static bool getStaticMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode);
		static bool getMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode);
		static std::string jstring2string(jstring str);

	private:
		static JavaVM *m_psJavaVM;
	};
}

#endif // __ANDROID_JNI_HELPER_H__


code:
/****************************************************************************
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 "MessageJni.h"
#include "CCDirector.h"
#include "JniHelper.h"
#include "CCApplication.h"
#include "CCFileUtils.h"

#include <android/log.h>
#include <jni.h>

#if 0
#define  LOG_TAG    "MessageJni"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#else
#define  LOGD(...)
#endif

using namespace cocos2d;

extern "C"
{
    //////////////////////////////////////////////////////////////////////////
    // native renderer
    //////////////////////////////////////////////////////////////////////////

    void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeRender(JNIEnv* env)
    {
        cocos2d::CCDirector::sharedDirector()->mainLoop();
    }

	// handle onPause and onResume

	void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnPause()
	{
	        CCApplication::sharedApplication().applicationDidEnterBackground();
	}

	void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnResume()
	{
	        // Shared OpenGL View instance doesn't exist yet when Activity.onResume is first called
	        if (CCDirector::sharedDirector()->getOpenGLView())
			{
	            CCApplication::sharedApplication().applicationWillEnterForeground();
			}
	}

	void showMessageBoxJNI(const char * pszMsg, const char * pszTitle)
	{
		if (! pszMsg)
		{
			return;
		}

        JniMethodInfo t;
		if (JniHelper::getStaticMethodInfo(t
            , "org/cocos2dx/lib/Cocos2dxActivity"
            , "showMessageBox"
            , "(Ljava/lang/String;Ljava/lang/String;)V"))
		{
			jstring stringArg1;

			if (! pszTitle)
			{
				stringArg1 = t.env->NewStringUTF("");
			}
			else
			{
				stringArg1 = t.env->NewStringUTF(pszTitle);
			}

			jstring stringArg2 = t.env->NewStringUTF(pszMsg);
			t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg1, stringArg2);

			t.env->DeleteLocalRef(stringArg1);
            t.env->DeleteLocalRef(stringArg2);
			t.env->DeleteLocalRef(t.classID);
		}
	}

	//////////////////////////////////////////////////////////////////////////
	// terminate the process
	//////////////////////////////////////////////////////////////////////////
	void terminateProcessJNI()
	{
		JniMethodInfo t;

		if (JniHelper::getStaticMethodInfo(t
			, "org/cocos2dx/lib/Cocos2dxActivity"
			, "terminateProcess"
			, "()V"))
		{
			t.env->CallStaticVoidMethod(t.classID, t.methodID);
			t.env->DeleteLocalRef(t.classID);
		}
	}

	//////////////////////////////////////////////////////////////////////////
	// set apk path
	//////////////////////////////////////////////////////////////////////////
	void Java_org_cocos2dx_lib_Cocos2dxActivity_nativeSetPaths(JNIEnv*  env, jobject thiz, jstring apkPath)
	{
		const char* str;
		jboolean isCopy;
		str = env->GetStringUTFChars(apkPath, &isCopy);
		if (isCopy) {
			cocos2d::CCFileUtils::setResourcePath(str);
			env->ReleaseStringUTFChars(apkPath, str);
		}
	}
}


code:
/****************************************************************************
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.
****************************************************************************/
#ifndef __ANDROID_MESSAGE_JNI_H__
#define __ANDROID_MESSAGE_JNI_H__

extern "C"

{
	extern void showMessageBoxJNI(const char * pszMsg, const char * pszTitle);
	extern void terminateProcessJNI();
}

#endif // __ANDROID_MESSAGE_JNI_H__


code:
/****************************************************************************
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 "SensorJni.h"
#include "CCGeometry.h"
#include "CCAccelerometer.h"
#include "platform/android/CCAccelerometer_android.h"
#include "CCEGLView.h"
#include "JniHelper.h"
#include <android/log.h>
#include <jni.h>

#if 0
#define  LOG_TAG    "SensorJni"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#else
#define  LOGD(...)
#endif

using namespace cocos2d;

extern "C"
{

    //////////////////////////////////////////////////////////////////////////
    // handle accelerometer changes
    //////////////////////////////////////////////////////////////////////////

    void Java_org_cocos2dx_lib_Cocos2dxAccelerometer_onSensorChanged(JNIEnv*  env, jobject thiz, jfloat x, jfloat y, jfloat z, jlong timeStamp)
    {
        // We need to invert to make it compatible with iOS.
        CCRect rcRect = CCEGLView::sharedOpenGLView().getViewPort();
        float fScreenScaleFactor = CCEGLView::sharedOpenGLView().getScreenScaleFactor();
//         cocos2d::CCAccelerometer::sharedAccelerometer()->update((x - rcRect.origin.x) / fScreenScaleFactor,
//             (y - rcRect.origin.y) / fScreenScaleFactor,
//             z,
//             timeStamp);
		cocos2d::CCAccelerometer::sharedAccelerometer()->update(x, y, z, timeStamp);
    }

	void enableAccelerometerJNI()
	{
		JniMethodInfo t;

		if (JniHelper::getStaticMethodInfo(t,
			                         "org/cocos2dx/lib/Cocos2dxActivity",
									 "enableAccelerometer",
									 "()V"))
		{
			t.env->CallStaticVoidMethod(t.classID, t.methodID);
			t.env->DeleteLocalRef(t.classID);
		}
	}

	void disableAccelerometerJNI()
	{
		JniMethodInfo t;

		if (JniHelper::getStaticMethodInfo(t,
			"org/cocos2dx/lib/Cocos2dxActivity",
			"disableAccelerometer",
			"()V"))
		{
			t.env->CallStaticVoidMethod(t.classID, t.methodID);
			t.env->DeleteLocalRef(t.classID);
		}
	}
}


code:
/****************************************************************************
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.
****************************************************************************/
#ifndef __ANDROID_SENSOR_JNI_H__
#define __ANDROID_SENSOR_JNI_H__

extern "C"

{
	extern void enableAccelerometerJNI();
	extern void disableAccelerometerJNI();
}

#endif // __ANDROID_SENSOR_JNI_H__


code:
/****************************************************************************
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 "SystemInfoJni.h"
#include "JniHelper.h"
#include "CCString.h"

#include <android/log.h>
#include <jni.h>

#if 0
#define  LOG_TAG    "SystemInfoJni"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#else
#define  LOGD(...)
#endif

using namespace cocos2d;

extern "C"
{
	const char* getPackageNameJNI()
	{
		JniMethodInfo t;

		if (JniHelper::getStaticMethodInfo(t,
						"org/cocos2dx/lib/Cocos2dxActivity",
						"getCocos2dxPackageName",
						"()Ljava/lang/String;"))
		{
			jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
			t.env->DeleteLocalRef(t.classID);
			CCString *ret = new CCString(JniHelper::jstring2string(str).c_str());
			ret->autorelease();

			LOGD("package name %s", ret->m_sString.c_str());

			return ret->m_sString.c_str();
		}

		return 0;
	}

	//////////////////////////////////////////////////////////////////////////
    // handle get current language
    //////////////////////////////////////////////////////////////////////////
    const char* getCurrentLanguageJNI()
    {
        JniMethodInfo t;

        if (JniHelper::getStaticMethodInfo(t
            , "org/cocos2dx/lib/Cocos2dxActivity"
            , "getCurrentLanguage"
            , "()Ljava/lang/String;"))
        {
            jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
			t.env->DeleteLocalRef(t.classID);
	        CCString *ret = new CCString(JniHelper::jstring2string(str).c_str());
			ret->autorelease();

	        LOGD("language name %s", ret.c_str());

			return ret->m_sString.c_str();
        }

        return 0;
    }
}


code:
/****************************************************************************
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.
****************************************************************************/
#ifndef __ANDROID_SYSTEM_INFO_JNI_H__
#define __ANDROID_SYSTEM_INFO_JNI_H__

#include <jni.h>

extern "C"

{
    extern const char* getCurrentLanguageJNI();
    extern const char* getPackageNameJNI();
}

#endif // __ANDROID_SYSTEM_INFO_JNI_H__


code:
/****************************************************************************
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 "CCSet.h"
#include "CCDirector.h"
#include "CCKeypadDispatcher.h"
#include "CCTouch.h"
#include "CCEGLView.h"
#include "CCTouchDispatcher.h"

#include <android/log.h>
#include <jni.h>

#if 0
#define  LOG_TAG    "NativeTouchesJni"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#else
#define  LOGD(...)
#endif

using namespace cocos2d;

extern "C"
{

#define MAX_TOUCHES         5
static CCTouch *s_pTouches[MAX_TOUCHES] = { NULL };

    // handle touch event
	void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesBegin(JNIEnv*  env, jobject thiz, jint id, jfloat x, jfloat y)
	{
		CCRect rcRect = CCEGLView::sharedOpenGLView().getViewPort();
		float fScreenScaleFactor = CCEGLView::sharedOpenGLView().getScreenScaleFactor();
		CCSet set;

		CCTouch *pTouch = s_pTouches[id];
		if (! pTouch)
		{
			LOGD("Beginning touches with id: %d, x=%f, y=%f", id, x, y);

			pTouch = new CCTouch();
			pTouch->SetTouchInfo((x - rcRect.origin.x) / fScreenScaleFactor, (y - rcRect.origin.y) / fScreenScaleFactor);
			s_pTouches[id] = pTouch;
			set.addObject(pTouch);

			cocos2d::CCDirector::sharedDirector()->getOpenGLView()->getDelegate()->touchesBegan(&set, NULL);
		}
		else
		{
			LOGD("Beginnig touches with id: %d error", id);
		}
	}

	void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesEnd(JNIEnv*  env, jobject thiz, jint id, jfloat x, jfloat y)
	{
		CCRect rcRect = CCEGLView::sharedOpenGLView().getViewPort();
		float fScreenScaleFactor = CCEGLView::sharedOpenGLView().getScreenScaleFactor();
		CCSet set;

		/* Add to the set to send to the director */
		CCTouch* pTouch = s_pTouches[id];
		if (pTouch)
		{
			LOGD("Ending touches with id: %d, x=%f, y=%f", id, x, y);

			pTouch->SetTouchInfo((x - rcRect.origin.x) / fScreenScaleFactor , (y - rcRect.origin.y) / fScreenScaleFactor);
		    set.addObject(pTouch);

			// release the object
			pTouch->release();
			s_pTouches[id] = NULL;

			cocos2d::CCDirector::sharedDirector()->getOpenGLView()->getDelegate()->touchesEnded(&set, NULL);
		} else {
			LOGD("Ending touches with id: %d error", id);
		}
	}

	void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesMove(JNIEnv*  env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys)
	{
		int size = env->GetArrayLength(ids);
		jint id[size];
		jfloat x[size];
		jfloat y[size];
		CCRect rcRect = CCEGLView::sharedOpenGLView().getViewPort();
		float fScreenScaleFactor = CCEGLView::sharedOpenGLView().getScreenScaleFactor();
		CCSet set;

		env->GetIntArrayRegion(ids, 0, size, id);
		env->GetFloatArrayRegion(xs, 0, size, x);
		env->GetFloatArrayRegion(ys, 0, size, y);

		for( int i = 0 ; i < size ; i++ ) {
			LOGD("Moving touches with id: %d, x=%f, y=%f", id[i], x[i], y[i]);
			cocos2d::CCTouch* pTouch = s_pTouches[id[i]];
			if (pTouch)
			{
				pTouch->SetTouchInfo((x[i] - rcRect.origin.x) / fScreenScaleFactor ,
			                        (y[i] - rcRect.origin.y) / fScreenScaleFactor);
				set.addObject(pTouch);
			}
			else
			{
				// It is error, should return.
				LOGD("Moving touches with id: %d error", id[i]);
				return;
			}
		}

		cocos2d::CCDirector::sharedDirector()->getOpenGLView()->getDelegate()->touchesMoved(&set, NULL);
	}

	void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesCancel(JNIEnv*  env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys)
	{
		int size = env->GetArrayLength(ids);
		jint id[size];
		jfloat x[size];
		jfloat y[size];
		CCRect rcRect = CCEGLView::sharedOpenGLView().getViewPort();
		float fScreenScaleFactor = CCEGLView::sharedOpenGLView().getScreenScaleFactor();
		CCSet set;

		env->GetIntArrayRegion(ids, 0, size, id);
		env->GetFloatArrayRegion(xs, 0, size, x);
		env->GetFloatArrayRegion(ys, 0, size, y);

		for( int i = 0 ; i < size ; i++ ) {
			cocos2d::CCTouch* pTouch = s_pTouches[id[i]];
			if (pTouch)
			{
				pTouch->SetTouchInfo((x[i] - rcRect.origin.x) / fScreenScaleFactor ,
			                        (y[i] - rcRect.origin.y) / fScreenScaleFactor);
				set.addObject(pTouch);
				s_pTouches[id[i]] = NULL;
				pTouch->release();
			}
		}

		cocos2d::CCDirector::sharedDirector()->getOpenGLView()->getDelegate()->touchesCancelled(&set, NULL);
	}

#define KEYCODE_BACK 0x04
#define KEYCODE_MENU 0x52

	// handle keydown event

	jboolean Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeKeyDown(JNIEnv*  env, jobject thiz, jint keyCode)
	{
		switch (keyCode)
		{
		case KEYCODE_BACK:
			if (CCKeypadDispatcher::sharedDispatcher()->dispatchKeypadMSG(kTypeBackClicked))
				return JNI_TRUE;
			break;
		case KEYCODE_MENU:
			if (CCKeypadDispatcher::sharedDispatcher()->dispatchKeypadMSG(kTypeMenuClicked))
				return JNI_TRUE;
			break;
		default:
			return JNI_FALSE;
		}
		return JNI_FALSE;
	}
}


code:
/****************************************************************************
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 "CCAccelerometer_bada.h"
#include "ccMacros.h"
#include "CCEGLView_bada.h"

using namespace Osp::Ui;
using namespace Osp::Uix;

NS_CC_BEGIN;

CCAccelerometer::CCAccelerometer()
: m_pAccelDelegate(NULL)
, m_pSensor(NULL)
, m_bEnabled(false)
{

}

CCAccelerometer::~CCAccelerometer()
{
	CC_SAFE_DELETE(m_pSensor);
}

CCAccelerometer* CCAccelerometer::sharedAccelerometer()
{
	static CCAccelerometer s_CCAccelerometer;
	return &s_CCAccelerometer;
}

void CCAccelerometer::setDelegate(CCAccelerometerDelegate* pDelegate)
{
	m_pAccelDelegate = pDelegate;
	if (pDelegate != NULL)
	{
		setEnable(true);
	}
	else
	{
		setEnable(false);
	}
}

void CCAccelerometer::OnDataReceived(SensorType sensorType, SensorData& sensorData, result r)
{
	long timeStamp = 0;
	float x = 0.0, y = 0.0, z = 0.0;

	sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_TIMESTAMP, timeStamp);
	sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_X, x);
	sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_Y, y);
	sensorData.GetValue((SensorDataKey)ACCELERATION_DATA_KEY_Z, z);

	/*
	 * Because the axes are not swapped when the device's screen orientation changes.
	 * So we should swap it here.
	 */
	Orientation orientation = CCEGLView::sharedOpenGLView().GetOrientation();
	if (orientation == ORIENTATION_LANDSCAPE || orientation == ORIENTATION_LANDSCAPE_REVERSE)
	{
		float tmp = x;
		x = -y;
		y = tmp;
	}

	CCAcceleration AccValue;
	AccValue.x = -x;
	AccValue.y = -y;
	AccValue.z = -z;
	AccValue.timestamp = timeStamp;

	if (m_pAccelDelegate != NULL)
	{
		m_pAccelDelegate->didAccelerate(&AccValue);
	}
	//AppLog("##TimeStamp:[%d], Accel.x,y,z:[%f,%f,%f]", timeStamp, x, y, z);
}

void CCAccelerometer::setEnable(bool bEnable)
{
	result	r = E_INVALID_STATE;
	if (m_bEnabled == bEnable)
	{
		return;
	}

	m_bEnabled = bEnable;

	if (m_bEnabled)
	{
		bool available = false;
		long interval = 50;

		CC_SAFE_DELETE(m_pSensor);
		m_pSensor = new SensorManager();
		m_pSensor->Construct();

		available = m_pSensor->IsAvailable(SENSOR_TYPE_ACCELERATION);
		if (available)
		{
			long intervalTemp = 0;
			m_pSensor->GetMaxInterval(SENSOR_TYPE_ACCELERATION, intervalTemp);
			if (interval > intervalTemp)
			{
				interval = intervalTemp;
			}
			m_pSensor->GetMinInterval(SENSOR_TYPE_ACCELERATION, intervalTemp);
			if (interval < intervalTemp)
			{
				interval = intervalTemp;
			}
			r = m_pSensor->AddSensorListener(*this, SENSOR_TYPE_ACCELERATION, interval, true);
		}
		else
		{
			CCLOG("Accelerometer Sensor unavailable!");
			delete m_pSensor;
			m_pSensor = NULL;
		}
	}
	else
	{
		if (m_pSensor != NULL)
		{
			r = m_pSensor->RemoveSensorListener(*this);
			delete m_pSensor;
			m_pSensor = NULL;
		}
	}
}

NS_CC_END;


code:
/****************************************************************************
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.
****************************************************************************/

#ifndef __PLATFORM_BADA_ACCELEROMETER_H__
#define __PLATFORM_BADA_ACCELEROMETER_H__

#include "CCAccelerometerDelegate.h"
#include "CCCommon.h"

#include <FUixSensorManager.h>
#include <FUixSensorTypes.h>
#include <FUixSensorData.h>

namespace   cocos2d {

class CC_DLL CCAccelerometer :
	public Osp::Uix::ISensorEventListener
{
public:
    CCAccelerometer();
    ~CCAccelerometer();
    static CCAccelerometer* sharedAccelerometer();

    void setDelegate(CCAccelerometerDelegate* pDelegate);
    virtual void OnDataReceived(Osp::Uix::SensorType sensorType, Osp::Uix::SensorData& sensorData , result r);
private:
    void setEnable(bool bEnable);

	CCAccelerometerDelegate* m_pAccelDelegate;
	Osp::Uix::SensorManager* m_pSensor;
	bool m_bEnabled;
};

}//namespace   cocos2d

#endif


code:
/****************************************************************************
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 "CCApplication_bada.h"
#include "CCDirector.h"

using namespace Osp::App;
using namespace Osp::System;
using namespace Osp::Base;
using namespace Osp::Base::Runtime;
using namespace Osp::Locales;

NS_CC_BEGIN;

static CCApplication * s_pApplication = NULL;
static long long s_nAnimationInterval = 1000/60;

CCApplication::CCApplication() :
		m_pTimer(null)
{
	s_pApplication = this;
}

CCApplication::~CCApplication()
{
	s_pApplication = NULL;
}

CCApplication::Orientation CCApplication::setOrientation(CCApplication::Orientation orientation)
{
    return orientation;
}

CCRect CCApplication::statusBarFrame(CCRect * rect)
{
    if (rect)
    {
        // bada doesn't have status bar.
        *rect = CCRectMake(0, 0, 0, 0);
    }
    return *rect;
}

//////////////////////////////////////////////////////////////////////////
/// Implement static class member
//////////////////////////////////////////////////////////////////////////
CCApplication& CCApplication::sharedApplication()
{
    CC_ASSERT(s_pApplication);
    return *s_pApplication;
}

ccLanguageType CCApplication::getCurrentLanguage()
{
	ccLanguageType ret = kLanguageEnglish;
	result r = E_SUCCESS;
	String value;
	r = SettingInfo::GetValue(L"Language", value);
	if (value.Equals("ZHO", false))
	{
		ret = kLanguageChinese;
	}
	else if (value.Equals("FRA", false))
	{
		ret = kLanguageFrench;
	}
	else if (value.Equals("ITA", false))
	{
		ret = kLanguageItalian;
	}
	else if (value.Equals("DEU", false))
	{
		ret = kLanguageGerman;
	}
	else if (value.Equals("SPA", false))
	{
		ret = kLanguageSpanish;
	}
	else if (value.Equals("RUS", false))
	{
		ret = kLanguageRussian;
	}

	return ret;
}

void CCApplication::setAnimationInterval(double interval)
{
    s_nAnimationInterval = (long long)(interval * 1000.0f);
}

bool CCApplication::OnAppInitializing(AppRegistry& appRegistry)
{
	result r = E_FAILURE;
	if (! initInstance() || !applicationDidFinishLaunching())
		return false;

	CCEGLView::sharedOpenGLView().AddKeyEventListener(*this);

	m_pTimer = new Timer;
	if (null == m_pTimer)
	{
		return E_FAILURE;
	}

	r = m_pTimer->Construct(*this);
	if (IsFailed(r))
	{
		delete m_pTimer;
		m_pTimer = null;
		return E_FAILURE;
	}

	return true;
}

bool CCApplication::OnAppTerminating(AppRegistry& appRegistry, bool forcedTermination)
{
	if (m_pTimer)
	{
		m_pTimer->Cancel();
		delete m_pTimer;
		m_pTimer = null;
	}
	return true;
}

void CCApplication::OnForeground(void)
{
	if (m_pTimer)
		m_pTimer->Start(s_nAnimationInterval);
    applicationWillEnterForeground();
}

void CCApplication::OnBackground(void)
{
	if (m_pTimer)
		m_pTimer->Cancel();
	applicationDidEnterBackground();
}

void CCApplication::OnLowMemory(void)
{
}

void CCApplication::OnBatteryLevelChanged(BatteryLevel batteryLevel)
{
}

void CCApplication::OnTimerExpired(Timer& timer)
{
	m_pTimer->Start(s_nAnimationInterval);
	CCDirector::sharedDirector()->mainLoop();
}

NS_CC_END;


code:
/****************************************************************************
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.
****************************************************************************/

#ifndef __CC_APPLICATION_BADA_H__
#define __CC_APPLICATION_BADA_H__

#include "CCGeometry.h"
#include "CCDirector.h"

#include <FApp.h>
#include <FSystem.h>

NS_CC_BEGIN;

class CC_DLL CCApplication
	: public Osp::App::Application
	, public Osp::Base::Runtime::ITimerEventListener
    , public Osp::Ui::IKeyEventListener
{
public:
    CCApplication();
    virtual ~CCApplication();
    /**
    @brief	Implement for initialize OpenGL instance, set source path, etc...
    */
    virtual bool initInstance() = 0;
    /**
    @brief	Implement Window create, CCDirector and CCScene init code here.
    @return true    Initialize success, app continue.
    @return false   Initialize failed, app terminate.
    */
    virtual bool applicationDidFinishLaunching() = 0;

    /**
    @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() {}

    /**
    @brief	Get status bar rectangle in EGLView window.
    */
    CCRect statusBarFrame(CCRect * rect);

    /**
    @brief	Get current applicaiton instance.
    @return Current application instance pointer.
    */
    static CCApplication& sharedApplication();

    /**
    @brief Get current language config
    @return Current language config
    */
    static ccLanguageType getCurrentLanguage();

    void setAnimationInterval(double interval);

    typedef enum
    {
        /// Device oriented vertically, home button on the bottom
        kOrientationPortrait = 0,
        /// Device oriented vertically, home button on the top
        kOrientationPortraitUpsideDown = 1,
        /// Device oriented horizontally, home button on the right
        kOrientationLandscapeLeft = 2,
        /// Device oriented horizontally, home button on the left
        kOrientationLandscapeRight = 3,
    } Orientation;

    /**
    @brief	Callback by CCDirector for change device orientation.
    @orientation    The defination of orientation which CCDirector want change to.
    @return         The actual orientation of the application.
    */
    Orientation setOrientation(Orientation orientation);
//
public:
    virtual bool OnAppInitializing(Osp::App::AppRegistry& appRegistry);
    virtual bool OnAppTerminating(Osp::App::AppRegistry& appRegistry, bool forcedTermination = false);
    virtual void OnForeground(void);
    virtual void OnBackground(void);
	virtual void OnKeyPressed(const Osp::Ui::Control& source, Osp::Ui::KeyCode keyCode){}
	virtual void OnKeyReleased(const Osp::Ui::Control& source, Osp::Ui::KeyCode keyCode){}
	virtual void OnKeyLongPressed(const Osp::Ui::Control& source, Osp::Ui::KeyCode keyCode){}
	virtual void OnLowMemory(void);
	virtual void OnBatteryLevelChanged(Osp::System::BatteryLevel batteryLevel);
	virtual void OnTimerExpired(Osp::Base::Runtime::Timer& timer);
protected:
	Osp::Base::Runtime::Timer* m_pTimer;
};

NS_CC_END;

#endif	// end of __CCX_APPLICATION_WIN32_H__


code:
/****************************************************************************
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 "CCEGLView.h"
#include "CCSet.h"
#include "CCDirector.h"
#include "CCTouch.h"
#include "CCTouchDispatcher.h"
#include "CCAccelerometer_bada.h"
#include "CCIMEDispatcher.h"
#include <FText.h>
#include <string>

using namespace std;
using namespace Osp::Base;
using namespace Osp::Base::Runtime;
using namespace Osp::Base::Collection;
using namespace Osp::Text;
using namespace Osp::System;
using namespace Osp::App;
using namespace Osp::Ui;
using namespace Osp::Ui::Controls;
using namespace Osp::Graphics;

NS_CC_BEGIN;

static CCEGLView * s_pMainWindow;
static HashMapT<int, CCTouch*> s_mapTouches; // key: pointer id; value: CCTouch*
//////////////////////////////////////////////////////////////////////////
// impliment CCEGL
//////////////////////////////////////////////////////////////////////////
class CCEGL
{
public:
	~CCEGL()
	{
		if (EGL_NO_SURFACE != m_eglSurface)
		{
			eglDestroySurface(m_eglDisplay, m_eglSurface);
		}
		if (EGL_NO_CONTEXT != m_eglContext)
		{
			eglDestroyContext(m_eglDisplay, m_eglContext);
		}
		eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
		eglTerminate(m_eglDisplay);
	}

	static CCEGL * create(CCEGLView * pWindow)
	{
		CCEGL * pEGL = new CCEGL;
		bool bSuccess = false;
		do
		{
			CC_BREAK_IF(! pEGL);

			pEGL->m_eglNativeWindow = pWindow;

			EGLDisplay eglDisplay;
			CC_BREAK_IF(EGL_NO_DISPLAY == (eglDisplay = eglGetDisplay(pEGL->m_eglNativeDisplay)));

			EGLint nMajor, nMinor;
			CC_BREAK_IF(EGL_FALSE == eglInitialize(eglDisplay, &nMajor, &nMinor) || 1 != nMajor);

			EGLint aConfigAttribs[] = {
				EGL_RED_SIZE,	5,
				EGL_GREEN_SIZE,	6,
				EGL_BLUE_SIZE,	5,
				EGL_ALPHA_SIZE,	0,
				EGL_DEPTH_SIZE, 8,
				EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
				EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT,
				EGL_NONE
			};
			eglBindAPI(EGL_OPENGL_ES_API);
			///

			EGLint iConfigs;
			EGLConfig eglConfig;
			CC_BREAK_IF(EGL_FALSE == eglChooseConfig(eglDisplay, aConfigAttribs, &eglConfig, 1, &iConfigs)
				|| (iConfigs != 1));

			EGLContext eglContext;
			eglContext = eglCreateContext(eglDisplay, eglConfig, NULL, NULL);
			CC_BREAK_IF(EGL_NO_CONTEXT == eglContext);

			EGLSurface eglSurface;
			eglSurface = eglCreateWindowSurface(eglDisplay, eglConfig, pEGL->m_eglNativeWindow, NULL);
			CC_BREAK_IF(EGL_NO_SURFACE == eglSurface);

			CC_BREAK_IF(EGL_FALSE == eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext));

			pEGL->m_eglDisplay = eglDisplay;
			pEGL->m_eglConfig  = eglConfig;
			pEGL->m_eglContext = eglContext;
			pEGL->m_eglSurface = eglSurface;
			bSuccess = true;

		} while (0);

		if (! bSuccess)
		{
			CC_SAFE_DELETE(pEGL);
		}

		return pEGL;
	}

	void resizeSurface()
	{
//  		if (! m_eglNativeWindow || EGL_NO_DISPLAY == m_eglDisplay)
//  		{
//  			return;
//  		}
//
//  		// release old surface
//  		if (EGL_NO_SURFACE != m_eglSurface)
//  		{
//  			eglDestroySurface(m_eglDisplay, m_eglSurface);
//  			m_eglSurface = EGL_NO_SURFACE;
//  		}
//
//  		// create new surface and make current
//  		m_eglSurface = eglCreateWindowSurface(m_eglDisplay, m_eglConfig, m_eglNativeWindow, NULL);
//  		eglMakeCurrent(m_eglDisplay, m_eglSurface, m_eglSurface, m_eglContext);
	}

	void swapBuffers()
	{
		if (EGL_NO_DISPLAY != m_eglDisplay)
		{
			eglSwapBuffers(m_eglDisplay, m_eglSurface);
		}
	}
private:
	CCEGL()
		: m_eglNativeWindow(NULL)
		, m_eglNativeDisplay(EGL_DEFAULT_DISPLAY)
		, m_eglDisplay(EGL_NO_DISPLAY)
		, m_eglConfig(0)
		, m_eglSurface(EGL_NO_SURFACE)
		, m_eglContext(EGL_NO_CONTEXT)
	{}

	EGLNativeWindowType     m_eglNativeWindow;
	EGLNativeDisplayType    m_eglNativeDisplay;
	EGLDisplay              m_eglDisplay;
	EGLConfig               m_eglConfig;
	EGLSurface              m_eglSurface;
	EGLContext              m_eglContext;
};

//////////////////////////////////////////////////////////////////////////
// impliment CCEGLView
//////////////////////////////////////////////////////////////////////////
#ifdef CC_BADA_2_0
PFNGLGENERATEMIPMAPOESPROC         CCEGLView::glGenerateMipmapOES = 0;
PFNGLGENFRAMEBUFFERSOESPROC        CCEGLView::glGenFramebuffersOES = 0;
PFNGLBINDFRAMEBUFFEROESPROC		   CCEGLView::glBindFramebufferOES = 0;
PFNGLFRAMEBUFFERTEXTURE2DOESPROC   CCEGLView::glFramebufferTexture2DOES = 0;
PFNGLDELETEFRAMEBUFFERSOESPROC     CCEGLView::glDeleteFramebuffersOES = 0;
PFNGLCHECKFRAMEBUFFERSTATUSOESPROC CCEGLView::glCheckFramebufferStatusOES = 0;
#endif
CCEGLView::CCEGLView()
: m_pKeypad(null)
, m_bNotHVGA(true)
, m_pDelegate(NULL)
, m_fScreenScaleFactor(1.0)
, m_bCaptured(false)
, m_pEGL(NULL)
{
#ifdef CC_BADA_2_0
	glGenerateMipmapOES = (PFNGLGENERATEMIPMAPOESPROC)eglGetProcAddress("glGenerateMipmapOES");
	glGenFramebuffersOES = (PFNGLGENFRAMEBUFFERSOESPROC)eglGetProcAddress("glGenFramebuffersOES");
	glBindFramebufferOES = (PFNGLBINDFRAMEBUFFEROESPROC)eglGetProcAddress("glBindFramebufferOES");
	glFramebufferTexture2DOES = (PFNGLFRAMEBUFFERTEXTURE2DOESPROC)eglGetProcAddress("glFramebufferTexture2DOES");
	glDeleteFramebuffersOES = (PFNGLDELETEFRAMEBUFFERSOESPROC)eglGetProcAddress("glDeleteFramebuffersOES");
	glCheckFramebufferStatusOES = (PFNGLCHECKFRAMEBUFFERSTATUSOESPROC)eglGetProcAddress("glCheckFramebufferStatusOES");
#endif
    m_pTouch    = new CCTouch;
    m_pSet      = new CCSet;
	m_eInitOrientation = CCDirector::sharedDirector()->getDeviceOrientation();
	s_mapTouches.Construct();
}

CCEGLView::~CCEGLView()
{
	release();
    CC_SAFE_DELETE(m_pSet);
    CC_SAFE_DELETE(m_pTouch);
    CC_SAFE_DELETE(m_pDelegate);
	CC_SAFE_DELETE(m_pEGL);
	CC_SAFE_DELETE(m_pKeypad);
}

CCSize CCEGLView::getSize()
{
	CCSize s;
//	if (m_bNotHVGA)
	{
		s = CCSizeMake(m_sSizeInPoint.width, m_sSizeInPoint.height);
	}
//	else
//	{
//		s = CCSizeMake(m_sSizeInPixel.width, m_sSizeInPixel.height);
//	}
	return s;
}

CCRect CCEGLView::getFrame()
{
	CCRect rc;
//	if (m_bNotHVGA)
//	{
//		rc = CCRectMake(0, 0, m_sSizeInPixel.width, m_sSizeInPixel.height);
//	}
//	else
	{
		rc = CCRectMake(0, 0, m_sSizeInPoint.width, m_sSizeInPoint.height);
	}
	return rc;
}

bool CCEGLView::isIpad()
{
    return false;
}

bool CCEGLView::isOpenGLReady()
{
    return (NULL != m_pEGL);
}

void CCEGLView::release()
{
	Application::GetInstance()->Terminate();
}

void CCEGLView::setTouchDelegate(EGLTouchDelegate * pDelegate)
{
    m_pDelegate = pDelegate;
}

void CCEGLView::swapBuffers()
{
    if (m_pEGL)
    {
        m_pEGL->swapBuffers();
    }
}

bool CCEGLView::canSetContentScaleFactor()
{
    // can scale content?
    return false;
}

void CCEGLView::setContentScaleFactor(float contentScaleFactor)
{
	m_fScreenScaleFactor = contentScaleFactor;
}

int CCEGLView::setDeviceOrientation(Orientation eOritation)
{
	SetOrientation(eOritation);

	if (eOritation == ORIENTATION_PORTRAIT || eOritation == ORIENTATION_PORTRAIT_REVERSE)
	{
		int width = MIN(m_sSizeInPixel.width, m_sSizeInPixel.height);
		m_sSizeInPixel.height = MAX(m_sSizeInPixel.width, m_sSizeInPixel.height);
		m_sSizeInPixel.width = width;
		width = MIN(m_sSizeInPoint.width, m_sSizeInPoint.height);
		m_sSizeInPoint.height = MAX(m_sSizeInPoint.width, m_sSizeInPoint.height);
		m_sSizeInPoint.width = width;
		resize(m_sSizeInPoint.width, m_sSizeInPoint.height);
	}
	else
	{
		int width = MAX(m_sSizeInPixel.width, m_sSizeInPixel.height);
		m_sSizeInPixel.height = MIN(m_sSizeInPixel.width, m_sSizeInPixel.height);
		m_sSizeInPixel.width = width;
		width = MAX(m_sSizeInPoint.width, m_sSizeInPoint.height);
		m_sSizeInPoint.height = MIN(m_sSizeInPoint.width, m_sSizeInPoint.height);
		m_sSizeInPoint.width = width;
		resize(m_sSizeInPoint.width, m_sSizeInPoint.height);
	}

	return m_eInitOrientation;
}

void CCEGLView::setViewPortInPoints(float x, float y, float w, float h)
{
	float factor = m_fScreenScaleFactor / CC_CONTENT_SCALE_FACTOR();
	glViewport((GLint)(x * factor) + m_rcViewPort.origin.x,
		(GLint)(y * factor) + m_rcViewPort.origin.y,
		(GLint)(w * factor),
		(GLint)(h * factor));
}

void CCEGLView::setScissorInPoints(float x, float y, float w, float h)
{
	float factor = m_fScreenScaleFactor / CC_CONTENT_SCALE_FACTOR();
	glScissor((GLint)(x * factor) + m_rcViewPort.origin.x,
		(GLint)(y * factor) + m_rcViewPort.origin.y,
		(GLint)(w * factor),
		(GLint)(h * factor));
}

void CCEGLView::setIMEKeyboardState(bool bOpen)
{
	if (bOpen)
	{
		const char * pszText = CCIMEDispatcher::sharedDispatcher()->getContentText();
		m_pKeypad->SetText(pszText);
	    m_pKeypad->SetShowState(bOpen);
	    m_pKeypad->Show();
	}
}

bool CCEGLView::Create(Osp::App::Application* pApp, int width, int height)
{
	m_sSizeInPoint.width = MIN(width, height);
	m_sSizeInPoint.height = MAX(width, height);
	Construct(FORM_STYLE_NORMAL);
	Frame *pFrame = Application::GetInstance()->GetAppFrame()->GetFrame();

	pFrame->AddControl(*this);
	pFrame->SetCurrentForm(*this);

	m_pEGL = CCEGL::create(this);
	if (m_pEGL == null)
		return false;
	s_pMainWindow = this;
	Draw();
	Show();
	return true;
}

void CCEGLView::resize(int width, int height)
{
	int viewPortW = (int)ceil(width * m_fScreenScaleFactor);
	int viewPortH = (int)ceil(height * m_fScreenScaleFactor);
	m_rcViewPort.origin.x = (m_sSizeInPixel.width - viewPortW) / 2;
	m_rcViewPort.origin.y = (m_sSizeInPixel.height - viewPortH) / 2;
	m_rcViewPort.size.width = viewPortW;
	m_rcViewPort.size.height = viewPortH;
	CCLOG("m_rcViewPort.origin.x = %f, y = %f, width = %f, height = %f", \
			m_rcViewPort.origin.x, m_rcViewPort.origin.y, m_rcViewPort.size.width, m_rcViewPort.size.height);
}

result CCEGLView::OnInitializing(void)
{
	result r = E_SUCCESS;

	AddTouchEventListener(*this);
	Touch touch;
	touch.SetMultipointEnabled(*this, true);

    m_pKeypad = new Keypad();
    m_pKeypad->Construct(KEYPAD_STYLE_NORMAL, KEYPAD_MODE_ALPHA);
    m_pKeypad->AddTextEventListener(*this);

	Rectangle rc = GetBounds();
	if ((rc.width == 480 && rc.height == 720)
			|| (rc.width == 720 && rc.height == 480))
	{
		m_bNotHVGA = false;
		m_sSizeInPixel.width = rc.width / 1.5f;
		m_sSizeInPixel.height = rc.height / 1.5f;
	}
	else
	{
		m_bNotHVGA = true;
		m_sSizeInPixel.width = rc.width;
		m_sSizeInPixel.height = rc.height;
	}

	// calculate the factor and the rect of viewport
	m_fScreenScaleFactor =  MIN((float)m_sSizeInPixel.width / m_sSizeInPoint.width,
		                         (float)m_sSizeInPixel.height / m_sSizeInPoint.height);
	CCLOG("rc.width = %d, rc.height = %d, m_fScreenScaleFactor = %f", rc.width, rc.height, m_fScreenScaleFactor);
	resize(m_sSizeInPoint.width, m_sSizeInPoint.height);

	return r;
}

result CCEGLView::OnTerminating(void)
{
	result r = E_SUCCESS;

	// TODO: Add your termination code here

	return r;
}

void CCEGLView::onTouchesBegin(int id[], float x[], float y[], int pointerNumber)
{
	result r = E_SUCCESS;
	CCSet set;
	for(int i = 0 ; i < pointerNumber ; i++ ) {
		CCTouch *pTouch = NULL;
		r = s_mapTouches.GetValue(id[i], pTouch);
		if (E_OBJ_NOT_FOUND == r && NULL == pTouch)
		{
			pTouch = new CCTouch();
			pTouch->SetTouchInfo((x[i] - m_rcViewPort.origin.x) / m_fScreenScaleFactor,
					             (y[i] - m_rcViewPort.origin.y) / m_fScreenScaleFactor);
			s_mapTouches.Add(id[i], pTouch);
			set.addObject(pTouch);
			m_pDelegate->touchesBegan(&set, NULL);
		}
		else
		{
			CCLOG("Beginnig touches with id: %d error", id[i]);
		}
	}
}

void CCEGLView::onTouchesMove(int id[], float x[], float y[], int pointerNumber)
{
	result r = E_SUCCESS;
	CCSet set;
	for(int i = 0 ; i < pointerNumber ; i++ ) {
		CCLOG("Moving touches with id: %d, x=%f, y=%f", id[i], x[i], y[i]);
		CCTouch *pTouch = NULL;
		r = s_mapTouches.GetValue(id[i], pTouch);

		if (E_SUCCESS == r && pTouch != NULL)
		{
			pTouch->SetTouchInfo((x[i] - m_rcViewPort.origin.x) / m_fScreenScaleFactor,
								(y[i] - m_rcViewPort.origin.y) / m_fScreenScaleFactor);
			set.addObject(pTouch);
		}
		else
		{
			// It is error, should return.
			CCLOG("Moving touches with id: %d error", id[i]);
			return;
		}
	}

	m_pDelegate->touchesMoved(&set, NULL);
}

void CCEGLView::onTouchesEnd(int id[], float x[], float y[], int pointerNumber)
{
	result r = E_SUCCESS;
	CCSet set;
	for(int i = 0 ; i < pointerNumber ; i++ ) {
		CCTouch *pTouch = NULL;
		r = s_mapTouches.GetValue(id[i], pTouch);
		if (E_SUCCESS == r && pTouch != NULL)
		{
			pTouch->SetTouchInfo((x[i] - m_rcViewPort.origin.x) / m_fScreenScaleFactor,
		                        (y[i] - m_rcViewPort.origin.y) / m_fScreenScaleFactor);
			set.addObject(pTouch);
			s_mapTouches.Remove(id[i]);
			pTouch->release();
			CCLOG("Ending touches with id: %d, x=%f, y=%f, retain count = %d", id[i], x[i], y[i], pTouch->retainCount());
		}
	}

	m_pDelegate->touchesEnded(&set, NULL);
}

void CCEGLView::onTouchEvent(const Control& source, TouchStatus status)
{
	IList *pList = null;
    do
    {
        CC_BREAK_IF(!m_pDelegate);
        int i = 0;
    	Touch touch;
    	pList = touch.GetTouchInfoListN(source);

    	CC_BREAK_IF(pList == NULL);

       	int pointerNumber = pList->GetCount();

        CC_BREAK_IF(pointerNumber <= 0);

    	int id[30] = {0};
    	float x[30] = {0};
    	float y[30] = {0};

    	for (i = 0; i < pointerNumber; i++) {
    		TouchInfo *pTouchInfo = static_cast<TouchInfo *>(pList->GetAt(i));
            id[i] = (int)pTouchInfo->id;
            float tmpX = (float)pTouchInfo->position.x;
            float tmpY = (float)pTouchInfo->position.y;
        	if (!m_bNotHVGA)
        	{
        		x[i] = tmpX * 2 / 3;
        		y[i] = tmpY * 2 / 3;
        	}
        	else
        	{
				x[i] = tmpX;
				y[i] = tmpY;
        	}
        }
    	if (TOUCH_PRESSED == status)
    	{
    		onTouchesBegin(id, x, y, pointerNumber);
    	}
    	else if (TOUCH_MOVED == status)
    	{
    		onTouchesMove(id, x, y, pointerNumber);
    	}
    	else if (TOUCH_RELEASED == status)
    	{
    		onTouchesEnd(id, x, y, pointerNumber);
    	}

    } while (0);

    if (pList != null)
    {
   		pList->RemoveAll(true);
    	delete pList;
    }
}

// touch event
void CCEGLView::OnTouchIndicated(const Control& source,
	const Point& startPosition, const Point& currentPoint)
{

}

void CCEGLView::OnTouchPressed(const Control& source,
	const Point& currentPosition, const TouchEventInfo & touchInfo)
{
	int id = (int)touchInfo.GetPointId();
    float x = (float)touchInfo.GetCurrentPosition().x;
    float y = (float)touchInfo.GetCurrentPosition().y;
    CCLOG("OnTouchPressed id = %d,x = %f,y = %f, count = %d", id, x, y, s_mapTouches.GetCount());
	if (!m_bNotHVGA)
	{
		x = x * 2 / 3;
		y = y * 2 / 3;
	}

	onTouchesBegin(&id, &x, &y, 1);
}

void CCEGLView::OnTouchLongPressed(const Control& source,
	const Point& currentPosition, const TouchEventInfo & touchInfo)
{

}

void CCEGLView::OnTouchReleased(const Control& source,
	const Point& currentPosition, const TouchEventInfo & touchInfo)
{
	int id = (int)touchInfo.GetPointId();
    float x = (float)touchInfo.GetCurrentPosition().x;
    float y = (float)touchInfo.GetCurrentPosition().y;
	if (!m_bNotHVGA)
	{
		x = x * 2 / 3;
		y = y * 2 / 3;
	}

	onTouchesEnd(&id, &x, &y, 1);
	CCLOG("OnTouchReleased id = %d,x = %f,y = %f", id, x, y);
}

void CCEGLView::OnTouchMoved(const Control& source,
	const Point& currentPosition, const TouchEventInfo & touchInfo)
{
	onTouchEvent(source, TOUCH_MOVED);
}

void CCEGLView::OnTouchDoublePressed(const Control& source,
	const Point& currentPosition, const TouchEventInfo & touchInfo)
{
	CCLOG("double pressed..");
	OnTouchPressed(source, currentPosition, touchInfo);
}

void CCEGLView::OnTouchFocusIn(const Control& source,
	const Point& currentPosition, const TouchEventInfo & touchInfo)
{

}

void CCEGLView::OnTouchFocusOut(const Control& source,
	const Point& currentPosition, const TouchEventInfo & touchInfo)
{

}

result CCEGLView::OnDraw(void)
{
	result r = E_SUCCESS;
	CCDirector * pDirector = CCDirector::sharedDirector();
	pDirector->drawScene();
	return r;
}

// Implement an ITextEventListener
void CCEGLView::OnTextValueChanged(const Control& source)
{
	// clear textinput text
	std::string strOldText = CCIMEDispatcher::sharedDispatcher()->getContentText();

	for (int i = 0; i < strOldText.length(); i++)
	{
		CCIMEDispatcher::sharedDispatcher()->dispatchDeleteBackward();
	}

	String str = m_pKeypad->GetText();
	if (str.GetLength() <= 0)
	{
		CCIMEDispatcher::sharedDispatcher()->dispatchInsertText("\n", 1);
	}
	else
	{
		Utf8Encoding utf8;
		ByteBuffer* pBuffer = utf8.GetBytesN(str);
		if (pBuffer != null)
		{
			const char* pszText = (const char*)pBuffer->GetPointer();
			if (pszText != NULL)
			{
				int len = strlen(pszText);
				if (pszText[len-1] != '\n')
				{
					std::string strText = pszText;
					strText.append("\n");
					CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(strText.c_str(), strText.length());
				}
			}
			delete pBuffer;
		}
	}
}

void CCEGLView::OnTextValueChangeCanceled(const Control& source)
{
	CCIMEDispatcher::sharedDispatcher()->dispatchInsertText("\n", 1);
}

CCEGLView& CCEGLView::sharedOpenGLView()
{
    CC_ASSERT(s_pMainWindow);
    return *s_pMainWindow;
}

NS_CC_END;


code:
/****************************************************************************
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.
****************************************************************************/

#ifndef __CCX_EGLVIEW_BADA_H__
#define __CCX_EGLVIEW_BADA_H__

#include <FApp.h>
#include <FBase.h>
#include <FUi.h>
#include <FSystem.h>
#include "CCGeometry.h"
#include <GLES/egl.h>
#include <GLES/gl.h>
#include <GLES/glext.h>

NS_CC_BEGIN;

class CCSet;
class CCTouch;
class EGLTouchDelegate;

class CCEGL;

class CC_DLL CCEGLView
	:public Osp::Ui::Controls::Form
	,public Osp::Ui::ITouchEventListener
	,public Osp::Ui::ITextEventListener
{
public:

    CCEGLView();
    virtual ~CCEGLView();

	CCRect  getFrame();
    CCSize  getSize();
    bool    isOpenGLReady();
    bool    isIpad();
    void    release();
    void    setTouchDelegate(EGLTouchDelegate * pDelegate);
    void    swapBuffers();
    bool    canSetContentScaleFactor();
    void    setContentScaleFactor(float contentScaleFactor);

	int setDeviceOrientation(Osp::Ui::Orientation eOritation);
    void setViewPortInPoints(float x, float y, float w, float h);
    void setScissorInPoints(float x, float y, float w, float h);

    void setIMEKeyboardState(bool bOpen);
	// static function
	/**
	@brief	get the shared main open gl window
	*/
	static CCEGLView& sharedOpenGLView();

	float getMainScreenScale() { return -1.0f; }

	/*
	 * param
	 *   width[in]: resource width
	 *   height[in]: resource height
	 */
	bool Create(Osp::App::Application* pApp, int width, int height);
	void resize(int width, int height);
	virtual result OnInitializing(void);
	virtual result OnTerminating(void);

	void onTouchesBegin(int id[], float x[], float y[], int pointerNumber);
	void onTouchesMove(int id[], float x[], float y[], int pointerNumber);
	void onTouchesEnd(int id[], float x[], float y[], int pointerNumber);
	void onTouchEvent(const Osp::Ui::Control& source, Osp::Ui::TouchStatus status);

	// touch event
	virtual void OnTouchIndicated(const Osp::Ui::Control& source,
		const Osp::Graphics::Point& startPosition, const Osp::Graphics::Point& currentPoint);

	virtual void OnTouchPressed(const Osp::Ui::Control& source,
		const Osp::Graphics::Point& currentPosition, const Osp::Ui::TouchEventInfo & touchInfo);

	virtual void OnTouchLongPressed(const Osp::Ui::Control& source,
		const Osp::Graphics::Point& currentPosition, const Osp::Ui::TouchEventInfo & touchInfo);

	virtual void OnTouchReleased(const Osp::Ui::Control& source,
		const Osp::Graphics::Point& currentPosition, const Osp::Ui::TouchEventInfo & touchInfo);

	virtual void OnTouchMoved(const Osp::Ui::Control& source,
		const Osp::Graphics::Point& currentPosition, const Osp::Ui::TouchEventInfo & touchInfo);

	virtual void OnTouchDoublePressed(const Osp::Ui::Control& source,
		const Osp::Graphics::Point& currentPosition, const Osp::Ui::TouchEventInfo & touchInfo);

	virtual void OnTouchFocusIn(const Osp::Ui::Control& source,
		const Osp::Graphics::Point& currentPosition, const Osp::Ui::TouchEventInfo & touchInfo);

	virtual void OnTouchFocusOut(const Osp::Ui::Control& source,
		const Osp::Graphics::Point& currentPosition, const Osp::Ui::TouchEventInfo & touchInfo);

	virtual result OnDraw(void);

    virtual void OnTextValueChanged(const Osp::Ui::Control& source);
	virtual void OnTextValueChangeCanceled(const Osp::Ui::Control& source);

#ifdef CC_BADA_2_0
	// pointer to OES methods from EGL
	static PFNGLGENERATEMIPMAPOESPROC         glGenerateMipmapOES;
	static PFNGLGENFRAMEBUFFERSOESPROC        glGenFramebuffersOES;
	static PFNGLBINDFRAMEBUFFEROESPROC		  glBindFramebufferOES;
	static PFNGLFRAMEBUFFERTEXTURE2DOESPROC   glFramebufferTexture2DOES;
	static PFNGLDELETEFRAMEBUFFERSOESPROC     glDeleteFramebuffersOES;
	static PFNGLCHECKFRAMEBUFFERSTATUSOESPROC glCheckFramebufferStatusOES;
#endif

private:
	Osp::Ui::Controls::Keypad *m_pKeypad;

	CCSize m_sSizeInPixel;
	CCSize m_sSizeInPoint;
	CCRect m_rcViewPort;
	bool   m_bNotHVGA;

	EGLTouchDelegate *m_pDelegate;
	float  m_fScreenScaleFactor;

    bool                m_bCaptured;

    CCSet *             m_pSet;
    CCTouch *           m_pTouch;
    CCEGL *            m_pEGL;

	int					m_eInitOrientation;

	Osp::Ui::Orientation  m_nowOrientation;
};

NS_CC_END;

#endif	// end of __CCX_EGLVIEW_WIN32_H__


code:
/****************************************************************************
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.
****************************************************************************/

// record the resource path

#include "CCCommon.h"

using namespace std;

NS_CC_BEGIN;
// record the resource path
static string s_strResourcePath = "";

void CCFileUtils::setResourcePath(const char* pszResourcePath)
{
	CCAssert(pszResourcePath != NULL, "[FileUtils setRelativePath] -- wrong relative path");
	s_strResourcePath = pszResourcePath;
}

const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath)
{
	int len = 0;
	if (pszRelativePath == NULL || (len = strlen(pszRelativePath)) <= 0)
		return NULL;
	CCString * pRet = new CCString();
    pRet->autorelease();
    if (len > 1 && pszRelativePath[0] == '/')
    {
        pRet->m_sString = pszRelativePath;
    }
    else
    {
        pRet->m_sString = s_strResourcePath;
        pRet->m_sString += pszRelativePath;
    }
	return pRet->m_sString.c_str();
}

const char *CCFileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile)
{
	std::string relativeFile = fullPathFromRelativePath(pszRelativeFile);
	CCString *pRet = new CCString();
	pRet->autorelease();
	pRet->m_sString = relativeFile.substr(0, relativeFile.rfind('/')+1);
	pRet->m_sString += pszFilename;
	return pRet->m_sString.c_str();
}

unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize)
{
	CC_ASSERT(pszFileName != NULL && pszMode != NULL);
    unsigned char * pData = 0;
    int len = 0;
    string fullPath;

    len = strlen(pszFileName);

    if (len > 1 && pszFileName[0] == '/')
    {
    	fullPath = pszFileName;
    }
    else
    {
    	fullPath = s_strResourcePath;
    	fullPath += pszFileName;
    }

    do
    {
        // read rrom other path than user set it
        FILE *fp = fopen(fullPath.c_str(), pszMode);
        CC_BREAK_IF(!fp);

        unsigned long size;
        fseek(fp,0,SEEK_END);
        size = ftell(fp);
        fseek(fp,0,SEEK_SET);
        pData = new unsigned char[size];
        size = fread(pData,sizeof(unsigned char), size,fp);
        fclose(fp);

        if (pSize)
        {
            *pSize = size;
        }
    } while (0);

    if (! pData && getIsPopupNotify())
    {
        std::string title = "Notification";
        std::string msg = "Get data from file(";
        msg.append(fullPath.c_str()).append(") failed!");
        CCMessageBox(msg.c_str(), title.c_str());
    }

    return pData;
}

void CCFileUtils::setResource(const char* pszZipFileName)
{
    CC_UNUSED_PARAM(pszZipFileName);
    CCAssert(0, "Have not implement!");;
}

int CCFileUtils::ccLoadFileIntoMemory(const char *filename, unsigned char **out)
{
    CCAssert(0, "Have not implement!");
    return 0;
}

string CCFileUtils::getWriteablePath()
{
	return "/Home/";
}

NS_CC_END;


code:
/****************************************************************************
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 <FBase.h>
#include <FGraphics.h>

using namespace Osp::Base;
using namespace Osp::Base::Collection;
using namespace Osp::Graphics;

NS_CC_BEGIN;

/**
@brief	A memory DC which uses to draw text on bitmap.
*/
class BitmapDC
{
public:
	BitmapDC()
	{
		m_pCanvas = NULL;
		m_pEnrichedText = NULL;
	}

	~BitmapDC()
	{
		CC_SAFE_DELETE(m_pCanvas);
	}

	bool drawText(const char * pszText, Dimension& dimensions, CCImage::ETextAlign alignment, const char * fontName = NULL, int fontSize = 0)
	{
		bool nRet = false;
		do
		{
			CC_BREAK_IF(pszText == NULL || strlen(pszText) <= 0);
			// text
			Osp::Base::String strText(pszText);
			// Set a font to the TextElement
			Font font;
			bool bUseDefaultFont = true;
			if (fontName != NULL && strlen(fontName) > 0)
			{
				String strFonName(fontName);
				if (strFonName.EndsWith(".ttf") || strFonName.EndsWith(".TTF"))
				{
					bUseDefaultFont = false;
					const char* pFullFontPath = CCFileUtils::fullPathFromRelativePath(fontName);
					font.Construct(pFullFontPath, FONT_STYLE_PLAIN, fontSize);
				}
				else
				{
					IList* pSystemFontList = Font::GetSystemFontListN();
					if (pSystemFontList != NULL)
					{
						IEnumerator* pEnum = pSystemFontList->GetEnumeratorN();
						Object* pObj = null;
						while (pEnum->MoveNext() == E_SUCCESS)
						{
							pObj = pEnum->GetCurrent();
							String* pStrName = static_cast<String*>(pObj);
							if (pStrName->Equals(strFonName, false))
							{
								bUseDefaultFont = false;
								font.Construct(*pStrName, FONT_STYLE_PLAIN, fontSize);
								break;
							}
						}

						delete pEnum;

						pSystemFontList->RemoveAll(true);
						delete pSystemFontList;
					}
				}
			}

			if (bUseDefaultFont)
			{
				font.Construct(FONT_STYLE_PLAIN, fontSize);
			}

			// calculate text size
			if (dimensions.width <= 0)
			{
				Dimension dim;
				font.GetTextExtent(strText, strText.GetLength(), dim);
				dimensions.width = dim.width;
				dimensions.height = dim.height;
			}

			CC_BREAK_IF(dimensions.width <= 0);

			// Create an EnrichedText
			m_pEnrichedText = new EnrichedText();
			m_pEnrichedText->Construct(Dimension(dimensions.width, 10));

			switch (alignment)
			{
			case CCImage::kAlignCenter:
				m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_CENTER);
				m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_MIDDLE);
				break;
			case CCImage::kAlignTop:
				m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_CENTER);
				m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_TOP);
				break;
			case CCImage::kAlignTopRight:
				m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_RIGHT);
				m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_TOP);
				break;
			case CCImage::kAlignRight:
				m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_RIGHT);
				m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_MIDDLE);
				break;
			case CCImage::kAlignBottomRight:
				m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_RIGHT);
				m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_BOTTOM);
				break;
			case CCImage::kAlignBottom:
				m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_CENTER);
				m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_BOTTOM);
				break;
			case CCImage::kAlignBottomLeft:
				m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_LEFT);
				m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_BOTTOM);
				break;
			case CCImage::kAlignLeft:
				m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_LEFT);
				m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_MIDDLE);
				break;
			case CCImage::kAlignTopLeft:
				m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_LEFT);
				m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_TOP);
				break;
			default:
				m_pEnrichedText->SetHorizontalAlignment(TEXT_ALIGNMENT_CENTER);
				m_pEnrichedText->SetVerticalAlignment(TEXT_ALIGNMENT_MIDDLE);
				break;
			}
			// Set attributes of the EnrichedText
			m_pEnrichedText->SetTextWrapStyle(TEXT_WRAP_CHARACTER_WRAP);
			m_pEnrichedText->SetTextAbbreviationEnabled(true);

			// Create a TextElement
			TextElement* pTextElement = new TextElement();
			pTextElement->Construct(strText);
			// After Adding, set attributes of the TextElement
			pTextElement->SetTextColor(Color::COLOR_WHITE);
			pTextElement->SetFont(font);
			// Add the TextElement to the EnrichedText
			m_pEnrichedText->Add(*pTextElement);

			m_pEnrichedText->Refresh();
			dimensions.height = m_pEnrichedText->GetTotalLineHeight();
			m_pEnrichedText->SetSize(dimensions.width, dimensions.height);

			CC_SAFE_DELETE(m_pCanvas);
			m_pCanvas = new Canvas();
			m_pCanvas->Construct(Rectangle(0, 0, dimensions.width, dimensions.height));
			m_pCanvas->DrawText(Point(0, 0), *m_pEnrichedText);

			m_pEnrichedText->RemoveAllTextElements(true);
			CC_SAFE_DELETE(m_pEnrichedText);

			nRet = true;
		} while (0);
		return nRet;
	}
private:
	friend class CCImage;
	Canvas* m_pCanvas;
	EnrichedText* m_pEnrichedText;
	std::string m_curFontPath;
};

static BitmapDC& sharedBitmapDC()
{
	static BitmapDC s_BmpDC;
	return s_BmpDC;
}

bool CCImage::initWithString(
                               const char *    pText,
                               int             nWidth/* = 0*/,
                               int             nHeight/* = 0*/,
                               ETextAlign      eAlignMask/* = kAlignCenter*/,
                               const char *    pFontName/* = nil*/,
                               int             nSize/* = 0*/)
{
    bool bRet = false;
    result r = E_FAILURE;
	do
	{
		int nLen = 0;
		CC_BREAK_IF(! pText);

		BitmapDC& dc = sharedBitmapDC();

		Dimension size(nWidth, nHeight);

		bRet = dc.drawText(pText, size, eAlignMask, pFontName, nSize);

		CC_BREAK_IF(!bRet);

		BufferInfo bufferInfo;
		r = dc.m_pCanvas->Lock(bufferInfo);
		CC_BREAK_IF(IsFailed(r));

		nLen = bufferInfo.pitch * bufferInfo.height;
		CC_SAFE_DELETE(m_pData);
		m_pData = new unsigned char [nLen];
		memset(m_pData, 0, nLen);
		CC_BREAK_IF(!m_pData);
		memcpy(m_pData, bufferInfo.pPixels, nLen);

		int iBytesPerPixel = bufferInfo.bitsPerPixel/8;

		m_nWidth = bufferInfo.pitch / iBytesPerPixel;
		m_nHeight = bufferInfo.height;
		m_bHasAlpha	= true;
		m_bPreMulti = false;
		m_nBitsPerComponent = 8;
		dc.m_pCanvas->Unlock();

		bRet = true;
	} while (0);

    return bRet;
}

NS_CC_END;