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 "EGL/egl.h"
#include "gles/gl.h"

#include "CCSet.h"
#include "ccMacros.h"
#include "CCDirector.h"
#include "CCTouch.h"
#include "CCTouchDispatcher.h"
#include "CCIMEDispatcher.h"
#include "CCKeypadDispatcher.h"
#include "CCApplication.h"

NS_CC_BEGIN;

//////////////////////////////////////////////////////////////////////////
// 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);
		if (m_eglNativeDisplay)
		{
			ReleaseDC(m_eglNativeWindow, m_eglNativeDisplay);
		}
	}

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

			pEGL->m_eglNativeWindow = pWindow->getHWnd();

			pEGL->m_eglNativeDisplay = GetDC(pEGL->m_eglNativeWindow);

			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);

			const EGLint aConfigAttribs[] =
			{
				EGL_LEVEL,				0,
				EGL_SURFACE_TYPE,		EGL_WINDOW_BIT,
				EGL_RENDERABLE_TYPE,	EGL_OPENGL_ES2_BIT,
				EGL_NATIVE_RENDERABLE,	EGL_FALSE,
				EGL_DEPTH_SIZE,			16,
				EGL_NONE,
			};
			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
//////////////////////////////////////////////////////////////////////////
static CCEGLView * s_pMainWindow;
static const WCHAR * kWindowClassName = L"Cocos2dxWin32";

static LRESULT CALLBACK _WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	if (s_pMainWindow && s_pMainWindow->getHWnd() == hWnd)
	{
		return s_pMainWindow->WindowProc(uMsg, wParam, lParam);
	}
	else
	{
		return DefWindowProc(hWnd, uMsg, wParam, lParam);
	}
}

CCEGLView::CCEGLView()
: m_bCaptured(false)
, m_bOrientationReverted(false)
, m_bOrientationInitVertical(false)
, m_pDelegate(NULL)
, m_pEGL(NULL)
, m_hWnd(NULL)
, m_eInitOrientation(CCDeviceOrientationPortrait)
, m_fScreenScaleFactor(1.0f)
, m_lpfnAccelerometerKeyHook(NULL)
{
    m_pTouch    = new CCTouch;
    m_pSet      = new CCSet;
    m_tSizeInPoints.cx = m_tSizeInPoints.cy = 0;
    SetRectEmpty(&m_rcViewPort);
}

CCEGLView::~CCEGLView()
{
}

bool CCEGLView::Create(LPCTSTR pTitle, int w, int h)
{
	bool bRet = false;
	do
	{
		CC_BREAK_IF(m_hWnd);

		HINSTANCE hInstance = GetModuleHandle( NULL );
		WNDCLASS  wc;		// Windows Class Structure

		// Redraw On Size, And Own DC For Window.
		wc.style          = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
		wc.lpfnWndProc    = _WindowProc;					// WndProc Handles Messages
		wc.cbClsExtra     = 0;                              // No Extra Window Data
		wc.cbWndExtra     = 0;								// No Extra Window Data
		wc.hInstance      = hInstance;						// Set The Instance
		wc.hIcon          = LoadIcon( NULL, IDI_WINLOGO );	// Load The Default Icon
		wc.hCursor        = LoadCursor( NULL, IDC_ARROW );	// Load The Arrow Pointer
		wc.hbrBackground  = NULL;                           // No Background Required For GL
		wc.lpszMenuName   = NULL;                           // We Don't Want A Menu
		wc.lpszClassName  = kWindowClassName;               // Set The Class Name

		CC_BREAK_IF(! RegisterClass(&wc) && 1410 != GetLastError());

		// center window position
		RECT rcDesktop;
		GetWindowRect(GetDesktopWindow(), &rcDesktop);

		// create window
		m_hWnd = CreateWindowEx(
			WS_EX_APPWINDOW | WS_EX_WINDOWEDGE,	// Extended Style For The Window
			kWindowClassName,									// Class Name
			pTitle,												// Window Title
			WS_CAPTION | WS_POPUPWINDOW | WS_MINIMIZEBOX,		// Defined Window Style
			0, 0,								                // Window Position
			0,                                                  // Window Width
			0,                                                  // Window Height
			NULL,												// No Parent Window
			NULL,												// No Menu
			hInstance,											// Instance
			NULL );

		CC_BREAK_IF(! m_hWnd);

        m_eInitOrientation = CCDirector::sharedDirector()->getDeviceOrientation();
        m_bOrientationInitVertical = (CCDeviceOrientationPortrait == m_eInitOrientation
            || kCCDeviceOrientationPortraitUpsideDown == m_eInitOrientation) ? true : false;
        m_tSizeInPoints.cx = w;
        m_tSizeInPoints.cy = h;
        resize(w, h);

		// init egl
		m_pEGL = CCEGL::create(this);

		if (! m_pEGL)
		{
			DestroyWindow(m_hWnd);
			m_hWnd = NULL;
			break;
		}

		s_pMainWindow = this;
		bRet = true;
	} while (0);

	return bRet;
}

LRESULT CCEGLView::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
	PAINTSTRUCT ps;

	switch (message)
	{
	case WM_LBUTTONDOWN:
		if (m_pDelegate && m_pTouch && MK_LBUTTON == wParam)
		{
            POINT pt = {(short)LOWORD(lParam), (short)HIWORD(lParam)};
            if (PtInRect(&m_rcViewPort, pt))
            {
                m_bCaptured = true;
                SetCapture(m_hWnd);
                m_pTouch->SetTouchInfo((float)(pt.x - m_rcViewPort.left) / m_fScreenScaleFactor,
                    (float)(pt.y - m_rcViewPort.top) / m_fScreenScaleFactor);
                m_pSet->addObject(m_pTouch);
                m_pDelegate->touchesBegan(m_pSet, NULL);
            }
		}
		break;

	case WM_MOUSEMOVE:
		if (MK_LBUTTON == wParam && m_bCaptured)
		{
            m_pTouch->SetTouchInfo((float)((short)LOWORD(lParam)- m_rcViewPort.left) / m_fScreenScaleFactor,
                (float)((short)HIWORD(lParam) - m_rcViewPort.top) / m_fScreenScaleFactor);
            m_pDelegate->touchesMoved(m_pSet, NULL);
		}
		break;

	case WM_LBUTTONUP:
		if (m_bCaptured)
		{
			m_pTouch->SetTouchInfo((float)((short)LOWORD(lParam)- m_rcViewPort.left) / m_fScreenScaleFactor,
                (float)((short)HIWORD(lParam) - m_rcViewPort.top) / m_fScreenScaleFactor);
			m_pDelegate->touchesEnded(m_pSet, NULL);
			m_pSet->removeObject(m_pTouch);
            ReleaseCapture();
			m_bCaptured = false;
		}
		break;
	case WM_SIZE:
		switch (wParam)
		{
		case SIZE_RESTORED:
			CCApplication::sharedApplication().applicationWillEnterForeground();
			break;
		case SIZE_MINIMIZED:
			CCApplication::sharedApplication().applicationDidEnterBackground();
			break;
		}
		break;
	case WM_KEYDOWN:
		if (wParam == VK_F1 || wParam == VK_F2)
		{
			if (GetKeyState(VK_LSHIFT) < 0 ||  GetKeyState(VK_RSHIFT) < 0 || GetKeyState(VK_SHIFT) < 0)
				CCKeypadDispatcher::sharedDispatcher()->dispatchKeypadMSG(wParam == VK_F1 ? kTypeBackClicked : kTypeMenuClicked);
		}
		if ( m_lpfnAccelerometerKeyHook!=NULL )
		{
			(*m_lpfnAccelerometerKeyHook)( message,wParam,lParam );
		}
		break;
	case WM_KEYUP:
		if ( m_lpfnAccelerometerKeyHook!=NULL )
		{
			(*m_lpfnAccelerometerKeyHook)( message,wParam,lParam );
		}
		break;
    case WM_CHAR:
        {
            if (wParam < 0x20)
            {
                if (VK_BACK == wParam)
                {
                    CCIMEDispatcher::sharedDispatcher()->dispatchDeleteBackward();
                }
                else if (VK_RETURN == wParam)
                {
                    CCIMEDispatcher::sharedDispatcher()->dispatchInsertText("\n", 1);
                }
                else if (VK_TAB == wParam)
                {
                    // tab input
                }
                else if (VK_ESCAPE == wParam)
                {
                    // ESC input
					CCDirector::sharedDirector()->end();
                }
            }
            else if (wParam < 128)
            {
                // ascii char
                CCIMEDispatcher::sharedDispatcher()->dispatchInsertText((const char *)&wParam, 1);
            }
            else
            {
                char szUtf8[8] = {0};
                int nLen = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)&wParam, 1, szUtf8, sizeof(szUtf8), NULL, NULL);

                CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(szUtf8, nLen);
            }
			if ( m_lpfnAccelerometerKeyHook!=NULL )
			{
				(*m_lpfnAccelerometerKeyHook)( message,wParam,lParam );
			}
        }
        break;

	case WM_PAINT:
		BeginPaint(m_hWnd, &ps);
		EndPaint(m_hWnd, &ps);
		break;

	case WM_CLOSE:
		CCDirector::sharedDirector()->end();
		break;

	case WM_DESTROY:
		PostQuitMessage(0);
		break;

	default:
		return DefWindowProc(m_hWnd, message, wParam, lParam);
	}
	return 0;
}

void CCEGLView::setAccelerometerKeyHook( LPFN_ACCELEROMETER_KEYHOOK lpfnAccelerometerKeyHook )
{
	m_lpfnAccelerometerKeyHook=lpfnAccelerometerKeyHook;
}

CCSize CCEGLView::getSize()
{
    if (m_bOrientationReverted)
    {
        return CCSize((float)(m_tSizeInPoints.cy), (float)(m_tSizeInPoints.cx));
    }
    return CCSize((float)(m_tSizeInPoints.cx), (float)(m_tSizeInPoints.cy));
}

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

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

