code:
#ifndef __CC_APPLICATION_QNX_H__
#define __CC_APPLICATION_QNX_H__

#include "CCApplication.h"

#include "CCCommon.h"

NS_CC_BEGIN;

class CCRect;

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

    /**
    @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	Run the message loop.
    */
    int run();

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

protected:
    static CCApplication * sm_pSharedApplication;

private:

    static long	m_animationInterval;
};

NS_CC_END;

#endif	// __CCX_APPLICATION_QNX_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_qnx.h"
#include "GLES/gl.h"

#include <ctype.h>
#include <input/screen_helpers.h>
#include <sys/keycodes.h>

#include <bps/bps.h>
#include <bps/event.h>
#include <bps/screen.h>
#include <bps/navigator.h>
#include <bps/orientation.h>
#include <bps/virtualkeyboard.h>

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

using namespace std;

namespace cocos2d {

bool CCEGLView::m_initializedFunctions = false;
const GLubyte *CCEGLView::m_extensions = 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;

enum Orientation
{
	PORTRAIT,
	LANDSCAPE,
	AUTO
};

static Orientation orientation = LANDSCAPE;

static struct {
	EGLint surface_type;
	EGLint red_size;
	EGLint green_size;
	EGLint blue_size;
	EGLint alpha_size;
	EGLint samples;
	EGLint config_id;
} the_configAttr;

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

CCEGLView::CCEGLView()
: m_pDelegate(NULL), m_pEventHandler(NULL),
  m_fScreenScaleFactor(1.0),
  m_bNotHVGA(false),
  m_isWindowActive(false)
{
	s_pInstance = this;
	m_eglDisplay = EGL_NO_DISPLAY;
	m_eglContext = EGL_NO_CONTEXT;
	m_eglSurface = EGL_NO_SURFACE;
    m_screenEvent = 0;
    m_screenWindow = 0;

    strcpy(m_window_group_id, "");
    snprintf(m_window_group_id, sizeof(m_window_group_id), "%d", getpid());
    bps_initialize();
    navigator_request_events(0);

    navigator_rotation_lock(true);

    the_configAttr.surface_type = EGL_WINDOW_BIT;
    the_configAttr.red_size 	= EGL_DONT_CARE;
    the_configAttr.green_size 	= EGL_DONT_CARE;
	the_configAttr.blue_size 	= EGL_DONT_CARE;
	the_configAttr.alpha_size 	= EGL_DONT_CARE;
	the_configAttr.samples 		= EGL_DONT_CARE;
	the_configAttr.config_id 	= EGL_DONT_CARE;

    m_isGLInitialized = initGL();

    if (m_isGLInitialized)
    	initEGLFunctions();
}

CCEGLView::~CCEGLView()
{
	release();

	CC_SAFE_DELETE(m_pDelegate);
}

void CCEGLView::initEGLFunctions()
{
	m_extensions = glGetString(GL_EXTENSIONS);

	glGenerateMipmapOES = 0;
	glGenFramebuffersOES = 0;
	glBindFramebufferOES = 0;
	glFramebufferTexture2DOES = 0;
	glDeleteFramebuffersOES = 0;
	glCheckFramebufferStatusOES = 0;

	if (isGLExtension("GL_OES_framebuffer_object"))
	{
		glGenerateMipmapOES = (PFNGLGENERATEMIPMAPOESPROC)eglGetProcAddress("glGenerateMipmapOES");
		glGenFramebuffersOES = (PFNGLGENFRAMEBUFFERSOESPROC)eglGetProcAddress("glGenFramebuffersOES");
		glBindFramebufferOES = (PFNGLBINDFRAMEBUFFEROESPROC)eglGetProcAddress("glBindFramebufferOES");
		glFramebufferTexture2DOES = (PFNGLFRAMEBUFFERTEXTURE2DOESPROC)eglGetProcAddress("glFramebufferTexture2DOES");
		glDeleteFramebuffersOES = (PFNGLDELETEFRAMEBUFFERSOESPROC)eglGetProcAddress("glDeleteFramebuffersOES");
		glCheckFramebufferStatusOES = (PFNGLCHECKFRAMEBUFFERSTATUSOESPROC)eglGetProcAddress("glCheckFramebufferStatusOES");
	}

	m_initializedFunctions = true;
}

void CCEGLView::setFrameWidthAndHeight(int width, int height)
{
	m_sSizeInPixel.width = width;
	m_sSizeInPixel.height = height;
}

bool CCEGLView::Create(int width, int height)
{
	if (width == 0 || height == 0)
	{
		return false;
	}

	m_sSizeInPoint.width = width;
	m_sSizeInPoint.height = 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);

