code:
//
//  AccelerometerSimulation.m
//  AccelerometerGraph
//
//  Created by Otto Chrons on 9/26/08.
//  Copyright 2008 Seastringo Oy. All rights reserved.
//

#import "AccelerometerSimulation.h"

// when compiling to ARM (iPhone device), hide everything and use system defaults
// if you wish to use simulation mode even on the device, remove the #if/#endif
#if !TARGET_CPU_ARM

#import <netdb.h>

#define kAccelerometerSimulationPort 10552

@implementation UIAccelerationSimulation

@synthesize timestamp;
@synthesize x;
@synthesize y;
@synthesize z;

-(UIAccelerationSimulation*)initWithTimestamp:(NSTimeInterval)aTimeStamp
											X:(UIAccelerationValue)ax
											Y:(UIAccelerationValue)ay
											Z:(UIAccelerationValue)az
{
	timestamp = aTimeStamp;
	x = ax;
	y = ay;
	z = az;

	return self;
}
@end

@implementation UIAccelerometer (Simulation)

// override the static method and return our simulated version instead
+ (UIAccelerometer *)sharedAccelerometer
{
	return [AccelerometerSimulation getAccelerometer];
}
@end
/*
 // callback that never got called with CFSocket UDP...

 void mySocketCallBack( CFSocketRef s,
 CFSocketCallBackType callbackType,
 CFDataRef address,
 const void *data,
 void *info)
 {
 AccelerometerSimulation *accSim = (AccelerometerSimulation*)info;

 NSLog(@"Data %s received", (char*)data);
 }
 */

// singleton
static AccelerometerSimulation *sharedAccelerometer = NULL;

@implementation AccelerometerSimulation

// this is straight from developer guide example for multi-threaded notifications
- (void) setUpThreadingSupport {
    if ( notifications ) return;

    notifications      = [[NSMutableArray alloc] init];
    notificationLock   = [[NSLock alloc] init];
    notificationThread = [[NSThread currentThread] retain];

    notificationPort = [[NSMachPort alloc] init];
    [notificationPort setDelegate:self];
    [[NSRunLoop currentRunLoop] addPort:notificationPort
								forMode:(NSString *) kCFRunLoopCommonModes];
}

// this is straight from developer guide example

- (void) processNotification:(NSNotification *) notification {
    if( [NSThread currentThread] != notificationThread ) {
        // Forward the notification to the correct thread, this is the socket thread
		NSDate* date = [[NSDate alloc] init];
        [notificationLock lock];
        [notifications addObject:notification];
        [notificationLock unlock];
        [notificationPort sendBeforeDate:date
							  components:nil
									from:nil
								reserved:0];
		[date release];
    }
    else {
		// now we are in the main thread
        // Process the notification here;
		NSString *data = (NSString*)[notification object];

		// parse the data, no error handling!
		NSArray *components = [data componentsSeparatedByString:@","];

		// create our own acceleration object
		[accObject initWithTimestamp:[[components objectAtIndex:1] doubleValue]
								   X:[[components objectAtIndex:2] doubleValue]
								   Y:[[components objectAtIndex:3] doubleValue]
								   Z:[[components objectAtIndex:4] doubleValue]];
		[accelDelegate accelerometer:self didAccelerate:(UIAcceleration*)accObject];
    }
}

// this is straight from developer guide example
- (void) handleMachMessage:(void *) msg {
    [notificationLock lock];
    while ( [notifications count] ) {
        NSNotification *notification = [[notifications objectAtIndex:0] retain];
        [notifications removeObjectAtIndex:0];
        [notificationLock unlock];
        [self processNotification:notification];
        [notification release];
        [notificationLock lock];
    };
    [notificationLock unlock];
}

+ (AccelerometerSimulation *)getAccelerometer
{
	if( sharedAccelerometer == NULL )
		sharedAccelerometer = [[AccelerometerSimulation alloc] initialize];

	return sharedAccelerometer;
}

- (void)threadLoop:(id)object
{
	char buffer[1024];
	// we never exit...
	while(1) {
		int count = recv( udpSocket, buffer, sizeof(buffer), 0 );
		if( count > 0 )
		{
			// got data, let's pass it on
			buffer[count] = 0;
			NSString *str = [[NSString alloc] initWithUTF8String:buffer];
			[[NSNotificationCenter defaultCenter]  postNotificationName:@"ThreadAccelNotification" object:str];
			[str release];
		}

	}
}

// initialize our version of the accelerometer
- (AccelerometerSimulation *)initialize
{
	accObject = [UIAccelerationSimulation alloc];
	isExiting = false;

	// couldn't get the CFSocket version to work with UDP and runloop, so used Berkely sockets and a thread instead

	udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	struct sockaddr_in sin;
	memset(&sin, 0, sizeof(sin));
	// listen on all interfaces
	sin.sin_addr.s_addr = INADDR_ANY;
	sin.sin_len = sizeof(struct sockaddr_in);
	sin.sin_family = AF_INET;
	sin.sin_port = htons(kAccelerometerSimulationPort);

	bind(udpSocket, (const struct sockaddr*)&sin, sizeof(sin));

	// create a separate thread for receiving UDP packets
	thread = [[NSThread alloc] initWithTarget:self
									 selector:@selector(threadLoop:)
									   object:nil];
	[thread start];

	// cross-thread communication setup
	[self setUpThreadingSupport];
	[[NSNotificationCenter defaultCenter]
	 addObserver:self
	 selector:@selector(processNotification:)
	 name:@"ThreadAccelNotification"
	 object:nil];
	/*
	 // create and initialize a socket
	 CFSocketContext ctx;

	 ctx.info = self;
	 ctx.version = 0;
	 ctx.retain = NULL;
	 ctx.release = NULL;
	 ctx.copyDescription = NULL;
	 udpSocket = CFSocketCreate(NULL, PF_INET, SOCK_DGRAM, IPPROTO_UDP, kCFSocketDataCallBack | 0xF, mySocketCallBack, NULL);

	 CFRunLoopSourceRef source;
	 CFDataRef addr;
	 CFSocketError theErr;
	 struct sockaddr_in sin;
	 memset(&sin, 0, sizeof(sin));
	 sin.sin_addr.s_addr = INADDR_ANY;
	 sin.sin_len = sizeof(struct sockaddr_in);
	 sin.sin_family = AF_INET;
	 sin.sin_port = htons(10552);
	 addr = CFDataCreate(NULL, (unsigned char *)&sin, sizeof(sin));
	 theErr = CFSocketConnectToAddress(udpSocket, addr, 0);
	 switch (theErr) {
	 case kCFSocketSuccess:
	 NSLog(@"UDP Logged in");
	 source = CFSocketCreateRunLoopSource(NULL, udpSocket, 0);
	 CFRunLoopAddSource(CFRunLoopGetMain(), source,
	 kCFRunLoopDefaultMode);
	 break;
	 case kCFSocketError:
	 NSLog(@"UDP Error");
	 break;
	 default:
	 NSLog(@"UDP Networking Error");
	 break;
	 }
	 */
	return self;
}

// we grab the delegate setting action
- (void)setDelegate:(id<UIAccelerometerDelegate>)delegate
{
	accelDelegate = delegate;
}

- (id<UIAccelerometerDelegate>)delegate
{
	return accelDelegate;
}
@end

#endif


code:
/*
 * CCAccelerometer_linux.h
 *
 *  Created on: Aug 9, 2011
 *      Author: laschweinski
 */

#ifndef CCACCELEROMETER_LINUX_H_
#define CCACCELEROMETER_LINUX_H_

#include "CCCommon.h"

namespace   cocos2d {

class CCAccelerometer
{
public:
    CCAccelerometer();
    ~CCAccelerometer();

    static CCAccelerometer* sharedAccelerometer() { return NULL; };

    void removeDelegate(CCAccelerometerDelegate* pDelegate) {CC_UNUSED_PARAM(pDelegate);};
    void addDelegate(CCAccelerometerDelegate* pDelegate) {CC_UNUSED_PARAM(pDelegate);};
    void setDelegate(CCAccelerometerDelegate* pDelegate) {CC_UNUSED_PARAM(pDelegate);}
};

}//namespace   cocos2d

#endif /* CCACCELEROMETER_LINUX_H_ */

license: mit


code:
/*
 * CCApplication_linux.cpp
 *
 *  Created on: Aug 8, 2011
 *      Author: laschweinski
 */
#include "CCApplication.h"
#include <unistd.h>
#include <sys/time.h>

#include "CCDirector.h"

NS_CC_BEGIN;

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

static long getCurrentMillSecond() {
	long lLastTime;
	struct timeval stCurrentTime;

	gettimeofday(&stCurrentTime,NULL);
	lLastTime = stCurrentTime.tv_sec*1000+stCurrentTime.tv_usec*0.001; //millseconds
	return lLastTime;
}

CCApplication::CCApplication()
{
	CC_ASSERT(! sm_pSharedApplication);
	sm_pSharedApplication = this;
}

CCApplication::~CCApplication()
{
	CC_ASSERT(this == sm_pSharedApplication);
	sm_pSharedApplication = NULL;
	m_nAnimationInterval = 1.0f/60.0f*1000.0f;
}

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

	for (;;) {
		long iLastTime = getCurrentMillSecond();
		CCDirector::sharedDirector()->mainLoop();
		long iCurTime = getCurrentMillSecond();
		if (iCurTime-iLastTime<m_nAnimationInterval){
			usleep((m_nAnimationInterval - iCurTime+iLastTime)*1000);
		}

	}
	return -1;
}

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(CCRect * rect) {

	if (rect)
	{
		// linux doesn't have status bar.
		*rect = CCRectMake(0, 0, 0, 0);
	}

}

void CCApplication::setAnimationInterval(double interval)
{
	//TODO do something else
	m_nAnimationInterval = interval*1000.0f;
}

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

ccLanguageType CCApplication::getCurrentLanguage()
{
	//TODO
	return kLanguageEnglish;
}

NS_CC_END;


code:
/*
 * CCApplication_linux.h
 *
 *  Created on: Aug 8, 2011
 *      Author: laschweinski
 */

#ifndef CCAPPLICATION_LINUX_H_
#define CCAPPLICATION_LINUX_H_

#include "CCCommon.h"

NS_CC_BEGIN;
class CCRect;

class 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:
    long       m_nAnimationInterval;  //micro second

	static CCApplication * sm_pSharedApplication;
};

NS_CC_END;

#endif /* CCAPPLICATION_LINUX_H_ */


code:
/*
 * CCEGLViewlinux.cpp
 *
 *  Created on: Aug 8, 2011
 *      Author: laschweinski
 */

#include "CCEGLView_linux.h"

#include "CCGL.h"

#include "GL/glfw.h"

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

PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffersEXT = NULL;
PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT = NULL;
PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebufferEXT = NULL;
PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatusEXT = NULL;
PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT = NULL;
PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmapEXT = NULL;