void CCEGLView::release()
{
	if (m_hWnd)
	{
		DestroyWindow(m_hWnd);
		m_hWnd = NULL;
	}
	s_pMainWindow = NULL;
	UnregisterClass(kWindowClassName, GetModuleHandle(NULL));

    CC_SAFE_DELETE(m_pSet);
    CC_SAFE_DELETE(m_pTouch);
    CC_SAFE_DELETE(m_pDelegate);
    CC_SAFE_DELETE(m_pEGL);
    delete this;
}

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

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

int CCEGLView::setDeviceOrientation(int eOritation)
{
	do
	{
		bool bVertical = (CCDeviceOrientationPortrait == eOritation
			|| kCCDeviceOrientationPortraitUpsideDown == eOritation) ? true : false;

		CC_BREAK_IF(m_bOrientationReverted && bVertical != m_bOrientationInitVertical);
		CC_BREAK_IF(! m_bOrientationReverted && bVertical == m_bOrientationInitVertical);

        m_bOrientationReverted = (bVertical == m_bOrientationInitVertical) ? false : true;

        // swap width and height
		RECT rc;
		GetClientRect(m_hWnd, &rc);
        resize(rc.bottom - rc.top, rc.right - rc.left);

	} while (0);

	return m_eInitOrientation;
}

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

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

void CCEGLView::setIMEKeyboardState(bool /*bOpen*/)
{
}

HWND CCEGLView::getHWnd()
{
    return m_hWnd;
}

void CCEGLView::resize(int width, int height)
{
    if (! m_hWnd)
    {
        return;
    }

    RECT rcClient;
    GetClientRect(m_hWnd, &rcClient);
    if (rcClient.right - rcClient.left == width &&
        rcClient.bottom - rcClient.top == height)
    {
        return;
    }
    // calculate new window width and height
    rcClient.right = rcClient.left + width;
    rcClient.bottom = rcClient.top + height;
    AdjustWindowRectEx(&rcClient, GetWindowLong(m_hWnd, GWL_STYLE), false, GetWindowLong(m_hWnd, GWL_EXSTYLE));

    // change width and height
    SetWindowPos(m_hWnd, 0, 0, 0, rcClient.right - rcClient.left,
        rcClient.bottom - rcClient.top, SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER);

    if (m_pEGL)
    {
        m_pEGL->resizeSurface();
    }

    // calculate view port in pixels
    int viewPortW = (int)(m_tSizeInPoints.cx * m_fScreenScaleFactor);
    int viewPortH = (int)(m_tSizeInPoints.cy * m_fScreenScaleFactor);
    if (m_bOrientationReverted)
    {
        int tmp = viewPortW;
        viewPortW = viewPortH;
        viewPortH = tmp;
    }
    GetClientRect(m_hWnd, &rcClient);

    // calculate client new width and height
    int newW = rcClient.right - rcClient.left;
    int newH = rcClient.bottom - rcClient.top;

    // calculate new view port
    m_rcViewPort.left   = rcClient.left + (newW - viewPortW) / 2;
    m_rcViewPort.top    = rcClient.top + (newH - viewPortH) / 2;
    m_rcViewPort.right  = m_rcViewPort.left + viewPortW;
    m_rcViewPort.bottom = m_rcViewPort.top + viewPortH;
}

void CCEGLView::centerWindow()
{
    if (! m_hWnd)
    {
        return;
    }

    RECT rcDesktop, rcWindow;
    GetWindowRect(GetDesktopWindow(), &rcDesktop);

    // substract the task bar
    HWND hTaskBar = FindWindow(TEXT("Shell_TrayWnd"), NULL);
    if (hTaskBar != NULL)
    {
        APPBARDATA abd;

        abd.cbSize = sizeof(APPBARDATA);
        abd.hWnd = hTaskBar;

        SHAppBarMessage(ABM_GETTASKBARPOS, &abd);
        SubtractRect(&rcDesktop, &rcDesktop, &abd.rc);
    }
    GetWindowRect(m_hWnd, &rcWindow);

    int offsetX = (rcDesktop.right - rcDesktop.left - (rcWindow.right - rcWindow.left)) / 2;
    offsetX = (offsetX > 0) ? offsetX : rcDesktop.left;
    int offsetY = (rcDesktop.bottom - rcDesktop.top - (rcWindow.bottom - rcWindow.top)) / 2;
    offsetY = (offsetY > 0) ? offsetY : rcDesktop.top;

    SetWindowPos(m_hWnd, 0, offsetX, offsetY, 0, 0, SWP_NOCOPYBITS | SWP_NOSIZE | SWP_NOOWNERZORDER | SWP_NOZORDER);
}

void CCEGLView::setScreenScale(float factor)
{
    m_fScreenScaleFactor = factor;
}

bool CCEGLView::canSetContentScaleFactor()
{
    return true;
}

void CCEGLView::setContentScaleFactor(float contentScaleFactor)
{
    m_fScreenScaleFactor = contentScaleFactor;
    if (m_bOrientationReverted)
    {
        resize((int)(m_tSizeInPoints.cy * contentScaleFactor), (int)(m_tSizeInPoints.cx * contentScaleFactor));
    }
    else
    {
        resize((int)(m_tSizeInPoints.cx * contentScaleFactor), (int)(m_tSizeInPoints.cy * contentScaleFactor));
    }
    centerWindow();
}

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 __CC_EGLVIEW_WIN32_H__
#define __CC_EGLVIEW_WIN32_H__

#include <Windows.h>

#include "CCCommon.h"
#include "CCGeometry.h"

NS_CC_BEGIN;

class CCSet;
class CCTouch;
class EGLTouchDelegate;

class CCEGL;

class CC_DLL CCEGLView
{
public:

    CCEGLView();
    virtual ~CCEGLView();

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

    float getMainScreenScale() { return -1.0f; }

	virtual bool Create(LPCTSTR pTitle, int w, int h);
	virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);

    int setDeviceOrientation(int 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);

    // win32 platform function
    HWND getHWnd();
    void resize(int width, int height);
    void centerWindow();
    void setScreenScale(float factor);
	typedef void (*LPFN_ACCELEROMETER_KEYHOOK)( UINT message,WPARAM wParam, LPARAM lParam );
	void setAccelerometerKeyHook( LPFN_ACCELEROMETER_KEYHOOK lpfnAccelerometerKeyHook );

    // static function

    /**
    @brief	get the shared main open gl window
    */
    static CCEGLView& sharedOpenGLView();

protected:

private:

    bool                m_bCaptured;
	bool				m_bOrientationReverted;
	bool				m_bOrientationInitVertical;
    CCSet *             m_pSet;
    CCTouch *           m_pTouch;
    EGLTouchDelegate *  m_pDelegate;

    CCEGL *            m_pEGL;

	HWND				m_hWnd;

	int					m_eInitOrientation;
    SIZE                m_tSizeInPoints;
    float               m_fScreenScaleFactor;
    RECT                m_rcViewPort;
	LPFN_ACCELEROMETER_KEYHOOK	m_lpfnAccelerometerKeyHook;
};

NS_CC_END;

#endif	// end of __CC_EGLVIEW_WIN32_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 "windows.h"
#include "CCDirector.h"

#define CC_RETINA_DISPLAY_FILENAME_SUFFIX "-hd"
#define CC_IPAD_FILENAME_SUFFIX "-ipad"
#define CC_IPAD_DISPLAY_RETINA_SUPPFIX "-ipadhd"

using namespace std;

NS_CC_BEGIN;

// record the resource path
static char s_pszResourcePath[MAX_PATH] = {0};

void _CheckPath()
{
	if (! s_pszResourcePath[0])
	{
		WCHAR  wszPath[MAX_PATH];
		int nNum = WideCharToMultiByte(CP_ACP, 0, wszPath,
			GetCurrentDirectoryW(sizeof(wszPath), wszPath),
			s_pszResourcePath, MAX_PATH, NULL, NULL);
        s_pszResourcePath[nNum] = '\\';
	}
}

void CCFileUtils::setResourcePath(const char *pszResourcePath)
{
    CCAssert(pszResourcePath != NULL, "[FileUtils setResourcePath] -- wrong resource path");
    CCAssert(strlen(pszResourcePath) <= MAX_PATH, "[FileUtils setResourcePath] -- resource path too long");

    strcpy(s_pszResourcePath, pszResourcePath);
}