	int viewPortW = (int)(m_sSizeInPoint.width * m_fScreenScaleFactor);
	int viewPortH = (int)(m_sSizeInPoint.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;

	m_bNotHVGA = true;

	return true;
}

EGLConfig CCEGLView::chooseConfig(const EGLDisplay &eglDisplay, const char* str)
{
	EGLConfig   config = (EGLConfig)0;
	EGLConfig  *configurations;
	EGLint      egl_num_configs;
	EGLint      val;
	EGLBoolean  rc;
	const char *tok;
	EGLint      i;

	if (str != NULL)
	{
		tok = str;
		while (*tok == ' ' || *tok == ',')
			tok++;

		while (*tok != '\0')
		{
			if (strncmp(tok, "rgba8888", strlen("rgba8888")) == 0)
			{
				the_configAttr.red_size   = 8;
				the_configAttr.green_size = 8;
				the_configAttr.blue_size  = 8;
				the_configAttr.alpha_size = 8;
				tok += strlen("rgba8888");
			}
			else if (strncmp(tok, "rgba5551", strlen("rgba5551")) == 0)
			{
				the_configAttr.red_size   = 5;
				the_configAttr.green_size = 5;
				the_configAttr.blue_size  = 5;
				the_configAttr.alpha_size = 1;
				tok += strlen("rgba5551");
			}
			else if (strncmp(tok, "rgba4444", strlen("rgba4444")) == 0)
			{
				the_configAttr.red_size   = 4;
				the_configAttr.green_size = 4;
				the_configAttr.blue_size  = 4;
				the_configAttr.alpha_size = 4;
				tok += strlen("rgba4444");
			}
			else if (strncmp(tok, "rgb565", strlen("rgb565")) == 0)
			{
				the_configAttr.red_size   = 5;
				the_configAttr.green_size = 6;
				the_configAttr.blue_size  = 5;
				the_configAttr.alpha_size = 0;
				tok += strlen("rgb565");
			}
			else if (isdigit(*tok))
			{
				val = atoi(tok);
				while (isdigit(*(++tok)));
				if (*tok == 'x')
				{
					the_configAttr.samples = val;
					tok++;
				}
				else
				{
					the_configAttr.config_id = val;
				}
			}
			else
			{
				fprintf(stderr, "invalid configuration specifier: ");
				while (*tok != ' ' && *tok != ',' && *tok != '\0')
					fputc(*tok++, stderr);

				fputc('\n', stderr);
			}

			while (*tok == ' ' || *tok == ',')
				tok++;
		}
	}

	rc = eglGetConfigs(eglDisplay, NULL, 0, &egl_num_configs);
	if (rc != EGL_TRUE)
	{
		fprintf(stderr, "eglGetConfigs");
		return config;
	}

	if (egl_num_configs == 0)
	{
		fprintf(stderr, "eglGetConfigs: could not find a configuration\n");
		return config;
	}

	configurations = (EGLConfig *)malloc(egl_num_configs * sizeof(*configurations));
	if (configurations == NULL)
	{
		fprintf(stderr, "could not allocate memory for %d EGL configs\n", egl_num_configs);
		return config;
	}

	rc = eglGetConfigs(eglDisplay, configurations, egl_num_configs, &egl_num_configs);
	if (rc != EGL_TRUE)
	{
		fprintf(stderr, "eglGetConfigs");
		free(configurations);
		return config;
	}

	for (i = 0; i < egl_num_configs; i++)
	{
		if (the_configAttr.config_id != EGL_DONT_CARE)
		{
			eglGetConfigAttrib(eglDisplay, configurations[i], EGL_CONFIG_ID, &val);
			if (val == the_configAttr.config_id)
			{
				config = configurations[i];
				break;
			}
			else
			{
				continue;
			}
		}

		eglGetConfigAttrib(eglDisplay, configurations[i], EGL_SURFACE_TYPE, &val);
		if ((val & the_configAttr.surface_type) != the_configAttr.surface_type)
			continue;

		eglGetConfigAttrib(eglDisplay, configurations[i], EGL_RENDERABLE_TYPE, &val);
		if (!(val & EGL_OPENGL_ES_BIT))
			continue;

		eglGetConfigAttrib(eglDisplay, configurations[i], EGL_DEPTH_SIZE, &val);
		if (val == 0)
			continue;

		if (the_configAttr.red_size != EGL_DONT_CARE)
		{
			eglGetConfigAttrib(eglDisplay, configurations[i], EGL_RED_SIZE, &val);
			if (val != the_configAttr.red_size)
				continue;
		}

		if (the_configAttr.green_size != EGL_DONT_CARE)
		{
			eglGetConfigAttrib(eglDisplay, configurations[i], EGL_GREEN_SIZE, &val);
			if (val != the_configAttr.green_size)
				continue;
		}

		if (the_configAttr.blue_size != EGL_DONT_CARE)
		{
			eglGetConfigAttrib(eglDisplay, configurations[i], EGL_BLUE_SIZE, &val);
			if (val != the_configAttr.blue_size)
				continue;
		}

		if (the_configAttr.alpha_size != EGL_DONT_CARE)
		{
			eglGetConfigAttrib(eglDisplay, configurations[i], EGL_ALPHA_SIZE, &val);
			if (val != the_configAttr.alpha_size)
				continue;
		}

		if (the_configAttr.samples != EGL_DONT_CARE)
		{
			eglGetConfigAttrib(eglDisplay, configurations[i], EGL_SAMPLES, &val);
			if (val != the_configAttr.samples)
				continue;
		}

		config = configurations[i];
		break;
	}

	free(configurations);

	if (config == (EGLConfig)0)
	{
		fprintf(stderr, "eglChooseConfig: could not find a matching configuration\n");
	}

	return config;
}

int CCEGLView::chooseFormat(const EGLDisplay &eglDisplay, const EGLConfig &config)
{
	EGLint buffer_bit_depth, alpha_bit_depth;

	eglGetConfigAttrib(eglDisplay, config, EGL_BUFFER_SIZE, &buffer_bit_depth);
	eglGetConfigAttrib(eglDisplay, config, EGL_ALPHA_SIZE,  &alpha_bit_depth);

	switch (buffer_bit_depth)
	{
		case 32: return SCREEN_FORMAT_RGBA8888;
		case 24: return SCREEN_FORMAT_RGB888;
		case 16:
		{
			switch (alpha_bit_depth)
			{
				case 4:  return SCREEN_FORMAT_RGBA4444;
				case 1:  return SCREEN_FORMAT_RGBA5551;
				default: return SCREEN_FORMAT_RGB565;
			}
		}

		default:  return 0;
	}
}

void CCEGLView::printEGLInfo(const EGLConfig &config) const
{
	int i;

	fprintf(stderr,"EGL_VENDOR = %s\n", eglQueryString(m_eglDisplay, EGL_VENDOR));
	fprintf(stderr,"EGL_VERSION = %s\n", eglQueryString(m_eglDisplay, EGL_VERSION));
	fprintf(stderr,"EGL_CLIENT_APIS = %s\n", eglQueryString(m_eglDisplay, EGL_CLIENT_APIS));
	fprintf(stderr,"EGL_EXTENSIONS = %s\n\n", eglQueryString(m_eglDisplay, EGL_EXTENSIONS));

	i = -1;
	eglGetConfigAttrib(m_eglDisplay, config, EGL_CONFIG_ID, &i);
	fprintf(stderr,"EGL_CONFIG_ID = %d\n", i);

	i = 0;
	eglGetConfigAttrib(m_eglDisplay, config, EGL_RED_SIZE, &i);
	fprintf(stderr,"EGL_RED_SIZE = %d\n", i);

	i = 0;
	eglGetConfigAttrib(m_eglDisplay, config, EGL_GREEN_SIZE, &i);
	fprintf(stderr,"EGL_GREEN_SIZE = %d\n", i);

	i = 0;
	eglGetConfigAttrib(m_eglDisplay, config, EGL_BLUE_SIZE, &i);
	fprintf(stderr,"EGL_BLUE_SIZE = %d\n", i);

	i = 0;
	eglGetConfigAttrib(m_eglDisplay, config, EGL_ALPHA_SIZE, &i);
	fprintf(stderr,"EGL_ALPHA_SIZE = %d\n", i);

	i = 0;
	eglGetConfigAttrib(m_eglDisplay, config, EGL_DEPTH_SIZE, &i);
	fprintf(stderr,"EGL_DEPTH_SIZE = %d\n", i);

	i = 0;
	eglGetConfigAttrib(m_eglDisplay, config, EGL_LEVEL, &i);
	fprintf(stderr,"EGL_LEVEL = %d\n", i);

	i = 0;
	eglGetConfigAttrib(m_eglDisplay, config, EGL_NATIVE_RENDERABLE, &i);
	fprintf(stderr,"EGL_NATIVE_RENDERABLE = %s\n", i ? "EGL_TRUE" : "EGL_FALSE");

	i = 0;
	eglGetConfigAttrib(m_eglDisplay, config, EGL_NATIVE_VISUAL_TYPE, &i);
	fprintf(stderr,"EGL_NATIVE_VISUAL_TYPE = %d\n", i);

	i = 0;
	eglGetConfigAttrib(m_eglDisplay, config, EGL_RENDERABLE_TYPE, &i);
	fprintf(stderr,"EGL_RENDERABLE_TYPE = 0x%04x\n", i);

	i = 0;
	eglGetConfigAttrib(m_eglDisplay, config, EGL_SURFACE_TYPE, &i);
	fprintf(stderr,"EGL_SURFACE_TYPE = 0x%04x\n", i);

	i = 0;
	eglGetConfigAttrib(m_eglDisplay, config, EGL_TRANSPARENT_TYPE, &i);
	if (i == EGL_TRANSPARENT_RGB)
	{
		fprintf(stderr,"EGL_TRANSPARENT_TYPE = EGL_TRANSPARENT_RGB\n");

		i = 0;
		eglGetConfigAttrib(m_eglDisplay, config, EGL_TRANSPARENT_RED_VALUE, &i);
		fprintf(stderr,"EGL_TRANSPARENT_RED = 0x%02x\n", i);

		i = 0;
		eglGetConfigAttrib(m_eglDisplay, config, EGL_TRANSPARENT_GREEN_VALUE, &i);
		fprintf(stderr,"EGL_TRANSPARENT_GREEN = 0x%02x\n", i);

		i = 0;
		eglGetConfigAttrib(m_eglDisplay, config, EGL_TRANSPARENT_BLUE_VALUE, &i);
		fprintf(stderr,"EGL_TRANSPARENT_BLUE = 0x%02x\n\n", i);
	}
	else
	{
		fprintf(stderr,"EGL_TRANSPARENT_TYPE = EGL_NONE\n\n");
	}
}

static void printEglError( GLuint errorCode )
{
    switch( errorCode )
    {
		case EGL_SUCCESS:
			fprintf( stderr, "EGL_SUCCESS");
			break;
		case EGL_NOT_INITIALIZED:
			fprintf( stderr, ">>EGL_NOT_INITIALIZED");
			break;
		case EGL_BAD_ACCESS:
			fprintf( stderr, ">>EGL_BAD_ACCESS");
			break;
		case EGL_BAD_ALLOC:
			fprintf( stderr, ">>EGL_BAD_ALLOC");
			break;
		case EGL_BAD_ATTRIBUTE:
			fprintf( stderr, ">>EGL_BAD_ATTRIBUTE");
			break;
		case EGL_BAD_CONTEXT:
			fprintf( stderr, ">>EGL_BAD_CONTEXT");
			break;
		case EGL_BAD_CONFIG:
			fprintf( stderr, ">>EGL_BAD_CONFIG");
			break;
		case EGL_BAD_CURRENT_SURFACE:
			fprintf( stderr, ">>EGL_BAD_CURRENT_SURFACE");
			break;
		case EGL_BAD_DISPLAY:
			fprintf( stderr, ">>EGL_BAD_DISPLAY");
			break;
		case EGL_BAD_SURFACE:
			fprintf( stderr, ">>EGL_BAD_SURFACE");
			break;
		case EGL_BAD_MATCH:
			fprintf( stderr, ">>EGL_BAD_MATCH");
			break;
		case EGL_BAD_PARAMETER:
			fprintf( stderr, ">>EGL_BAD_PARAMETER");
			break;
		case EGL_BAD_NATIVE_PIXMAP:
			fprintf( stderr, ">>EGL_BAD_NATIVE_PIXMAP");
			break;
		case EGL_BAD_NATIVE_WINDOW:
			fprintf( stderr, ">>EGL_BAD_NATIVE_WIN i=i+2DOW");
			break;
		case EGL_CONTEXT_LOST:
			fprintf( stderr, ">>EGL_CONTEXT_LOST");
			break;
		default:
			fprintf( stderr, ">>Unknown error");
			break;
    }
}

bool CCEGLView::initDriver()
{
    int         err;
    int         egl_ret;
    EGLint      majorVersion;
    EGLint      minorVersion;

    // Get EGL display
    m_eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    err = eglGetError();
    if (m_eglDisplay == EGL_NO_DISPLAY || err != EGL_SUCCESS)
    {
        printEglError( err );
        return false;
    }

    // Initialize EGL
    egl_ret = eglInitialize(m_eglDisplay, &majorVersion, &minorVersion);
    err = eglGetError();
    if ( egl_ret != EGL_TRUE || err != EGL_SUCCESS )
    {
        printEglError( err );
        return false;
    }

    return true;
}

bool CCEGLView::createNativeWindow(const EGLConfig &config)
{
    int 	usage = SCREEN_USAGE_OPENGL_ES1;
	int 	transp = SCREEN_TRANSPARENCY_NONE;
	int 	pos[2] = { 0, 0 };
	int 	nbuffers = 2;
	EGLint 	interval = 1;
	int 	format;
    EGLint  err;

    err = screen_create_context(&m_screenContext, 0);
	if (err)
	{
		fprintf(stderr, "screen_create_context");
		return false;
	}

    err = screen_create_window(&m_screenWindow, m_screenContext);
	if (err)
	{
		fprintf(stderr, "screen_create_window");
		return false;
	}

err = screen_create_window_group(m_screenWindow, m_window_group_id);
	if (err)
	{
		fprintf(stderr, "screen_create_window_group");
		return false;
	}
	format = chooseFormat(m_eglDisplay, config);
	err = screen_set_window_property_iv(m_screenWindow, SCREEN_PROPERTY_FORMAT, &format);
	if (err)
	{
		fprintf(stderr, "screen_set_window_property_iv(SCREEN_PROPERTY_FORMAT)");
		return false;
	}

	err = screen_set_window_property_iv(m_screenWindow, SCREEN_PROPERTY_USAGE, &usage);
	if (err)
	{
		fprintf(stderr, "screen_set_window_property_iv(SCREEN_PROPERTY_USAGE)");
		return false;
	}

	if (pos[0] != 0 || pos[1] != 0)
	{
		err = screen_set_window_property_iv(m_screenWindow, SCREEN_PROPERTY_POSITION, pos);
		if (err)
		{
			fprintf(stderr, "screen_set_window_property_iv(SCREEN_PROPERTY_POSITION)");
			return false;
		}
	}

	err = screen_set_window_property_iv(m_screenWindow, SCREEN_PROPERTY_TRANSPARENCY, &transp);
	if (err)
	{
		fprintf(stderr, "screen_set_window_property_iv(SCREEN_PROPERTY_TRANSPARENCY)");
		return false;
	}

	err = screen_set_window_property_iv(m_screenWindow, SCREEN_PROPERTY_SWAP_INTERVAL, &interval);
	if (err)
	{
		fprintf(stderr, "screen_set_window_property_iv(SCREEN_PROPERTY_SWAP_INTERVAL)");
		return false;
	}

	screen_display_t screen_disp;
    int rc = screen_get_window_property_pv(m_screenWindow, SCREEN_PROPERTY_DISPLAY, (void **)&screen_disp);
    if (rc)
    {
    	fprintf(stderr, "screen_get_window_property_pv(SCREEN_PROPERTY_DISPLAY)");
        return false;
    }

	screen_display_mode_t screen_mode;
	rc = screen_get_display_property_pv(screen_disp, SCREEN_PROPERTY_MODE, (void**)&screen_mode);
	if (rc)
	{
		fprintf(stderr, "screen_get_display_property_pv(SCREEN_PROPERTY_MODE)");
	    return false;
	}

    int size[2];
	rc = screen_get_window_property_iv(m_screenWindow, SCREEN_PROPERTY_BUFFER_SIZE, size);
	if (rc)
	{
		fprintf(stderr, "screen_get_window_property_iv(SCREEN_PROPERTY_BUFFER_SIZE)");
		return false;
	}

	int angle = atoi(getenv("ORIENTATION"));
	int buffer_size[2] = { size[0], size[1] };

	if ((angle == 0) || (angle == 180))
	{
		if (((screen_mode.width > screen_mode.height) && (size[0] < size[1])) ||
			((screen_mode.width < screen_mode.height) && (size[0] > size[1])))
		{
			buffer_size[1] = size[0];
			buffer_size[0] = size[1];
		}
	}
	else if ((angle == 90) || (angle == 270))
	{
		if (((screen_mode.width > screen_mode.height) && (size[0] > size[1])) ||
			((screen_mode.width < screen_mode.height && size[0] < size[1])))
		{
			buffer_size[1] = size[0];
			buffer_size[0] = size[1];
		}
	}
	else
	{
		fprintf(stderr, "Navigator returned an unexpected orientation angle of %d.\n", angle);
		return false;
	}

	rc = screen_set_window_property_iv(m_screenWindow, SCREEN_PROPERTY_BUFFER_SIZE, buffer_size);
	if (rc)
	{
		fprintf(stderr, "screen_set_window_property_iv(SCREEN_PROPERTY_BUFFER_SIZE)");
		return false;
	}

	rc = screen_set_window_property_iv(m_screenWindow, SCREEN_PROPERTY_ROTATION, &angle);
	if (rc)
	{
		fprintf(stderr, "screen_set_window_property_iv(SCREEN_PROPERTY_ROTATION)");
		return false;
	}

	err = screen_create_window_buffers(m_screenWindow, nbuffers);
	if (err)
	{
		fprintf(stderr, "screen_create_window_buffers");
		return false;
	}

	return true;
}

#define N_BPS_EVENTS 1

bool CCEGLView::initGL()
{
	EGLConfig 			config;
    EGLint    			err;

    initDriver();

    config = chooseConfig(m_eglDisplay, "rgb565");
    if (config == (EGLConfig)0)
    {
        fprintf(stderr, "Failed to find config!" );
        return false;
	}

    // Create EGL rendering context
    m_eglContext = eglCreateContext( m_eglDisplay, config, EGL_NO_CONTEXT, NULL );
    err = eglGetError( );
    if ( m_eglContext == EGL_NO_CONTEXT )
    {
        fprintf(stderr, "Can't create gles2 context!" );
        printEglError( err );
		return false;
    }

//    printEGLInfo(config);

    if (!createNativeWindow(config))
    {
    	fprintf(stderr, "Unable to create a native window\n");
    	return false;
    }

    // set up the screen events
	err = screen_create_event(&m_screenEvent);
	if (err)
	{
		fprintf(stderr, "screen_create_event");
		return false;
	}

#ifdef BPS_EVENTS
	// Request screen events
	screen_request_events(m_screenContext);
#endif

	m_eglSurface = eglCreateWindowSurface(m_eglDisplay, config, m_screenWindow, NULL);
	if (m_eglSurface == EGL_NO_SURFACE)
	{
        fprintf(stderr, "Demo Thread Init: can't create surface!" );
        printEglError( err );
        return false;
	}

	err = eglMakeCurrent(m_eglDisplay, m_eglSurface, m_eglSurface, m_eglContext);
	if (err != EGL_TRUE)
	{
        fprintf(stderr, "Demo Thread Init: can't make current!" );
		return false;
	}

    EGLint width, height;

    if ((m_eglDisplay == EGL_NO_DISPLAY) || (m_eglSurface == EGL_NO_SURFACE) )
    	return EXIT_FAILURE;

	eglQuerySurface(m_eglDisplay, m_eglSurface, EGL_WIDTH, &width);
    eglQuerySurface(m_eglDisplay, m_eglSurface, EGL_HEIGHT, &height);

	m_sSizeInPixel.width = width;
	m_sSizeInPixel.height = height;

    return true;
}

CCSize CCEGLView::getSize()
{
	if (m_bNotHVGA)
	{
		CCSize size(m_sSizeInPoint.width, m_sSizeInPoint.height);
		return size;
	}
	else
	{
		CCSize size(m_sSizeInPixel.width, m_sSizeInPixel.height);
		return size;
	}
}

bool CCEGLView::isOpenGLReady()
{
	return (m_isGLInitialized && m_sSizeInPixel.width != 0 && m_sSizeInPixel.height != 0);
}

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

void CCEGLView::release()
{
	if (!m_eglContext || !m_eglDisplay)
		return;
#ifdef BPS_EVENTS
	screen_stop_events(m_screenContext);
#endif
	bps_shutdown();

	screen_destroy_event(m_screenEvent);

	eglMakeCurrent(m_eglDisplay, NULL, NULL, NULL);
	eglDestroySurface(m_eglDisplay, m_eglSurface);
	screen_destroy_window(m_screenWindow);
	screen_destroy_context(m_screenContext);
	eglDestroyContext(m_eglDisplay, m_eglContext);
	eglTerminate(m_eglDisplay);
	eglReleaseThread();

	m_eglDisplay = NULL;
	m_eglContext = NULL;
	m_eglSurface = NULL;

	m_isGLInitialized = false;

	exit(0);
}

void CCEGLView::setEventHandler(EventHandler* pHandler)
{
	m_pEventHandler = pHandler;
}

const char* CCEGLView::getWindowGroupId() const
{
	return m_window_group_id;
}
void CCEGLView::setTouchDelegate(EGLTouchDelegate * pDelegate)
{
	m_pDelegate = pDelegate;
}

EGLTouchDelegate* CCEGLView::getDelegate(void)
{
	return m_pDelegate;
}

bool CCEGLView::HandleEvents()
{
	bps_event_t*    event = NULL;
	mtouch_event_t  mtouch_event;
	int				touch_id = 0;
	int				val = 0;
	int				rc = 0;
	int 			domain = 0;
	char 			buf[4] = {0};

	for (;;)
	{
		rc = bps_get_event(&event, 1);
		assert(rc == BPS_SUCCESS);

#ifdef BPS_EVENTS
		// break if no more events
		if (event == NULL)
			break;
#else
		if (event != NULL)
		{
#endif
		if (m_pEventHandler && m_pEventHandler->HandleBPSEvent(event))
			continue;

		domain = bps_event_get_domain(event);

		if (domain == navigator_get_domain())
		{
			switch (bps_event_get_code(event))
			{
				case NAVIGATOR_SWIPE_DOWN:
					CCKeypadDispatcher::sharedDispatcher()->dispatchKeypadMSG(kTypeMenuClicked);
					break;

				case NAVIGATOR_EXIT:
					// exit the application
				//	release();
					break;

				case NAVIGATOR_WINDOW_INACTIVE:
					if(m_isWindowActive)
					{
						CCApplication::sharedApplication().applicationDidEnterBackground();
						m_isWindowActive = false;
					}
					break;

				case NAVIGATOR_WINDOW_ACTIVE:
					if(!m_isWindowActive)
					{
						CCApplication::sharedApplication().applicationWillEnterForeground();
						m_isWindowActive = true;
					}
					break;

				case NAVIGATOR_WINDOW_STATE:
				{
					switch(navigator_event_get_window_state(event))
					{
						case NAVIGATOR_WINDOW_FULLSCREEN:
							if(!m_isWindowActive)
							{
								CCApplication::sharedApplication().applicationWillEnterForeground();
								m_isWindowActive = true;
							}
							break;
						case NAVIGATOR_WINDOW_THUMBNAIL:
							if(m_isWindowActive)
							{
								CCApplication::sharedApplication().applicationDidEnterBackground();
								m_isWindowActive = false;
							}
							break;
					}
					break;
				}

				default:
					break;
			}
		}
		}
#ifndef BPS_EVENTS
		// for now handle screen events separately from BPS events
		if (screen_get_event(m_screenContext, m_screenEvent, 0) < 0)
		{
			// we have an error condition in the screen event
			break;
		}
		else
		{
#else
		else if (domain == screen_get_domain())
		{
			m_screenEvent = screen_event_get_event(event);
#endif
			rc = screen_get_event_property_iv(m_screenEvent, SCREEN_PROPERTY_TYPE, &val);
			if (rc || val == SCREEN_EVENT_NONE)
				break;

			switch (val)
			{
				case SCREEN_EVENT_CLOSE:
					fprintf(stderr, "SCREEN CLOSE EVENT!\n");
					break;

				case SCREEN_EVENT_MTOUCH_RELEASE:
					screen_get_mtouch_event(m_screenEvent, &mtouch_event, 0);
					touch_id = mtouch_event.contact_id;

					if (m_pDelegate && touch_id < MAX_TOUCHES)
					{
						CCTouch* touch = s_pTouches[touch_id];
						if (touch)
						{
							CCSet set;
							touch->SetTouchInfo(((float)(mtouch_event.x) - m_rcViewPort.origin.x) / m_fScreenScaleFactor,
												   ((float)(mtouch_event.y) - m_rcViewPort.origin.y) / m_fScreenScaleFactor);
							set.addObject(touch);
							m_pDelegate->touchesEnded(&set, NULL);

							touch->release();
							for (int i = touch_id; i < MAX_TOUCHES; i++)
							{
								if (i != (MAX_TOUCHES - 1))
								{
									s_pTouches[i] = s_pTouches[i + 1];
								}
								else
								{
									s_pTouches[i] = NULL;
								}
							}
						}
					}

					break;

				case SCREEN_EVENT_MTOUCH_TOUCH:
					screen_get_mtouch_event(m_screenEvent, &mtouch_event, 0);
					touch_id = mtouch_event.contact_id;

					if (m_pDelegate && touch_id < MAX_TOUCHES)
					{
						CCTouch* touch = s_pTouches[touch_id];
						if (!touch)
							touch = new CCTouch;

						touch->SetTouchInfo(((float)(mtouch_event.x) - m_rcViewPort.origin.x) / m_fScreenScaleFactor,
											   ((float)(mtouch_event.y) - m_rcViewPort.origin.y) / m_fScreenScaleFactor);
						s_pTouches[touch_id] = touch;

						CCSet set;
						set.addObject(touch);
						m_pDelegate->touchesBegan(&set, NULL);
					}

					break;

				case SCREEN_EVENT_MTOUCH_MOVE:
					screen_get_mtouch_event(m_screenEvent, &mtouch_event, 0);
					touch_id = mtouch_event.contact_id;

					if (m_pDelegate && touch_id < MAX_TOUCHES)
					{
						CCTouch* touch = s_pTouches[touch_id];
						if (touch)
						{
							CCSet set;
							touch->SetTouchInfo(((float)(mtouch_event.x) - m_rcViewPort.origin.x) / m_fScreenScaleFactor,
												   ((float)(mtouch_event.y) - m_rcViewPort.origin.y) / m_fScreenScaleFactor);
							set.addObject(touch);
							m_pDelegate->touchesMoved(&set, NULL);
						}
					}

					break;

				case SCREEN_EVENT_POINTER:
					{
						int buttons;
						int pair[2];
						static bool mouse_pressed = false;

						// this is a mouse move event, it is applicable to a device with a usb mouse or simulator
						screen_get_event_property_iv(m_screenEvent, SCREEN_PROPERTY_BUTTONS, &buttons);
						screen_get_event_property_iv(m_screenEvent, SCREEN_PROPERTY_SOURCE_POSITION, pair);

						if (buttons & SCREEN_LEFT_MOUSE_BUTTON)
						{
							if (mouse_pressed)
							{
								// Left mouse button was released
								if (m_pDelegate && touch_id < MAX_TOUCHES)
								{
									CCTouch* touch = s_pTouches[touch_id];
									if (touch)
									{
										CCSet set;
										touch->SetTouchInfo(((float)(pair[0]) - m_rcViewPort.origin.x) / m_fScreenScaleFactor,
															   ((float)(pair[1]) - m_rcViewPort.origin.y) / m_fScreenScaleFactor);
										set.addObject(touch);
										m_pDelegate->touchesMoved(&set, NULL);
									}
								}
							}
							else
							{
								// Left mouse button is pressed
								mouse_pressed = true;
								if (m_pDelegate && touch_id < MAX_TOUCHES)
								{
									CCTouch* touch = s_pTouches[touch_id];
									if (!touch)
										touch = new CCTouch;

									touch->SetTouchInfo(((float)(pair[0]) - m_rcViewPort.origin.x) / m_fScreenScaleFactor,
														   ((float)(pair[1]) - m_rcViewPort.origin.y) / m_fScreenScaleFactor);
									s_pTouches[touch_id] = touch;

									CCSet set;
									set.addObject(touch);
									m_pDelegate->touchesBegan(&set, NULL);
								}
							}
						}
						else
						{
							if (mouse_pressed)
							{
								if (m_pDelegate && touch_id < MAX_TOUCHES)
								{
									mouse_pressed = false;

									CCTouch* touch = s_pTouches[touch_id];
									if (touch)
									{
										CCSet set;
										touch->SetTouchInfo(((float)(pair[0]) - m_rcViewPort.origin.x) / m_fScreenScaleFactor,
															   ((float)(pair[1]) - m_rcViewPort.origin.y) / m_fScreenScaleFactor);
										set.addObject(touch);
										m_pDelegate->touchesEnded(&set, NULL);

										touch->release();
										for (int i = touch_id; i < MAX_TOUCHES; i++)
										{
											if (i != (MAX_TOUCHES - 1))
											{
												s_pTouches[i] = s_pTouches[i + 1];
											}
											else
											{
												s_pTouches[i] = NULL;
											}
										}
									}
								}
							}
						}
					}
					break;

				case SCREEN_EVENT_KEYBOARD:
					screen_get_event_property_iv(m_screenEvent, SCREEN_PROPERTY_KEY_FLAGS, &val);
					if (val & KEY_DOWN)
					{
						screen_get_event_property_iv(m_screenEvent, SCREEN_PROPERTY_KEY_SYM, &val);

						if (val >= ' ' && val < '~')
						{
							buf[0] = val;
							buf[1]=  '\0';
							CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(buf, 1);
						}
						else
						{
							val = val - 0xf000;
							buf[0] = val;
							buf[1]=  '\0';

							switch (val)
							{
								case 8: // backspace
									//		CCKeypadDispatcher::sharedDispatcher()->dispatchKeypadMSG(kTypeBackClicked);
									CCIMEDispatcher::sharedDispatcher()->dispatchDeleteBackward();
									break;

								default:
									CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(buf, 1);
									break;
							}
						}
					}

					break;

				default:
					break;
			}
		}
	}

	return true;
}

void CCEGLView::swapBuffers()
{
	eglSwapBuffers(m_eglDisplay, m_eglSurface);
}

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

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

void CCEGLView::setViewPortInPoints(float x, float y, float w, float h)
{
    if (m_bNotHVGA)
    {
        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));
    }
    else
    {
        glViewport( (GLint)x,
					(GLint)y,
					(GLint)w,
					(GLint)h);
    }
}