PFNGLGENBUFFERSARBPROC glGenBuffersARB = NULL;
PFNGLBINDBUFFERARBPROC glBindBufferARB = NULL;
PFNGLBUFFERDATAARBPROC glBufferDataARB = NULL;
PFNGLBUFFERSUBDATAARBPROC glBufferSubDataARB = NULL;
PFNGLDELETEBUFFERSARBPROC glDeleteBuffersARB = NULL;

bool initExtensions() {
#define LOAD_EXTENSION_FUNCTION(TYPE, FN)  FN = (TYPE)glfwGetProcAddress(#FN);
	bool bRet = false;
	do {

//		char* p = (char*) glGetString(GL_EXTENSIONS);
//		printf(p);

		/* Supports frame buffer? */
		if (glfwExtensionSupported("GL_EXT_framebuffer_object") != GL_FALSE)
		{

			/* Loads frame buffer extension functions */
			LOAD_EXTENSION_FUNCTION(PFNGLGENERATEMIPMAPEXTPROC,
					glGenerateMipmapEXT);
			LOAD_EXTENSION_FUNCTION(PFNGLGENFRAMEBUFFERSEXTPROC,
					glGenFramebuffersEXT);
			LOAD_EXTENSION_FUNCTION(PFNGLDELETEFRAMEBUFFERSEXTPROC,
					glDeleteFramebuffersEXT);
			LOAD_EXTENSION_FUNCTION(PFNGLBINDFRAMEBUFFEREXTPROC,
					glBindFramebufferEXT);
			LOAD_EXTENSION_FUNCTION(PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC,
					glCheckFramebufferStatusEXT);
			LOAD_EXTENSION_FUNCTION(PFNGLFRAMEBUFFERTEXTURE2DEXTPROC,
					glFramebufferTexture2DEXT);

		} else {
			break;
		}

		if (glfwExtensionSupported("GL_ARB_vertex_buffer_object") != GL_FALSE) {
			LOAD_EXTENSION_FUNCTION(PFNGLGENBUFFERSARBPROC, glGenBuffersARB);
			LOAD_EXTENSION_FUNCTION(PFNGLBINDBUFFERARBPROC, glBindBufferARB);
			LOAD_EXTENSION_FUNCTION(PFNGLBUFFERDATAARBPROC, glBufferDataARB);
			LOAD_EXTENSION_FUNCTION(PFNGLBUFFERSUBDATAARBPROC,
					glBufferSubDataARB);
			LOAD_EXTENSION_FUNCTION(PFNGLDELETEBUFFERSARBPROC,
					glDeleteBuffersARB);
		} else {
			break;
		}
		bRet = true;
	} while (0);
	return bRet;
}

NS_CC_BEGIN;
static CCEGLView* s_pMainWindow = NULL;

CCEGLView::CCEGLView()
: m_bCaptured(false)
, m_bOrientationReverted(false)
, m_bOrientationInitVertical(false)
, m_pDelegate(NULL)
, bIsInit(false)
, m_eInitOrientation(CCDeviceOrientationPortrait)
, m_fScreenScaleFactor(1.0f)
{
	m_pTouch = new CCTouch;
	m_pSet = new CCSet;
	m_sSizeInPoint.width = m_sSizeInPoint.height = 0;
//    SetRectEmpty(&m_rcViewPort);
}

CCEGLView::~CCEGLView()
{
}

void keyEventHandle(int iKeyID,int iKeyState) {
	if (iKeyState ==GLFW_RELEASE) {
		return;
	}

	if (iKeyID == GLFW_KEY_DEL) {
		CCIMEDispatcher::sharedDispatcher()->dispatchDeleteBackward();
	} else if (iKeyID == GLFW_KEY_ENTER) {
		CCIMEDispatcher::sharedDispatcher()->dispatchInsertText("\n", 1);
	} else if (iKeyID == GLFW_KEY_TAB) {

	}
}

void charEventHandle(int iCharID,int iCharState) {
	if (iCharState ==GLFW_RELEASE) {
		return;
	}

	// ascii char
	CCIMEDispatcher::sharedDispatcher()->dispatchInsertText((const char *)&iCharID, 1);

}

void mouseButtonEventHandle(int iMouseID,int iMouseState) {
	if (iMouseID == GLFW_MOUSE_BUTTON_LEFT) {
		//get current mouse pos
		int x,y;
		glfwGetMousePos(&x, &y);
		CCPoint oPoint((float)x,(float)y);

		if (!CCRect::CCRectContainsPoint(s_pMainWindow->m_rcViewPort,oPoint)) {
			CCLOG("not in the viewport");
			return;
		}

		s_pMainWindow->m_pTouch->SetTouchInfo((float)(oPoint.x - s_pMainWindow->m_rcViewPort.origin.x) / s_pMainWindow->m_fScreenScaleFactor,
				(float)(oPoint.y - s_pMainWindow->m_rcViewPort.origin.y) / s_pMainWindow->m_fScreenScaleFactor);
		s_pMainWindow->m_pSet->addObject(s_pMainWindow->m_pTouch);
		s_pMainWindow->m_mousePoint = oPoint;

		if (iMouseState == GLFW_PRESS) {
			s_pMainWindow->m_pDelegate->touchesBegan(s_pMainWindow->m_pSet,NULL);

		} else if (iMouseState == GLFW_RELEASE) {
			s_pMainWindow->m_pDelegate->touchesEnded(s_pMainWindow->m_pSet,NULL);
		}
	}
}

void mousePosEventHandle(int iPosX,int iPosY) {
	int iButtonState = glfwGetMouseButton(GLFW_MOUSE_BUTTON_LEFT);

	//to test move
	if (iButtonState == GLFW_PRESS) {
		if (iPosX!=(int)s_pMainWindow->m_mousePoint.x||iPosY!=(int)s_pMainWindow->m_mousePoint.y) {
			//it movies
			s_pMainWindow->m_pTouch->SetTouchInfo((float)(iPosX- s_pMainWindow->m_rcViewPort.origin.x) / s_pMainWindow->m_fScreenScaleFactor,
					(float)(iPosY - s_pMainWindow->m_rcViewPort.origin.y) / s_pMainWindow->m_fScreenScaleFactor);
			s_pMainWindow->m_pDelegate->touchesMoved(s_pMainWindow->m_pSet, NULL);
			//update new mouse pos
			s_pMainWindow->m_mousePoint.x = iPosX;
			s_pMainWindow->m_mousePoint.y = iPosY;
		}
	}
}

bool CCEGLView::Create(const char* pTitle, int iPixelWidth, int iPixelHeight, int iWidth, int iHeight, int iDepth) {
	bool eResult;
	int u32GLFWFlags = GLFW_WINDOW;
	//create the window by glfw.

	//check
	CCAssert(iPixelWidth!=0&&iPixelHeight!=0, "invalid window's size equal 0");
	CCAssert(iWidth!=0&&iHeight!=0, "invalid the size in points equal 0");

	//Inits GLFW
	eResult = glfwInit() != GL_FALSE;

	if (!eResult) {
		CCAssert(0, "fail to init the glfw");
	}

	/* Updates window hint */
	glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);

	/* Depending on video depth */
	switch(iDepth)
	{
		/* 16-bit */
		case 16:
		{
			/* Updates video mode */
			eResult = (glfwOpenWindow(iPixelWidth, iPixelHeight, 5, 6, 5, 0, 16, 0, (int)u32GLFWFlags) != false) ? true : false;

			break;
		}

		/* 24-bit */
		case 24:
		{
			/* Updates video mode */
			eResult = (glfwOpenWindow(iPixelWidth, iPixelHeight, 8, 8, 8, 0, 16, 0, (int)u32GLFWFlags) != false) ? true : false;

			break;
		}

		/* 32-bit */
		default:
		case 32:
		{
			/* Updates video mode */
			eResult = (glfwOpenWindow(iPixelWidth, iPixelHeight, 8, 8, 8, 8, 16, 0, (int)u32GLFWFlags) != GL_FALSE) ? true :false;
			break;
		}
	}

	/* Success? */
	if(eResult)
	{

		/* Updates actual size */
		glfwGetWindowSize(&iPixelWidth, &iPixelHeight);

		//assign screen size and point's size
		m_sSizeInPixel.width = iPixelWidth;
		m_sSizeInPixel.height = iPixelHeight;

		m_sSizeInPoint.width = iWidth;
		m_sSizeInPoint.height = iHeight;

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

		/* Updates its title */
		glfwSetWindowTitle(pTitle);

		//set the init flag
		bIsInit = true;
		s_pMainWindow = this;

		//register the glfw key event
		glfwSetKeyCallback(keyEventHandle);
		//register the glfw char event
		glfwSetCharCallback(charEventHandle);
		//register the glfw mouse event
		glfwSetMouseButtonCallback(mouseButtonEventHandle);
		//register the glfw mouse pos event
		glfwSetMousePosCallback(mousePosEventHandle);

		//Inits extensions
		eResult = initExtensions();

		if (!eResult) {
			CCAssert(0, "fail to init the extensions of opengl");
		}

	}
	return true;
}

CCSize CCEGLView::getSize()
{
	return CCSize((float)(m_sSizeInPoint.width), (float)(m_sSizeInPoint.height));
}

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

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

void CCEGLView::release()
{
	/* Exits from GLFW */
	glfwTerminate();
	exit(0);
}

void CCEGLView::setTouchDelegate(EGLTouchDelegate * pDelegate) {
	//TODO touch event
	m_pDelegate = pDelegate;

}
void CCEGLView::swapBuffers() {
	if (bIsInit) {
		/* Swap buffers */
		glfwSwapBuffers();
	}
}

int CCEGLView::setDeviceOrientation(int eOritation) {
	CCLog("warning:could not setDeviceOrientation after initialized");
    return -1;
}

void CCEGLView::setViewPortInPoints(float x, float y, float w, float h) {
//	TODO
	if (bIsInit) {
		float factor = m_fScreenScaleFactor / CC_CONTENT_SCALE_FACTOR();
		glViewport((GLint)(x * factor) + m_rcViewPort.origin.x,
				(GLint)(y * factor) + m_rcViewPort.origin.y,
				(GLint)(w * factor),
				(GLint)(h * factor));
	}
}
void CCEGLView::setScissorInPoints(float x, float y, float w, float h) {
	//TODO
	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::setIMEKeyboardState(bool bOpen) {

}

//void CCEGLView::resize(int width, int height) {
//	//TODO
//	return;
//}

//void CCEGLView::centerWindow() {
//	//TODO
//	return;
//}
//void CCEGLView::setScreenScale(float factor) {
//	m_fScreenScaleFactor = factor;
//
//}

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

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

}

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

NS_CC_END;


code:
/*
 * CCEGLViewlinux.h
 *
 *  Created on: Aug 8, 2011
 *      Author: laschweinski
 */

#ifndef CCEGLVIEWLINUX_H_
#define CCEGLVIEWLINUX_H_

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

bool initExtensions();

NS_CC_BEGIN;

class CCSet;
class CCTouch;
class EGLTouchDelegate;

class CCEGLView {
public:
	CCEGLView();
	virtual ~CCEGLView();