const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath)
{
	_CheckPath();

    CCString * pRet = new CCString();
    pRet->autorelease();
    if ((strlen(pszRelativePath) > 1 && pszRelativePath[1] == ':'))
    {
        // path start with "x:", is absolute path
        pRet->m_sString = pszRelativePath;
    }
    else if (strlen(pszRelativePath) > 0
        && ('/' == pszRelativePath[0] || '\\' == pszRelativePath[0]))
    {
        // path start with '/' or '\', is absolute path without driver name
		char szDriver[3] = {s_pszResourcePath[0], s_pszResourcePath[1], 0};
        pRet->m_sString = szDriver;
        pRet->m_sString += pszRelativePath;
    }
    else
    {
        pRet->m_sString = s_pszResourcePath;
        pRet->m_sString += pszRelativePath;
    }

	// is ipad?
	CCSize winSize = CCDirector::sharedDirector()->getWinSize();
	bool isIpad = (winSize.width == 1024 || winSize.height == 768);

	std::string hiRes = pRet->m_sString.c_str();
    std::string::size_type pos = hiRes.find_last_of("/\\");
    std::string::size_type dotPos = hiRes.find_last_of(".");

	if (isIpad)
	{
		if (CC_CONTENT_SCALE_FACTOR() == 1.0f)
		{
			// ipad

			if (std::string::npos != dotPos && dotPos > pos)
            {
                hiRes.insert(dotPos, CC_IPAD_FILENAME_SUFFIX);
            }
            else
            {
                hiRes.append(CC_IPAD_FILENAME_SUFFIX);
            }
		}
		else
		{
			// ipad retina

			if (std::string::npos != dotPos && dotPos > pos)
            {
                hiRes.insert(dotPos, CC_IPAD_DISPLAY_RETINA_SUPPFIX);
            }
            else
            {
                hiRes.append(CC_IPAD_DISPLAY_RETINA_SUPPFIX);
            }
		}
	}
	else
	{
		if (CC_CONTENT_SCALE_FACTOR() != 1.0f)
        {
			// iphone retina

            if (std::string::npos != dotPos && dotPos > pos)
            {
                hiRes.insert(dotPos, CC_RETINA_DISPLAY_FILENAME_SUFFIX);
            }
            else
            {
                hiRes.append(CC_RETINA_DISPLAY_FILENAME_SUFFIX);
            }
        }
	}

	DWORD attrib = GetFileAttributesA(hiRes.c_str());
	if (attrib != INVALID_FILE_ATTRIBUTES && ! (FILE_ATTRIBUTE_DIRECTORY & attrib))
    {
        pRet->m_sString.swap(hiRes);
    }

	return pRet->m_sString.c_str();
}

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

unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize)
{
    unsigned char * pBuffer = NULL;

    do
    {
        // read the file from hardware
        FILE *fp = fopen(pszFileName, pszMode);
        CC_BREAK_IF(!fp);

        fseek(fp,0,SEEK_END);
        *pSize = ftell(fp);
        fseek(fp,0,SEEK_SET);
        pBuffer = new unsigned char[*pSize];
        *pSize = fread(pBuffer,sizeof(unsigned char), *pSize,fp);
        fclose(fp);
    } while (0);

    if (! pBuffer && getIsPopupNotify())
    {
        std::string title = "Notification";
        std::string msg = "Get data from file(";
        msg.append(pszFileName).append(") failed!");

        CCMessageBox(msg.c_str(), title.c_str());
    }
    return pBuffer;
}

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

string CCFileUtils::getWriteablePath()
{
	// return the path that the exe file saved in

	char full_path[_MAX_PATH + 1];
	::GetModuleFileNameA(NULL, full_path, _MAX_PATH + 1);

	string ret((char*)full_path);

	// remove xxx.exe
	ret =  ret.substr(0, ret.rfind("\\") + 1);

	return ret;
}

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

NS_CC_BEGIN;

/**
@brief	A memory DC which uses to draw text on bitmap.
*/
class BitmapDC
{
public:
    BitmapDC(HWND hWnd = NULL)
    : m_hDC(NULL)
    , m_hBmp(NULL)
    , m_hFont((HFONT)GetStockObject(DEFAULT_GUI_FONT))
	, m_hWnd(NULL)
    {
		m_hWnd = hWnd;
        HDC hdc = GetDC(hWnd);
        m_hDC   = CreateCompatibleDC(hdc);
        ReleaseDC(hWnd, hdc);
    }

    ~BitmapDC()
    {
        prepareBitmap(0, 0);
        if (m_hDC)
        {
            DeleteDC(m_hDC);
        }
        HFONT hDefFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
        if (hDefFont != m_hFont)
        {
            DeleteObject(m_hFont);
            m_hFont = hDefFont;
        }
		// release temp font resource
		if (m_curFontPath.size() > 0)
		{
			wchar_t * pwszBuffer = utf8ToUtf16(m_curFontPath);
			if (pwszBuffer)
			{
				RemoveFontResource(pwszBuffer);
				SendMessage( m_hWnd, WM_FONTCHANGE, 0, 0);
				delete [] pwszBuffer;
				pwszBuffer = NULL;
			}
		}
    }

	wchar_t * utf8ToUtf16(std::string nString)
	{
		wchar_t * pwszBuffer = NULL;
		do
		{
			if (nString.size() < 0)
			{
				break;
			}
			// utf-8 to utf-16
			int nLen = nString.size();
			int nBufLen  = nLen + 1;
			pwszBuffer = new wchar_t[nBufLen];
			CC_BREAK_IF(! pwszBuffer);
			memset(pwszBuffer,0,nBufLen);
			nLen = MultiByteToWideChar(CP_UTF8, 0, nString.c_str(), nLen, pwszBuffer, nBufLen);
			pwszBuffer[nLen] = '\0';
		} while (0);
		return pwszBuffer;

	}

    bool setFont(const char * pFontName = NULL, int nSize = 0)
    {
        bool bRet = false;
        do
        {
			std::string fontName = pFontName;
			std::string fontPath;
            HFONT       hDefFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
            LOGFONTA    tNewFont = {0};
            LOGFONTA    tOldFont = {0};
            GetObjectA(hDefFont, sizeof(tNewFont), &tNewFont);
            if (fontName.c_str())
            {
				// create font from ttf file
				int nFindttf = fontName.find(".ttf");
				int nFindTTF = fontName.find(".TTF");
				if (nFindttf >= 0 || nFindTTF >= 0)
				{
					fontPath = CCFileUtils::fullPathFromRelativePath(fontName.c_str());
					int nFindPos = fontName.rfind("/");
					fontName = &fontName[nFindPos+1];
					nFindPos = fontName.rfind(".");
					fontName = fontName.substr(0,nFindPos);
				}
				tNewFont.lfCharSet = DEFAULT_CHARSET;
                strcpy_s(tNewFont.lfFaceName, LF_FACESIZE, fontName.c_str());
            }
            if (nSize)
            {
                tNewFont.lfHeight = -nSize;
            }
            GetObjectA(m_hFont,  sizeof(tOldFont), &tOldFont);

            if (tOldFont.lfHeight == tNewFont.lfHeight
                && ! strcpy(tOldFont.lfFaceName, tNewFont.lfFaceName))
            {
                // already has the font
                bRet = true;
                break;
            }

            // delete old font
            if (m_hFont != hDefFont)
            {
                DeleteObject(m_hFont);
				// release old font register
				if (m_curFontPath.size() > 0)
				{
					wchar_t * pwszBuffer = utf8ToUtf16(m_curFontPath);
					if (pwszBuffer)
					{
						if(RemoveFontResource(pwszBuffer))
						{
							SendMessage( m_hWnd, WM_FONTCHANGE, 0, 0);
						}
						delete [] pwszBuffer;
						pwszBuffer = NULL;
					}
				}
				fontPath.size()>0?(m_curFontPath = fontPath):(m_curFontPath.clear());
				// register temp font
				if (m_curFontPath.size() > 0)
				{
					wchar_t * pwszBuffer = utf8ToUtf16(m_curFontPath);
					if (pwszBuffer)
					{
						if(AddFontResource(pwszBuffer))
						{
							SendMessage( m_hWnd, WM_FONTCHANGE, 0, 0);
						}
						delete [] pwszBuffer;
						pwszBuffer = NULL;
					}
				}
            }
            m_hFont = NULL;

            // create new font
            m_hFont = CreateFontIndirectA(&tNewFont);
            if (! m_hFont)
            {
                // create failed, use default font
                m_hFont = hDefFont;
                break;
            }

            bRet = true;
        } while (0);
        return bRet;
    }

    SIZE sizeWithText(const char * pszText, int nLen, DWORD dwFmt, LONG nWidthLimit)
    {
        SIZE tRet = {0};
        do
        {
            CC_BREAK_IF(! pszText || nLen <= 0);

            RECT rc = {0, 0, 0, 0};
            DWORD dwCalcFmt = DT_CALCRECT;

            if (nWidthLimit > 0)
            {
                rc.right = nWidthLimit;
                dwCalcFmt |= DT_WORDBREAK
                    | (dwFmt & DT_CENTER)
                    | (dwFmt & DT_RIGHT);
            }
            // use current font to measure text extent
            HGDIOBJ hOld = SelectObject(m_hDC, m_hFont);

            // measure text size
            DrawTextA(m_hDC, pszText, nLen, &rc, dwCalcFmt);
            SelectObject(m_hDC, hOld);

            tRet.cx = rc.right;
            tRet.cy = rc.bottom;
        } while (0);

        return tRet;
    }

    bool prepareBitmap(int nWidth, int nHeight)
    {
        // release bitmap
        if (m_hBmp)
        {
            DeleteObject(m_hBmp);
            m_hBmp = NULL;
        }
        if (nWidth > 0 && nHeight > 0)
        {
            m_hBmp = CreateBitmap(nWidth, nHeight, 1, 32, NULL);
            if (! m_hBmp)
            {
                return false;
            }
        }
        return true;
    }