void CCEGLView::setScissorInPoints(float x, float y, float w, float h)
{
    if (m_bNotHVGA)
    {
        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));
    }
    else
    {
        glScissor(  (GLint)x,
					(GLint)y,
					(GLint)w,
					(GLint)h);
    }
}

CCEGLView& CCEGLView::sharedOpenGLView()
{
	CCAssert(s_pInstance != NULL, "CCEGLView wasn't constructed yet");
	return *s_pInstance;
}

float CCEGLView::getScreenScaleFactor()
{
    return m_fScreenScaleFactor;
}

CCRect CCEGLView::getViewPort()
{
    if (m_bNotHVGA)
    {
        return m_rcViewPort;
    }
    else
    {
        CCRect rect(0, 0, 0, 0);
        return rect;
    }
}

bool CCEGLView::isGLExtension(const char *searchName) const
{
	const GLubyte *start;
	GLubyte *where, *terminator;

	/* It takes a bit of care to be fool-proof about parsing the
	 OpenGL extensions string. Don't be fooled by sub-strings,
	 etc. */
	start = m_extensions;
	for (;;)
	{
		where = (GLubyte *) strstr((const char *) start, searchName);
		if (!where)
			break;

		terminator = where + strlen(searchName);
		if (where == start || *(where - 1) == ' ')
			if (*terminator == ' ' || *terminator == '\0')
				return true;

		start = terminator;
	}

	return false;
}