	friend void keyEventHandle(int,int);
	friend void mouseButtonEventHandle(int,int);
	friend void mousePosEventHandle(int,int);
	friend void charEventHandle(int,int);

	/**
	 * iPixelWidth, height: the window's size
	 * iWidth ,height: the point size, which may scale.
	 * iDepth is not the buffer depth of opengl, it indicate how may bits for a pixel
	 */
	virtual bool Create(const char* pTitle, int iPixelWidth, int iPixelHeight, int iWidth, int iHeight, int iDepth=16);

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

	int setDeviceOrientation(int eOritation);
	void setViewPortInPoints(float x, float y, float w, float h);
	void setScissorInPoints(float x, float y, float w, float h);

	float getMainScreenScale() { return 1.0f; }

	void setIMEKeyboardState(bool bOpen);

//	void resize(int width, int height);

	/**
	 * not essential
	 */
//	void centerWindow();
//	void setScreenScale(float factor);

	/**
	 * the width and height is the real size of phone
	 */
	void setFrameWidthAndHeight(int width, int height);

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

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

	//store current mouse point for moving, valid if and only if the mouse pressed
	CCPoint m_mousePoint;

	EGLTouchDelegate * m_pDelegate;

	CCSize m_sSizeInPixel;
	CCSize m_sSizeInPoint;
	CCRect m_rcViewPort;

	bool bIsInit;
	int m_eInitOrientation;
	float m_fScreenScaleFactor;
};

NS_CC_END;

#endif /* CCEGLVIEWLINUX_H_ */


code:
/*
 * CCFileUtils_linux.cpp
 *
 *  Created on: Aug 9, 2011
 *      Author: laschweinski
 */
#include "CCCommon.h"
#include "ccMacros.h"

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

#include <unistd.h>

using namespace std;

NS_CC_BEGIN;

static string s_strResourcePath = "";

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

//	s_strResourcePath = pszResourcePath;
	/* Sets current directory */
	if(chdir(pszResourcePath) < 0)
	{
		CCLog("set base folder error");
	}
}

const char* CCFileUtils::fullPathFromRelativePath(const char *pszRelativePath) {
	CCString *pRet = new CCString();
	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) {

	string fullPath = pszFileName;
	unsigned char * pData = 0;

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

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

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

}

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

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

string CCFileUtils::getWriteablePath() {
	//return current resource path
	return s_strResourcePath;
}

NS_CC_END;


code:
#include <string.h>

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

#include "CCFileUtils.h"

#include "CCPlatformMacros.h"
#include "CCImage.h"
#include "ft2build.h"
#include "CCStdC.h"
#include FT_FREETYPE_H
#ifdef USE_FONTCONFIG
	#include <fontconfig/fontconfig.h>
#endif

#define szFont_kenning 2

#define SHIFT6(num) (num>>6)

using namespace std;

struct TextLine {
	string sLineStr;
	int iLineWidth;
};

NS_CC_BEGIN;
class BitmapDC
{
public:
	BitmapDC() {
		libError = FT_Init_FreeType( &library );
		iInterval = szFont_kenning;
		m_pData = NULL;
		reset();

#ifdef USE_FONTCONFIG
		libError |= ! FcInit();
#endif
	}

	~BitmapDC() {
		FT_Done_FreeType(library);
		//data will be deleted by CCImage
//		if (m_pData) {
//			delete m_pData;
//		}
#ifdef USE_FONTCONFIG
		FcFini();
#endif

	}

	void reset() {
		iMaxLineWidth = 0;
		iMaxLineHeight = 0;
		vLines.clear();
	}

	void buildLine(stringstream& ss, FT_Face face, int iCurXCursor, char cLastChar) {
		TextLine oTempLine;
		ss << '\0';
		oTempLine.sLineStr = ss.str();
		//get last glyph
		FT_Load_Glyph(face, FT_Get_Char_Index(face, cLastChar),
				FT_LOAD_DEFAULT);

        oTempLine.iLineWidth = iCurXCursor - SHIFT6((face->glyph->metrics.horiAdvance + face->glyph->metrics.horiBearingX - face->glyph->metrics.width))/*-iInterval*/;//TODO interval
		iMaxLineWidth = MAX(iMaxLineWidth, oTempLine.iLineWidth);
		ss.clear();
		ss.str("");
		vLines.push_back(oTempLine);
	}

	bool divideString(FT_Face face, const char* sText, int iMaxWidth, int iMaxHeight) {
		const char* pText = sText;
		int iError = 0;
		int iCurXCursor;
		iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText),
				FT_LOAD_DEFAULT);
		if (iError) {
			return false;
		}
		iCurXCursor = -SHIFT6(face->glyph->metrics.horiBearingX);
		//init stringstream
		stringstream ss;

		int cLastCh = 0;

		while (*pText != '\0') {
			if (*pText == '\n') {
				buildLine(ss, face, iCurXCursor, cLastCh);

				pText++;
				iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText),
						FT_LOAD_DEFAULT);
				if (iError) {
					return false;
				}
				iCurXCursor = -SHIFT6(face->glyph->metrics.horiBearingX);
				continue;
			}

			iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText),
					FT_LOAD_DEFAULT);

			if (iError) {
				return false;
				//break;
			}
			//check its width
			//divide it when exceeding
			if ((iMaxWidth > 0
							&& iCurXCursor + SHIFT6(face->glyph->metrics.width)
							> iMaxWidth)) {
				buildLine(ss, face , iCurXCursor, cLastCh);

				iCurXCursor = -SHIFT6(face->glyph->metrics.horiBearingX);

			}

			cLastCh = *pText;
			ss << *pText;
			iCurXCursor += SHIFT6(face->glyph->metrics.horiAdvance) + iInterval;
			pText++;

		}
		if (iError) {
			return false;
		}

		buildLine(ss,face, iCurXCursor, cLastCh);

		return true;
	}

	/**
	 * compute the start pos of every line
	 *
	 * return >0 represent the start x pos of the line
	 * while -1 means fail
	 *
	 */
	int computeLineStart(FT_Face face, CCImage::ETextAlign eAlignMask, char cText,
			int iLineIndex) {
		int iRet;
		int iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, cText),
				FT_LOAD_DEFAULT);
		if (iError) {
			return -1;
		}

		if (eAlignMask == CCImage::kAlignCenter) {
			iRet = (iMaxLineWidth - vLines[iLineIndex].iLineWidth) / 2
			- SHIFT6(face->glyph->metrics.horiBearingX );

		} else if (eAlignMask == CCImage::kAlignRight) {
			iRet = (iMaxLineWidth - vLines[iLineIndex].iLineWidth)
			- SHIFT6(face->glyph->metrics.horiBearingX );
		} else {
			// left or other situation
			iRet = -SHIFT6(face->glyph->metrics.horiBearingX );
		}
		return iRet;
	}

	bool getBitmap(const char *text, int nWidth, int nHeight, CCImage::ETextAlign eAlignMask, const char * pFontName, float fontSize) {
		FT_Face face;
		FT_Error iError;

		const char* pText = text;
		//data will be deleted by CCImage
//		if (m_pData) {
//			delete m_pData;
//		}

		int iCurXCursor, iCurYCursor;
		bool bRet = false;
		if (libError) {
			return false;
		}
		do {
			iError = FT_New_Face( library, pFontName, 0, &face );

			if (iError) {
				//no valid font found use default
//				CCLog("no valid font, use default %s\n", pFontName);
				iError = FT_New_Face( library, "/usr/share/fonts/truetype/freefont/FreeSerif.ttf", 0, &face );
			}
			CC_BREAK_IF(iError);

			//select utf8 charmap
			iError = FT_Select_Charmap(face,FT_ENCODING_UNICODE);
			CC_BREAK_IF(iError);

			iError = FT_Set_Pixel_Sizes(face, fontSize,fontSize);
			CC_BREAK_IF(iError);

			iError = divideString(face, text, nWidth, nHeight)?0:1;

			//compute the final line width
			iMaxLineWidth = MAX(iMaxLineWidth, nWidth);

			iMaxLineHeight = (face->size->metrics.ascender >> 6)
			- (face->size->metrics.descender >> 6);
			iMaxLineHeight *= vLines.size();

			//compute the final line height
			iMaxLineHeight = MAX(iMaxLineHeight, nHeight);
			m_pData = new unsigned char[iMaxLineWidth * iMaxLineHeight*4];
			iCurYCursor = SHIFT6(face->size->metrics.ascender);

			memset(m_pData,0, iMaxLineWidth * iMaxLineHeight*4);

            for (size_t i = 0; i < vLines.size(); i++) {
				pText = vLines[i].sLineStr.c_str();
				//initialize the origin cursor
				iCurXCursor = computeLineStart(face, eAlignMask, *pText, i);

				while (*pText != 0) {
					int iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText),
							FT_LOAD_RENDER);
					if (iError) {
						break;
					}

					//  convert glyph to bitmap with 256 gray
					//  and get the bitmap
					FT_Bitmap & bitmap = face->glyph->bitmap;

					for (int i = 0; i < bitmap.rows; ++i) {
						for (int j = 0; j < bitmap.width; ++j) {
							//  if it has gray>0 we set show it as 1, o otherwise
							int iY = iCurYCursor + i
							- (face->glyph->metrics.horiBearingY
									>> 6);
							int iX = iCurXCursor
							+ (face->glyph->metrics.horiBearingX
									>> 6) + j;

							if (iY>=iMaxLineHeight) {
								//exceed the height truncate
								continue;
							}

//							m_pData[(iY * iMaxLineWidth + iX) * 4 + 3] =
//							bitmap.buffer[i * bitmap.width + j] ?
//							0xff : 0;//alpha
//							m_pData[(iY * iMaxLineWidth + iX) * 4 + 1] =
//							bitmap.buffer[i * bitmap.width + j];//R
//							m_pData[(iY * iMaxLineWidth + iX) * 4 + 2] =
//							bitmap.buffer[i * bitmap.width + j];//G
//							m_pData[(iY * iMaxLineWidth + iX) * 4 + 0] =
//							bitmap.buffer[i * bitmap.width + j];//B
							int iTemp = 0;
							unsigned char cTemp = bitmap.buffer[i
							* bitmap.width + j];
							iTemp |= (cTemp ? 0xff : 0)<<24;
							iTemp |= cTemp << 16 | cTemp << 8 | cTemp;
							*(int*) &m_pData[(iY * iMaxLineWidth + iX)
							* 4 + 0] = iTemp;
						}
					}
					//step to next glyph
					iCurXCursor += (face->glyph->metrics.horiAdvance >> 6)
					+ iInterval;

					pText++;
				}
				iCurYCursor += (face->size->metrics.ascender >> 6)
				- (face->size->metrics.descender >> 6);
			}
			//print all image bitmap
//			for (int i = 0; i < iMaxLineHeight; i++) {
//				for (int j = 0; j < iMaxLineWidth; j++) {
//					printf("%d",
//							m_pData[(i * iMaxLineWidth + j) * 4] ? 1 : 0);
//				}
//				printf("\n");
//			}

			//  free face
			FT_Done_Face(face);
			face = NULL;

			//clear all lines
			vLines.clear();

			//success;
			if (iError) {
				bRet = false;
			} else
			bRet = true;
		}while(0);

		return bRet;
	}