    int drawText(const char * pszText, SIZE& tSize, CCImage::ETextAlign eAlign)
    {
        int nRet = 0;
        wchar_t * pwszBuffer = 0;
        do
        {
            CC_BREAK_IF(! pszText);

            DWORD dwFmt = DT_WORDBREAK;
            DWORD dwHoriFlag = eAlign & 0x0f;
            DWORD dwVertFlag = (eAlign & 0xf0) >> 4;

            switch (dwHoriFlag)
            {
            case 1: // left
                dwFmt |= DT_LEFT;
                break;
            case 2: // right
                dwFmt |= DT_RIGHT;
                break;
            case 3: // center
                dwFmt |= DT_CENTER;
                break;
            }

            int nLen = strlen(pszText);
            SIZE newSize = sizeWithText(pszText, nLen, dwFmt, tSize.cx);

            RECT rcText = {0};
            // if content width is 0, use text size as content size
            if (tSize.cx <= 0)
            {
                tSize = newSize;
                rcText.right  = newSize.cx;
                rcText.bottom = newSize.cy;
            }
            else
            {

                LONG offsetX = 0;
                LONG offsetY = 0;
                rcText.right = newSize.cx; // store the text width to rectangle

                // calculate text horizontal offset
                if (1 != dwHoriFlag          // and text isn't align to left
                    && newSize.cx < tSize.cx)   // and text's width less then content width,
                {                               // then need adjust offset of X.
                    offsetX = (2 == dwHoriFlag) ? tSize.cx - newSize.cx     // align to right
                        : (tSize.cx - newSize.cx) / 2;                      // align to center
                }

                // if content height is 0, use text height as content height
                // else if content height less than text height, use content height to draw text
                if (tSize.cy <= 0)
                {
                    tSize.cy = newSize.cy;
                    dwFmt   |= DT_NOCLIP;
                    rcText.bottom = newSize.cy; // store the text height to rectangle
                }
                else if (tSize.cy < newSize.cy)
                {
                    // content height larger than text height need, clip text to rect
                    rcText.bottom = tSize.cy;
                }
                else
                {
                    rcText.bottom = newSize.cy; // store the text height to rectangle

                    // content larger than text, need adjust vertical position
                    dwFmt |= DT_NOCLIP;

                    // calculate text vertical offset
                    offsetY = (2 == dwVertFlag) ? tSize.cy - newSize.cy     // align to bottom
                        : (3 == dwVertFlag) ? (tSize.cy - newSize.cy) / 2   // align to middle
                        : 0;                                                // align to top
                }

                if (offsetX || offsetY)
                {
                    OffsetRect(&rcText, offsetX, offsetY);
                }
            }

            CC_BREAK_IF(! prepareBitmap(tSize.cx, tSize.cy));

            // draw text
            HGDIOBJ hOldFont = SelectObject(m_hDC, m_hFont);
            HGDIOBJ hOldBmp  = SelectObject(m_hDC, m_hBmp);

            SetBkMode(m_hDC, TRANSPARENT);
            SetTextColor(m_hDC, RGB(255, 255, 255)); // white color

            // utf-8 to utf-16
            int nBufLen  = nLen + 1;
            pwszBuffer = new wchar_t[nBufLen];
            CC_BREAK_IF(! pwszBuffer);
            nLen = MultiByteToWideChar(CP_UTF8, 0, pszText, nLen, pwszBuffer, nBufLen);

            // draw text
            nRet = DrawTextW(m_hDC, pwszBuffer, nLen, &rcText, dwFmt);
            //DrawTextA(m_hDC, pszText, nLen, &rcText, dwFmt);

            SelectObject(m_hDC, hOldBmp);
            SelectObject(m_hDC, hOldFont);
        } while (0);
        CC_SAFE_DELETE_ARRAY(pwszBuffer);
        return nRet;
    }

    CC_SYNTHESIZE_READONLY(HDC, m_hDC, DC);
    CC_SYNTHESIZE_READONLY(HBITMAP, m_hBmp, Bitmap);
private:
    friend class CCImage;
    HFONT   m_hFont;
	HWND	m_hWnd;
	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;
    unsigned char * pImageData = 0;
    do
    {
        CC_BREAK_IF(! pText);

        BitmapDC& dc = sharedBitmapDC();

        if (! dc.setFont(pFontName, nSize))
        {
            CCLog("Can't found font(%s), use system default", pFontName);
        }

        // draw text
        SIZE size = {nWidth, nHeight};
        CC_BREAK_IF(! dc.drawText(pText, size, eAlignMask));

        pImageData = new unsigned char[size.cx * size.cy * 4];
        CC_BREAK_IF(! pImageData);

        struct
        {
            BITMAPINFOHEADER bmiHeader;
            int mask[4];
        } bi = {0};
        bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
        CC_BREAK_IF(! GetDIBits(dc.getDC(), dc.getBitmap(), 0, 0,
            NULL, (LPBITMAPINFO)&bi, DIB_RGB_COLORS));

        m_nWidth    = (short)size.cx;
        m_nHeight   = (short)size.cy;
        m_bHasAlpha = true;
        m_bPreMulti = false;
        m_pData     = pImageData;
        pImageData  = 0;
        m_nBitsPerComponent = 8;
        // copy pixed data
        bi.bmiHeader.biHeight = (bi.bmiHeader.biHeight > 0)
           ? - bi.bmiHeader.biHeight : bi.bmiHeader.biHeight;
        GetDIBits(dc.getDC(), dc.getBitmap(), 0, m_nHeight, m_pData,
            (LPBITMAPINFO)&bi, DIB_RGB_COLORS);

        // change pixel's alpha value to 255, when it's RGB != 0
        COLORREF * pPixel = NULL;
        for (int y = 0; y < m_nHeight; ++y)
        {
            pPixel = (COLORREF *)m_pData + y * m_nWidth;
            for (int x = 0; x < m_nWidth; ++x)
            {
                COLORREF& clr = *pPixel;
                if (GetRValue(clr) || GetGValue(clr) || GetBValue(clr))
                {
                    clr |= 0xff000000;
                }
                ++pPixel;
            }
        }

        bRet = true;
    } while (0);

    return bRet;
}

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 "CCAccelerometer_wophone.h"
#include "CCMacros.h"

#include "TCOM_Generic_Method_IIDs.h"

// Can only include once
#include "TCOM_Sensors_IIDs.h"

namespace   cocos2d {

static CCAccelerometer s_Accelerometer;

//------------------------------------------------------------------
//
// CCAccelerometer
//
//------------------------------------------------------------------
CCAccelerometer::CCAccelerometer()
: m_pSensor(NULL)
, m_pDelegate(NULL)
{
}

CCAccelerometer::~CCAccelerometer()
{
    if (m_pSensor)
    {
        m_pSensor->Release();
        m_pSensor = NULL;
    }

	m_pDelegate = NULL;
}

CCAccelerometer* CCAccelerometer::sharedAccelerometer()
{
    return &s_Accelerometer;
}

void CCAccelerometer::setDelegate(CCAccelerometerDelegate* pDelegate)
{
	m_pDelegate = pDelegate;

	if (m_pDelegate)
	{
		do
		{
			if (m_pSensor)
			{
				break;
			}

			m_pSensor = TCOM_Sensors_DataType_Client::GetInstance();

			if (m_pSensor)
			{
				m_pSensor->StartUp();
				m_pSensor->SetDelay(TG3_SENSOR_DELAY_FASTEST);

				TApplication* pApp = TApplication::GetCurrentApplication();
				TWindow* pWnd = pApp->GetActiveWindow();
				m_pSensor->SetWindowCtrlId(pWnd->GetWindowHwndId(), 0);
				m_pSensor->Activate(TG3_SENSOR_TYPE_ACCELEROMETER, TRUE);
			}
			else
			{
				CCLOG("cocos2d: The Accelerometer Sensor Open failed");
			}
		} while (0);
	}
	else
	{
		if (m_pSensor)
		{
			m_pSensor->Release();
			m_pSensor = NULL;
		}
	}
}

void CCAccelerometer::didAccelerate(CCAcceleration* pAccelerationValue)
{
	if (m_pDelegate)
	{
		m_pDelegate->didAccelerate(pAccelerationValue);
	}
}

}//namespace   cocos2d


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_WOPHONE_UIACCELEROMETER_H__
#define __PLATFORM_WOPHONE_UIACCELEROMETER_H__

#include "CCAccelerometerDelegate.h"
#include "TG3.h"
#include "CCCommon.h"
#include "TCOM_Sensors_Interface.h"

namespace   cocos2d {

/**
@brief
The CCAccelerometer class lets you register to receive
acceleration-related data from the onboard hardware.
*/
class CC_DLL CCAccelerometer
{
public:
    CCAccelerometer();
    ~CCAccelerometer();

    /**
    @brief Returns the shared accelerometer object for the system.
    */
    static CCAccelerometer* sharedAccelerometer();

    /**
    @brief add delegate to concern accelerometer sensor
    */
    void setDelegate(CCAccelerometerDelegate* pDelegate);

    /**
    @brief call delegates' didAccelerate function
    */
    void didAccelerate(CCAcceleration* pAccelerationValue);

protected:
	CCAccelerometerDelegate*        m_pDelegate;
    TCOM_Sensors_DataType_Client*   m_pSensor;
};

}//namespace   cocos2d

#endif


code:
// #define COCOS2D_DEBUG   1

#include "CCApplication_wophone.h"

#include "ssBackLightControl.h"
//#include "ssKeyLockControl.h"

#include "CCScheduler.h"

NS_CC_BEGIN;

static const Int32 CC_ON_APPLICATION_IDLE = (EVENT_FirstUser + EVENT_LastUser) / 2;

#ifdef _TRANZDA_VM_
static  LARGE_INTEGER s_nAnimationInterval;
static  LARGE_INTEGER s_nFreq;
static  LARGE_INTEGER s_nLast;
#else
#include <sys/time.h>
static long long s_nAnimationInterval;
static long long s_nLast;
static long long getTimeOfDayMicroSecond()
{
    timeval val;
    gettimeofday(&val, NULL);
    return (long long)val.tv_sec * 1000 * 1000 + val.tv_usec;
}
#endif