void CCEGLView::showKeyboard()
{
	int height;

	virtualkeyboard_get_height(&height);

	float factor = m_fScreenScaleFactor / CC_CONTENT_SCALE_FACTOR();
	height = (float)height / factor;

	CCRect rect_begin(0, 0 - height, m_sSizeInPixel.width / factor, height);
	CCRect rect_end(0, 0, m_sSizeInPixel.width / factor, height);

    CCIMEKeyboardNotificationInfo info;
    info.begin = rect_begin;
    info.end = rect_end;
    info.duration = 0;

    CCIMEDispatcher::sharedDispatcher()->dispatchKeyboardWillShow(info);
    virtualkeyboard_show();
    CCIMEDispatcher::sharedDispatcher()->dispatchKeyboardDidShow(info);
}

void CCEGLView::hideKeyboard()
{
	virtualkeyboard_hide();
}

void CCEGLView::setIMEKeyboardState(bool bOpen)
{
	if (bOpen)
		showKeyboard();
	else
		hideKeyboard();
}

}       // end of namespace cocos2d

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

#ifndef __CC_EGLVIEW_QNX_H__
#define __CC_EGLVIEW_QNX_H__

#include "CCGeometry.h"
#include <GLES/gl.h>
#include <GLES/glext.h>
#include <EGL/egl.h>
#include <screen/screen.h>

#include <bps/event.h>
namespace   cocos2d {
class CCSet;
class CCTouch;
class EGLTouchDelegate;

class CC_DLL CCEGLView
{
public:
class CC_DLL EventHandler
	{
	public:
		virtual bool HandleBPSEvent(bps_event_t* event) = 0;

	    virtual ~EventHandler() {}
	};
public:
    CCEGLView();
    virtual ~CCEGLView();

    CCSize  getSize();
    bool    isOpenGLReady();
    bool    isIpad();
	/**
	 * the width and height is the real size of phone
	 */
    void    setFrameWidthAndHeight(int width, int height);
	/**
	 * create a drawing rect,
	 * the width and heiht is the resource size match best
	 */
	bool    Create(int width, int height);
    EGLTouchDelegate* getDelegate(void);

	void    setEventHandler(EventHandler* pHandler);
    const char* getWindowGroupId() const;
    // keep compatible
    void    release();
    void    setTouchDelegate(EGLTouchDelegate * pDelegate);
    void    swapBuffers();
    bool    canSetContentScaleFactor();
    void    setContentScaleFactor(float contentScaleFactor);
	void    setViewPortInPoints(float x, float y, float w, float h);
    void    setScissorInPoints(float x, float y, float w, float h);
	CCRect  getViewPort();
	float   getScreenScaleFactor();
    void    setIMEKeyboardState(bool bOpen);

    float   getMainScreenScale() { return 1.0f; }

    bool 	HandleEvents();

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

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

private:

	bool 		initGL();
	void		initEGLFunctions();
	bool    	isGLExtension(const char *searchName) const;
	bool 		initDriver();
	void 		printEGLInfo(const EGLConfig &config) const;
	EGLConfig   chooseConfig(const EGLDisplay &eglDisplay, const char* str);
	int         chooseFormat(const EGLDisplay &eglDisplay, const EGLConfig &config);
	bool		createNativeWindow(const EGLConfig &config);
	void		showKeyboard();
	void		hideKeyboard();

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

	EventHandler*		m_pEventHandler;
	EGLTouchDelegate   *m_pDelegate;
	float  				m_fScreenScaleFactor;

	bool 				m_isWindowActive;

	static bool 		m_initializedFunctions;
	static const GLubyte *m_extensions;

	EGLDisplay 		 m_eglDisplay;
	EGLContext 		 m_eglContext;
	EGLSurface 		 m_eglSurface;
    screen_event_t 	 m_screenEvent;
    screen_window_t  m_screenWindow;
    screen_context_t m_screenContext;
    char 			 m_window_group_id[16];
};

}   // end of namespace   cocos2d

#endif	// end of __CC_EGLVIEW_QNX_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 "CCFileUtils.h"
#include "CCCommon.h"
#include "CCString.h"
#include <string>
#include <unistd.h>

NS_CC_BEGIN;

#define  MAX_PATH 256

// record the resource path
static std::string s_strResourcePath = "";
static std::string s_pszZipFilePath  = "";

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

    if (!pszResourcePath)
    	return;

    s_strResourcePath = pszResourcePath;

	// if the path is not ended with '/', append it
	if (s_strResourcePath.find("/") != (strlen(s_strResourcePath.c_str()) - 1))
	{
		s_strResourcePath += "/";
	}
}

const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath)
{
	// It works like this: if the relative path already includes the resource path
	// it will be returned as it is
	const std::string relPath = pszRelativePath;
	if (relPath.find(s_strResourcePath) == std::string::npos)
    {
		CCString *pRet = new CCString();
		pRet->autorelease();
		pRet->m_sString = s_strResourcePath + pszRelativePath;
		return pRet->m_sString.c_str();
	}
	else
    {
		return pszRelativePath;
	}
}

const char *CCFileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile)
{
	std::string relativeFile = 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)
{
	unsigned char * buffer = NULL;

	std::string full_path = pszFileName;

	// If it is not inside resource path
	if (full_path.find(s_strResourcePath) == std::string::npos)
    {
			full_path = s_strResourcePath + pszFileName;
	}

	// if specify the zip file,load from it first
	if (s_pszZipFilePath[0] != 0)
	{
		buffer = getFileDataFromZip(s_pszZipFilePath.c_str(), full_path.c_str(), pSize);
	}

	// if that failed then let's try and load the file ourselves
	if (!buffer)
	{
		// read the file from hardware
		FILE *fp = fopen(full_path.c_str(), pszMode);
		if (fp)
		{
			fseek(fp, 0, SEEK_END);
			*pSize = ftell(fp);
			fseek(fp, 0, SEEK_SET);
			buffer = new unsigned char[*pSize];
			*pSize = fread(buffer, sizeof(unsigned char), *pSize, fp);
			fclose(fp);
		}
	}

	// we couldn't find the file
	if (!buffer && getIsPopupNotify())
	{
		std::string title = "Notification";
		std::string msg = "Get data from file(";
		msg.append(full_path);
		if (s_pszZipFilePath[0] != 0)
		{
			msg.append(") in zip archive(").append(s_pszZipFilePath);
		}
		msg.append(") failed!");

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

	return buffer;
}

void CCFileUtils::setResource(const char* pszZipFileName)
{
    s_pszZipFilePath = pszZipFileName;
}

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

std::string CCFileUtils::getWriteablePath()
{
	// Let's write it in the current working directory's data folder
	char cwd[FILENAME_MAX];

	getcwd(cwd, FILENAME_MAX - 1);
	cwd[FILENAME_MAX-1] = '\0';

	std::string path = cwd;
	path += "/data/";

	return path;
}

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 "CCImage.h"

#include "SkTypeface.h"
#include "SkBitmap.h"
#include "SkPaint.h"
#include "SkCanvas.h"

using namespace std;

NS_CC_BEGIN;

class BitmapDC
{
public:
    BitmapDC() : m_pBitmap(NULL),
	  	  	  	 m_pPaint(NULL)
    {
    }

    ~BitmapDC(void)
    {
		CC_SAFE_DELETE(m_pPaint);
		CC_SAFE_DELETE(m_pBitmap);
    }

	bool setFont(const char *pFontName = NULL, int nSize = 0)
	{
		bool bRet = false;

		if (m_pPaint)
		{
			delete m_pPaint;
			m_pPaint = NULL;
		}

		do
		{
			/* init paint */
			m_pPaint = new SkPaint();
			CC_BREAK_IF(! m_pPaint);
			m_pPaint->setColor(SK_ColorWHITE);
			m_pPaint->setTextSize(nSize);

			/* create font */
			SkTypeface *pTypeFace = SkTypeface::CreateFromName(pFontName, SkTypeface::kNormal);
			if (! pTypeFace)
			{
				// let's replace with Arial first before failing
				pTypeFace = SkTypeface::CreateFromName("Arial", SkTypeface::kNormal);
				CCLOG("could not find font %s replacing with Arial\n", pFontName);

				if (!pTypeFace)
				{
					CC_SAFE_DELETE(m_pPaint);
					break;
				}
			}
			m_pPaint->setTypeface( pTypeFace );
			/* cannot unref, I don't know why. It may be memory leak, but how to avoid? */
			pTypeFace->unref();

			bRet = true;
		} while (0);

		return bRet;
	}

	bool prepareBitmap(int nWidth, int nHeight)
	{
		// release bitmap
		if (m_pBitmap)
		{
			delete m_pBitmap;
			m_pBitmap = NULL;
		}

		if (nWidth > 0 && nHeight > 0)
		{
			/* create and init bitmap */
			m_pBitmap = new SkBitmap();
			if (! m_pBitmap)
			{
				return false;
			}

			/* use rgba8888 and alloc memory */
            m_pBitmap->setConfig(SkBitmap::kARGB_8888_Config, nWidth, nHeight);
			if (! m_pBitmap->allocPixels())
			{
				CC_SAFE_DELETE(m_pBitmap);
				return false;
			}

			/* start with black/transparent pixels */
			m_pBitmap->eraseColor(0);
		}

		return true;
	}

	bool drawText(const char *pszText, int nWidth, int nHeight, CCImage::ETextAlign eAlignMask)
    {
        bool bRet = false;

        do
        {
            CC_BREAK_IF(! pszText);
            CC_BREAK_IF(! prepareBitmap(nWidth, nHeight));

			/* create canvas */
			SkPaint::FontMetrics font;
			m_pPaint->getFontMetrics(&font);
			SkCanvas canvas(*m_pBitmap);

			/*
			 * draw text
			 * @todo: alignment
			 */
			canvas.drawText(pszText, strlen(pszText), 0.0, -font.fAscent, *m_pPaint);
			bRet = true;
        } while (0);

        return bRet;
    }

	bool getTextExtentPoint(const char * pszText, int *pWidth, int *pHeight)
	{
		bool bRet = false;

		do
		{
			CC_BREAK_IF(!pszText || !pWidth || !pHeight);

			// get text width and height
			if (m_pPaint)
			{
				SkPaint::FontMetrics font;
				m_pPaint->getFontMetrics(&font);
				*pHeight = (int)ceil((font.fDescent - font.fAscent));
				*pWidth = (int)ceil((m_pPaint->measureText(pszText, strlen(pszText))));

				bRet = true;
			}
		} while (0);

		return bRet;
	}

	SkBitmap* getBitmap()
	{
		return m_pBitmap;
	}

private:
    SkPaint  *m_pPaint;
	SkBitmap *m_pBitmap;

};

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;

    do
    {
        CC_BREAK_IF(! pText);

        BitmapDC &dc = sharedBitmapDC();

		/* init font with font name and size */
		CC_BREAK_IF(! dc.setFont(pFontName, nSize));

		/* compute text width and height */
		if (nWidth <= 0 || nHeight <= 0)
		{
			dc.getTextExtentPoint(pText, &nWidth, &nHeight);
		}
		CC_BREAK_IF(nWidth <= 0 || nHeight <= 0);

		CC_BREAK_IF( false == dc.drawText(pText, nWidth, nHeight, eAlignMask) );

		/*init image information */
		SkBitmap *pBitmap = dc.getBitmap();
		CC_BREAK_IF(! pBitmap);

		int nWidth	= pBitmap->width();
		int nHeight	= pBitmap->height();
		CC_BREAK_IF(nWidth <= 0 || nHeight <= 0);

		int nDataLen = pBitmap->rowBytes() * pBitmap->height();
		m_pData = new unsigned char[nDataLen];
		CC_BREAK_IF(! m_pData);
		memcpy((void*) m_pData, pBitmap->getPixels(), nDataLen);

		m_nWidth    = (short)nWidth;
		m_nHeight   = (short)nHeight;
		m_bHasAlpha = true;
		m_bPreMulti = true;
		m_nBitsPerComponent = pBitmap->bytesPerPixel();

		bRet = true;
    } while (0);

    return bRet;
}

NS_CC_END;


code:
/**
* Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* For the applicable distribution terms see the license text file included in
* the distribution.
*/

#include "CCAccelerometer_qt.h"
#include "ccMacros.h"
#include "accelerometerfilter.h"

#include "CCDirector.h"
#include "CCEGLView_qt.h"

#include <QAccelerometer>

QTM_USE_NAMESPACE

NS_CC_BEGIN;

CCAccelerometer::CCAccelerometer()
    : m_pAccelDelegate(NULL),
      m_pAccelFilter(NULL)
{
}

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

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

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