public:
	FT_Library library;
	unsigned char *m_pData;
	int libError;
	vector<TextLine> vLines;
	int iInterval;
	int iMaxLineWidth;
	int iMaxLineHeight;
};

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*/)
{
#ifdef USE_FONTCONFIG
	FcPattern *pat = NULL, *match = NULL;
#endif

	bool bRet = false;
	do
	{
		CC_BREAK_IF(! pText);

		BitmapDC &dc = sharedBitmapDC();

#ifdef USE_FONTCONFIG
		// convert pFontName into a fontconfig pattern
		pat = FcNameParse( (FcChar8 *) pFontName );
		CC_BREAK_IF( ! pat );

		// set pattern substitution
		FcConfigSubstitute( 0, pat, FcMatchPattern );
		FcDefaultSubstitute( pat );

		// look for a match
		FcResult result;
		match = FcFontMatch( 0, pat, &result );
		CC_BREAK_IF( ! match );

		// gett result file name
		FcValue v;
		FcPatternGet( match, "file", 0, &v );
		const char* pFullFontName = (const char*) v.u.s;
		CC_BREAK_IF(! pFullFontName);
#else
		const char* pFullFontName = CCFileUtils::fullPathFromRelativePath(pFontName);
#endif

		CC_BREAK_IF(! dc.getBitmap(pText, nWidth, nHeight, eAlignMask, pFullFontName, nSize));

		// assign the dc.m_pData to m_pData in order to save time
		m_pData = dc.m_pData;
		CC_BREAK_IF(! m_pData);

		m_nWidth = (short)dc.iMaxLineWidth;
		m_nHeight = (short)dc.iMaxLineHeight;
		m_bHasAlpha = true;
		m_bPreMulti = true;
		m_nBitsPerComponent = 8;

		bRet = true;

		dc.reset();
	}while (0);

#ifdef USE_FONTCONFIG
	if( pat ) FcPatternDestroy( pat );
	if( match ) FcPatternDestroy( match );
#endif

	//do nothing
	return bRet;
}

NS_CC_END;


code:
/****************************************************************************
 Copyright (c) 2011      cocos2d-x.org   http://cocos2d-x.org
 Copyright (c) 2011      Максим Аксенов
 Copyright (c) 2011      Giovanni Zito, Francis Styck

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

#include "CCAccelerometer_marmalade.h"
#include "ccMacros.h"

namespace cocos2d
{

CCAccelerometer* CCAccelerometer::m_spCCAccelerometer = NULL;

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

CCAccelerometer::~CCAccelerometer()
{
	if( m_spCCAccelerometer ) {
		delete m_spCCAccelerometer ;
		m_spCCAccelerometer = NULL;
	}
}

CCAccelerometer* CCAccelerometer::sharedAccelerometer()
{

	if (m_spCCAccelerometer == NULL)
	{
		m_spCCAccelerometer = new CCAccelerometer();
	}

	return m_spCCAccelerometer;
}

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

	if (pDelegate)
	{
		if (s3eAccelerometerStart() != S3E_RESULT_SUCCESS)
		{
			CCLog("s3eAccelerometerStart() - ERROR\n");
		}
	}
	else
	{
		s3eAccelerometerStop();
	}
}

void CCAccelerometer::update(float x, float y, float z, uint64 sensorTimeStamp)
{
	if (m_pAccelDelegate)
	{
		m_obAccelerationValue.x = ((double)x)/S3E_ACCELEROMETER_1G ;
		m_obAccelerationValue.y = ((double)y)/S3E_ACCELEROMETER_1G ;
		m_obAccelerationValue.z = ((double)z)/S3E_ACCELEROMETER_1G ;
		m_obAccelerationValue.timestamp = (double)(sensorTimeStamp / 1000.0);

		m_pAccelDelegate->didAccelerate(&m_obAccelerationValue);
	}
}

} // end of namespace cococs2d


code:
/****************************************************************************
 Copyright (c) 2011      cocos2d-x.org   http://cocos2d-x.org
 Copyright (c) 2011      Максим Аксенов
 Copyright (c) 2011      Giovanni Zito, Francis Styck

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/
#ifndef __PLATFORM_MARMALADE_ACCELEROMETER_H__
#define __PLATFORM_MARMALADE_ACCELEROMETER_H__

#include "CCAccelerometerDelegate.h"
#include "CCMutableArray.h"
#include "ccCommon.h"

namespace   cocos2d {

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

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

	void setDelegate(CCAccelerometerDelegate* pDelegate);
	void update(float x, float y, float z, uint64 sensorTimeStamp);

private:
	static CCAccelerometer* m_spCCAccelerometer;
	CCAccelerometerDelegate* m_pAccelDelegate;
	CCAcceleration m_obAccelerationValue;
};

}//namespace   cocos2d

#endif


code:
/****************************************************************************
 Copyright (c) 2011      cocos2d-x.org   http://cocos2d-x.org
 Copyright (c) 2011      Максим Аксенов
 Copyright (c) 2011      Giovanni Zito, Francis Styck

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

#include "CCApplication.h"
#include "CCEGLView.h"
#include "CCDirector.h"
#include "CCAccelerometer.h"
#include "CCTouchDispatcher.h"

#include <s3e.h>
#include <IwMemBucketHelpers.h>

NS_CC_BEGIN;

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

CCApplication::CCApplication()
{
	IW_CALLSTACK("CCApplication::CCApplication");

	m_nAnimationInterval = 0;
	CC_ASSERT(! sm_pSharedApplication);
	sm_pSharedApplication = this;
}

CCApplication::~CCApplication()
{
	IW_CALLSTACK("CCApplication::~CCApplication");

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

int CCApplication::Run()
{
	IW_CALLSTACK("CCApplication::Run");

	s3eBool quitRequested = 0;

	if ( ! initInstance() || !applicationDidFinishLaunching() )
	{
		return 0;
	}

	uint64 updateTime = 0 ;

	while (true)
	{
		updateTime = s3eTimerGetMs();

		s3eDeviceYield(0);
		s3eKeyboardUpdate();
		s3ePointerUpdate();

		ccAccelerationUpdate();

		quitRequested = s3eDeviceCheckQuitRequest() ;
		if( quitRequested && CCDirector::sharedDirector()->getOpenGLView() != NULL ) {
			CCDirector::sharedDirector()->end() ;
			// end status will be processed in CCDirector::sharedDirector()->mainLoop();
		}

		CCDirector::sharedDirector()->mainLoop();

		if( quitRequested ) {
			break ;
		}

		while ((s3eTimerGetMs() - updateTime) < m_nAnimationInterval) {
			int32 yield = (int32) (m_nAnimationInterval - (s3eTimerGetMs() - updateTime));
			if (yield<0)
				break;
			s3eDeviceYield(yield);
		}

	}
	return -1;
}

void CCApplication::setAnimationInterval(double interval)
{
	IW_CALLSTACK("CCXApplication::setAnimationInterval");
	m_nAnimationInterval = 1000 * interval;

}

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

void CCApplication::statusBarFrame(CCRect * rect)
{
	if (rect)
	{
		*rect = CCRectMake(0, 0, 0, 0);
	}
}
void CCApplication::ccAccelerationUpdate()
{
// Accelerometer doesn't work on Marmalade X86 MacOS-X simulator
#if !(defined(__APPLE__) && defined(I3D_ARCH_X86))
	CCAccelerometer::sharedAccelerometer()->update(s3eAccelerometerGetX(),s3eAccelerometerGetY(),s3eAccelerometerGetZ(),s3eTimerGetMs());
#endif
}

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

ccLanguageType CCApplication::getCurrentLanguage()
{
	int nLanguageIdx;
	ccLanguageType currentLanguage;

	nLanguageIdx = s3eDeviceGetInt(S3E_DEVICE_LANGUAGE);

	switch (nLanguageIdx)
	{
		case S3E_DEVICE_LANGUAGE_ENGLISH:
			currentLanguage = kLanguageEnglish;
			break;

		case S3E_DEVICE_LANGUAGE_SIMPL_CHINESE:
		case  S3E_DEVICE_LANGUAGE_TRAD_CHINESE:
			currentLanguage = kLanguageChinese;
			break;

		case S3E_DEVICE_LANGUAGE_FRENCH:
			currentLanguage = kLanguageFrench;
			break;

		case S3E_DEVICE_LANGUAGE_ITALIAN:
			currentLanguage = kLanguageItalian;
			break;

		case S3E_DEVICE_LANGUAGE_GERMAN:
			currentLanguage = kLanguageGerman;
			break;

		case S3E_DEVICE_LANGUAGE_SPANISH:
			currentLanguage = kLanguageSpanish;
			break;

		case S3E_DEVICE_LANGUAGE_RUSSIAN:
			currentLanguage = kLanguageItalian;
			break;

		default:
			currentLanguage = kLanguageRussian;
			break;
	}
	return currentLanguage;
}

NS_CC_END;


code:
/****************************************************************************
 Copyright (c) 2011      cocos2d-x.org   http://cocos2d-x.org
 Copyright (c) 2011      Максим Аксенов
 Copyright (c) 2011      Giovanni Zito, Francis Styck

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

#ifndef __CC_APPLICATION_MARMALADE_H__
#define __CC_APPLICATION_MARMALADE_H__

#include "CCCommon.h"

#include "CCGeometry.h"
#include "CCDirector.h"
#include "IwUtil.h"
#include "IwUtilInitTerm.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 sense 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;

	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.
	 */
    virtual int Run();

	void ccAccelerationUpdate();
	/**
	@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:
	uint64       m_nAnimationInterval;

	static CCApplication * sm_pSharedApplication;
};

NS_CC_END;
#endif	// end of __CC_APPLICATION_MARMALADE_H__


code:
/****************************************************************************
 Copyright (c) 2011      cocos2d-x.org   http://cocos2d-x.org
 Copyright (c) 2011      Максим Аксенов
 Copyright (c) 2011      Giovanni Zito, Francis Styck

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

#include "CCEGLView.h"

#include "IwGL.h"

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

#include <stdlib.h>
#include <s3eOSReadString.h>

NS_CC_BEGIN;

CCEGLView* CCEGLView::m_pInstance = 0 ;

CCEGLView::CCEGLView()
: m_pDelegate(NULL)
, m_fScreenScaleFactor(1.0)
, m_bNotHVGA(false)
, m_bCaptured(false)
, m_bAccelState(false)
, m_Key(s3eKeyFirst)
{
	IW_CALLSTACK("CCEGLView::CCEGLView");

	IwGLInit();

	m_sSizeInPixel.width = IwGLGetInt(IW_GL_WIDTH);
	m_sSizeInPixel.height = IwGLGetInt(IW_GL_HEIGHT);

    m_pSet      = new CCSet;
	m_pTouch    = new CCTouch;

    // Determine if the device supports multi-touch
    m_isMultiTouch = s3ePointerGetInt(S3E_POINTER_MULTI_TOUCH_AVAILABLE) ? true : false;

	// For multi-touch devices we handle touch and motion events using different callbacks
    if (m_isMultiTouch)
    {
        s3ePointerRegister(S3E_POINTER_TOUCH_EVENT, &MultiTouchEventHandler, this);
        s3ePointerRegister(S3E_POINTER_TOUCH_MOTION_EVENT, &MultiMotionEventHandler, this);

        for (int i = 0; i < S3E_POINTER_TOUCH_MAX; i++) {
            touchSet[i] = NULL;
        }
    }
    else
    {
        // Register pointer touch button event handler
        s3ePointerRegister(S3E_POINTER_BUTTON_EVENT, &TouchEventHandler, this);

        // Register pointer motion button event handler
        s3ePointerRegister(S3E_POINTER_MOTION_EVENT, &MotionEventHandler, this);
    }

    // Register keyboard event handler
//	s3eKeyboardRegister(S3E_KEYBOARD_KEY_EVENT, &KeyEventHandler, this);
//	s3eKeyboardRegister(S3E_KEYBOARD_CHAR_EVENT, &CharEventHandler, this);
}

void CCEGLView::setFrameWidthAndHeight(int width, int height)
{
	m_sSizeInPixel.width = width;
	m_sSizeInPixel.height = height;
}
void CCEGLView::create(int width, int height)
{
	if (width == 0 || height == 0)
	{
		return;
	}

	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;

}
CCEGLView::~CCEGLView()
{
	IW_CALLSTACK("CCEGLView::~CCEGLView");

	CC_SAFE_DELETE(m_pDelegate);
    CC_SAFE_DELETE(m_pSet);
	CC_SAFE_DELETE(m_pTouch);

}

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

}

void CCEGLView::setTouch(void* systemData)
{
	s3ePointerEvent* event =(s3ePointerEvent*)systemData;

	switch (event->m_Pressed)
	{
	case S3E_POINTER_STATE_DOWN :
		m_bCaptured = true;
		m_pTouch->SetTouchInfo((float)event->m_x, (float)event->m_y);
		m_pSet->addObject(m_pTouch);
		m_pDelegate->touchesBegan(m_pSet, NULL);
		break;

	case S3E_POINTER_STATE_UP :
		if (m_bCaptured)
		{
			m_pTouch->SetTouchInfo((float)event->m_x, (float)event->m_y);
			m_pDelegate->touchesEnded(m_pSet, NULL);
			m_pSet->removeObject(m_pTouch);
			m_bCaptured = false;
		}
		break;
	}
}

void CCEGLView::setMotionTouch(void* systemData)
{
		s3ePointerMotionEvent* event =(s3ePointerMotionEvent*)systemData;
		if (m_bCaptured)
		{
            m_pTouch->SetTouchInfo((float)event->m_x, (float)event->m_y);
            m_pDelegate->touchesMoved(m_pSet, NULL);

		}
}

void CCEGLView::setMultiTouch(void* systemData)
{
	s3ePointerTouchEvent* event =(s3ePointerTouchEvent*)systemData;

    if (touchSet[event->m_TouchID] == NULL) {
        m_pTouch = new CCTouch;
        touchSet[event->m_TouchID] = m_pTouch;
    }
    else {
        m_pTouch = touchSet[event->m_TouchID];
    }

	switch (event->m_Pressed)
	{
        case S3E_POINTER_STATE_DOWN :
            m_pTouch->SetTouchInfo((float)event->m_x, (float)event->m_y);
            m_pSet->addObject(m_pTouch);
            m_pDelegate->touchesBegan(m_pSet, NULL);
            break;

        case S3E_POINTER_STATE_UP :
            {
                m_pTouch->SetTouchInfo((float)event->m_x, (float)event->m_y);
                m_pDelegate->touchesEnded(m_pSet, NULL);
                m_pSet->removeObject(m_pTouch);
                touchSet[event->m_TouchID] = NULL;
            }
            break;
	}
}

void CCEGLView::setMultiMotionTouch(void* systemData)
{
    s3ePointerTouchMotionEvent* event =(s3ePointerTouchMotionEvent*)systemData;
     m_pTouch = touchSet[event->m_TouchID];
    if (m_pTouch)
    {
        m_pTouch->SetTouchInfo((float)event->m_x, (float)event->m_y);
        m_pDelegate->touchesMoved(m_pSet, NULL);

    }
}

void CCEGLView::setKeyTouch(void* systemData)
{
// 	s3eKeyboardEvent* event = (s3eKeyboardEvent*)systemData;
// 	if (event->m_Pressed)
// 	{
// 		if (event->m_Key!=m_Key)
// 		{
// 			CCKeypadDispatcher::sharedDispatcher()->dispatchKeypadMSG(kTypeMenuClicked);
// 		}
// 		else
// 		{
// 			CCKeypadDispatcher::sharedDispatcher()->dispatchKeypadMSG(kTypeBackClicked);
//
// 		}
// 		m_Key =event->m_Key;
// 	}
}

void CCEGLView::setCharTouch( void* systemData )
{
//     s3eKeyboardCharEvent* event = (s3eKeyboardCharEvent*)systemData;
// 	s3eWChar c = event->m_Char ;
// 	CCIMEDispatcher::sharedDispatcher()->dispatchInsertText((const char *)&c, 1);
}

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

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

void CCEGLView::release()
{
	IW_CALLSTACK("CCEGLView::release");

    if (m_isMultiTouch)
    {
        s3ePointerUnRegister(S3E_POINTER_TOUCH_EVENT, &MultiTouchEventHandler);
        s3ePointerUnRegister(S3E_POINTER_TOUCH_MOTION_EVENT, &MultiMotionEventHandler);
    }
    else
    {
        s3ePointerUnRegister(S3E_POINTER_BUTTON_EVENT, &TouchEventHandler);
        s3ePointerUnRegister(S3E_POINTER_MOTION_EVENT, &MotionEventHandler);
    }

//	s3eKeyboardUnRegister(S3E_KEYBOARD_KEY_EVENT, &KeyEventHandler);
//	s3eKeyboardUnRegister(S3E_KEYBOARD_KEY_EVENT, &CharEventHandler);

	if (IwGLIsInitialised())
  		IwGLTerminate();

	 s3eDeviceRequestQuit() ;

	 delete this ;
}

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

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

void CCEGLView::swapBuffers()
{
	IW_CALLSTACK("CCEGLView::swapBuffers(");
	IwGLSwapBuffers();
}

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

void CCEGLView::setIMEKeyboardState(bool bOpen)
{
	if(bOpen && s3eOSReadStringAvailable() == S3E_TRUE) {
		const char* inputText = s3eOSReadStringUTF8("") ;
		if( inputText!=0 ) {
			CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(inputText, strlen(inputText));
		}
	}
}

CCEGLView& CCEGLView::sharedOpenGLView()
{
	if( !m_pInstance ) {
		m_pInstance = new CCEGLView() ;
	}
	return *m_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;
	}
}

NS_CC_END;


code:
/****************************************************************************
 Copyright (c) 2011      cocos2d-x.org   http://cocos2d-x.org
 Copyright (c) 2011      Максим Аксенов
 Copyright (c) 2011      Giovanni Zito, Francis Styck

 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_MARMALADE_H__
#define __CC_EGLVIEW_MARMALADE_H__

#include "CCGeometry.h"
#include "s3eKeyboard.h"
#include "s3ePointer.h"
#include "IwUtil.h"

NS_CC_BEGIN;
class CCSet;
class CCTouch;
class EGLTouchDelegate;
class CCKeypadDelegate;

class CC_DLL CCEGLView
{
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
	 */
	void	create(int width, int height);
    EGLTouchDelegate* getDelegate(void);

    // 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);
    void	setIMEKeyboardState(bool bOpen);
	CCRect	getViewPort();
	float	getScreenScaleFactor();

	float getMainScreenScale() { return 1.0f; }

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