CCApplication::CCApplication()
: m_bRunning(false)
, m_bNeedStop(false)
, m_bInBackground(false)
, m_bEnterBackgroundCalled(false)
{
    memset(&m_tMsg, 0, sizeof(m_tMsg));
    SS_GetCurrentGTID(&m_tMsg.gtid);
    m_tMsg.type = CC_ON_APPLICATION_IDLE;

    Sys_RegisterMessageCallBack(CC_ON_APPLICATION_IDLE, CCApplication::_OnAppIdle, (UInt32)this);

    memset(m_AppDataPath, 0, sizeof(char) * EOS_FILE_MAX_PATH);

    do
    {
        TUChar AppID[EOS_FILE_MAX_PATH] = {0};
        UInt32 nCmdType = 0;
        Int32  nRet = SS_AppRequest_GetAppName(AppID, &nCmdType);
        CC_BREAK_IF(nRet < 0);

#ifndef _TRANZDA_VM_
        char *pszDriver = "";
#else
        char *pszDriver = "D:/Work7";
#endif

        TUChar AppPath[EOS_FILE_MAX_PATH] = {0};
        char   DataPath[EOS_FILE_MAX_PATH] = {0};

        // get the const data path of the application and record it
        SS_GetApplicationPath(AppID, SS_APP_PATH_TYPE_CONST, AppPath);
        TUString::StrUnicodeToStrUtf8((Char*) DataPath, AppPath);
        strcpy(m_AppDataPath, pszDriver);
        strcat(m_AppDataPath, DataPath);

        // get the writable data path of the application and record it
        SS_GetApplicationPath(AppID, SS_APP_PATH_TYPE_DATA, AppPath);
        TUString::StrUnicodeToStrUtf8((Char*) DataPath, AppPath);
        strcpy(m_AppWritablePath, pszDriver);
        strcat(m_AppWritablePath, DataPath);
    } while (0);

    CC_ASSERT(! sm_pSharedApplication);
    sm_pSharedApplication = this;
}

CCApplication::~CCApplication()
{
    Sys_RegisterMessageCallBack(CC_ON_APPLICATION_IDLE, NULL, NULL);

    CC_ASSERT(this == sm_pSharedApplication);
    sm_pSharedApplication = NULL;
}

Boolean  CCApplication::EventHandler(EventType*  pEvent)
{
    Boolean     bHandled = FALSE;

    switch(pEvent->eType)
    {
    case EVENT_AppLoad:
        if (! initInstance() || ! applicationDidFinishLaunching())
        {
            CCScheduler::purgeSharedScheduler();
            SendStopEvent();
        }
#ifdef _TRANZDA_VM_
        QueryPerformanceFrequency(&s_nFreq);
        QueryPerformanceCounter(&s_nLast);
#else
        s_nLast = getTimeOfDayMicroSecond();
#endif
        bHandled = TRUE;
        break;

    case EVENT_AppStopNotify:
        break;

    case EVENT_AppActiveNotify:
        if (pEvent->sParam1 == 0)
        {
            CCLOG("EVENT_AppActiveNotify false");
            if (!m_bInBackground)
            {
                if (! m_bEnterBackgroundCalled)
                {
                    applicationDidEnterBackground();
                    m_bEnterBackgroundCalled = true;
                }
                m_bInBackground = true;
            }

            if (CCDirector::sharedDirector()->isPaused())
            {
                StopMainLoop();
            }

            // restore back light open mode
            if (CfgGetBackLightStatus())
            {
                CfgTurnOnBackLightEx(SYS_BACK_LIGHT_MODE_TIME_LONG);
                CCLOG("AppActiveNotify::TurnOnBackLight:MODE_TIME_LONG");
            }
        }
        else if (pEvent->sParam1 > 0)
        {
            CCLOG("EVENT_AppActiveNotify true");
            if (m_bInBackground)
            {
                if (m_bEnterBackgroundCalled)
                {
                    applicationWillEnterForeground();
                    m_bEnterBackgroundCalled = false;
                }
                m_bInBackground = false;
            }

            StartMainLoop();

            // modify back light open mode
            if (CfgGetBackLightStatus())
            {
                // Why doesn't use CfgTurnOnBackLightEx(SYS_BACK_LIGHT_MODE_TIME_ALWAYS)?
                // MODE_TIME_ALWAYS cause phone can't sleep when power button pressed.
                CfgTurnOnBackLightDelay(0x7fffffff);
                CCLOG("AppActiveNotify::TurnOnBackLight:0x7fffffff");
            }
        }
        break;
    }
    if (FALSE == bHandled)
    {
        return TApplication::EventHandler(pEvent);
    }

    return bHandled;
}

void CCApplication::setAnimationInterval(double interval)
{
#ifdef _TRANZDA_VM_
    LARGE_INTEGER nFreq;
    QueryPerformanceFrequency(&nFreq);
    s_nAnimationInterval.QuadPart = (LONGLONG)(interval * nFreq.QuadPart);
#else
    s_nAnimationInterval = (long long)(interval * 1000 * 1000);
#endif
}

CCApplication::Orientation CCApplication::setOrientation(CCApplication::Orientation orientation)
{
    return sm_OrientationTable[sm_uDesignOrientation][orientation];
}

void CCApplication::statusBarFrame(CCRect * rect)
{
}

const char* CCApplication::getAppDataPath()
{
    return m_AppDataPath;
}

const char* CCApplication::getAppWritablePath()
{
    return m_AppWritablePath;
}

void CCApplication::switchNotify(int nTurnOn)
{
    bool bInBack = isInBackground();

    // set the auto close screen and auto key lock status

    do
    {
        // if the app have be in background,don't handle this message
        CC_BREAK_IF(bInBack);

        if (! nTurnOn)  // turn off screen
        {
            if (! m_bEnterBackgroundCalled)
            {
                applicationDidEnterBackground();
                m_bEnterBackgroundCalled = true;
            }
            StopMainLoop();
        }
        else
        {
            // modify back light open mode
            // Why doesn't use CfgTurnOnBackLightEx(SYS_BACK_LIGHT_MODE_TIME_ALWAYS)?
            // MODE_TIME_ALWAYS cause phone can't sleep when power button pressed.
            CfgTurnOnBackLightDelay(0x7fffffff);
            CCLOG("AppActiveNotify::TurnOnBackLight:0x7fffffff");

            if (m_bEnterBackgroundCalled)
            {
                applicationWillEnterForeground();
                m_bEnterBackgroundCalled = false;
            }
            StartMainLoop();
        }
    } while (0);
}

bool CCApplication::isInBackground()
{
    return m_bInBackground;
}

void CCApplication::StartMainLoop()
{
    m_bNeedStop = FALSE;
    if (m_bRunning)
    {
        return;
    }
    CCLOG("Post StartMainLoop");
    Sys_PostMessage2(MESSAGE_PRIOR_LOWEST, &m_tMsg);
}

void CCApplication::StopMainLoop()
{
    m_bNeedStop = TRUE;
}

Int32 CCApplication::_OnAppIdle(MESSAGE_t * pMsg, UInt32 uData)
{
    CCApplication& rThis = (CCApplication&) CCApplication::sharedApplication();
    CCEGLView *     pView = CCDirector::sharedDirector()->getOpenGLView();
    if (pView)
    {
        if (rThis.m_bNeedStop)
        {
            CCLOG("_OnAppIdle: Stop");
            rThis.m_bNeedStop = FALSE;
            rThis.m_bRunning  = FALSE;
        }
        else
        {
            rThis.m_bRunning  = TRUE;
#ifdef _TRANZDA_VM_
            LARGE_INTEGER nNow;
            QueryPerformanceCounter(&nNow);
            if (nNow.QuadPart - s_nLast.QuadPart >= s_nAnimationInterval.QuadPart)
            {
                pView->UpdateWindow(0);
                s_nLast.QuadPart = nNow.QuadPart;
            }
#else
            long long nNow = getTimeOfDayMicroSecond();
            if (nNow - s_nLast >= s_nAnimationInterval)
            {
                pView->UpdateWindow(0);
                s_nLast = nNow;
            }
#endif
            else
            {
                Sys_SchedYield();
            }
            Sys_PostMessage2(MESSAGE_PRIOR_LOWEST, &rThis.m_tMsg);
        }
    }
    return 1;
}

//////////////////////////////////////////////////////////////////////////
// static member function
//////////////////////////////////////////////////////////////////////////

// shared application
CCApplication * CCApplication::sm_pSharedApplication = 0;

CCApplication& CCApplication::sharedApplication()
{
    CC_ASSERT(sm_pSharedApplication);
    return *sm_pSharedApplication;
}

ccLanguageType CCApplication::getCurrentLanguage()
{
    return kLanguageChinese;
}

// rotate device support
static const CCApplication::Orientation s_OrientationModeNormal[] =
{
    CCApplication::kOrientationPortrait,
    CCApplication::kOrientationPortraitUpsideDown,
    CCApplication::kOrientationLandscapeLeft,
    CCApplication::kOrientationLandscapeRight,
};

static const CCApplication::Orientation s_OrientationModeCW[] =
{
    CCApplication::kOrientationLandscapeLeft,
    CCApplication::kOrientationLandscapeRight,
    CCApplication::kOrientationPortraitUpsideDown,
    CCApplication::kOrientationPortrait,
};

static const CCApplication::Orientation s_OrientationModeUD[] =
{
    CCApplication::kOrientationPortraitUpsideDown,
    CCApplication::kOrientationPortrait,
    CCApplication::kOrientationLandscapeRight,
    CCApplication::kOrientationLandscapeLeft,
};

static const CCApplication::Orientation s_OrientationModeCCW[] =
{
    CCApplication::kOrientationLandscapeRight,
    CCApplication::kOrientationLandscapeLeft,
    CCApplication::kOrientationPortrait,
    CCApplication::kOrientationPortraitUpsideDown,
};

const CCApplication::Orientation * const CCApplication::sm_OrientationTable[] =
{
    s_OrientationModeNormal,
    s_OrientationModeCW,
    s_OrientationModeUD,
    s_OrientationModeCCW,
};

UInt32 CCApplication::sm_uDesignOrientation = WM_WINDOW_ROTATE_MODE_NORMAL;

void  CCApplication::setDesignOrientation(UInt32 uOrientation)
{
    sm_uDesignOrientation = uOrientation;
}

UInt32 CCApplication::getDesignOrientation()
{
    return sm_uDesignOrientation;
}

NS_CC_END;


code:
#ifndef  __CC_APPLICATION_WOPHONE_H__
#define  __CC_APPLICATION_WOPHONE_H__