void CCAccelerometer::readingChanged(QVariant x, QVariant y, QVariant z)
{
    if (!m_pAccelDelegate)
    {
        return;
    }

    CCAcceleration AccValue;
    const time_t theTime = time(NULL);
    const double timestamp = (double)theTime / 100.0;

#if defined(Q_OS_SYMBIAN)
    switch(CCEGLView::sharedOpenGLView().getDeviceOrientation())
    {
    case kCCDeviceOrientationPortrait:
    case kCCDeviceOrientationPortraitUpsideDown:
        AccValue.x = y.toDouble();
        AccValue.y =-x.toDouble();
        AccValue.z = z.toDouble();
        break;

    case kCCDeviceOrientationLandscapeLeft:
    case kCCDeviceOrientationLandscapeRight:
        AccValue.x = x.toDouble();
        AccValue.y = y.toDouble();
        AccValue.z = z.toDouble();
        break;

    default:
        break;
    }
#elif defined(MEEGO_EDITION_HARMATTAN)
    AccValue.x = x.toDouble();
    AccValue.y = y.toDouble();
    AccValue.z = z.toDouble();
#endif

    AccValue.timestamp = timestamp;

    m_pAccelDelegate->didAccelerate(&AccValue);
}

void CCAccelerometer::setEnable(bool bEnable)
{
    if (!bEnable)
    {
        delete m_pAccelFilter;
        m_pAccelFilter = NULL;
    }
    else if (!m_pAccelFilter)
    {
        m_pAccelFilter = new AccelerometerFilter;
        connect(m_pAccelFilter, SIGNAL(readingChanged(QVariant, QVariant, QVariant)),
                this, SLOT(readingChanged(QVariant, QVariant, QVariant)));
    }
}

NS_CC_END;


code:
/**
* Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* For the applicable distribution terms see the license text file included in
* the distribution.
*/

#ifndef CCACCELEROMETER_QT_H_
#define CCACCELEROMETER_QT_H_

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

#include <QObject>
#include <QVariant>

class AccelerometerFilter;

namespace   cocos2d {

class CCAccelerometer : public QObject
{
    Q_OBJECT

public:
    explicit CCAccelerometer();
    virtual ~CCAccelerometer();

    static CCAccelerometer* sharedAccelerometer();

    void removeDelegate(CCAccelerometerDelegate* pDelegate);
    void addDelegate(CCAccelerometerDelegate* pDelegate);
    void setDelegate(CCAccelerometerDelegate* pDelegate);

public slots:
    void readingChanged(QVariant x, QVariant y, QVariant z);

private:
    void setEnable(bool bEnable);

private:
    CCAccelerometerDelegate* m_pAccelDelegate;
    AccelerometerFilter *m_pAccelFilter;
};

}//namespace   cocos2d

#endif /* CCACCELEROMETER_QT_H_ */


code:
/**
* Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* For the applicable distribution terms see the license text file included in
* the distribution.
*/

#include "CCApplication.h"
#include <unistd.h>
#include <sys/time.h>
#include <QTimer>
#include <QSystemInfo>

#include "CCDirector.h"

using namespace cocos2d;
QTM_USE_NAMESPACE

// sharedApplication pointer
CCApplication * CCApplication::sm_pSharedApplication = 0;

CCApplication::CCApplication(int &argc, char **argv)
    : QApplication(argc, argv),
      m_timer(NULL),
      m_refCount(0)
{
	CC_ASSERT(! sm_pSharedApplication);
	sm_pSharedApplication = this;
    m_nAnimationInterval = 1.0f / 60.0f * 1000.0f;

#ifdef Q_OS_SYMBIAN
    QCoreApplication:setAttribute(Qt::AA_S60DisablePartialScreenInputMode, false);
#endif
}

void CCApplication::timerUpdate()
{
    // m_refCount is here to prevent calling the mainloop from nested event loops
    if (!m_refCount)
    {
        CCDirector::sharedDirector()->mainLoop();
    }
}

CCApplication::~CCApplication()
{
	CC_ASSERT(this == sm_pSharedApplication);
	sm_pSharedApplication = NULL;

    CC_SAFE_DELETE(m_timer);
}

void CCApplication::lock()
{
    m_refCount++;
}

void CCApplication::unlock()
{
    CC_ASSERT(m_refCount > 0);
    if (m_refCount > 0)
    {
        m_refCount--;
    }
}

int CCApplication::run()
{
    // Initialize instance and cocos2d.
    if (! initInstance() || ! applicationDidFinishLaunching())
    {
        return 0;
    }

    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));
    m_timer->start(m_nAnimationInterval);
    return exec();
}

CCApplication::Orientation CCApplication::setOrientation(Orientation orientation)
{
	// swap width and height
	CCEGLView * pView = CCDirector::sharedDirector()->getOpenGLView();
	if (pView)
	{
		return (Orientation)pView->setDeviceOrientation(orientation);
	}
	return (Orientation)CCDirector::sharedDirector()->getDeviceOrientation();
}

void CCApplication::statusBarFrame(cocos2d::CCRect * rect)
{
	if (rect)
	{
        // No status bar
		*rect = CCRectMake(0, 0, 0, 0);
	}
}

void CCApplication::setAnimationInterval(double interval)
{
    m_nAnimationInterval = interval * 1000.0f;
    if (m_timer)
    {
        m_timer->start(m_nAnimationInterval);
    }
}

//////////////////////////////////////////////////////////////////////////
// static member function
//////////////////////////////////////////////////////////////////////////
CCApplication& CCApplication::sharedApplication()
{
	CC_ASSERT(sm_pSharedApplication);
	return *sm_pSharedApplication;
}

ccLanguageType CCApplication::getCurrentLanguage()
{
    QSystemInfo sysInfo;
    QString lang = sysInfo.currentLanguage();

    if (lang == "zh")
    {
        return kLanguageChinese;
    }
    else if (lang == "fr")
    {
        return kLanguageFrench;
    }
    else if (lang == "it")
    {
        return kLanguageItalian;
    }
    else if (lang == "de")
    {
        return kLanguageGerman;
    }
    else if (lang == "es")
    {
        return kLanguageSpanish;
    }
    else if (lang == "ru")
    {
        return kLanguageRussian;
    }

    return kLanguageEnglish;
}


code:
/**
* Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* For the applicable distribution terms see the license text file included in
* the distribution.
*/

#ifndef CCAPPLICATION_QT_H_
#define CCAPPLICATION_QT_H_

#include <QApplication>
#include <Qt/qobject.h>
#include <QTimer>

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

using namespace cocos2d;

NS_CC_BEGIN;

class CC_DLL CCApplication : public QApplication {
    Q_OBJECT
public:
    CCApplication(int &argc, char **argv);
    virtual ~CCApplication();

	/**
	 @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(cocos2d::CCRect * rect);

	/**
	 @brief	Run the message loop.
	 */
	int run();