private:

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

	EGLTouchDelegate*	m_pDelegate;
	float				m_fScreenScaleFactor;

	bool				m_bAccelState;
	bool				m_bCaptured;
	s3eKey				m_Key;
    CCSet *             m_pSet;
    CCTouch *           m_pTouch;

    bool				m_isMultiTouch;

	static CCEGLView*	m_pInstance ;

	void	setTouch(void* systemData);
	void	setMotionTouch(void* systemData);
    void	setMultiTouch(void* systemData);
	void	setMultiMotionTouch(void* systemData);
	void	setKeyTouch(void* systemData);
	void	setCharTouch(void* systemData);

    CCTouch* touchSet[S3E_POINTER_TOUCH_MAX];

	static int32 TouchEventHandler(void* systemData, void* userData)
	{
		((CCEGLView*)userData)->setTouch(systemData);
		return 0;
	}

	static int32 MotionEventHandler(void* systemData, void* userData)
	{
		((CCEGLView*)userData)->setMotionTouch(systemData);
		return 0;
	}

    static int32 MultiTouchEventHandler(void* systemData, void* userData)
	{
		((CCEGLView*)userData)->setMultiTouch(systemData);
		return 0;
	}

    static int32 MultiMotionEventHandler(void* systemData, void* userData)
	{
		((CCEGLView*)userData)->setMultiMotionTouch(systemData);
		return 0;
	}

	static int32 KeyEventHandler(void* systemData, void* userData)
	{
		((CCEGLView*)userData)->setKeyTouch(systemData);
		return 0;
	}

	static int32 CharEventHandler(void* systemData, void* userData)
	{
		((CCEGLView*)userData)->setCharTouch(systemData);
		return 0;
	}
};

NS_CC_END;

#endif	// end of __CC_EGLVIEW_MARMALADE_H__