#include "TG3.h"
#include "CCDirector.h"
#include "CCCommon.h"

NS_CC_BEGIN;

class CC_DLL CCApplication : public  TApplication
{
public:
    CCApplication();
    virtual ~CCApplication();

    virtual Boolean EventHandler(EventType * pEvent);

public:
    /**
    @brief	Implement for initialize OpenGL instance, set source path, etc...
    */
    virtual bool initInstance() = 0;

    /**
    @brief	Implement 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() = 0;

    /**
    @brief  The function be called when the application enter foreground
    @param  the pointer of the application
    */
    virtual void applicationWillEnterForeground() = 0;

    /**
    @brief	Callback by CCDirector for limit FPS.
    @interval       The time, which expressed in second in second, between current frame and next.
    */
    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);

    /**
    @brief	Get status bar rectangle in EGLView window.
    */
    void    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();

    /**
    @brief Get the data path of the Application.
    @return If the app is installed,the return value is the "Const" path of the application,
    else the return value is "/NEWPLUS/TG3/ConstData/"
    */
    const char* getAppDataPath();

    /**
    @brief Get the writable path for the Application.
    @return If the app is installed,the return value is the "Data" path of the application.
    else the return value is "/NEWPLUS/TG3/TDA_DATA/Data/Data/"
    */
    const char* getAppWritablePath();

    void switchNotify(int nTurnOn);

    /**
    @brief	Wophone hasn't support window rotate orientation with EGL, so use orientation table instead.
    */
    static void  setDesignOrientation(UInt32 uOrientation);
    static UInt32 getDesignOrientation();

protected:
    bool isInBackground();
    void StartMainLoop();
    void StopMainLoop();

protected:
    static Int32 _OnAppIdle(MESSAGE_t * pMsg, UInt32 uData);

    MESSAGE_t   m_tMsg;
    bool        m_bRunning;
    bool        m_bNeedStop;
    bool        m_bInBackground;
    bool        m_bEnterBackgroundCalled;
    char        m_AppDataPath[EOS_FILE_MAX_PATH];
    char        m_AppWritablePath[EOS_FILE_MAX_PATH];

    static CCApplication *  sm_pSharedApplication;
    static UInt32           sm_uDesignOrientation;
    static const Orientation * const sm_OrientationTable[];
};

NS_CC_END;

#endif // __CC_APPLICATION_WOPHONE_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 "TG3.h"
#include "ssBackLightControl.h"

#include "EGL/egl.h"
#include "GLES/gl.h"

#include "CCSet.h"
#include "CCDirector.h"
#include "CCTouch.h"
#include "CCTouchDispatcher.h"

#include "TCOM_Sensors_Interface.h"
#include "CCAccelerometer.h"
#include "CCKeypadDispatcher.h"
#include "CCIMEDispatcher.h"

#include "CCApplication.h"
#include "ccMacros.h"