	/**
	 @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 lock();
    void unlock();

public slots:
    void timerUpdate();

public:
    QTimer *m_timer;
    int m_refCount;

protected:
    long m_nAnimationInterval;
	static CCApplication * sm_pSharedApplication;
};

NS_CC_END;

#endif /* CCAPPLICATION_QT_H_ */


code:
/**
* Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* For the applicable distribution terms see the license text file included in
* the distribution.
*/

#include "CCEGLView_qt.h"

#include "CCGL.h"

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

#ifdef Q_OS_LINUX
#include <QX11Info>
#endif

#include <QEvent>

#ifdef Q_OS_SYMBIAN
#include <eikenv.h>
#include <aknappui.h>
#endif

#ifdef MEEGO_EDITION_HARMATTAN
#include <qmeegographicssystemhelper.h>
#endif

PFNGLGENERATEMIPMAPOESPROC glGenerateMipmapOES = NULL;
PFNGLGENFRAMEBUFFERSOESPROC glGenFramebuffersOES = NULL;
PFNGLBINDFRAMEBUFFEROESPROC glBindFramebufferOES = NULL;
PFNGLFRAMEBUFFERTEXTURE2DOESPROC glFramebufferTexture2DOES = NULL;
PFNGLDELETEFRAMEBUFFERSOESPROC glDeleteFramebuffersOES = NULL;
PFNGLCHECKFRAMEBUFFERSTATUSOESPROC glCheckFramebufferStatusOES = NULL;

#define LOAD_EXTENSION(type, name) (name = (type)eglGetProcAddress(#name))
#define NULL_EXTENSION(name) (name = name##_null)

void GL_APIENTRY glBindFramebufferOES_null(GLenum target, GLuint framebuffer)
{
    Q_UNUSED(target);
    Q_UNUSED(framebuffer);
    //CCLOGERROR("%s\n", "glBindFramebufferOES not supported");
}

void GL_APIENTRY glDeleteFramebuffersOES_null(GLsizei n,
                                              const GLuint* framebuffers)
{
    Q_UNUSED(n);
    Q_UNUSED(framebuffers);
    //CCLOGERROR("%s\n", "glDeleteFramebuffersOES not supported");
}

void GL_APIENTRY glGenFramebuffersOES_null(GLsizei n, GLuint* framebuffers)
{
    Q_UNUSED(n);
    Q_UNUSED(framebuffers);
    //CCLOGERROR("%s\n", "glGenFramebuffersOES not supported");
}

GLenum GL_APIENTRY glCheckFramebufferStatusOES_null(GLenum target)
{
    Q_UNUSED(target);
    //CCLOGERROR("%s\n", "glCheckFramebufferStatusOES not supported");
    return 0;
}

void GL_APIENTRY glFramebufferTexture2DOES_null(GLenum target,
                                                GLenum attachment,
                                                GLenum textarget,
                                                GLuint texture,
                                                GLint level)
{
    Q_UNUSED(target);
    Q_UNUSED(attachment);
    Q_UNUSED(textarget);
    Q_UNUSED(texture);
    Q_UNUSED(level);
    //CCLOGERROR("%s\n", "glFramebufferTexture2DOES not supported");
}

void GL_APIENTRY glGenerateMipmapOES_null(GLenum target)
{
    Q_UNUSED(target);
    //CCLOGERROR("%s\n", "glGenerateMipmapOES not supported");
}

bool initExtensions()
{
    const char* extensions = (const char*)glGetString(GL_EXTENSIONS);

    CCLOG(extensions);

    if(!LOAD_EXTENSION(PFNGLGENERATEMIPMAPOESPROC, glGenerateMipmapOES))
        NULL_EXTENSION(glGenerateMipmapOES);

    if(!LOAD_EXTENSION(PFNGLGENFRAMEBUFFERSOESPROC, glGenFramebuffersOES))
        NULL_EXTENSION(glGenFramebuffersOES);

    if(!LOAD_EXTENSION(PFNGLBINDFRAMEBUFFEROESPROC, glBindFramebufferOES))
        NULL_EXTENSION(glBindFramebufferOES);

    if(!LOAD_EXTENSION(PFNGLFRAMEBUFFERTEXTURE2DOESPROC, glFramebufferTexture2DOES))
        NULL_EXTENSION(glFramebufferTexture2DOES);

    if(!LOAD_EXTENSION(PFNGLDELETEFRAMEBUFFERSOESPROC, glDeleteFramebuffersOES))
        NULL_EXTENSION(glDeleteFramebuffersOES);

    if(!LOAD_EXTENSION(PFNGLCHECKFRAMEBUFFERSTATUSOESPROC, glCheckFramebufferStatusOES))
        NULL_EXTENSION(glCheckFramebufferStatusOES);

    return true;
}

NS_CC_BEGIN;

#ifdef MEEGO_EDITION_HARMATTAN

namespace Maliit {
    enum OrientationAngle {
        Angle0 = 0,
        Angle90 = 90,
        Angle180 = 180,
        Angle270 = 270
    };
}

#endif

static CCEGLView* s_pMainWindow = NULL;

CCEGLView::CCEGLView(QWidget* parent):
    QWidget(parent),
    m_bCaptured(false),
    m_bOrientationReverted(false),
    m_bOrientationInitVertical(false),
    m_pDelegate(NULL),
    bIsInit(false),
    m_eInitOrientation(CCDeviceOrientationPortrait),
    m_eOrientation(CCDeviceOrientationPortrait),
    m_fScreenScaleFactor(1.0f),
    m_eglDisplay(NULL),
    m_eglConfig(NULL),
    m_eglSurface(NULL),
    m_eglContext(NULL)
{
    m_sSizeInPoint.width = m_sSizeInPoint.height = 0;
    setAutoFillBackground(false);
    setAttribute(Qt::WA_OpaquePaintEvent);
    setAttribute(Qt::WA_NoSystemBackground);
    setAttribute(Qt::WA_NativeWindow);
    setAttribute(Qt::WA_PaintOnScreen, true);
    setAttribute(Qt::WA_StyledBackground, false);
    setAttribute(Qt::WA_PaintUnclipped);

    setAttribute(Qt::WA_InputMethodEnabled, true);
    setAttribute(Qt::WA_KeyboardFocusChange, true);
    setInputMethodHints(Qt::ImhNoPredictiveText);

    qApp->installEventFilter(this);

#ifdef MS_USE_TOUCH_EVENTS
    setAttribute(Qt::WA_AcceptTouchEvents);

    for(int i = 0; i < MAX_TOUCH_POINTS; i++)
        m_pTouch[i] = NULL;
#else
    m_pTouch = NULL;
#endif

#ifdef MEEGO_EDITION_HARMATTAN
    QMeeGoGraphicsSystemHelper::setSwitchPolicy(QMeeGoGraphicsSystemHelper::NoSwitch);

    QInputContext *ic = QInputContextFactory::create("MInputContext", 0);
    if (ic)
    {
        qApp->setInputContext(ic);
    }
#endif // MEEGO_EDITION_HARMATTAN

#if defined(Q_OS_SYMBIAN)
    CAknAppUiBase::TAppUiOrientation uiOrientation;

    switch(m_eInitOrientation)
    {
    case kCCDeviceOrientationPortrait:
    case kCCDeviceOrientationPortraitUpsideDown:
        uiOrientation = CAknAppUi::EAppUiOrientationPortrait;
        m_eOrientation = kCCDeviceOrientationPortrait;
        break;

    case kCCDeviceOrientationLandscapeLeft:
    case kCCDeviceOrientationLandscapeRight:
        uiOrientation = CAknAppUi::EAppUiOrientationLandscape;
        m_eOrientation = kCCDeviceOrientationLandscapeLeft;
        break;

    default:
        uiOrientation = CAknAppUi::EAppUiOrientationPortrait;
        m_eOrientation = kCCDeviceOrientationPortrait;
    }

    CAknAppUi *ui = dynamic_cast<CAknAppUi *>(CEikonEnv::Static()->AppUi());
    TRAPD(error,
        if(ui) {
            ui->SetOrientationL(uiOrientation);
        }
    );

    Q_UNUSED(error);
#elif defined(MEEGO_EDITION_HARMATTAN)
    // TODO: The code below doesn't work on harmattan, FIX! (if possible and needed)
    /*
    switch(m_eInitOrientation)
    {
    case kCCDeviceOrientationPortrait:
    case kCCDeviceOrientationPortraitUpsideDown:
        //setAttribute(Qt::WA_Maemo5PortraitOrientation, true);
        setAttribute(Qt::WA_LockPortraitOrientation, true);
        break;

    case kCCDeviceOrientationLandscapeLeft:
    case kCCDeviceOrientationLandscapeRight:
        //setAttribute(Qt::WA_Maemo5LandscapeOrientation, true);
        setAttribute(Qt::WA_LockLandscapeOrientation, true);
        break;

    default:
        //setAttribute(Qt::WA_Maemo5PortraitOrientation, true);
        setAttribute(Qt::WA_LockPortraitOrientation, true);
        break;
    }
    */
#endif
}

CCEGLView::~CCEGLView()
{
}

bool CCEGLView::Create()
{
#ifdef Q_OS_SYMBIAN
    showFullScreen();
#endif

    CCLOG("Create: width = %d height = %d", width(), height());

    s_pMainWindow = this;

    m_rcViewPort.size.width = width();
    m_rcViewPort.size.height = height();

#ifdef MEEGO_EDITION_HARMATTAN
    showFullScreen();
#endif

    if (!initEGL())
    {
        return false;
    }

    activateWindow();
    setFocus();
    grabKeyboard();

    return true;
}

CCSize CCEGLView::getSize()
{
    CCLOG("getSize() width = %.1f height = %.1f",
          m_rcViewPort.size.width, m_rcViewPort.size.height);

    return m_rcViewPort.size;
}

float CCEGLView::getMainScreenScale()
{
    // TODO: return correct value
    return -1.0f;
}

bool CCEGLView::isOpenGLReady()
{
    return bIsInit;
}

void CCEGLView::release()
{
    releaseEGL();

    qApp->exit(0);
}

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

void CCEGLView::swapBuffers()
{
    if(bIsInit)
    {
        eglSwapBuffers(m_eglDisplay, m_eglSurface);
    }
}

int CCEGLView::setDeviceOrientation(int eOrientation)
{
#if defined(Q_OS_SYMBIAN)
    CAknAppUiBase::TAppUiOrientation uiOrientation;

    switch(eOrientation)
    {
    case kCCDeviceOrientationPortrait:
    case kCCDeviceOrientationPortraitUpsideDown:
        uiOrientation = CAknAppUi::EAppUiOrientationPortrait;
        m_eOrientation = kCCDeviceOrientationPortrait;
        break;

    case kCCDeviceOrientationLandscapeLeft:
    case kCCDeviceOrientationLandscapeRight:
        uiOrientation = CAknAppUi::EAppUiOrientationLandscape;
        m_eOrientation = kCCDeviceOrientationLandscapeLeft;
        break;

    default:
        uiOrientation = CAknAppUi::EAppUiOrientationPortrait;
        m_eOrientation = kCCDeviceOrientationPortrait;
    }

    CAknAppUi *ui = dynamic_cast<CAknAppUi *>(CEikonEnv::Static()->AppUi());
    TRAPD(error,
        if(ui) {
            ui->SetOrientationL(uiOrientation);
        }
    );

    Q_UNUSED(error);

    m_rcViewPort.size.width = width();
    m_rcViewPort.size.height = height();

    // Return portrait orientation to prevent cocos from rotating the scene
    return kCCDeviceOrientationPortrait;
#elif defined(MEEGO_EDITION_HARMATTAN)
    /* Tell cocos2d to rotate 90-degrees on ccw because
     * the device is on landscape mode instead of portrait mode.
     */
    switch(eOrientation)
    {
    case kCCDeviceOrientationPortrait:
        m_eOrientation = kCCDeviceOrientationLandscapeRight;
        break;

    case kCCDeviceOrientationPortraitUpsideDown:
        m_eOrientation = kCCDeviceOrientationLandscapeLeft;
        break;

    case kCCDeviceOrientationLandscapeLeft:
        m_eOrientation = kCCDeviceOrientationPortrait;
        break;

    case kCCDeviceOrientationLandscapeRight:
        m_eOrientation = kCCDeviceOrientationPortraitUpsideDown;
        break;

    default:
        m_eOrientation = kCCDeviceOrientationPortrait;
        break;
    }
    updateVkbOrientation();
    return m_eOrientation;
#endif
}

int CCEGLView::getDeviceOrientation() const
{
    return m_eOrientation;
}

void CCEGLView::setViewPortInPoints(float x, float y, float w, float h)
{
    CCLOG("setViewPortInPoints x = %.1f y = %.1f w = %.1f h = %.1f", x, y, w, h);

    if (bIsInit) {
        float factor = m_fScreenScaleFactor / CC_CONTENT_SCALE_FACTOR();
        CCLOG("factor = %d", 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)
{
    CCLOG("setScissorInPointsx = %d y = %d w = %d h = %d", x, y, w, h);

    if (bIsInit) {
        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::updateVkbOrientation()
{
#ifdef MEEGO_EDITION_HARMATTAN
    Maliit::OrientationAngle mtfOrient;

    switch (m_eOrientation)
    {
    case kCCDeviceOrientationPortrait:
        mtfOrient = Maliit::Angle0;
        break;
    case kCCDeviceOrientationLandscapeLeft:
        mtfOrient = Maliit::Angle90;
        break;
    case kCCDeviceOrientationPortraitUpsideDown:
        mtfOrient = Maliit::Angle180;
        break;
    default: // kCCDeviceOrientationLandscapeRight
        mtfOrient = Maliit::Angle270;
        break;
    }

    QMetaObject::invokeMethod(qApp->inputContext(),
        "notifyOrientationChanged",
        Q_ARG(Maliit::OrientationAngle, mtfOrient));
#endif
}

void CCEGLView::setIMEKeyboardState(bool bOpen)
{
    QInputContext *ic = qApp->inputContext();

    if(!ic)
        return;

    if(bOpen)
    {
        QWidget* focusWidget = qApp->focusWidget();
        if(focusWidget)
        {
            focusWidget->setInputMethodHints(Qt::ImhNoPredictiveText);
            focusWidget->setAttribute(Qt::WA_InputMethodEnabled, true);
            ic->setFocusWidget(focusWidget);

            QEvent request(QEvent::RequestSoftwareInputPanel);
            ic->filterEvent(&request);
            updateVkbOrientation();
        }
    }
    else
    {
        QEvent close(QEvent::CloseSoftwareInputPanel);
        ic->filterEvent(&close);
        ic->reset();
    }
}

bool CCEGLView::canSetContentScaleFactor()
{
    // TODO: Implement
    return false;
}

void CCEGLView::setContentScaleFactor(float contentScaleFactor)
{
    CCLog("could not set contentScaleFactor after initialized");
    // TODO: Implement
}

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

void CCEGLView::inputMethodEvent(QInputMethodEvent *event)
{
#if defined(Q_OS_SYMBIAN)
    // This section of code is used when the virtual keyboard is in "keypad"-mode
    static bool charStart = true;
    static char lastChar = 0;

    QString commitString = event->commitString();
    if(commitString.length() > 0)
    {
        charStart = true;
        lastChar = 0;
    }
    else
    {
        QString preeditString = event->preeditString();
        if(preeditString.length() > 0)
        {
            char newChar = preeditString.at(preeditString.length()-1).toAscii();
            if(newChar != lastChar)
            {
                if(!charStart)
                    CCIMEDispatcher::sharedDispatcher()->dispatchDeleteBackward();

                CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(&newChar, 1);
                lastChar = newChar;
            }

            charStart = false;
        }
    }
#elif defined(MEEGO_EDITION_HARMATTAN)
    QString commitString = event->commitString();
    if(commitString.length() > 0)
    {
        char newChar = commitString.at(commitString.length()-1).toAscii();
        CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(&newChar, 1);
    }
#endif
}

bool CCEGLView::eventFilter(QObject *object, QEvent *event)
{
    switch(event->type())
    {
    case QEvent::ActivationChange:
        {
            if(isActiveWindow())
            {
                CCLOG("Activate");
                CCApplication::sharedApplication().applicationWillEnterForeground();
            }
            else
            {
                CCLOG("Deactivate");
                CCApplication::sharedApplication().applicationDidEnterBackground();
            }

            return false;
        }break;

    default:
        {
        }break;
    }

    return QObject::eventFilter(object, event);
}

void CCEGLView::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
}

void CCEGLView::resizeEvent(QResizeEvent *event)
{
    int w = event->size().width();
    int h = event->size().height();

    if(event->size().width() == event->oldSize().width() &&
       event->size().height() == event->oldSize().width()) {
        return;
    }

    CCLOG("Resize viewport to %d x %d", w, h);
    glViewport(0, 0, w, h);

    QWidget::resizeEvent(event);
}

#ifdef MS_USE_TOUCH_EVENTS

bool CCEGLView::handleTouchEvent(QEvent* event)
{
    CCSet beganSet;
    CCSet updateSet;
    CCSet releaseSet;

    QList<QTouchEvent::TouchPoint> touchPoints =
            static_cast<QTouchEvent *>(event)->touchPoints();
    foreach(const QTouchEvent::TouchPoint &tp, touchPoints)
    {
        int ind = tp.id();
        if(ind >= MAX_TOUCH_POINTS)
            continue;

        if(m_pTouch[ind])
        {
            if(tp.state() & Qt::TouchPointReleased)
            {
                // release
                m_pTouch[ind]->SetTouchInfo(tp.pos().x(), tp.pos().y());
                releaseSet.addObject(m_pTouch[ind]);
                m_pTouch[ind]->release();
                m_pTouch[ind] = NULL;
            }
            else
            {
                // update
                m_pTouch[ind]->SetTouchInfo(tp.pos().x(), tp.pos().y());
                updateSet.addObject(m_pTouch[ind]);
            }
        }
        else
        {
            // begin
            m_pTouch[ind] = new CCTouch;
            m_pTouch[ind]->SetTouchInfo(tp.pos().x(), tp.pos().y());
            beganSet.addObject(m_pTouch[ind]);
        }
    }

    if(beganSet.count() > 0)
        m_pDelegate->touchesBegan(&beganSet, NULL);
    if(updateSet.count() > 0)
        m_pDelegate->touchesMoved(&updateSet, NULL);
    if(releaseSet.count() > 0)
        m_pDelegate->touchesEnded(&releaseSet, NULL);

    return true;
}

bool CCEGLView::handleKeyEvent(QEvent* event)
{
    QKeyEvent* ke = (QKeyEvent*)event;

    switch(ke->key())
    {
    case Qt::Key_Backspace:
        CCIMEDispatcher::sharedDispatcher()->dispatchDeleteBackward();
        return true;

    case Qt::Key_Tab:
        break;

    case Qt::Key_Return:
    case Qt::Key_Enter:
        CCIMEDispatcher::sharedDispatcher()->dispatchInsertText("\n", 1);
        return true;

    default:
        {
            QString str = ke->text();

            QByteArray ba = str.toAscii();
            if(ba.size() > 0)
            {
                const char* c = ba.constData();
                CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(c, 1);
            }

            return true;
        }
    }

    return false;
}

bool CCEGLView::event(QEvent* event)
{
    switch(event->type())
    {
    case QEvent::TouchBegin:
    case QEvent::TouchUpdate:
    case QEvent::TouchEnd:
        if (handleTouchEvent(event))
            return true;
        else
            break;

    case QEvent::KeyPress:
        if (handleKeyEvent(event))
            return true;
        else
            break;

    case QEvent::KeyRelease:
        return true;

    default:
        break;
    }

    return QWidget::event(event);
}
#else
void CCEGLView::mousePressEvent(QMouseEvent *event)
{
    QMouseEvent* mouseEvent = (QMouseEvent*)event;
    CCPoint point(mouseEvent->x(), mouseEvent->y());

    if(m_pTouch)
        m_pTouch->release();

    m_pTouch = new CCTouch;
    m_pTouch->SetTouchInfo(point.x, point.y);

    CCSet set;
    set.addObject(m_pTouch);

    m_pDelegate->touchesBegan(&set, NULL);

    QWidget::mousePressEvent(event);
}

void CCEGLView::mouseReleaseEvent(QMouseEvent *event)
{
    QMouseEvent* mouseEvent = (QMouseEvent*)event;
    CCPoint point(mouseEvent->x(), mouseEvent->y());

    if(!m_pTouch)
        m_pTouch = new CCTouch;

    m_pTouch->SetTouchInfo(point.x, point.y);

    CCSet set;
    set.addObject(m_pTouch);

    m_pTouch->release();
    m_pTouch = NULL;

    m_pDelegate->touchesEnded(&set, NULL);

    QWidget::mouseReleaseEvent(event);
}

void CCEGLView::mouseMoveEvent(QMouseEvent *event)
{
    QMouseEvent* mouseEvent = (QMouseEvent*)event;
    CCPoint point(mouseEvent->x(), mouseEvent->y());

    if(!m_pTouch)
        m_pTouch = new CCTouch;

    m_pTouch->SetTouchInfo(point.x, point.y);

    CCSet set;
    set.addObject(m_pTouch);

    m_pDelegate->touchesMoved(&set, NULL);

    QWidget::mouseMoveEvent(event);
}
#endif

bool CCEGLView::initEGL()
{
    if(bIsInit)
        return true;

    EGLNativeWindowType nativeWindow = (EGLNativeWindowType)this->winId();
    EGLNativeDisplayType nativeDisplay = EGL_DEFAULT_DISPLAY;

#ifdef Q_OS_LINUX
    nativeDisplay = (EGLNativeDisplayType)x11Info().display();
#endif // Q_OS_LINUX

#ifdef Q_OS_SYMBIAN
    nativeWindow = (EGLNativeWindowType)(winId()->DrawableWindow());
    nativeDisplay = EGL_DEFAULT_DISPLAY;
#endif // Q_OS_SYMBIAN

    m_eglDisplay = eglGetDisplay(nativeDisplay);
    if(!m_eglDisplay)
    {
        return false;
    }

    if(!eglInitialize(m_eglDisplay, NULL, NULL))
    {
        return false;
    }

    eglBindAPI(EGL_OPENGL_ES_API);

    int configAttributes[] =
    {
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT,
        EGL_DEPTH_SIZE, 16,
        EGL_NONE,
    };

    int configCount = 0;
    if(!eglChooseConfig(m_eglDisplay, configAttributes, &m_eglConfig, 1,
                        &configCount) || configCount != 1)
    {
        CCLOG("eglChooseConfig failed");
        return false;
    }

    m_eglSurface = eglCreateWindowSurface(m_eglDisplay, m_eglConfig,
                                          nativeWindow, NULL);
    if(!m_eglSurface)
    {
        CCLOG("eglCreateWindowSurface failed");
        return false;
    }

    int contextAttributes[] =
    {
        EGL_CONTEXT_CLIENT_VERSION, 1, // 2
        EGL_NONE,
    };

    m_eglContext = eglCreateContext(m_eglDisplay, m_eglConfig, NULL,
                                    contextAttributes);
    if(m_eglContext == EGL_NO_CONTEXT)
    {
        CCLOG("eglCreateContext failed");
        return false;
    }

    if(!eglMakeCurrent(m_eglDisplay, m_eglSurface, m_eglSurface, m_eglContext))
    {
        CCLOG("eglMakeCurrent failed");
        return false;
    }

    if(!initExtensions())
    {
        CCLOG("initExtensions failed");
        return false;
    }

    bIsInit = true;

    return true;
}

void CCEGLView::releaseEGL()
{
    if(m_eglContext)
    {
        eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE,
                       EGL_NO_CONTEXT);
        eglDestroyContext(m_eglDisplay, m_eglContext);
        m_eglContext = NULL;
    }

    if(m_eglSurface)
    {
        eglDestroySurface(m_eglDisplay, m_eglSurface);
        m_eglSurface = NULL;
    }

    m_eglConfig = NULL;

    if(m_eglDisplay)
    {
        eglTerminate(m_eglDisplay);
        m_eglDisplay = NULL;
    }

    bIsInit = false;
}

NS_CC_END;


code:
/**
* Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* For the applicable distribution terms see the license text file included in
* the distribution.
*/

#ifndef CCEGLVIEWQT_H_
#define CCEGLVIEWQT_H_

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

#include <QtGui>
#include <QWidget>

#include <EGL/egl.h>

/*
#ifdef Q_OS_SYMBIAN
#define MS_USE_TOUCH_EVENTS
#define MAX_TOUCH_POINTS 5
#endif
*/

//#ifdef Q_WS_MAEMO_6
#define MS_USE_TOUCH_EVENTS
#define MAX_TOUCH_POINTS 5
//#endif

bool initExtensions();

NS_CC_BEGIN;

class CCSet;
class CCTouch;
class EGLTouchDelegate;

class CC_DLL CCEGLView: public QWidget
{
    Q_OBJECT
public:
    CCEGLView(QWidget* parent = NULL);
    virtual ~CCEGLView();

    virtual bool Create();

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

    int setDeviceOrientation(int eOrientation);
    int getDeviceOrientation() const;
    void setViewPortInPoints(float x, float y, float w, float h);
    void setScissorInPoints(float x, float y, float w, float h);

    void setIMEKeyboardState(bool bOpen);

    float getMainScreenScale();

    bool isIpad() { return false; }

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

protected: // From QWidget (and other base classes)
    void inputMethodEvent(QInputMethodEvent *event);
    bool eventFilter(QObject *object, QEvent *event);
    void paintEvent(QPaintEvent *event);
    virtual void resizeEvent(QResizeEvent *event);

private:
    bool initEGL();
    void releaseEGL();
    bool handleKeyEvent(QEvent*);
    void updateVkbOrientation();
#ifdef MS_USE_TOUCH_EVENTS
    bool handleTouchEvent(QEvent*);
    bool event(QEvent*);
#else
    void mousePressEvent(QMouseEvent *event);
    void mouseReleaseEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
#endif

private:
    bool m_bCaptured;
    bool m_bOrientationReverted;
    bool m_bOrientationInitVertical;

#ifdef MS_USE_TOUCH_EVENTS
    CCTouch *m_pTouch[MAX_TOUCH_POINTS];
#else
    CCTouch *m_pTouch;
#endif
    EGLTouchDelegate * m_pDelegate;

    CCSize m_sSizeInPixel;
    CCSize m_sSizeInPoint;
    CCRect m_rcViewPort;

    bool bIsInit;
    int m_eInitOrientation;
    int m_eOrientation;
    float m_fScreenScaleFactor;

    EGLDisplay  m_eglDisplay;
    EGLConfig   m_eglConfig;
    EGLSurface  m_eglSurface;
    EGLContext  m_eglContext;
};

NS_CC_END;

using namespace cocos2d;

#endif /* CCEGLVIEWLINUX_H_ */


code:
/**
* Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* For the applicable distribution terms see the license text file included in
* the distribution.
*/

#include "CCCommon.h"
#include "ccMacros.h"

#include "CCFileUtils.h"
#include "CCString.h"

#include <QFile>

NS_CC_BEGIN;

static string s_strResourcePath = "";

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

    s_strResourcePath = pszResourcePath;
    s_strResourcePath += "/";
}

const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath)
{
    CCString *pRet = new CCString();

    // check if relative path already contains the resource path
    if(strstr(pszRelativePath, s_strResourcePath.c_str()) == pszRelativePath)
    {
        pRet->autorelease();
        pRet->m_sString = pszRelativePath;
    }
    else
    {
        pRet->autorelease();
        pRet->m_sString = s_strResourcePath + pszRelativePath;
    }

    return pRet->m_sString.c_str();
}

const char *CCFileUtils::fullPathFromRelativeFile(const char *pszFilename,
                                                  const char *pszRelativeFile)
{
    std::string relativeFile = 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)
{
    Q_UNUSED(pszMode);
    QString fullPath(pszFileName);
    unsigned char *pData = 0;

    QFile file(fullPath);
    if (!file.open(QIODevice::ReadOnly))
    {
        if (getIsPopupNotify())
        {
            std::string title = "Notification";
            std::string msg = "Get data from file(";
            msg.append(fullPath.toLatin1()).append(") failed!");
            CCMessageBox(msg.c_str(), title.c_str());
        }
        return NULL;
    }

    *pSize = file.size();
    pData = new unsigned char[*pSize];
    *pSize = file.read((char*)pData, *pSize);
    file.close();

    return pData;
}

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

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

string CCFileUtils::getWriteablePath()
{
    // Return current resource path.
    // TODO: this will not work when using Qt resources
    return s_strResourcePath;
}

NS_CC_END;


code:
/**
* Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* For the applicable distribution terms see the license text file included in
* the distribution.
*/

#include <string.h>

#include <vector>
#include <string>
#include <sstream>

#include <QImage>
#include <QPainter>
#include <QFontDatabase>
#include <QFont>

#include <QMap>

#include "CCPlatformMacros.h"
#include "CCImage.h"
#include "CCStdC.h"

#include "CCFileUtils.h"

NS_CC_BEGIN;

QMap<QString, QString> loadedFontMap;

// TODO: Get rid of this function
static int getBitsPerComponent(const QImage::Format fmt)
{
    switch(fmt)
    {
    case QImage::Format_Mono: return 1;
    case QImage::Format_MonoLSB: return 1;
    case QImage::Format_Indexed8: return 8;
    case QImage::Format_RGB32: return 8;
    case QImage::Format_ARGB32: return 8;
    case QImage::Format_ARGB32_Premultiplied: return 8;
    case QImage::Format_RGB16: return 5;
    case QImage::Format_ARGB8565_Premultiplied: return 8;
    case QImage::Format_RGB666: return 6;
    case QImage::Format_ARGB6666_Premultiplied: return 6;
    case QImage::Format_RGB555: return 5;
    case QImage::Format_ARGB8555_Premultiplied: return 5;
    case QImage::Format_RGB888: return 8;
    case QImage::Format_RGB444: return 4;
    case QImage::Format_ARGB4444_Premultiplied: return 4;
    default:
        CCLOGERROR("Unknown QImage::Format %d", fmt);
        return 0;
    }
}

bool CCImage::initWithString(
        const char * pText,
        int nWidth/* = 0*/,
        int nHeight/* = 0*/,
        ETextAlign eAlignMask/* = kAlignCenter*/,
        const char * pFontName/* = nil*/,
        int nSize/* = 0*/)
{
    if (!pText)
    {
        return false;
    }

    QString fontPath(CCFileUtils::fullPathFromRelativePath(pFontName));

    QString fontFamily = pFontName;
    QString fontStyle = "Normal";

    // font already loaded?
    QMap<QString, QString>::iterator fontIter = loadedFontMap.find(fontPath);
    if(fontIter == loadedFontMap.end())
    {
        int fontID = QFontDatabase::addApplicationFont(fontPath);
        if(fontID != -1)
        {
            QStringList familyList = QFontDatabase::applicationFontFamilies(fontID);

            if(familyList.size() > 0)
                fontFamily = familyList.at(0);
        }

        loadedFontMap.insert(fontPath, fontFamily);
    }
    else
    {
        fontFamily = fontIter.value();
    }

    QFontDatabase fd;
    QFont f = fd.font(fontFamily, fontStyle, nSize);
    f.setPixelSize(nSize);

    QFontMetrics fm(f);

    if (nWidth)
    {
        m_nWidth = (short)nWidth;
    }
    else
    {
        m_nWidth = fm.width(QString(pText));
    }

    if (nHeight)
    {
        m_nHeight = (short)nHeight;
    }
    else
    {
        m_nHeight = fm.height();
    }

    m_bHasAlpha = true;
    m_bPreMulti = false;
    m_pData = new unsigned char[m_nWidth * m_nHeight * 4];
    memset(m_pData, 0, m_nWidth * m_nHeight * 4);
    m_nBitsPerComponent = 8;

    QImage image(m_pData, m_nWidth, m_nHeight, QImage::Format_ARGB32_Premultiplied);
    QPainter painter(&image);
    painter.setFont(f);
    painter.setPen(Qt::white);

    int flags = 0;
    switch (eAlignMask)
    {
    case kAlignCenter: // Horizontal center and vertical center.
        flags |= Qt::AlignHCenter;
        flags |= Qt::AlignVCenter;
        break;
    case kAlignTop: // Horizontal center and vertical top.
        flags |= Qt::AlignHCenter;
        flags |= Qt::AlignTop;
        break;
    case kAlignTopRight: // Horizontal right and vertical top.
        flags |= Qt::AlignRight;
        flags |= Qt::AlignTop;
        break;
    case kAlignRight: // Horizontal right and vertical center.
        flags |= Qt::AlignRight;
        flags |= Qt::AlignVCenter;
        break;
    case kAlignBottomRight: // Horizontal right and vertical bottom.
        flags |= Qt::AlignRight;
        flags |= Qt::AlignBottom;
        break;
    case kAlignBottom: // Horizontal center and vertical bottom.
        flags |= Qt::AlignHCenter;
        flags |= Qt::AlignBottom;
        break;
    case kAlignBottomLeft: // Horizontal left and vertical bottom.
        flags |= Qt::AlignLeft;
        flags |= Qt::AlignBottom;
        break;
    case kAlignLeft: // Horizontal left and vertical center.
        flags |= Qt::AlignLeft;
        flags |= Qt::AlignVCenter;
        break;
    case kAlignTopLeft: // Horizontal left and vertical top.
        flags |= Qt::AlignLeft;
        flags |= Qt::AlignTop;
        break;
    }

    painter.drawText(QRect(0, 0, m_nWidth, m_nHeight), flags, QString(pText));
    painter.end();

    return true;
}

bool CCImage::_initWithJpgData(void * data, int nSize)
{
    QImage image;

    bool bRet = image.loadFromData((const uchar*)data, nSize, "JPG");
    if (!bRet)
        return false;

    // TODO: Better/faster conversion
    QImage convertedImg = image.convertToFormat(
                QImage::Format_ARGB32_Premultiplied);
    convertedImg = convertedImg.rgbSwapped();

    m_bPreMulti = true;
    m_bHasAlpha = convertedImg.hasAlphaChannel();
    m_nBitsPerComponent = cocos2d::getBitsPerComponent(convertedImg.format());
    m_nHeight = (short)convertedImg.height();
    m_nWidth = (short)convertedImg.width();
    m_pData  = new unsigned char[convertedImg.byteCount()];
    memcpy(m_pData, convertedImg.bits(), convertedImg.byteCount());

    return bRet;
}

bool CCImage::_initWithPngData(void * pData, int nDatalen)
{
    QImage image;

    bool bRet = image.loadFromData((const uchar*)pData, nDatalen, "PNG");
    if (!bRet)
        return false;

    // TODO: Better/faster conversion
    QImage convertedImg = image.convertToFormat(
                QImage::Format_ARGB32_Premultiplied);
    convertedImg = convertedImg.rgbSwapped();

    m_bPreMulti = true;
    m_bHasAlpha = convertedImg.hasAlphaChannel();
    m_nBitsPerComponent = cocos2d::getBitsPerComponent(convertedImg.format());
    m_nHeight = (short)convertedImg.height();
    m_nWidth = (short)convertedImg.width();
    m_pData  = new unsigned char[convertedImg.byteCount()];
    memcpy(m_pData, convertedImg.bits(), convertedImg.byteCount());

    return bRet;
}

bool CCImage::_saveImageToPNG(const char * pszFilePath, bool bIsToRGB)
{
    QImage image(m_pData, m_nWidth, m_nHeight, QImage::Format_ARGB32);

    if(bIsToRGB)
        image = image.convertToFormat(QImage::Format_RGB32);

    image = image.rgbSwapped();
    bool bRet = image.save(pszFilePath, "PNG");

    return bRet;
}

bool CCImage::_saveImageToJPG(const char * pszFilePath)
{
    QImage image(m_pData, m_nWidth, m_nHeight, QImage::Format_ARGB32);

    image = image.rgbSwapped();
    bool bRet = image.save(pszFilePath, "JPG");

    return bRet;
}

NS_CC_END;


code:
/**
* Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* For the applicable distribution terms see the license text file included in
* the distribution.
*/

#include "CCSAXParser.h"
#include "CCMutableDictionary.h"
#ifdef Q_OS_SYMBIAN
#include <QXmlSimpleReader>
#include <QXmlDefaultHandler>
#include <QVector>
#else
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlmemory.h>
#include "CCLibxml2.h"
#endif // Q_OS_SYMBIAN
#include "CCFileUtils.h"

NS_CC_BEGIN;

#ifdef Q_OS_SYMBIAN
class CCXmlContentHandler: public QXmlDefaultHandler
{
public:
    CCXmlContentHandler(CCSAXParser* pParser):
        m_pParser(pParser)
    {
    }