code:
/****************************************************************************
 Copyright (c) 2011      cocos2d-x.org   http://cocos2d-x.org
 Copyright (c) 2011      Максим Аксенов
 Copyright (c) 2011      Giovanni Zito, Francis Styck

 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 "string.h"
#include "stack"
#include "CCString.h"

#include "CCApplication.h"

NS_CC_BEGIN;

static char s_pszResourcePath[S3E_FILE_MAX_PATH] = {0};

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

	IwAssert(GAME, pszRelativePath);

	CCString * pRet = new CCString();
    pRet->autorelease();
    if ((strlen(pszRelativePath) > 1 && pszRelativePath[1] == ':'))
    {
        pRet->m_sString = pszRelativePath;
    }
    else if (strlen(pszRelativePath) > 0 && pszRelativePath[0] == '/')
    {
		char szDriver[3] = {s_pszResourcePath[0], s_pszResourcePath[1], 0};
        pRet->m_sString = szDriver;
        pRet->m_sString += pszRelativePath;
    }
    else
    {
        pRet->m_sString = s_pszResourcePath;
        pRet->m_sString += pszRelativePath;
    }

	return pRet->m_sString.c_str();
}

const char *CCFileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile)
{

	std::string relativeFile = fullPathFromRelativePath(pszRelativeFile);

	CCString *pRet = new CCString();
	pRet->autorelease();
	pRet->m_sString = relativeFile.substr(0, relativeFile.rfind('/')+1);
	pRet->m_sString += pszFilename;
	return pRet->m_sString.c_str();
}

unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize)
{
	IW_CALLSTACK("CCFileUtils::getFileData");

	s3eFile* pFile = s3eFileOpen(pszFileName, pszMode);

    if (! pFile && getIsPopupNotify())
    {
        IwAssertMsg(GAME, pFile, ("Open file %s Failed. s3eFileError Code : %i", pszFileName, s3eFileGetError()));
    }
    if (! pFile)
    {
        *pSize = 0;
        return 0;
    }
	int32 fileSize = s3eFileGetSize(pFile);
	*pSize=fileSize;

	static int32* pDataToBeReadBinary;

	pDataToBeReadBinary = (int32*)s3eMallocBase(fileSize);
	memset(pDataToBeReadBinary, 0, fileSize);
	s3eFileRead(pDataToBeReadBinary, fileSize, 1, pFile);
	s3eFileClose(pFile);

	return (unsigned char*)pDataToBeReadBinary;
}

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

NS_CC_END;


code:
/****************************************************************************
 Copyright (c) 2011      cocos2d-x.org   http://cocos2d-x.org
 Copyright (c) 2011      Максим Аксенов
 Copyright (c) 2011      Giovanni Zito, Francis Styck

 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 <vector>
#include <string>
#include <sstream>

#include "CCImage.h"
#include "CCCommon.h"
#include "CCStdC.h"
#include "CCFileUtils.h"
#include "s3eFile.h"
#include "IwUtil.h"
#include "png.h"
#include "ft2build.h"
#include FT_FREETYPE_H
#define FONT_KERNING 2
#define RSHIFT6(num) ((num)>>6)

#include <strings.h>

extern "C"
{
#include <jpeglib.h>
}

#include <string>

// typedef struct
// {
//     unsigned char* data;
//     int size;
//     int offset;
// }tImageSource;

struct TextLine {
	string sLineStr;
	int iLineWidth;
};

NS_CC_BEGIN;

class CC_DLL CCImageHelper
{
public:
	CCImageHelper();
	~CCImageHelper();
	// dummy funcs to help libjpeg
	static void JPEGInitSource(j_decompress_ptr cinfo)
	{
	}

	static boolean JPEGFillInputBuffer(j_decompress_ptr cinfo)
	{
		return 0;
	}

	static void JPEGSkipInputData(j_decompress_ptr cinfo, long num_bytes)
	{
		cinfo->src->next_input_byte += num_bytes;
		cinfo->src->bytes_in_buffer -= num_bytes;
	}

	static void JPEGTermSource(j_decompress_ptr cinfo)
	{
	}
};

class BitmapDC
{
public:
	BitmapDC();
	~BitmapDC();

	void reset();
	bool getBitmap(const char *text, int nWidth, int nHeight, CCImage::ETextAlign eAlignMask, const char * pFontName, uint fontSize);

public:
	unsigned char*		m_pData;
	int					m_iMaxLineWidth;
	int					m_iMaxLineHeight;

private:
	void buildLine(stringstream& ss, FT_Face face, int iCurXCursor, char cLastChar);

	bool divideString(FT_Face face, const char* sText, int iMaxWidth, int iMaxHeight);

	/**
	 * compute the start pos of every line
	 * return value>0 represents the start x pos of the line, while -1 means fail
	 */
	int computeLineStart(FT_Face face, CCImage::ETextAlign eAlignMask, char cText, int iLineIndex);

	bool startsWith(const std::string& str, const std::string& what);
	bool endsWith(const std::string& str, const std::string& what);
	std::string fileNameExtension(const std::string& pathName);
	std::string basename(const std::string& pathName);
	int openFont(const std::string& fontName, uint fontSize);

private:
	FT_Library		m_library;
	FT_Face			m_face ;
	std::string		m_fontName ;
	uint			m_fontSize ;

	int				m_libError;
	int				m_iInterval;
	vector<TextLine> m_vLines;
};

bool BitmapDC::startsWith(const std::string& str, const std::string& what)
{
	bool result = false ;
	if( what.size() <= str.size() ) {
		result = (str.substr( 0, what.size() ) == what) ;
	}
	return result ;
}

bool BitmapDC::endsWith(const std::string& str, const std::string& what)
{
	bool result = false ;
	if( what.size() <= str.size() ) {
		result = (str.substr( str.size() - what.size() ) == what) ;
	}
	return result ;
}

std::string BitmapDC::fileNameExtension(const std::string& pathName)
{
	std::string ext ;
	std::string::size_type pos = pathName.find_last_of(".") ;
	if( pos != std::string::npos && pos != pathName.size()-1 ) {
		ext = pathName.substr(pos+1) ;
	}

	return ext ;
}

std::string BitmapDC::basename(const std::string& pathName)
{
	int pos = pathName.rfind("/");
	std::string bn = pathName.substr(pos + 1, pathName.length() - pos + 1);
	return bn ;
}

BitmapDC::BitmapDC() :
	m_face(NULL)
	,m_fontName()
	,m_fontSize(0)
	,m_iInterval(FONT_KERNING)
	,m_pData(NULL)
{
	m_libError = FT_Init_FreeType( &m_library );
	reset();
}

BitmapDC::~BitmapDC()
{
	//  free face
	if( m_face ) {
		FT_Done_Face(m_face);
		m_face = NULL;
	}

	FT_Done_FreeType(m_library);
	//data will be deleted by CCImage
	//	if (m_pData) {
	//		delete [] m_pData;
	//	}
}

void BitmapDC::reset()
{
	m_iMaxLineWidth = 0;
	m_iMaxLineHeight = 0;
	m_vLines.clear();
}

void BitmapDC::buildLine( stringstream& ss, FT_Face face, int iCurXCursor, char cLastChar )
{
	TextLine oTempLine;
	ss << '\0';
	oTempLine.sLineStr = ss.str();
	//get last glyph
	FT_Load_Glyph(face, FT_Get_Char_Index(face, cLastChar), FT_LOAD_DEFAULT);

	oTempLine.iLineWidth =
		iCurXCursor -
		RSHIFT6( face->glyph->metrics.horiAdvance +
		face->glyph->metrics.horiBearingX
		- face->glyph->metrics.width)/*-iInterval*/;	//TODO interval

	m_iMaxLineWidth = MAX(m_iMaxLineWidth, oTempLine.iLineWidth);
	ss.clear();
	ss.str("");
	m_vLines.push_back(oTempLine);
}

bool BitmapDC::divideString( FT_Face face, const char* sText, int iMaxWidth, int iMaxHeight )
{
	const char* pText = sText;
	int iError = 0;
	int iCurXCursor;
	iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText), FT_LOAD_DEFAULT);
	if (iError) {
		return false;
	}
	iCurXCursor = -RSHIFT6(face->glyph->metrics.horiBearingX);
	//init stringstream
	stringstream ss;

	int cLastCh = 0;

	while (*pText != '\0') {
		if (*pText == '\n') {
			buildLine(ss, face, iCurXCursor, cLastCh);

			pText++;
			iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText), FT_LOAD_DEFAULT);
			if (iError) {
				return false;
			}
			iCurXCursor = -RSHIFT6(face->glyph->metrics.horiBearingX);
			continue;
		}

		iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText), FT_LOAD_DEFAULT);

		if (iError) {
			return false;
			//break;
		}
		//check its width
		//divide it when exceeding
		if ((iMaxWidth > 0 && iCurXCursor + RSHIFT6(face->glyph->metrics.width) > iMaxWidth)) {
			buildLine(ss, face , iCurXCursor, cLastCh);

			iCurXCursor = -RSHIFT6(face->glyph->metrics.horiBearingX);

		}

		cLastCh = *pText;
		ss << *pText;
		iCurXCursor += RSHIFT6(face->glyph->metrics.horiAdvance) + m_iInterval;
		pText++;

/*
		if (cLastCh == ' ' || cLastCh == ',' || cLastCh == '.' || cLastCh == '!' || cLastCh == '?')
		{
			char *pText_temp = (char *)pText;
			int	iCurXCursor_temp = 0;
			while((strlen(pText_temp) > 0) && (*pText_temp!=' ') && (*pText_temp !=',') && (*pText_temp != '.') && (*pText_temp != '!') && (*pText_temp != '?') && (*pText_temp != '/0') && (*pText_temp != '/n'))
			{
				iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, *pText_temp), FT_LOAD_DEFAULT);

				if (iError) {
					return false;
					//break;
				}
				iCurXCursor_temp += SHIFT6(face->glyph->metrics.horiAdvance) + iInterval;
				if (iCurXCursor + iCurXCursor_temp > iMaxWidth && iMaxWidth > 0)
				{
					buildLine(ss, face , iCurXCursor, cLastCh);

					iCurXCursor = -SHIFT6(face->glyph->metrics.horiBearingX);
				}
				pText_temp++;
			}
		}
*/
	}

	if (iError) {
		return false;
	}

	buildLine(ss,face, iCurXCursor, cLastCh);

	return true;
}

int BitmapDC::computeLineStart( FT_Face face, CCImage::ETextAlign eAlignMask, char cText, int iLineIndex )
{
	int iRet;
	int iError = FT_Load_Glyph(face, FT_Get_Char_Index(face, cText), FT_LOAD_DEFAULT);
	if (iError) {
		return -1;
	}

	if (eAlignMask == CCImage::kAlignCenter) {
		iRet = (m_iMaxLineWidth - m_vLines[iLineIndex].iLineWidth) / 2 - RSHIFT6(face->glyph->metrics.horiBearingX );

	} else if (eAlignMask == CCImage::kAlignRight) {
		iRet = (m_iMaxLineWidth - m_vLines[iLineIndex].iLineWidth) - RSHIFT6(face->glyph->metrics.horiBearingX );
	} else {
		// left or other situation
		iRet = -RSHIFT6(face->glyph->metrics.horiBearingX );
	}
	return iRet;
}

int BitmapDC::openFont(const string& fontName, uint fontSize)
{
	FT_Face aFace ;

	int iError = 0 ;
	if( m_fontName != basename(fontName) || m_fontSize != fontSize ) {
		iError = FT_New_Face( m_library, fontName.c_str(), 0, &aFace );
		if( !iError ) {
			if(m_face) {
				FT_Done_Face(m_face);
			}

			m_face = aFace ;
			m_fontName = basename(fontName) ;
			m_fontSize = fontSize ;
		}
	}

	return iError ;
}