namespace cocos2d {

class CCEGL
{
public:
	~CCEGL()
	{
		if (EGL_NO_DISPLAY == m_eglDisplay)
		{
			return;
		}

		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(TWindow * pWindow)
	{
		CCEGL * pEGL = new CCEGL;
		Boolean bSuccess = FALSE;
		do
		{
			CC_BREAK_IF(! pEGL);

			TUChar szError[] = {'E','R','R','O','R',0};
			TUChar szEglInitFailed[] = {'e','g','l','I','n','i','t','i','a','l','i','z','e',' ','f','a','i','l','e','d',0};
			TUChar szCreateContextFailed[] = {'e','g','l','C','r','e','a','t','e','C','o','n','t','e','x','t',' ','f','a','i','l','e','d',0};
			TUChar szEglCreateWindowSurfaceFailed[] = {'e','g','l','C','r','e','a','t','e','W','i','n','d','o','w','S','u','r','f','a','c','e',' ','f','a','i','l','e','d',0};
			TUChar szEglMakeCurrentFailed[] = {'e','g','l','M','a','k','e','C','u','r','r','e','n','t',' ','f','a','i','l','e','d',0};

			pEGL->m_eglNativeWindow = pWindow;

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

			EGLint nMajor, nMinor;
			EGLBoolean bEglRet;

			bEglRet = eglInitialize(eglDisplay, &nMajor, &nMinor);
			if ( EGL_FALSE == bEglRet || 1 != nMajor )
			{
				TApplication::GetCurrentApplication()->MessageBox(szEglInitFailed, szError, WMB_OK);
				break;
			}

			const EGLint aConfigAttribs[] =
			{
				EGL_LEVEL,				0,
				EGL_SURFACE_TYPE,		EGL_WINDOW_BIT,
				EGL_RENDERABLE_TYPE,	EGL_OPENGL_ES2_BIT,
				EGL_NATIVE_RENDERABLE,	EGL_FALSE,
				EGL_DEPTH_SIZE,			16,
				EGL_NONE,
			};
			EGLint iConfigs;
			EGLConfig eglConfig;
			CC_BREAK_IF( EGL_FALSE == eglChooseConfig(eglDisplay, aConfigAttribs, &eglConfig, 1, &iConfigs) ||
						  (iConfigs != 1) );

			EGLContext eglContext = eglCreateContext(eglDisplay, eglConfig, NULL, NULL);
			if (EGL_NO_CONTEXT == eglContext)
			{
				TApplication::GetCurrentApplication()->MessageBox(szCreateContextFailed, szError, WMB_OK);
				break;
			}

			EGLSurface eglSurface;
			eglSurface = eglCreateWindowSurface(eglDisplay, eglConfig, pEGL->m_eglNativeWindow, NULL);
			if (EGL_NO_SURFACE == eglSurface)
			{
				TApplication::GetCurrentApplication()->MessageBox(szEglCreateWindowSurfaceFailed, szError, WMB_OK);
				break;
			}

			bEglRet = eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext);
			if (EGL_FALSE == bEglRet)
			{
				TApplication::GetCurrentApplication()->MessageBox(szEglMakeCurrentFailed, szError, WMB_OK);
				break;
			}

			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_eglWnd || 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_eglWnd, 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;
};

// We add a space character in the TEdit box.
// If not do like this, once the IME closed, the chars inputted will can't be deleted.
static const TUChar s_BaseStr[] = { ' ', '\0'};

class CCInputView : public TWindow
{
public:
    CCInputView(TApplication * pApp)
    : TWindow(pApp)
    , m_pTextField(NULL)
    , m_nTextLen(1)
    {
    }

    virtual Boolean EventHandler(TApplication * pApp, EventType * pEvent)
    {
        Boolean bRet = FALSE;
        switch (pEvent->eType)
        {
        case EVENT_WinInit:
            do
            {
                m_pTextField = new TEdit;
                CC_BREAK_IF(! m_pTextField);

                if (! m_pTextField->Create(this))
                {
                    delete m_pTextField;
                    m_pTextField = 0;
                    break;
                }

                // add a space character into the TEdit and update the insert point
                m_pTextField->SetCaption(s_BaseStr, FALSE);
                m_pTextField->SetInsertPoint(1);

                this->SetWindowMovieMode(TG3_WINDOW_MOVIE_MODE_NONE, TG3_WINDOW_MOVIE_MODE_NONE);

                m_pTextField->SetFocusStatus(TRUE);

                TRectangle rcTextField(0, 0, 1, 1);
                m_pTextField->SetBounds(&rcTextField);
                ImeOpenIme(IME_MODE_STATIC, IME_CLASS_UNDEFINED);
                bRet = TRUE;
            } while (0);
            break;

        case EVENT_WinClose:
            ImeCloseIme();
            break;

        case EVENT_WinImeStatusNotify:
            {
                EosImeNotifyEventType * pNotify = (EosImeNotifyEventType*)pEvent;
                if (IME_NOTIFY_TYPE_KEYBOARD_SIZE == pNotify->notifyType)
                {
                    RectangleType rcKbd = pNotify->rtKeyboard;

                    // let text field out of window
                    TRectangle rcTextField(
                        rcKbd.topLeft.X + rcKbd.extent.X,
                        rcKbd.topLeft.Y + rcKbd.extent.Y,
                        rcKbd.extent.X, rcKbd.extent.Y);
                    m_pTextField->SetBounds(&rcTextField);

                    // let input view rectangle same as keyboard
                    TRectangle rcWnd(rcKbd);
                    this->SetBounds(&rcWnd);

                    // calculate the keyboard coordination in EGLView.
                    Int32 nScrWidth = TApplication::GetCurrentApplication()->GetScreenWidth();
                    Int32 nScrHeight = TApplication::GetCurrentApplication()->GetScreenHeight();

                    //keyboard open
                    m_rcBegin = CCRectMake((float)0
                        , (float)0 - rcKbd.extent.Y
                        , (float)rcKbd.extent.X
                        , (float)rcKbd.extent.Y);
                    m_rcEnd = CCRectMake((float)0
                        , (float)0
                        , (float)rcKbd.extent.X
                        , (float)rcKbd.extent.Y);

                    CCIMEKeyboardNotificationInfo info;
                    info.begin = m_rcBegin;
                    info.end = m_rcEnd;
                    info.duration = 0;
                    CCIMEDispatcher::sharedDispatcher()->dispatchKeyboardWillShow(info);
                    CCIMEDispatcher::sharedDispatcher()->dispatchKeyboardDidShow(info);
                }
                else if (IME_NOTIFY_TYPE_IME_CLOSE == pNotify->notifyType)
                {
                    CCIMEKeyboardNotificationInfo info;
                    info.begin = m_rcEnd;
                    info.end = m_rcBegin;
                    info.duration = 0;
                    CCIMEDispatcher::sharedDispatcher()->dispatchKeyboardWillHide(info);
                    CCIMEDispatcher::sharedDispatcher()->dispatchKeyboardDidHide(info);
                }
            }
            break;

        case EVENT_FieldChanged:
            do
            {
                CC_BREAK_IF(pEvent->sParam1 != m_pTextField->GetId());

                const TUChar * ptszText = m_pTextField->GetCaption();
                CC_BREAK_IF(! ptszText);

                int nLen = TUString::StrLen(ptszText);
                if (nLen > m_nTextLen)
                {
                    char szText[MAX_PATH] = {0};
                    CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(szText
                        , TUString::StrUnicodeToStrUtf8((Char *)szText, ptszText + m_nTextLen));
                    m_nTextLen = nLen;
                }
                else if (nLen < m_nTextLen)
                {
                    for (int i = m_nTextLen - nLen; i > 0; --i)
                    {
                        CCIMEDispatcher::sharedDispatcher()->dispatchDeleteBackward();
                    }
                    m_nTextLen = nLen;
                }
                else
                {
                    const char * pszReturn = "\n";
                    CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(pszReturn, 1);
                }

                if (0 == nLen)
                {
                    // add a space character into the TEdit and update the insert point
                    m_pTextField->SetCaption(s_BaseStr, FALSE);
                    m_pTextField->SetInsertPoint(1);
                    m_nTextLen = 1;
                }
            } while (0);
            break;

        case EVENT_PenDown:
        case EVENT_PenMove:
        case EVENT_PenUp:
            // if input view doesn't process the pen event,
            // means the pen event out of input view,
            // let CCEGLView process
            if (! TWindow::EventHandler(pApp, pEvent))
            {
                CCEGLView::sharedOpenGLView().EventHandler(pApp, pEvent);
                bRet = TRUE;
            }
            break;
        }

        if (! bRet)
        {
            return TWindow::EventHandler(pApp, pEvent);
        }
        return bRet;
    }

private:
    TEdit *             m_pTextField;
    int                 m_nTextLen;
    CCRect              m_rcBegin;
    CCRect              m_rcEnd;
};

//////////////////////////////////////////////////////////////////////////
// implement CCEGLView
//////////////////////////////////////////////////////////////////////////

static CCEGLView* s_pMainWindow = NULL;

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

CCEGLView::CCEGLView(TApplication * pApp)
: TWindow(pApp)
, m_pDelegate(NULL)
, m_pEGL(NULL)
, m_fScreenScaleFactor(1.0f)
, m_pInputView(0)
{
}

CCEGLView::~CCEGLView()
{
    CC_SAFE_DELETE(m_pDelegate);
    CC_SAFE_DELETE(m_pEGL);
}

Boolean CCEGLView::Create(int nWidthInPoints, int nHeightInPoints, UInt32 eRotateMode)
{
    // record the window size in points
    m_tSizeInPoints.SetWidth(nWidthInPoints);
    m_tSizeInPoints.SetHeight(nHeightInPoints);

    // get the screen size
    TApplication* pApp = TApplication::GetCurrentApplication();
    Int32 nWidth  = pApp->GetScreenWidth();
    Int32 nHeight = pApp->GetScreenHeight();

    // calculate the factor and the rect of view port
    m_fScreenScaleFactor =  MIN((float)nWidth / nWidthInPoints, (float)nHeight / nHeightInPoints);
    int viewPortW = (int)(m_tSizeInPoints.Width() * m_fScreenScaleFactor);
    int viewPortH = (int)(m_tSizeInPoints.Height() * m_fScreenScaleFactor);
    m_rcViewPort.SetX((nWidth - viewPortW) / 2);
    m_rcViewPort.SetY((nHeight - viewPortH) / 2);
    m_rcViewPort.SetWidth(viewPortW);
    m_rcViewPort.SetHeight(viewPortH);

    Boolean bRet = TWindow::Create(&TRectangle(0, 0, nWidth, nHeight));

    if (bRet)
    {
        s_pMainWindow = this;
        if (WM_WINDOW_ROTATE_MODE_NORMAL != eRotateMode)
        {
            CCApplication::setDesignOrientation(eRotateMode);
            CCDirector::sharedDirector()->setDeviceOrientation(CCDeviceOrientationPortrait);
        }
    }

    return bRet;
}

Boolean CCEGLView::AfterCreate(void)
{
    return (m_pEGL = CCEGL::create(this)) ? TRUE : FALSE;
}

Boolean CCEGLView::EventHandler(TApplication * pApp, EventType * pEvent)
{
    Boolean bHandled = FALSE;

    switch(pEvent->eType)
    {
    case EVENT_WinInit:
        CfgRegisterScreenSwitchNotify(GetWindowHwndId(), 0);
        bHandled = TRUE;
        break;

    case EVENT_WinPaint:
        if (CfgGetScreenStatus())
        {
            // draw
            CCDirector::sharedDirector()->mainLoop();
        }
        bHandled = TRUE;
        break;

    case EVENT_PenDown:
        bHandled = onPenDown(pEvent, 0);
        break;

    case EVENT_PenMove:
        bHandled = onPenMove(pEvent);
        break;

    case EVENT_PenUp:
        bHandled = onPenUp(pEvent, 0);
        break;

    case EVENT_MultiTouchDown:
        bHandled = onPenDown(pEvent, pEvent->lParam3);
        break;

    case EVENT_MultiTouchUp:
        bHandled = onPenUp(pEvent, pEvent->lParam3);
        break;

    case EVENT_KeyCommand:
        {
            if (pEvent->sParam1 == SYS_KEY_SOFTKEY_RIGHT_UP ||
                pEvent->sParam1 == SYS_KEY_SOFTKEY_RIGHT_LONG)
            {
                bHandled = CCKeypadDispatcher::sharedDispatcher()->dispatchKeypadMSG(kTypeBackClicked);
            }
            else if (pEvent->sParam1 == KEY_COMMAND_MAINMENU)
            {
                bHandled = CCKeypadDispatcher::sharedDispatcher()->dispatchKeypadMSG(kTypeMenuClicked);
            }
        }
        break;

    case MESSAGE_SENSORS_DATA:
        {
            TG3SensorsDataType	data;

            if (Sys_GetMessageBody((MESSAGE_t *)pEvent, &data, sizeof(TG3SensorsDataType)) == sizeof(TG3SensorsDataType) &&
                TG3_SENSOR_TYPE_ACCELEROMETER == data.sensorMask)
            {
                // convert the data to iphone format
                CCAcceleration AccValue;
                AccValue.x = -(data.acceleration.x / TG3_GRAVITY_EARTH);
                AccValue.y = -(data.acceleration.y / TG3_GRAVITY_EARTH);
                AccValue.z = -(data.acceleration.z / TG3_GRAVITY_EARTH);
                AccValue.timestamp = (double) TimGetTicks() / 100;

                // call delegates' didAccelerate function
                CCAccelerometer::sharedAccelerometer()->didAccelerate(&AccValue);
                bHandled = TRUE;
            }
        }
        break;

    case EVENT_WinClose:
        CfgUnRegisterScreenSwitchNotify(GetWindowHwndId(), 0);
        // Stop the application since the main form has been closed
        pApp->SendStopEvent();
        break;

    case EVENT_ScreenSwitchNotify:
        {
            CCApplication::sharedApplication().switchNotify(pEvent->sParam1);
            break;
        }

    }

    if (! bHandled)
    {
        return TWindow::EventHandler(pApp, pEvent);
    }
    return bHandled;
}

Boolean CCEGLView::onPenDown(EventType* pEvent, Int32 nIndex)
{
    if (m_pDelegate && nIndex < MAX_TOUCHES)
    {
        CCTouch* pTouch = s_pTouches[nIndex];
        if (!pTouch)
        {
            pTouch = new CCTouch;
        }

        pTouch->SetTouchInfo(0, (float)(pEvent->sParam1 - m_rcViewPort.X()) / m_fScreenScaleFactor,
                             (float)(pEvent->sParam2 - m_rcViewPort.Y()) / m_fScreenScaleFactor);
        s_pTouches[nIndex] = pTouch;
        CCSet set;
        set.addObject(pTouch);
        m_pDelegate->touchesBegan(&set, NULL);
    }

    return FALSE;
}

Boolean CCEGLView::onPenUp(EventType* pEvent, Int32 nIndex)
{
    if (m_pDelegate && nIndex < MAX_TOUCHES)
    {
        CCTouch* pTouch = s_pTouches[nIndex];
        if (pTouch)
        {
            CCSet set;
            pTouch->SetTouchInfo(0, (float)(pEvent->sParam1 - m_rcViewPort.X()) / m_fScreenScaleFactor,
                                 (float)(pEvent->sParam2 - m_rcViewPort.Y()) / m_fScreenScaleFactor);
            set.addObject(pTouch);
            m_pDelegate->touchesEnded(&set, NULL);

            pTouch->release();
            for (Int32 i = nIndex; i < MAX_TOUCHES; ++i)
            {
                if (i != (MAX_TOUCHES - 1))
                {
                    s_pTouches[i] = s_pTouches[i + 1];
                }
                else
                {
                    s_pTouches[i] = NULL;
                }
            }
        }
    }

    return FALSE;
}

Boolean CCEGLView::onPenMove(EventType* pEvent)
{
    do
    {
        CC_BREAK_IF(!m_pDelegate);

        Int32 nCount = EvtGetPenMultiPointCount(pEvent);
        CC_BREAK_IF(nCount <= 0 || nCount > MAX_TOUCHES);

        CCSet set;
        Int32 nPosX, nPosY;
        for (Int32 i = 0; i < nCount; ++i)
        {
            CCTouch* pTouch = s_pTouches[i];
            CC_BREAK_IF(!pTouch);

            EvtGetPenMultiPointXY(pEvent, i, &nPosX, &nPosY);
            pTouch->SetTouchInfo(0, (float) (nPosX - m_rcViewPort.X()) / m_fScreenScaleFactor,
                                 (float) (nPosY - m_rcViewPort.Y()) / m_fScreenScaleFactor);
            set.addObject(pTouch);
        }

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

    return FALSE;
}

CCSize CCEGLView::getSize()
{
    return CCSize((float)m_tSizeInPoints.Width(), (float)m_tSizeInPoints.Height());
}

CCRect CCEGLView::getFrame()
{
	TRectangle rc;
	GetClientBounds(&rc);
	return (CCRect((float)rc.X(), (float)rc.Y(), (float)rc.Width(), (float)rc.Height()));
}

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

void CCEGLView::release()
{
    CloseWindow();
}

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)
{
	// if it supports scaling content, set it
    m_fScreenScaleFactor = contentScaleFactor;
}

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

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

void CCEGLView::setIMEKeyboardState(bool bOpen)
{
    do
    {
        // if input view opened, close it first
        if (m_pInputView)
        {
            m_pInputView->CloseWindow();
            m_pInputView = 0;
        }

        CC_BREAK_IF(! bOpen);

        // open input view
        m_pInputView = new CCInputView(TApplication::GetCurrentApplication());
        CC_BREAK_IF(! m_pInputView);

        TRectangle rcInputView(0, 0, 1, 1);
        if (! m_pInputView->Create(&rcInputView))
        {
            delete m_pInputView;
            m_pInputView = 0;
            break;
        }

        UInt32 eOritation = CCApplication::getDesignOrientation();

        if (WM_WINDOW_ROTATE_MODE_NORMAL != eOritation)
        {
            m_pInputView->RotateWindow(eOritation);
        }
    } while (0);
}

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

}       // end of namespace cocos2d


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_EGLVIEW_WOPHONE_H__
#define __CC_EGLVIEW_WOPHONE_H__

#include "GuiBase.h"
#include "TWindow.h"

#include "CCGeometry.h"
#include "TG3.h"

class TApplication;

namespace   cocos2d {
class CCSet;
class CCTouch;
class EGLTouchDelegate;

class CCEGL;

class CC_DLL CCEGLView : public TWindow
{
public:

    CCEGLView(TApplication * pApp);
    virtual ~CCEGLView();

    virtual Boolean Create(int nWidthInPoints, int nHeightInPoints, UInt32 eRotateMode = WM_WINDOW_ROTATE_MODE_NORMAL);
    virtual Boolean AfterCreate(void);
    virtual Boolean EventHandler(TApplication * pApp, EventType * pEvent);

	CCRect  getFrame();
    CCSize  getSize();
    bool    isOpenGLReady();
    void    release();
    void    setTouchDelegate(EGLTouchDelegate * pDelegate);
    void    swapBuffers();
	bool    canSetContentScaleFactor();
	void    setContentScaleFactor(float contentScaleFactor);
	void    setAnimationInterval(double interval) {};
    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();

protected:
    Boolean onPenDown(EventType* pEvent, Int32 nIndex);
    Boolean onPenUp(EventType* pEvent, Int32 nIndex);
    Boolean onPenMove(EventType* pEvent);

private:

    MESSAGE_t m_tMsg;
    CCEGL *            m_pEGL;
    EGLTouchDelegate *  m_pDelegate;

    TSize               m_tSizeInPoints;
    float               m_fScreenScaleFactor;
    TRectangle          m_rcViewPort;
    TWindow *           m_pInputView;
};

}   // end of namespace   cocos2d

#endif	// end of __CC_EGLVIEW_WOPHONE_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 <TG3.h>
#include "CCApplication.h"

#include <string>

using namespace std;

NS_CC_BEGIN;

// record the resource path
static char s_pszResourcePath[EOS_FILE_MAX_PATH] = {0};
static char s_pszZipFilePath[EOS_FILE_MAX_PATH]  = {0};

bool isResourceExist(const char* pszResName)
{
    bool bRet = false;

    TUChar FilePath[EOS_FILE_MAX_PATH] = {0};
    TUString::StrGBToUnicode(FilePath, (const Char *) pszResName);

    if (strlen(s_pszZipFilePath) != 0)
    {
        // if have set the zip file path,find the resource in the zip file
        unzFile pZipFile = unzOpen(s_pszZipFilePath);
        do
        {
            CC_BREAK_IF(!pZipFile);

            Int32 nPos = unzLocateFile(pZipFile, pszResName, 1);
            CC_BREAK_IF(nPos != UNZ_OK);

            bRet = true;

        } while (0);
        if (pZipFile)
        {
            unzClose(pZipFile);
        }
    }
    else
    {
        // find in the hardware
        if (EOS_IsFileExist(FilePath))
        {
            bRet = true;
        }
    }

    return bRet;
}

const char* getDiffResolutionPath(const char *pszPath)
{
    CCString *pRet = new CCString(pszPath);
    pRet->autorelease();

    do
    {
        TApplication* pApp = TApplication::GetCurrentApplication();
        CC_BREAK_IF(!pApp);

        // get the Resolution
        int nScreenWidth  = pApp->GetScreenWidth();
        int nScreenHeight = pApp->GetScreenHeight();

        // it's default resolution, do nothing
        CC_BREAK_IF(nScreenWidth == 320 && nScreenHeight == 480);

        if (nScreenWidth == 480 && nScreenHeight == 800)
        {
            // it's WVGA
            CC_BREAK_IF(pRet->m_sString.find("@WVGA") != -1);

            std::string filePathWithoutExtension = pszPath;
            std::string extension = "";
            std::string filePath = pszPath;
            int nExPos = filePath.find_last_of(".");

            if (nExPos != -1)
            {
                filePathWithoutExtension = filePath.substr(0, nExPos);
                extension = filePath.substr(nExPos);
            }

            // new path, add "@WVGA" before the extension
            pRet->m_sString = filePathWithoutExtension + "@WVGA" + extension;

            // not find the resource of new path,use the original path
            if (! isResourceExist(pRet->m_sString.c_str()))
            {
                pRet->m_sString = filePath;
            }
        }
        else
        {
            // not support resolution
            CCAssert(0, "it's not supportted resolution.");
        }
    } while (0);

    return pRet->m_sString.c_str();
}

void CCFileUtils::setResource(const char* pZipFileName)
{
    CCAssert(pZipFileName != NULL, "[FileUtils setResourceZipFile] -- wrong zip file path");

    // get the full path of zip file
    char fullPath[EOS_FILE_MAX_PATH] = {0};
    if (strlen(s_pszResourcePath))
    {
        strcpy(fullPath, s_pszResourcePath);
    }
    else
    {
        const char* pAppDataPath = CCApplication::sharedApplication().getAppDataPath();
        strcpy(fullPath, pAppDataPath);
    }
    strcat(fullPath, pZipFileName);

    // if the zip file not exist,use message box to warn developer
    TUChar pszTmp[EOS_FILE_MAX_PATH] = {0};
    TUString::StrGBToUnicode(pszTmp, (const Char*) fullPath);
    Boolean bExist = EOS_IsFileExist(pszTmp);
    if (!bExist)
    {
        std::string strErr = "zip file ";
        strErr += fullPath;
        strErr += " not exist!";
        CCMessageBox(strErr.c_str(), "Error");
        return;
    }

    // clear the zip file path recorded before and record the new path
    memset(s_pszZipFilePath, 0, sizeof(char) * EOS_FILE_MAX_PATH);
    strcpy(s_pszZipFilePath, fullPath);
}

const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath)
{
    // if have set the zip file path,return the relative path of zip file
    if (strlen(s_pszZipFilePath) != 0)
    {
        return getDiffResolutionPath(pszRelativePath);
    }

    // get the user data path and append relative path to it
    if (strlen(s_pszResourcePath) == 0)
    {
        const char* pAppDataPath = CCApplication::sharedApplication().getAppDataPath();
        strcpy(s_pszResourcePath, pAppDataPath);
    }

    CCString * pRet = new CCString();
    pRet->autorelease();
    if ((strlen(pszRelativePath) > 1 && pszRelativePath[1] == ':') ||
        (strlen(pszRelativePath) > 0 && pszRelativePath[0] == '/'))
    {
        pRet->m_sString = pszRelativePath;
    }
    else
    {
        pRet->m_sString = s_pszResourcePath;
        pRet->m_sString += pszRelativePath;
    }
    return getDiffResolutionPath(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 getDiffResolutionPath(pRet->m_sString.c_str());
}

unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize)
{
    unsigned char * pBuffer = NULL;

    do
    {
        if (0 != s_pszZipFilePath[0])
        {
            // if specify the zip file,load from it first
            pBuffer = getFileDataFromZip(s_pszZipFilePath, pszFileName, pSize);
            CC_BREAK_IF(pBuffer);
        }

        // read the file from hardware
        FILE *fp = fopen(pszFileName, pszMode);
        CC_BREAK_IF(!fp);

        fseek(fp,0,SEEK_END);
        *pSize = ftell(fp);
        fseek(fp,0,SEEK_SET);
        pBuffer = new unsigned char[*pSize];
        *pSize = fread(pBuffer,sizeof(unsigned char), *pSize,fp);
        fclose(fp);
    } while (0);

    if (! pBuffer && getIsPopupNotify())
    {
        std::string title = "Notification";
        std::string msg = "Get data from file(";
        msg.append(pszFileName);
        if (0 != s_pszZipFilePath[0])
        {
            msg.append(") in zip archive(").append(s_pszZipFilePath);
        }
        msg.append(") failed!");

        CCMessageBox(msg.c_str(), title.c_str());
    }

    return pBuffer;
}

void CCFileUtils::setResourcePath(const char *pszResourcePath)
{
    CCAssert(0, "Have not implement!");
}

string CCFileUtils::getWriteablePath()
{
	return string(CCApplication::sharedApplication().getAppWritablePath());
}

NS_CC_END;