    virtual ~CCXmlContentHandler()
    {
    }

    virtual bool characters(const QString& ch)
    {
        QByteArray text = ch.toLatin1();
        CCSAXParser::textHandler(m_pParser, (const CC_XML_CHAR*)text.constData(), text.length());

        return true;
    }

    virtual bool endElement(const QString& namespaceURI, const QString& localName, const QString& qName)
    {
        QByteArray name = qName.toLatin1();
        CCSAXParser::endElement(m_pParser, (const CC_XML_CHAR*)name.constData());

        return true;
    }

    virtual bool startElement(const QString& namespaceURI, const QString& localName, const QString& qName, const QXmlAttributes& atts)
    {
        int attributeCount = atts.count();
        int attributeCount2 = attributeCount * 2;

        QVector<QByteArray> bav(attributeCount2);
        QVector<const char*> strv(attributeCount2+1);
        if(attributeCount > 0)
        {
            for(int i = 0; i < attributeCount; i++)
            {
                bav[i*2+0] = atts.qName(i).toLatin1();
                bav[i*2+1] = atts.value(i).toLatin1();
            }

            for(int i = 0; i < attributeCount2; i++)
                strv[i] = bav[i].constData();
        }

        strv[attributeCount2] = NULL;

        QByteArray name = qName.toLatin1();
        CCSAXParser::startElement(m_pParser, (const CC_XML_CHAR*)name.constData(), (const CC_XML_CHAR**)&strv[0]);

        return true;
    }
private:
    CCSAXParser* m_pParser;
};
#endif

CCSAXParser::CCSAXParser()
{
    m_pDelegator = NULL;

}

CCSAXParser::~CCSAXParser(void)
{
}

bool CCSAXParser::init(const char *pszEncoding)
{
    CC_UNUSED_PARAM(pszEncoding);
    // nothing to do
    return true;
}

bool CCSAXParser::parse(const char *pszFile)
{
#ifdef Q_OS_SYMBIAN
    QFile xmlFile(pszFile);
    xmlFile.open(QIODevice::ReadOnly);
    if(!xmlFile.isOpen())
    {
        return false;
    }

    CCXmlContentHandler xmlContentHandler(this);
    QXmlInputSource xmlSource(&xmlFile);

    QXmlSimpleReader xmlReader;
    xmlReader.setContentHandler(&xmlContentHandler);
    xmlReader.parse(xmlSource);

    return true;
#else
    CCFileData data(pszFile, "rt");
    unsigned long size = data.getSize();
    char *pBuffer = (char*) data.getBuffer();

    if (!pBuffer)
    {
        return false;
    }

    /*
     * this initialize the library and check potential ABI mismatches
     * between the version it was compiled for and the actual shared
     * library used.
     */
    LIBXML_TEST_VERSION
    xmlSAXHandler saxHandler;
    memset( &saxHandler, 0, sizeof(saxHandler) );
    // Using xmlSAXVersion( &saxHandler, 2 ) generate crash as it sets plenty of other pointers...
    saxHandler.initialized = XML_SAX2_MAGIC;  // so we do this to force parsing as SAX2.
    saxHandler.startElement = &CCSAXParser::startElement;
    saxHandler.endElement = &CCSAXParser::endElement;
    saxHandler.characters = &CCSAXParser::textHandler;

    int result = xmlSAXUserParseMemory( &saxHandler, this, pBuffer, size );
    if ( result != 0 )
    {
        return false;
    }
    /*
     * Cleanup function for the XML library.
     */
    xmlCleanupParser();
    /*
     * this is to debug memory for regression tests
     */
#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA)
    xmlMemoryDump();
#endif

    return true;
#endif
}

void CCSAXParser::startElement(void *ctx, const CC_XML_CHAR *name, const CC_XML_CHAR **atts)
{
    ((CCSAXParser*)(ctx))->m_pDelegator->startElement(ctx, (char*)name, (const char**)atts);
}

void CCSAXParser::endElement(void *ctx, const CC_XML_CHAR *name)
{
    ((CCSAXParser*)(ctx))->m_pDelegator->endElement(ctx, (char*)name);
}
void CCSAXParser::textHandler(void *ctx, const CC_XML_CHAR *name, int len)
{
    ((CCSAXParser*)(ctx))->m_pDelegator->textHandler(ctx, (char*)name, len);
}
void CCSAXParser::setDelegator(CCSAXDelegator* pDelegator)
{
    m_pDelegator = pDelegator;
}

NS_CC_END;


code:
/**
* Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* For the applicable distribution terms see the license text file included in
* the distribution.
*/

#include <math.h>
#include "accelerometerfilter.h"

QTM_USE_NAMESPACE

AccelerometerFilter::AccelerometerFilter()
{
    m_pAccel = new QAccelerometer(this);
    m_pAccel->addFilter(this);
    m_pAccel->setDataRate(50);
    m_pAccel->start();
}

AccelerometerFilter::~AccelerometerFilter()
{
    delete m_pAccel;
}

bool AccelerometerFilter::filter(QAccelerometerReading *reading)
{
    // Harmattan landscape
    qreal rx = reading->y();
    qreal ry = -reading->x();
    qreal rz = reading->z();

    emit readingChanged(rx, ry, rz);

    return false;
}


code:
/**
* Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* For the applicable distribution terms see the license text file included in
* the distribution.
*/

#ifndef ACCELEROMETERFILTER_H_
#define ACCELEROMETERFILTER_H_

#include <QAccelerometerFilter>
#include <QAccelerometer>
#include <QVariant>

QTM_USE_NAMESPACE

class AccelerometerFilter : public QObject,
                            public QAccelerometerFilter
{
    Q_OBJECT

public:
    explicit AccelerometerFilter();
    virtual ~AccelerometerFilter();

protected: // from QAccelerometerFilter
    bool filter(QAccelerometerReading *reading);

signals:
    void readingChanged(QVariant x, QVariant y, QVariant z);

private:
    QAccelerometer *m_pAccel;
};

#endif // ACCELEROMETERFILTER_H_


code:
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE := curl_static_prebuilt
LOCAL_MODULE_FILENAME := curl
LOCAL_SRC_FILES := libs/$(TARGET_ARCH_ABI)/libcurl.a
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_STATIC_LIBRARY)