bool BitmapDC::getBitmap( const char *text, int nWidth, int nHeight, CCImage::ETextAlign eAlignMask, const char * pFontName, uint fontSize )
{
	FT_Error iError;

	unsigned char cTemp ;
	int iY, iX, iTemp ;
	uint32 offset, rowOffset ;

	//data will be deleted by CCImage
	//		if (m_pData) {
	//			delete m_pData;
	//		}

	int iCurXCursor, iCurYCursor;
	bool bRet = false;
	if (m_libError) {
		return false;
	}

	do {
		std::string fName = pFontName ;

		string ext = fileNameExtension(fName) ;
		if( ext.empty() || (ext != "ttf" && ext != "TTF") ) {
			fName += ".ttf" ;
		}

		if( !m_face || (m_fontName != basename(fName) || m_fontSize != fontSize) ) {

			iError = openFont( fName, fontSize );
			if (iError) {		// try loading from "fonts" folder
				if( !startsWith(fName,"fonts/") ) {
				 	fName = string("fonts/") + fName ;
				}

				iError = openFont( fName, fontSize );
				if (iError) { //no valid font found, try to use default

					fName = "fonts/Marker Felt.ttf" ;
					//CCLog("No valid font, use default %s\n", fName.c_str());
					iError = openFont( fName, fontSize );
				}
			}
			CC_BREAK_IF(iError);

			//select utf8 charmap
			iError = FT_Select_Charmap(m_face,FT_ENCODING_UNICODE);
			CC_BREAK_IF(iError);

			iError = FT_Set_Pixel_Sizes(m_face, fontSize,fontSize);
			CC_BREAK_IF(iError);
		}

		iError = divideString(m_face, text, nWidth, nHeight) ? 0 : 1 ;

		//compute the final line width
		m_iMaxLineWidth = MAX(m_iMaxLineWidth, nWidth);

		FT_Pos ascenderPixels = RSHIFT6(m_face->size->metrics.ascender) ;
		FT_Pos descenderPixels = RSHIFT6(m_face->size->metrics.descender) ;

		m_iMaxLineHeight = ascenderPixels - descenderPixels;
		m_iMaxLineHeight *= m_vLines.size();

		//compute the final line height
		m_iMaxLineHeight = MAX(m_iMaxLineHeight, nHeight);

		uint bitmapSize = m_iMaxLineWidth * m_iMaxLineHeight*4 ;

		m_pData = new unsigned char[bitmapSize];
		memset(m_pData,0, bitmapSize);

		const char* pText = text;
		iCurYCursor = ascenderPixels;

		for (size_t i = 0; i < m_vLines.size(); i++) {
			pText = m_vLines[i].sLineStr.c_str();
			//initialize the origin cursor
			iCurXCursor = computeLineStart(m_face, eAlignMask, *pText, i);

			while (*pText != 0) {
				int iError = FT_Load_Glyph(m_face, FT_Get_Char_Index(m_face, *pText), FT_LOAD_RENDER);
				if (iError) {
					break;
				}

				//  convert glyph to bitmap with 256 gray
				//  and get the bitmap
				FT_Bitmap & bitmap = m_face->glyph->bitmap;

				FT_Pos horiBearingYPixels = RSHIFT6(m_face->glyph->metrics.horiBearingY) ;
				FT_Pos horiBearingXPixels = RSHIFT6(m_face->glyph->metrics.horiBearingX) ;
				FT_Pos horiAdvancePixels = RSHIFT6(m_face->glyph->metrics.horiAdvance) ;

				for (int i = 0; i < bitmap.rows; ++i) {

					iY = iCurYCursor + i - horiBearingYPixels;
					if (iY < 0 || iY>=m_iMaxLineHeight) {
						//exceed the height truncate
						continue;
					}

					rowOffset = iY * m_iMaxLineWidth ;

					// if it has gray>0 we set show it as 1, otherwise 0
					for (int j = 0; j < bitmap.width; ++j) {
						cTemp = bitmap.buffer[i	* bitmap.width + j];
						if( cTemp )
						{
							iX = iCurXCursor + j + horiBearingXPixels;

							offset = (rowOffset + iX) * 4 ;

							IwAssert( GAME, ((offset + 3) < bitmapSize) ) ;

							iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp;
 							*(int*) &m_pData[ offset ] = iTemp ;	// ARGB
						}
					}
				}

				//step to next glyph
				iCurXCursor += horiAdvancePixels + m_iInterval;
				pText++;
			}
			iCurYCursor += ascenderPixels - descenderPixels ;
		}

		//clear all lines
		m_vLines.clear();

		//success;
		if (iError) {
			bRet = false;
		} else
			bRet = true;
	}while(0);

	return bRet;
}

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

//////////////////////////////////////////////////////////////////////////
// Implement CCImage
//////////////////////////////////////////////////////////////////////////

CCImage::CCImage()
: m_nWidth(0)
, m_nHeight(0)
, m_nBitsPerComponent(0)
, m_pData(0)
, m_bHasAlpha(false)
, m_bPreMulti(false)
{

}

CCImage::~CCImage()
{
    CC_SAFE_DELETE_ARRAY(m_pData);
}
bool CCImage::initWithImageFile(const char * strPath, EImageFormat eImgFmt/* = eFmtPng*/)
{
	IW_CALLSTACK("UIImage::initWithImageFile");
    CCFileData data(CCFileUtils::fullPathFromRelativePath(strPath), "rb");
    return initWithImageData(data.getBuffer(), data.getSize(), eImgFmt);
}

bool CCImage::initWithImageFileThreadSafe( const char *fullpath, EImageFormat imageType /*= kFmtPng*/ )
{
	CC_UNUSED_PARAM(imageType);
	CCFileData data(fullpath, "rb");
	return initWithImageData(data.getBuffer(), data.getSize(), imageType);
}

bool CCImage::initWithImageData(void * pData,
								int nDataLen,
								EImageFormat eFmt,
								int nWidth,
								int nHeight,
								int nBitsPerComponent)
{
    bool bRet = false;
    do
    {
    	CC_BREAK_IF(! pData || nDataLen <= 0);

        if (kFmtPng == eFmt)
        {
            bRet = _initWithPngData(pData, nDataLen);
            break;
        }
        else if (kFmtJpg == eFmt)
        {
            bRet = _initWithJpgData(pData, nDataLen);
            break;
        }
    } while (0);
    return bRet;
}

bool CCImage::_initWithJpgData(void * data, int nSize)
{
	IW_CALLSTACK("CCImage::_initWithJpgData");

	bool bRet = false;

	s3eFile* pFile = s3eFileOpenFromMemory(data, nSize);

	IwAssert(GAME, pFile);

    jpeg_decompress_struct cinfo;
    bzero(&cinfo, sizeof(cinfo));

    JSAMPARRAY buffer;      /* Output row buffer */
    int row_stride;     /* physical row width in output buffer */

    jpeg_source_mgr srcmgr;

    srcmgr.bytes_in_buffer = nSize;
    srcmgr.next_input_byte = (JOCTET*) data;
    srcmgr.init_source = CCImageHelper::JPEGInitSource;
    srcmgr.fill_input_buffer = CCImageHelper::JPEGFillInputBuffer;
    srcmgr.skip_input_data = CCImageHelper::JPEGSkipInputData;
    srcmgr.resync_to_restart = jpeg_resync_to_restart;
    srcmgr.term_source = CCImageHelper::JPEGTermSource;

    jpeg_error_mgr jerr;
    cinfo.err = jpeg_std_error(&jerr);

    jpeg_create_decompress(&cinfo);
    cinfo.src = &srcmgr;

    jpeg_read_header(&cinfo, TRUE);
    jpeg_start_decompress(&cinfo);

    /* JSAMPLEs per row in output buffer */
    row_stride = cinfo.output_width * cinfo.output_components;

    /* Make a one-row-high sample array that will go away when done with image */
    buffer = (*cinfo.mem->alloc_sarray)
        ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);

    int copy_rows  = (int)cinfo.output_height;
    int copy_width = (int)cinfo.output_width;

   if (copy_width < 0 || copy_rows < 0)
    {
        printf("jpeg is fully off screen\n");
        return bRet;
    }
	int startx=0;
	int starty=0;
	int bytesPerPix = 4;
	m_pData = new unsigned char[copy_rows * copy_width * bytesPerPix];
	memset(m_pData,0, copy_rows * copy_width * bytesPerPix);
	// init image info
	m_bPreMulti	= false;
	m_bHasAlpha = false;
	m_nHeight = copy_rows;
	m_nWidth = copy_width;
	m_nBitsPerComponent = bytesPerPix;
	unsigned char *dst = m_pData;
	unsigned char *pData = m_pData;

    while (cinfo.output_scanline < cinfo.output_height)// count through the image
    {
        /* jpeg_read_scanlines expects an array of pointers to scanlines.
         * Here the array is only one element long, but you could ask for
         * more than one scanline at a time if that's more convenient.
         */
        (void) jpeg_read_scanlines(&cinfo, buffer, 1);

        if (starty-- <= 0)// count down from start
        {
            if (copy_rows-- > 0)
            {
                for (int xx=startx; xx < copy_width; xx++)
                {
                    uint8 r = buffer[0][xx*3+0];
                    uint8 b = buffer[0][xx*3+1];
                    uint8 g = buffer[0][xx*3+2];

					*dst++ = r;
					*dst++ = b;
					*dst++ = g;
					*dst++ = 255;
                }
            }
        }
    }

    (void) jpeg_finish_decompress(&cinfo);
    jpeg_destroy_decompress(&cinfo);

    printf("jpeg display done\n");

	bRet = true;
	return bRet;
}

void userReadData(png_structp pngPtr, png_bytep data, png_size_t length) {
	png_voidp png_pointer = png_get_io_ptr(pngPtr);
	s3eFileRead((char*)data, length, 1, (s3eFile*)png_pointer);
}

#define PNGSIGSIZE 8
bool CCImage::_initWithPngData(void * pData, int nDatalen)
{
	IW_CALLSTACK("CCImage::_initWithPngData");

    bool bRet = false;

	s3eFile* pFile = s3eFileOpenFromMemory(pData, nDatalen);

	IwAssert(GAME, pFile);

	png_byte pngsig[PNGSIGSIZE];

	bool is_png = false;

	s3eFileRead((char*)pngsig, PNGSIGSIZE, 1, pFile);

	is_png = png_sig_cmp(pngsig, 0, PNGSIGSIZE) == 0 ? true : false;

	if (!is_png)
		return false;

	png_structp pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

	if (!pngPtr)
		return false;

	png_infop infoPtr = png_create_info_struct(pngPtr);

	if (!infoPtr)
		return false;

	png_bytep* rowPtrs = NULL;
	m_pData = NULL;

	if (setjmp(png_jmpbuf(pngPtr))) {
		png_destroy_read_struct(&pngPtr, &infoPtr,(png_infopp)0);
		if (rowPtrs != NULL) delete [] rowPtrs;
		if (m_pData != NULL) delete [] m_pData;

		CCLog("ERROR: An error occured while reading the PNG file");

		return false;
	}

	png_set_read_fn(pngPtr, pFile, userReadData);
	png_set_sig_bytes(pngPtr, PNGSIGSIZE);
	png_read_info(pngPtr, infoPtr);

	png_uint_32 bitdepth   = png_get_bit_depth(pngPtr, infoPtr);
	png_uint_32 channels   = png_get_channels(pngPtr, infoPtr);
	png_uint_32 color_type = png_get_color_type(pngPtr, infoPtr);

	// Convert palette color to true color
	if (color_type ==PNG_COLOR_TYPE_PALETTE)
		png_set_palette_to_rgb(pngPtr);

	// Convert low bit colors to 8 bit colors
	if (png_get_bit_depth(pngPtr, infoPtr) < 8)
	{
		if (color_type==PNG_COLOR_TYPE_GRAY || color_type==PNG_COLOR_TYPE_GRAY_ALPHA)
			png_set_gray_1_2_4_to_8(pngPtr);
		else
			png_set_packing(pngPtr);
	}

	if (png_get_valid(pngPtr, infoPtr, PNG_INFO_tRNS))
		png_set_tRNS_to_alpha(pngPtr);

	// Convert high bit colors to 8 bit colors
	if (bitdepth == 16)
		png_set_strip_16(pngPtr);

	// Convert gray color to true color
	if (color_type==PNG_COLOR_TYPE_GRAY || color_type==PNG_COLOR_TYPE_GRAY_ALPHA)
		png_set_gray_to_rgb(pngPtr);

	// Update the changes
	png_read_update_info(pngPtr, infoPtr);

	// init image info
	m_bPreMulti	= true;

	unsigned int bytesPerComponent = png_get_channels(pngPtr, infoPtr);

	m_bHasAlpha = (bytesPerComponent == 4 ? true : false);

	m_nHeight = (unsigned int)png_get_image_height(pngPtr, infoPtr);
	m_nWidth = (unsigned int) png_get_image_width(pngPtr, infoPtr);

	m_nBitsPerComponent = (unsigned int)png_get_bit_depth(pngPtr, infoPtr);

	m_pData = new unsigned char[m_nHeight * m_nWidth * bytesPerComponent];

	unsigned int bytesPerRow = m_nWidth * bytesPerComponent;

	{
		unsigned char *ptr = m_pData;
		rowPtrs = new png_bytep[m_nHeight];

		for (int i = 0; i < m_nHeight; i++) {

			int q = (i) * bytesPerRow;

			rowPtrs[i] = (png_bytep)m_pData + q;
		}

		png_read_image(pngPtr, rowPtrs);

		delete[] (png_bytep)rowPtrs;
		png_destroy_read_struct(&pngPtr, &infoPtr,(png_infopp)0);

		s3eFileClose(pFile);
		pFile = 0;
	}

	// premultiplay if alpha
	if(m_bHasAlpha)
		for(unsigned int i = 0; i < m_nHeight*bytesPerRow; i += bytesPerComponent){
			*(m_pData + i + 0)	=  (*(m_pData + i + 0) * *(m_pData + i + 3) + 1) >> 8;
			*(m_pData + i + 1)	=  (*(m_pData + i + 1) * *(m_pData + i + 3) + 1) >> 8;
			*(m_pData + i + 2)	=  (*(m_pData + i + 2) * *(m_pData + i + 3) + 1) >> 8;
			*(m_pData + i + 3)	=   *(m_pData + i + 3);
	}

	bRet = true;
    return bRet;
}

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

		const char* pFullFontName = CCFileUtils::fullPathFromRelativePath(pFontName);

		CC_BREAK_IF(! dc.getBitmap(pText, nWidth, nHeight, eAlignMask, pFullFontName, nSize));

		// assign the dc.m_pData to m_pData in order to save time
		m_pData = dc.m_pData;
		CC_BREAK_IF(! m_pData);

		m_nWidth = (short)dc.m_iMaxLineWidth;
		m_nHeight = (short)dc.m_iMaxLineHeight;
		m_bHasAlpha = true;
		m_bPreMulti = true;
		m_nBitsPerComponent = 8;

		bRet = true;

		dc.reset();
	}while (0);

	//do nothing
	return bRet;
}

bool CCImage::saveToFile(const char *pszFilePath, bool bIsToRGB)
{
	// todo
	return false;
}

bool CCImage::_initWithRawData(void * pData, int nDatalen, int nWidth, int nHeight, int nBitsPerComponent)
{
	// todo
	return false;
}

bool CCImage::_saveImageToPNG(const char * pszFilePath, bool bIsToRGB)
{
	// todo
	return false;
}

bool CCImage::_saveImageToJPG(const char * pszFilePath)
{
	// todo
	return false;
}

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

#include "CCStdC.h"

NS_CC_BEGIN;

int CCTime::gettimeofdayCocos2d(struct cc_timeval *tp, void *tzp)
{
    CC_UNUSED_PARAM(tzp);
    if (tp)
    {
        gettimeofday((struct timeval *)tp,  0);
    }
    return 0;
}

void CCTime::timersubCocos2d(struct cc_timeval *out, struct cc_timeval *start, struct cc_timeval *end)
{
    if (! out || ! start || ! end)
    {
        return;
    }
    out->tv_sec = end->tv_sec - start->tv_sec;
    out->tv_usec = end->tv_usec - start->tv_usec;
}

NS_CC_END;


code:
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __PLATFORM_H__
#define __PLATFORM_H__

#include "CCThread.h"
#include "CCPlatformMacros.h"

NS_CC_BEGIN;

struct CC_DLL cc_timeval
{
    long	tv_sec;		// seconds
    long	tv_usec;    // microSeconds
};

class CC_DLL CCTime
{
public:
    static int gettimeofdayCocos2d(struct cc_timeval *tp, void *tzp);
    static void timersubCocos2d(struct cc_timeval *out, struct cc_timeval *start, struct cc_timeval *end);
};

NS_CC_END;

#endif // __PLATFORM_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 "CCAccelerometer_qnx.h"

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <bps/accelerometer.h>
#include <fcntl.h>

#define BUFFER_SIZE 			30

namespace cocos2d
{
	CCAccelerometer* CCAccelerometer::m_spCCAccelerometer = NULL;
	int	CCAccelerometer::m_initialOrientationAngle = 0;

	CCAccelerometer::CCAccelerometer()
	{
		m_pAccelDelegate = NULL;
		m_initialOrientationAngle = atoi(getenv("ORIENTATION"));

		accelerometer_set_update_frequency(FREQ_40_HZ);
	}

    CCAccelerometer::~CCAccelerometer()
    {

    }

    CCAccelerometer* CCAccelerometer::sharedAccelerometer()
    {
    	if (m_spCCAccelerometer == NULL)
    		m_spCCAccelerometer = new CCAccelerometer();

    	return m_spCCAccelerometer;
    }

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

	void CCAccelerometer::update(long timeStamp)
	{
		if ( m_pAccelDelegate != NULL)
		{
			int angle = atoi(getenv("ORIENTATION"));

			double x, y, z;

			accelerometer_read_forces(&x, &y, &z);

			if (m_initialOrientationAngle == 270)
		    {
		    	m_accelerationValue.x = y;
		    	m_accelerationValue.y = -x;
		    }
			else if (m_initialOrientationAngle == 90)
			{
				m_accelerationValue.x = -y;
				m_accelerationValue.y = x;
			}
			else if (m_initialOrientationAngle == 0)
			{
				m_accelerationValue.x = x;
				m_accelerationValue.y = y;
		    }
			else if (m_initialOrientationAngle == 180)
			{
				m_accelerationValue.x = -x;
				m_accelerationValue.y = -y;
			}

			m_accelerationValue.z = z;
			m_accelerationValue.timestamp = (double)timeStamp;

			m_pAccelDelegate->didAccelerate(&m_accelerationValue);
		}
	}

} // end of namespace cococs2d


code:
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#ifndef __PLATFORM_QNX_CCACCELEROMETER_H__
#define __PLATFORM_QNX_CCACCELEROMETER_H__

#include "CCCommon.h"
#include "CCAccelerometerDelegate.h"
#include <list>

namespace   cocos2d {

class CC_DLL CCAccelerometer
{
public:
	CCAccelerometer();
    ~CCAccelerometer();

    static CCAccelerometer* sharedAccelerometer();

    void setDelegate(CCAccelerometerDelegate* pDelegate);
    void update(long sensorTimeStamp);

private:

	static CCAccelerometer*  m_spCCAccelerometer;
	CCAccelerometerDelegate* m_pAccelDelegate;
	CCAcceleration 			 m_accelerationValue;
    static int				 m_initialOrientationAngle;
};

}//namespace cocos2d

#endif


code:
#include "CCApplication.h"

#include "CCDirector.h"
#include "CCEGLView.h"
#include "CCAccelerometer.h"
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <bps/locale.h>

#define  LOGD(...)  fprintf(stderr, __VA_ARGS__)

NS_CC_BEGIN;

// sharedApplication pointer
CCApplication * CCApplication::sm_pSharedApplication = 0;
long CCApplication::m_animationInterval = 1000;

// convert the timespec into milliseconds
static long time2millis(struct timespec *times)
{
    return times->tv_sec*1000 + times->tv_nsec/1000000;
}

CCApplication::CCApplication()
{
    CC_ASSERT(! sm_pSharedApplication);
    sm_pSharedApplication = this;
}

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

int CCApplication::run()
{
	struct timespec time_struct;
	long current_time, update_time;

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

	clock_gettime(CLOCK_REALTIME, &time_struct);
	update_time = time2millis(&time_struct);

	while (1) // or device wants to quit
	{
		CCEGLView::sharedOpenGLView().HandleEvents();

		clock_gettime(CLOCK_REALTIME, &time_struct);
		current_time = time2millis(&time_struct);

		if ((current_time - update_time) > m_animationInterval)
		{
			update_time = current_time;

			CCAccelerometer::sharedAccelerometer()->update(current_time);
			CCDirector::sharedDirector()->mainLoop();
		}
		else
		{
//			sleep(0);
		}
	}

	return -1;
}

void CCApplication::setAnimationInterval(double interval)
{
	// interval in milliseconds
	m_animationInterval = (long)(interval * 1000);
}

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

void CCApplication::statusBarFrame(CCRect * rect)
{
    if (rect)
    {
        // qnx doesn't have a status bar
        *rect = CCRectMake(0, 0, 0, 0);
    }
}

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

ccLanguageType CCApplication::getCurrentLanguage()
{
	ccLanguageType ret_language = kLanguageEnglish;
	char *language, *country;

	locale_get(&language, &country);

	if (strcmp(language, "en") == 0)
	{
		ret_language = kLanguageEnglish;
	}
	else if (strcmp(language, "fr") == 0)
	{
		ret_language = kLanguageFrench;
	}
	else if (strcmp(language, "de") == 0)
	{
		ret_language = kLanguageGerman;
	}
	else if (strcmp(language, "it") == 0)
	{
		ret_language = kLanguageItalian;
	}
	else if (strcmp(language, "es") == 0)
	{
		ret_language = kLanguageSpanish;
	}
	else if (strcmp(language, "ch") == 0)
	{
		ret_language = kLanguageChinese;
	}
	else if (strcmp(language, "ru") == 0)
	{
		ret_language = kLanguageRussian;
	}

	free(language);
	free(country);

    return ret_language;
}

NS_CC_END;