Android JAVA refactoring. Android JNI Cleanup.

This commit is contained in:
Nicolas Gramlich 2012-09-07 17:23:04 -07:00
parent 23e5c69616
commit 4c7705171a
107 changed files with 3010 additions and 3113 deletions

View File

@ -82,12 +82,12 @@ platform/android/CCApplication.cpp \
platform/android/CCCommon.cpp \
platform/android/CCFileUtils.cpp \
platform/android/CCImage.cpp \
platform/android/jni/EditBoxJni.cpp \
platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp \
platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp \
platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp \
platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp \
platform/android/jni/JniHelper.cpp \
platform/android/jni/IMEJni.cpp \
platform/android/jni/MessageJni.cpp \
platform/android/jni/SensorJni.cpp \
platform/android/jni/SystemInfoJni.cpp \
platform/android/jni/TouchesJni.cpp \
script_support/CCScriptSupport.cpp \
shaders/ccShaders.cpp \

View File

@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCAccelerometer.h"
#include "jni/SensorJni.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#include <stdio.h>
#include <android/log.h>

View File

@ -1,5 +1,5 @@
#include "jni/JniHelper.h"
#include "jni/SystemInfoJni.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#include "CCApplication.h"
#include "CCDirector.h"
#include "CCEGLView.h"

View File

@ -23,7 +23,7 @@ THE SOFTWARE.
****************************************************************************/
#include "platform/CCCommon.h"
#include "jni/MessageJni.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#include <android/log.h>
#include <stdio.h>
#include <jni.h>
@ -46,7 +46,7 @@ void CCLog(const char * pszFormat, ...)
void CCMessageBox(const char * pszMsg, const char * pszTitle)
{
showMessageBoxJNI(pszMsg, pszTitle);
showDialogJNI(pszMsg, pszTitle);
}
void CCLuaLog(const char * pszFormat)

View File

@ -27,8 +27,7 @@ THE SOFTWARE.
#include "ccMacros.h"
#include "touch_dispatcher/CCTouchDispatcher.h"
#include "jni/IMEJni.h"
#include "jni/EditBoxJni.h"
#include "jni/MessageJni.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#include "CCGL.h"
#include <stdlib.h>

View File

@ -30,8 +30,7 @@ using namespace std;
NS_CC_BEGIN
#include "platform/CCCommon.h"
#include "jni/SystemInfoJni.h"
#include "jni/MessageJni.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
// record the resource path
static string s_strResourcePath = "";

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>java</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -1,6 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.cocos2dx.lib"
android:versionCode="1"
android:versionName="1.0">
package="org.cocos2dx.lib"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8"/>
</manifest>

View File

@ -15,4 +15,3 @@
# 'key.alias' for the name of the key to use.
# The password will be asked during the build when you use the 'release' target.
source.dir=src_common

View File

@ -0,0 +1,129 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
public class Cocos2dxAccelerometer implements SensorEventListener {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = Cocos2dxAccelerometer.class.getSimpleName();
// ===========================================================
// Fields
// ===========================================================
private final Context mContext;
private final SensorManager mSensorManager;
private final Sensor mAccelerometer;
private final int mNaturalOrientation;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxAccelerometer(final Context pContext) {
this.mContext = pContext;
this.mSensorManager = (SensorManager) this.mContext.getSystemService(Context.SENSOR_SERVICE);
this.mAccelerometer = this.mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
final Display display = ((WindowManager) this.mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
this.mNaturalOrientation = display.getOrientation();
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void enable() {
this.mSensorManager.registerListener(this, this.mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
}
public void disable() {
this.mSensorManager.unregisterListener(this);
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onSensorChanged(final SensorEvent pSensorEvent) {
if (pSensorEvent.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return;
}
float x = pSensorEvent.values[0];
float y = pSensorEvent.values[1];
final float z = pSensorEvent.values[2];
/*
* Because the axes are not swapped when the device's screen orientation
* changes. So we should swap it here. In tablets such as Motorola Xoom,
* the default orientation is landscape, so should consider this.
*/
final int orientation = this.mContext.getResources().getConfiguration().orientation;
if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (this.mNaturalOrientation != Surface.ROTATION_0)) {
final float tmp = x;
x = -y;
y = tmp;
} else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (this.mNaturalOrientation != Surface.ROTATION_0)) {
final float tmp = x;
x = y;
y = -tmp;
}
Cocos2dxAccelerometer.onSensorChanged(x, y, z, pSensorEvent.timestamp);
if(BuildConfig.DEBUG) {
Log.d(TAG, "x = " + pSensorEvent.values[0] + " y = " + pSensorEvent.values[1] + " z = " + pSensorEvent.values[2]);
}
}
@Override
public void onAccuracyChanged(final Sensor pSensor, final int pAccuracy) {
}
// ===========================================================
// Methods
// ===========================================================
private static native void onSensorChanged(final float pX, final float pY, final float pZ, final long pTimestamp);
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}

View File

@ -0,0 +1,93 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = Cocos2dxActivity.class.getSimpleName();
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cocos2dxHelper.init(this, this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected void onResume() {
super.onResume();
Cocos2dxHelper.onResume();
}
@Override
protected void onPause() {
super.onPause();
Cocos2dxHelper.onPause();
}
@Override
public void showDialog(final String pTitle, final String pMessage) {
new AlertDialog.Builder(this).setTitle(pTitle).setMessage(pMessage).setPositiveButton("OK", null).create().show(); // TODO Dialog will not survive configuration changes
}
@Override
public void showEditTextDialog(final String pTitle, final String pContent, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) { // TODO Dialog will not survive configuration changes
new Cocos2dxEditBoxDialog(this, pTitle, pContent, pInputMode, pInputFlag, pReturnType, pMaxLength).show();
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}

View File

@ -0,0 +1,420 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.LinkedList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.FloatMath;
import android.util.Log;
public class Cocos2dxBitmap {
// ===========================================================
// Constants
// ===========================================================
/* The values are the same as cocos2dx/platform/CCImage.h. */
private static final int HORIZONTALALIGN_LEFT = 1;
private static final int HORIZONTALALIGN_RIGHT = 2;
private static final int HORIZONTALALIGN_CENTER = 3;
private static final int VERTICALALIGN_TOP = 1;
private static final int VERTICALALIGN_BOTTOM = 2;
private static final int VERTICALALIGN_CENTER = 3;
// ===========================================================
// Fields
// ===========================================================
private static Context sContext;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public static void setContext(final Context pContext) {
Cocos2dxBitmap.sContext = pContext;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
private static native void nativeInitBitmapDC(final int pWidth, final int pHeight, final byte[] pPixels);
/**
* @param pWidth
* the width to draw, it can be 0
* @param pHeight
* the height to draw, it can be 0
*/
public static void createTextBitmap(String pString, final String pFontName, final int pFontSize, final int pAlignment, final int pWidth, final int pHeight) {
final int horizontalAlignment = pAlignment & 0x0F;
final int verticalAlignment = (pAlignment >> 4) & 0x0F;
pString = Cocos2dxBitmap.refactorString(pString);
final Paint paint = Cocos2dxBitmap.newPaint(pFontName, pFontSize, horizontalAlignment);
final TextProperty textProperty = Cocos2dxBitmap.computeTextProperty(pString, pWidth, pHeight, paint);
final int bitmapTotalHeight = (pHeight == 0 ? textProperty.mTotalHeight : pHeight);
final Bitmap bitmap = Bitmap.createBitmap(textProperty.mMaxWidth, bitmapTotalHeight, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
/* Draw string. */
final FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();
int x = 0;
int y = Cocos2dxBitmap.computeY(fontMetricsInt, pHeight, textProperty.mTotalHeight, verticalAlignment);
final String[] lines = textProperty.mLines;
for (final String line : lines) {
x = Cocos2dxBitmap.computeX(line, textProperty.mMaxWidth, horizontalAlignment);
canvas.drawText(line, x, y, paint);
y += textProperty.mHeightPerLine;
}
Cocos2dxBitmap.initNativeObject(bitmap);
}
private static Paint newPaint(final String pFontName, final int pFontSize, final int pHorizontalAlignment) {
final Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(pFontSize);
paint.setAntiAlias(true);
/* Set type face for paint, now it support .ttf file. */
if (pFontName.endsWith(".ttf")) {
try {
final Typeface typeFace = Cocos2dxTypefaces.get(Cocos2dxBitmap.sContext, pFontName);
paint.setTypeface(typeFace);
} catch (final Exception e) {
Log.e("Cocos2dxBitmap", "error to create ttf type face: " + pFontName);
/* The file may not find, use system font. */
paint.setTypeface(Typeface.create(pFontName, Typeface.NORMAL));
}
} else {
paint.setTypeface(Typeface.create(pFontName, Typeface.NORMAL));
}
switch (pHorizontalAlignment) {
case HORIZONTALALIGN_CENTER:
paint.setTextAlign(Align.CENTER);
break;
case HORIZONTALALIGN_RIGHT:
paint.setTextAlign(Align.RIGHT);
break;
case HORIZONTALALIGN_LEFT:
default:
paint.setTextAlign(Align.LEFT);
break;
}
return paint;
}
private static TextProperty computeTextProperty(final String pString, final int pWidth, final int pHeight, final Paint pPaint) {
final FontMetricsInt fm = pPaint.getFontMetricsInt();
final int h = (int) Math.ceil(fm.bottom - fm.top);
int maxContentWidth = 0;
final String[] lines = Cocos2dxBitmap.splitString(pString, pWidth, pHeight, pPaint);
if (pWidth != 0) {
maxContentWidth = pWidth;
} else {
/* Compute the max width. */
int temp = 0;
for (final String line : lines) {
temp = (int) FloatMath.ceil(pPaint.measureText(line, 0, line.length()));
if (temp > maxContentWidth) {
maxContentWidth = temp;
}
}
}
return new TextProperty(maxContentWidth, h, lines);
}
private static int computeX(final String pText, final int pMaxWidth, final int pHorizontalAlignment) {
int ret = 0;
switch (pHorizontalAlignment) {
case HORIZONTALALIGN_CENTER:
ret = pMaxWidth / 2;
break;
case HORIZONTALALIGN_RIGHT:
ret = pMaxWidth;
break;
case HORIZONTALALIGN_LEFT:
default:
break;
}
return ret;
}
private static int computeY(final FontMetricsInt pFontMetricsInt, final int pConstrainHeight, final int pTotalHeight, final int pVerticalAlignment) {
int y = -pFontMetricsInt.top;
if (pConstrainHeight > pTotalHeight) {
switch (pVerticalAlignment) {
case VERTICALALIGN_TOP:
y = -pFontMetricsInt.top;
break;
case VERTICALALIGN_CENTER:
y = -pFontMetricsInt.top + (pConstrainHeight - pTotalHeight) / 2;
break;
case VERTICALALIGN_BOTTOM:
y = -pFontMetricsInt.top + (pConstrainHeight - pTotalHeight);
break;
default:
break;
}
}
return y;
}
/*
* If maxWidth or maxHeight is not 0, split the string to fix the maxWidth and maxHeight.
*/
private static String[] splitString(final String pString, final int pMaxWidth, final int pMaxHeight, final Paint pPaint) {
final String[] lines = pString.split("\\n");
String[] ret = null;
final FontMetricsInt fm = pPaint.getFontMetricsInt();
final int heightPerLine = (int) Math.ceil(fm.bottom - fm.top);
final int maxLines = pMaxHeight / heightPerLine;
if (pMaxWidth != 0) {
final LinkedList<String> strList = new LinkedList<String>();
for (final String line : lines) {
/* The width of line is exceed maxWidth, should divide it into two or more lines. */
final int lineWidth = (int) FloatMath.ceil(pPaint.measureText(line));
if (lineWidth > pMaxWidth) {
strList.addAll(Cocos2dxBitmap.divideStringWithMaxWidth(line, pMaxWidth, pPaint));
} else {
strList.add(line);
}
/* Should not exceed the max height. */
if (maxLines > 0 && strList.size() >= maxLines) {
break;
}
}
/* Remove exceeding lines. */
if (maxLines > 0 && strList.size() > maxLines) {
while (strList.size() > maxLines) {
strList.removeLast();
}
}
ret = new String[strList.size()];
strList.toArray(ret);
} else if (pMaxHeight != 0 && lines.length > maxLines) {
/* Remove exceeding lines. */
final LinkedList<String> strList = new LinkedList<String>();
for (int i = 0; i < maxLines; i++) {
strList.add(lines[i]);
}
ret = new String[strList.size()];
strList.toArray(ret);
} else {
ret = lines;
}
return ret;
}
private static LinkedList<String> divideStringWithMaxWidth(final String pString, final int pMaxWidth, final Paint pPaint) {
final int charLength = pString.length();
int start = 0;
int tempWidth = 0;
final LinkedList<String> strList = new LinkedList<String>();
/* Break a String into String[] by the width & should wrap the word. */
for (int i = 1; i <= charLength; ++i) {
tempWidth = (int) FloatMath.ceil(pPaint.measureText(pString, start, i));
if (tempWidth >= pMaxWidth) {
final int lastIndexOfSpace = pString.substring(0, i).lastIndexOf(" ");
if (lastIndexOfSpace != -1 && lastIndexOfSpace > start) {
/* Should wrap the word. */
strList.add(pString.substring(start, lastIndexOfSpace));
i = lastIndexOfSpace;
} else {
/* Should not exceed the width. */
if (tempWidth > pMaxWidth) {
strList.add(pString.substring(start, i - 1));
/* Compute from previous char. */
--i;
} else {
strList.add(pString.substring(start, i));
}
}
/* Remove spaces at the beginning of a new line. */
while (pString.indexOf(i++) == ' ') {
;
}
start = i;
}
}
/* Add the last chars. */
if (start < charLength) {
strList.add(pString.substring(start));
}
return strList;
}
private static String refactorString(final String pString) {
/* Avoid error when content is "". */
if (pString.compareTo("") == 0) {
return " ";
}
/*
* If the font of "\n" is "" or "\n", insert " " in front of it. For example: "\nabc" -> " \nabc" "\nabc\n\n" -> " \nabc\n \n".
*/
final StringBuilder strBuilder = new StringBuilder(pString);
int start = 0;
int index = strBuilder.indexOf("\n");
while (index != -1) {
if (index == 0 || strBuilder.charAt(index - 1) == '\n') {
strBuilder.insert(start, " ");
start = index + 2;
} else {
start = index + 1;
}
if (start > strBuilder.length() || index == strBuilder.length()) {
break;
}
index = strBuilder.indexOf("\n", start);
}
return strBuilder.toString();
}
private static void initNativeObject(final Bitmap pBitmap) {
final byte[] pixels = Cocos2dxBitmap.getPixels(pBitmap);
if (pixels == null) {
return;
}
Cocos2dxBitmap.nativeInitBitmapDC(pBitmap.getWidth(), pBitmap.getHeight(), pixels);
}
private static byte[] getPixels(final Bitmap pBitmap) {
if (pBitmap != null) {
final byte[] pixels = new byte[pBitmap.getWidth() * pBitmap.getHeight() * 4];
final ByteBuffer buf = ByteBuffer.wrap(pixels);
buf.order(ByteOrder.nativeOrder());
pBitmap.copyPixelsToBuffer(buf);
return pixels;
}
return null;
}
private static int getFontSizeAccordingHeight(int height) {
Paint paint = new Paint();
Rect bounds = new Rect();
paint.setTypeface(Typeface.DEFAULT);
int incr_text_size = 1;
boolean found_desired_size = false;
while (!found_desired_size) {
paint.setTextSize(incr_text_size);
String text = "SghMNy";
paint.getTextBounds(text, 0, text.length(), bounds);
incr_text_size++;
if (height - bounds.height() <= 2) {
found_desired_size = true;
}
Log.d("font size", "incr size:" + incr_text_size);
}
return incr_text_size;
}
private static String getStringWithEllipsis(String pString, float width, float fontSize) {
if (TextUtils.isEmpty(pString)) {
return "";
}
TextPaint paint = new TextPaint();
paint.setTypeface(Typeface.DEFAULT);
paint.setTextSize(fontSize);
return TextUtils.ellipsize(pString, paint, width, TextUtils.TruncateAt.END).toString();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
private static class TextProperty {
/** The max width of lines. */
private final int mMaxWidth;
/** The height of all lines. */
private final int mTotalHeight;
private final int mHeightPerLine;
private final String[] mLines;
TextProperty(final int pMaxWidth, final int pHeightPerLine, final String[] pLines) {
this.mMaxWidth = pMaxWidth;
this.mHeightPerLine = pHeightPerLine;
this.mTotalHeight = pHeightPerLine * pLines.length;
this.mLines = pLines;
}
}
}

View File

@ -0,0 +1,320 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.InputType;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class Cocos2dxEditBoxDialog extends Dialog {
// ===========================================================
// Constants
// ===========================================================
/**
* The user is allowed to enter any text, including line breaks.
*/
private final int kEditBoxInputModeAny = 0;
/**
* The user is allowed to enter an e-mail address.
*/
private final int kEditBoxInputModeEmailAddr = 1;
/**
* The user is allowed to enter an integer value.
*/
private final int kEditBoxInputModeNumeric = 2;
/**
* The user is allowed to enter a phone number.
*/
private final int kEditBoxInputModePhoneNumber = 3;
/**
* The user is allowed to enter a URL.
*/
private final int kEditBoxInputModeUrl = 4;
/**
* The user is allowed to enter a real number value. This extends kEditBoxInputModeNumeric by allowing a decimal point.
*/
private final int kEditBoxInputModeDecimal = 5;
/**
* The user is allowed to enter any text, except for line breaks.
*/
private final int kEditBoxInputModeSingleLine = 6;
/**
* Indicates that the text entered is confidential data that should be obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE.
*/
private final int kEditBoxInputFlagPassword = 0;
/**
* Indicates that the text entered is sensitive data that the implementation must never store into a dictionary or table for use in predictive, auto-completing, or other accelerated input schemes. A credit card number is an example of sensitive data.
*/
private final int kEditBoxInputFlagSensitive = 1;
/**
* This flag is a hint to the implementation that during text editing, the initial letter of each word should be capitalized.
*/
private final int kEditBoxInputFlagInitialCapsWord = 2;
/**
* This flag is a hint to the implementation that during text editing, the initial letter of each sentence should be capitalized.
*/
private final int kEditBoxInputFlagInitialCapsSentence = 3;
/**
* Capitalize all characters automatically.
*/
private final int kEditBoxInputFlagInitialCapsAllCharacters = 4;
private final int kKeyboardReturnTypeDefault = 0;
private final int kKeyboardReturnTypeDone = 1;
private final int kKeyboardReturnTypeSend = 2;
private final int kKeyboardReturnTypeSearch = 3;
private final int kKeyboardReturnTypeGo = 4;
// ===========================================================
// Fields
// ===========================================================
private EditText mInputEditText;
private TextView mTextViewTitle;
private final String mTitle;
private final String mMessage;
private final int mInputMode;
private final int mInputFlag;
private final int mReturnType;
private final int mMaxLength;
private int mInputFlagConstraints;
private int mInputModeContraints;
private boolean mIsMultiline;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxEditBoxDialog(final Context pContext, final String pTitle, final String pMessage, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) {
super(pContext, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
// super(context, R.style.Theme_Translucent);
this.mTitle = pTitle;
this.mMessage = pMessage;
this.mInputMode = pInputMode;
this.mInputFlag = pInputFlag;
this.mReturnType = pReturnType;
this.mMaxLength = pMaxLength;
}
@Override
protected void onCreate(final Bundle pSavedInstanceState) {
super.onCreate(pSavedInstanceState);
this.getWindow().setBackgroundDrawable(new ColorDrawable(0x80000000));
final LinearLayout layout = new LinearLayout(this.getContext());
layout.setOrientation(LinearLayout.VERTICAL);
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
this.mTextViewTitle = new TextView(this.getContext());
final LinearLayout.LayoutParams textviewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textviewParams.leftMargin = textviewParams.rightMargin = this.convertDipsToPixels(10);
this.mTextViewTitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
layout.addView(this.mTextViewTitle, textviewParams);
this.mInputEditText = new EditText(this.getContext());
final LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
editTextParams.leftMargin = editTextParams.rightMargin = this.convertDipsToPixels(10);
layout.addView(this.mInputEditText, editTextParams);
this.setContentView(layout, layoutParams);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.mTextViewTitle.setText(this.mTitle);
this.mInputEditText.setText(this.mMessage);
int oldImeOptions = this.mInputEditText.getImeOptions();
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
oldImeOptions = this.mInputEditText.getImeOptions();
switch (this.mInputMode) {
case kEditBoxInputModeAny:
this.mInputModeContraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE;
break;
case kEditBoxInputModeEmailAddr:
this.mInputModeContraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
break;
case kEditBoxInputModeNumeric:
this.mInputModeContraints = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case kEditBoxInputModePhoneNumber:
this.mInputModeContraints = InputType.TYPE_CLASS_PHONE;
break;
case kEditBoxInputModeUrl:
this.mInputModeContraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI;
break;
case kEditBoxInputModeDecimal:
this.mInputModeContraints = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case kEditBoxInputModeSingleLine:
this.mInputModeContraints = InputType.TYPE_CLASS_TEXT;
break;
default:
break;
}
if (this.mIsMultiline) {
this.mInputModeContraints |= InputType.TYPE_TEXT_FLAG_MULTI_LINE;
}
this.mInputEditText.setInputType(this.mInputModeContraints | this.mInputFlagConstraints);
switch (this.mInputFlag) {
case kEditBoxInputFlagPassword:
this.mInputFlagConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
break;
case kEditBoxInputFlagSensitive:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
break;
case kEditBoxInputFlagInitialCapsWord:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_WORDS;
break;
case kEditBoxInputFlagInitialCapsSentence:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
break;
case kEditBoxInputFlagInitialCapsAllCharacters:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS;
break;
default:
break;
}
this.mInputEditText.setInputType(this.mInputFlagConstraints | this.mInputModeContraints);
switch (this.mReturnType) {
case kKeyboardReturnTypeDefault:
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_NONE);
break;
case kKeyboardReturnTypeDone:
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_DONE);
break;
case kKeyboardReturnTypeSend:
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_SEND);
break;
case kKeyboardReturnTypeSearch:
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_SEARCH);
break;
case kKeyboardReturnTypeGo:
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_GO);
break;
default:
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_NONE);
break;
}
if (this.mMaxLength > 0) {
this.mInputEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(this.mMaxLength) });
}
final Handler initHandler = new Handler();
initHandler.postDelayed(new Runnable() {
@Override
public void run() {
Cocos2dxEditBoxDialog.this.mInputEditText.requestFocus();
Cocos2dxEditBoxDialog.this.mInputEditText.setSelection(Cocos2dxEditBoxDialog.this.mInputEditText.length());
Cocos2dxEditBoxDialog.this.openKeyboard();
}
}, 200);
this.mInputEditText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event) {
/* If user didn't set keyboard type, this callback will be invoked twice with 'KeyEvent.ACTION_DOWN' and 'KeyEvent.ACTION_UP'. */
if (actionId != EditorInfo.IME_NULL || (actionId == EditorInfo.IME_NULL && event != null && event.getAction() == KeyEvent.ACTION_DOWN)) {
Cocos2dxHelper.setEditTextDialogResult(Cocos2dxEditBoxDialog.this.mInputEditText.getText().toString());
Cocos2dxEditBoxDialog.this.closeKeyboard();
Cocos2dxEditBoxDialog.this.dismiss();
return true;
}
return false;
}
});
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
private int convertDipsToPixels(final float pDIPs) {
final float scale = this.getContext().getResources().getDisplayMetrics().density;
return Math.round(pDIPs * scale);
}
private void openKeyboard() {
final InputMethodManager imm = (InputMethodManager) this.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(this.mInputEditText, 0);
}
private void closeKeyboard() {
final InputMethodManager imm = (InputMethodManager) this.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(this.mInputEditText.getWindowToken(), 0);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}

View File

@ -0,0 +1,89 @@
/****************************************************************************
Copyright (c) 2012 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;
public class Cocos2dxEditText extends EditText {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private Cocos2dxGLSurfaceView mCocos2dxGLSurfaceView;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxEditText(final Context context) {
super(context);
}
public Cocos2dxEditText(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public Cocos2dxEditText(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void setCocos2dxGLSurfaceView(final Cocos2dxGLSurfaceView pCocos2dxGLSurfaceView) {
this.mCocos2dxGLSurfaceView = pCocos2dxGLSurfaceView;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
super.onKeyDown(pKeyCode, pKeyEvent);
/* Let GlSurfaceView get focus if back key is input. */
if (pKeyCode == KeyEvent.KEYCODE_BACK) {
this.mCocos2dxGLSurfaceView.requestFocus();
}
return true;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}

View File

@ -0,0 +1,356 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.inputmethod.InputMethodManager;
public class Cocos2dxGLSurfaceView extends GLSurfaceView {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = Cocos2dxGLSurfaceView.class.getSimpleName();
private final static int HANDLER_OPEN_IME_KEYBOARD = 2;
private final static int HANDLER_CLOSE_IME_KEYBOARD = 3;
// ===========================================================
// Fields
// ===========================================================
// TODO Static handler -> Potential leak!
private static Handler sHandler;
private static Cocos2dxGLSurfaceView mCocos2dxGLSurfaceView;
private static Cocos2dxTextInputWraper sCocos2dxTextInputWraper;
private Cocos2dxRenderer mCocos2dxRenderer;
private Cocos2dxEditText mCocos2dxEditText;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxGLSurfaceView(final Context context) {
super(context);
this.setEGLContextClientVersion(2);
this.initView();
}
public Cocos2dxGLSurfaceView(final Context context, final AttributeSet attrs) {
super(context, attrs);
this.setEGLContextClientVersion(2);
this.initView();
}
protected void initView() {
this.setFocusableInTouchMode(true);
Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView = this;
Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper = new Cocos2dxTextInputWraper(this);
Cocos2dxGLSurfaceView.sHandler = new Handler() {
@Override
public void handleMessage(final Message msg) {
switch (msg.what) {
case HANDLER_OPEN_IME_KEYBOARD:
if (null != Cocos2dxGLSurfaceView.this.mCocos2dxEditText && Cocos2dxGLSurfaceView.this.mCocos2dxEditText.requestFocus()) {
Cocos2dxGLSurfaceView.this.mCocos2dxEditText.removeTextChangedListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper);
Cocos2dxGLSurfaceView.this.mCocos2dxEditText.setText("");
final String text = (String) msg.obj;
Cocos2dxGLSurfaceView.this.mCocos2dxEditText.append(text);
Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper.setOriginText(text);
Cocos2dxGLSurfaceView.this.mCocos2dxEditText.addTextChangedListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper);
final InputMethodManager imm = (InputMethodManager) Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(Cocos2dxGLSurfaceView.this.mCocos2dxEditText, 0);
Log.d("GLSurfaceView", "showSoftInput");
}
break;
case HANDLER_CLOSE_IME_KEYBOARD:
if (null != Cocos2dxGLSurfaceView.this.mCocos2dxEditText) {
Cocos2dxGLSurfaceView.this.mCocos2dxEditText.removeTextChangedListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper);
final InputMethodManager imm = (InputMethodManager) Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(Cocos2dxGLSurfaceView.this.mCocos2dxEditText.getWindowToken(), 0);
Log.d("GLSurfaceView", "HideSoftInput");
}
break;
}
}
};
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void setCocos2dxRenderer(final Cocos2dxRenderer renderer) {
this.mCocos2dxRenderer = renderer;
this.setRenderer(this.mCocos2dxRenderer);
}
private String getContentText() {
return this.mCocos2dxRenderer.getContentText();
}
public Cocos2dxEditText getCocos2dxEditText() {
return this.mCocos2dxEditText;
}
public void setCocos2dxEditText(final Cocos2dxEditText pCocos2dxEditText) {
this.mCocos2dxEditText = pCocos2dxEditText;
if (null != this.mCocos2dxEditText && null != Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper) {
this.mCocos2dxEditText.setOnEditorActionListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper);
this.mCocos2dxEditText.setCocos2dxGLSurfaceView(this);
this.requestFocus();
}
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onResume() {
super.onResume();
this.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnResume();
}
});
}
@Override
public void onPause() {
this.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnPause();
}
});
super.onPause();
}
@Override
public boolean onTouchEvent(final MotionEvent pMotionEvent) {
// these data are used in ACTION_MOVE and ACTION_CANCEL
final int pointerNumber = pMotionEvent.getPointerCount();
final int[] ids = new int[pointerNumber];
final float[] xs = new float[pointerNumber];
final float[] ys = new float[pointerNumber];
for (int i = 0; i < pointerNumber; i++) {
ids[i] = pMotionEvent.getPointerId(i);
xs[i] = pMotionEvent.getX(i);
ys[i] = pMotionEvent.getY(i);
}
switch (pMotionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_POINTER_DOWN:
final int indexPointerDown = pMotionEvent.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT;
final int idPointerDown = pMotionEvent.getPointerId(indexPointerDown);
final float xPointerDown = pMotionEvent.getX(indexPointerDown);
final float yPointerDown = pMotionEvent.getY(indexPointerDown);
this.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionDown(idPointerDown, xPointerDown, yPointerDown);
}
});
break;
case MotionEvent.ACTION_DOWN:
// there are only one finger on the screen
final int idDown = pMotionEvent.getPointerId(0);
final float xDown = xs[0];
final float yDown = ys[0];
this.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionDown(idDown, xDown, yDown);
}
});
break;
case MotionEvent.ACTION_MOVE:
this.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionMove(ids, xs, ys);
}
});
break;
case MotionEvent.ACTION_POINTER_UP:
final int indexPointUp = pMotionEvent.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT;
final int idPointerUp = pMotionEvent.getPointerId(indexPointUp);
final float xPointerUp = pMotionEvent.getX(indexPointUp);
final float yPointerUp = pMotionEvent.getY(indexPointUp);
this.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionUp(idPointerUp, xPointerUp, yPointerUp);
}
});
break;
case MotionEvent.ACTION_UP:
// there are only one finger on the screen
final int idUp = pMotionEvent.getPointerId(0);
final float xUp = xs[0];
final float yUp = ys[0];
this.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionUp(idUp, xUp, yUp);
}
});
break;
case MotionEvent.ACTION_CANCEL:
this.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionCancel(ids, xs, ys);
}
});
break;
}
if (BuildConfig.DEBUG) {
Cocos2dxGLSurfaceView.dumpMotionEvent(pMotionEvent);
}
return true;
}
/*
* This function is called before Cocos2dxRenderer.nativeInit(), so the
* width and height is correct.
*/
@Override
protected void onSizeChanged(final int pNewSurfaceWidth, final int pNewSurfaceHeight, final int pOldSurfaceWidth, final int pOldSurfaceHeight) {
if(!this.isInEditMode()) {
this.mCocos2dxRenderer.setScreenWidthAndHeight(pNewSurfaceWidth, pNewSurfaceHeight);
}
}
@Override
public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
switch (pKeyCode) {
case KeyEvent.KEYCODE_BACK:
case KeyEvent.KEYCODE_MENU:
this.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleKeyDown(pKeyCode);
}
});
return true;
default:
return super.onKeyDown(pKeyCode, pKeyEvent);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static void openIMEKeyboard() {
final Message msg = new Message();
msg.what = Cocos2dxGLSurfaceView.HANDLER_OPEN_IME_KEYBOARD;
msg.obj = Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView.getContentText();
Cocos2dxGLSurfaceView.sHandler.sendMessage(msg);
}
public static void closeIMEKeyboard() {
final Message msg = new Message();
msg.what = Cocos2dxGLSurfaceView.HANDLER_CLOSE_IME_KEYBOARD;
Cocos2dxGLSurfaceView.sHandler.sendMessage(msg);
}
public void insertText(final String pText) {
this.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleInsertText(pText);
}
});
}
public void deleteBackward() {
this.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleDeleteBackward();
}
});
}
private static void dumpMotionEvent(final MotionEvent event) {
final String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE", "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
final StringBuilder sb = new StringBuilder();
final int action = event.getAction();
final int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP) {
sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i = 0; i < event.getPointerCount(); i++) {
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
sb.append(")=").append((int) event.getX(i));
sb.append(",").append((int) event.getY(i));
if (i + 1 < event.getPointerCount()) {
sb.append(";");
}
}
sb.append("]");
Log.d(Cocos2dxGLSurfaceView.TAG, sb.toString());
}
}

View File

@ -0,0 +1,253 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.AssetManager;
import android.os.Environment;
public class Cocos2dxHelper {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static Cocos2dxMusic sCocos2dMusic;
private static Cocos2dxSound sCocos2dSound;
private static AssetManager sAssetManager;
private static Cocos2dxAccelerometer sCocos2dxAccelerometer;
private static boolean sAccelerometerEnabled;
private static String sPackageName;
private static Cocos2dxHelperListener sCocos2dxHelperListener;
// ===========================================================
// Constructors
// ===========================================================
public static void init(final Context pContext, final Cocos2dxHelperListener pCocos2dxHelperListener) {
final ApplicationInfo applicationInfo = pContext.getApplicationInfo();
Cocos2dxHelper.sCocos2dxHelperListener = pCocos2dxHelperListener;
Cocos2dxHelper.sPackageName = applicationInfo.packageName;
Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir);
Cocos2dxHelper.nativeSetExternalAssetPath(Cocos2dxHelper.getAbsolutePathOnExternalStorage(applicationInfo, "assets/"));
Cocos2dxHelper.nativeSetAssetManager(pContext.getAssets());
Cocos2dxHelper.sCocos2dxAccelerometer = new Cocos2dxAccelerometer(pContext);
Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(pContext);
Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(pContext);
Cocos2dxHelper.sAssetManager = pContext.getAssets();
Cocos2dxBitmap.setContext(pContext);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
private static native void nativeSetApkPath(final String pApkPath);
private static native void nativeSetExternalAssetPath(final String pExternalAssetPath);
private static native void nativeSetAssetManager(final AssetManager pAssetManager);
private static native void nativeSetEditTextDialogResult(final byte[] pBytes);
public static String getCocos2dxPackageName() {
return Cocos2dxHelper.sPackageName;
}
public static String getCurrentLanguage() {
return Locale.getDefault().getLanguage();
}
public static AssetManager getAssetManager() {
return Cocos2dxHelper.sAssetManager;
}
public static void enableAccelerometer() {
Cocos2dxHelper.sAccelerometerEnabled = true;
Cocos2dxHelper.sCocos2dxAccelerometer.enable();
}
public static void disableAccelerometer() {
Cocos2dxHelper.sAccelerometerEnabled = false;
Cocos2dxHelper.sCocos2dxAccelerometer.disable();
}
public static void preloadBackgroundMusic(final String pPath) {
Cocos2dxHelper.sCocos2dMusic.preloadBackgroundMusic(pPath);
}
public static void playBackgroundMusic(final String pPath, final boolean isLoop) {
Cocos2dxHelper.sCocos2dMusic.playBackgroundMusic(pPath, isLoop);
}
public static void resumeBackgroundMusic() {
Cocos2dxHelper.sCocos2dMusic.resumeBackgroundMusic();
}
public static void pauseBackgroundMusic() {
Cocos2dxHelper.sCocos2dMusic.pauseBackgroundMusic();
}
public static void stopBackgroundMusic() {
Cocos2dxHelper.sCocos2dMusic.stopBackgroundMusic();
}
public static void rewindBackgroundMusic() {
Cocos2dxHelper.sCocos2dMusic.rewindBackgroundMusic();
}
public static boolean isBackgroundMusicPlaying() {
return Cocos2dxHelper.sCocos2dMusic.isBackgroundMusicPlaying();
}
public static float getBackgroundMusicVolume() {
return Cocos2dxHelper.sCocos2dMusic.getBackgroundVolume();
}
public static void setBackgroundMusicVolume(final float volume) {
Cocos2dxHelper.sCocos2dMusic.setBackgroundVolume(volume);
}
public static void preloadEffect(final String path) {
Cocos2dxHelper.sCocos2dSound.preloadEffect(path);
}
public static int playEffect(final String path, final boolean isLoop) {
return Cocos2dxHelper.sCocos2dSound.playEffect(path, isLoop);
}
public static void resumeEffect(final int soundId) {
Cocos2dxHelper.sCocos2dSound.resumeEffect(soundId);
}
public static void pauseEffect(final int soundId) {
Cocos2dxHelper.sCocos2dSound.pauseEffect(soundId);
}
public static void stopEffect(final int soundId) {
Cocos2dxHelper.sCocos2dSound.stopEffect(soundId);
}
public static float getEffectsVolume() {
return Cocos2dxHelper.sCocos2dSound.getEffectsVolume();
}
public static void setEffectsVolume(final float volume) {
Cocos2dxHelper.sCocos2dSound.setEffectsVolume(volume);
}
public static void unloadEffect(final String path) {
Cocos2dxHelper.sCocos2dSound.unloadEffect(path);
}
public static void pauseAllEffects() {
Cocos2dxHelper.sCocos2dSound.pauseAllEffects();
}
public static void resumeAllEffects() {
Cocos2dxHelper.sCocos2dSound.resumeAllEffects();
}
public static void stopAllEffects() {
Cocos2dxHelper.sCocos2dSound.stopAllEffects();
}
public static void end() {
Cocos2dxHelper.sCocos2dMusic.end();
Cocos2dxHelper.sCocos2dSound.end();
}
public static void onResume() {
if (Cocos2dxHelper.sAccelerometerEnabled) {
Cocos2dxHelper.sCocos2dxAccelerometer.enable();
}
}
public static void onPause() {
if (Cocos2dxHelper.sAccelerometerEnabled) {
Cocos2dxHelper.sCocos2dxAccelerometer.disable();
}
}
public static void terminateProcess() {
android.os.Process.killProcess(android.os.Process.myPid());
}
private static void showDialog(final String pTitle, final String pMessage) {
Cocos2dxHelper.sCocos2dxHelperListener.showDialog(pTitle, pMessage);
}
private static void showEditTextDialog(final String pTitle, final String pMessage, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) {
Cocos2dxHelper.sCocos2dxHelperListener.showEditTextDialog(pTitle, pMessage, pInputMode, pInputFlag, pReturnType, pMaxLength);
}
public static void setEditTextDialogResult(final String pResult) {
try {
final byte[] bytesUTF8 = pResult.getBytes("UTF8");
Cocos2dxHelper.sCocos2dxHelperListener.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxHelper.nativeSetEditTextDialogResult(bytesUTF8);
}
});
} catch (UnsupportedEncodingException pUnsupportedEncodingException) {
/* Nothing. */
}
}
private static String getAbsolutePathOnExternalStorage(final ApplicationInfo pApplicationInfo, final String pPath) {
return Environment.getExternalStorageDirectory() + "/Android/data/" + pApplicationInfo.packageName + "/files/" + pPath;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static interface Cocos2dxHelperListener {
public void showDialog(final String pTitle, final String pMessage);
public void showEditTextDialog(final String pTitle, final String pMessage, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength);
public void runOnGLThread(final Runnable pRunnable);
}
}

View File

@ -0,0 +1,250 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.util.Log;
public class Cocos2dxMusic {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = Cocos2dxMusic.class.getSimpleName();
// ===========================================================
// Fields
// ===========================================================
private final Context mContext;
private MediaPlayer mBackgroundMediaPlayer;
private float mLeftVolume;
private float mRightVolume;
private boolean mPaused;
private String mCurrentPath;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxMusic(final Context pContext) {
this.mContext = pContext;
this.initData();
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void preloadBackgroundMusic(final String pPath) {
if ((this.mCurrentPath == null) || (!this.mCurrentPath.equals(pPath))) {
// preload new background music
// release old resource and create a new one
if (this.mBackgroundMediaPlayer != null) {
this.mBackgroundMediaPlayer.release();
}
this.mBackgroundMediaPlayer = this.createMediaplayerFromAssets(pPath);
// record the path
this.mCurrentPath = pPath;
}
}
public void playBackgroundMusic(final String pPath, final boolean isLoop) {
if (this.mCurrentPath == null) {
// it is the first time to play background music or end() was called
this.mBackgroundMediaPlayer = this.createMediaplayerFromAssets(pPath);
this.mCurrentPath = pPath;
} else {
if (!this.mCurrentPath.equals(pPath)) {
// play new background music
// release old resource and create a new one
if (this.mBackgroundMediaPlayer != null) {
this.mBackgroundMediaPlayer.release();
}
this.mBackgroundMediaPlayer = this.createMediaplayerFromAssets(pPath);
// record the path
this.mCurrentPath = pPath;
}
}
if (this.mBackgroundMediaPlayer == null) {
Log.e(Cocos2dxMusic.TAG, "playBackgroundMusic: background media player is null");
} else {
// if the music is playing or paused, stop it
this.mBackgroundMediaPlayer.stop();
this.mBackgroundMediaPlayer.setLooping(isLoop);
try {
this.mBackgroundMediaPlayer.prepare();
this.mBackgroundMediaPlayer.seekTo(0);
this.mBackgroundMediaPlayer.start();
this.mPaused = false;
} catch (final Exception e) {
Log.e(Cocos2dxMusic.TAG, "playBackgroundMusic: error state");
}
}
}
public void stopBackgroundMusic() {
if (this.mBackgroundMediaPlayer != null) {
this.mBackgroundMediaPlayer.stop();
// should set the state, if not, the following sequence will be error
// play -> pause -> stop -> resume
this.mPaused = false;
}
}
public void pauseBackgroundMusic() {
if (this.mBackgroundMediaPlayer != null && this.mBackgroundMediaPlayer.isPlaying()) {
this.mBackgroundMediaPlayer.pause();
this.mPaused = true;
}
}
public void resumeBackgroundMusic() {
if (this.mBackgroundMediaPlayer != null && this.mPaused) {
this.mBackgroundMediaPlayer.start();
this.mPaused = false;
}
}
public void rewindBackgroundMusic() {
if (this.mBackgroundMediaPlayer != null) {
this.mBackgroundMediaPlayer.stop();
try {
this.mBackgroundMediaPlayer.prepare();
this.mBackgroundMediaPlayer.seekTo(0);
this.mBackgroundMediaPlayer.start();
this.mPaused = false;
} catch (final Exception e) {
Log.e(Cocos2dxMusic.TAG, "rewindBackgroundMusic: error state");
}
}
}
public boolean isBackgroundMusicPlaying() {
boolean ret = false;
if (this.mBackgroundMediaPlayer == null) {
ret = false;
} else {
ret = this.mBackgroundMediaPlayer.isPlaying();
}
return ret;
}
public void end() {
if (this.mBackgroundMediaPlayer != null) {
this.mBackgroundMediaPlayer.release();
}
this.initData();
}
public float getBackgroundVolume() {
if (this.mBackgroundMediaPlayer != null) {
return (this.mLeftVolume + this.mRightVolume) / 2;
} else {
return 0.0f;
}
}
public void setBackgroundVolume(float pVolume) {
if (pVolume < 0.0f) {
pVolume = 0.0f;
}
if (pVolume > 1.0f) {
pVolume = 1.0f;
}
this.mLeftVolume = this.mRightVolume = pVolume;
if (this.mBackgroundMediaPlayer != null) {
this.mBackgroundMediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume);
}
}
private void initData() {
this.mLeftVolume = 0.5f;
this.mRightVolume = 0.5f;
this.mBackgroundMediaPlayer = null;
this.mPaused = false;
this.mCurrentPath = null;
}
/**
* create mediaplayer for music
*
* @param pPath
* the pPath relative to assets
* @return
*/
private MediaPlayer createMediaplayerFromAssets(final String pPath) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
if (pPath.startsWith("/")) {
mediaPlayer.setDataSource(pPath);
} else {
final AssetFileDescriptor assetFileDescritor = this.mContext.getAssets().openFd(pPath);
mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength());
}
mediaPlayer.prepare();
mediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume);
} catch (final Exception e) {
mediaPlayer = null;
Log.e(Cocos2dxMusic.TAG, "error: " + e.getMessage(), e);
}
return mediaPlayer;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}

View File

@ -0,0 +1,162 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView;
public class Cocos2dxRenderer implements GLSurfaceView.Renderer {
// ===========================================================
// Constants
// ===========================================================
private final static long NANOSECONDSPERSECOND = 1000000000L;
private final static long NANOSECONDSPERMICROSECOND = 1000000;
private static long sAnimationInterval = (long) (1.0 / 60 * Cocos2dxRenderer.NANOSECONDSPERSECOND);
// ===========================================================
// Fields
// ===========================================================
private long mLastTickInNanoSeconds;
private int mScreenWidth;
private int mScreenHeight;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public static void setAnimationInterval(final double pAnimationInterval) {
Cocos2dxRenderer.sAnimationInterval = (long) (pAnimationInterval * Cocos2dxRenderer.NANOSECONDSPERSECOND);
}
public void setScreenWidthAndHeight(final int pSurfaceWidth, final int pSurfaceHeight) {
this.mScreenWidth = pSurfaceWidth;
this.mScreenHeight = pSurfaceHeight;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onSurfaceCreated(final GL10 pGL10, final EGLConfig pEGLConfig) {
Cocos2dxRenderer.nativeInit(this.mScreenWidth, this.mScreenHeight);
this.mLastTickInNanoSeconds = System.nanoTime();
}
@Override
public void onSurfaceChanged(final GL10 pGL10, final int pWidth, final int pHeight) {
}
@Override
public void onDrawFrame(final GL10 gl) {
final long nowInNanoSeconds = System.nanoTime();
final long interval = nowInNanoSeconds - this.mLastTickInNanoSeconds;
// should render a frame when onDrawFrame() is called or there is a
// "ghost"
Cocos2dxRenderer.nativeRender();
// fps controlling
if (interval < Cocos2dxRenderer.sAnimationInterval) {
try {
// because we render it before, so we should sleep twice time interval
Thread.sleep((Cocos2dxRenderer.sAnimationInterval - interval) * 2 / Cocos2dxRenderer.NANOSECONDSPERMICROSECOND);
} catch (final Exception e) {
}
}
this.mLastTickInNanoSeconds = nowInNanoSeconds;
}
// ===========================================================
// Methods
// ===========================================================
private static native void nativeTouchesBegin(final int pID, final float pX, final float pY);
private static native void nativeTouchesEnd(final int pID, final float pX, final float pY);
private static native void nativeTouchesMove(final int[] pIDs, final float[] pXs, final float[] pYs);
private static native void nativeTouchesCancel(final int[] pIDs, final float[] pXs, final float[] pYs);
private static native boolean nativeKeyDown(final int pKeyCode);
private static native void nativeRender();
private static native void nativeInit(final int pWidth, final int pHeight);
private static native void nativeOnPause();
private static native void nativeOnResume();
public void handleActionDown(final int pID, final float pX, final float pY) {
Cocos2dxRenderer.nativeTouchesBegin(pID, pX, pY);
}
public void handleActionUp(final int pID, final float pX, final float pY) {
Cocos2dxRenderer.nativeTouchesEnd(pID, pX, pY);
}
public void handleActionCancel(final int[] pIDs, final float[] pXs, final float[] pYs) {
Cocos2dxRenderer.nativeTouchesCancel(pIDs, pXs, pYs);
}
public void handleActionMove(final int[] pIDs, final float[] pXs, final float[] pYs) {
Cocos2dxRenderer.nativeTouchesMove(pIDs, pXs, pYs);
}
public void handleKeyDown(final int pKeyCode) {
Cocos2dxRenderer.nativeKeyDown(pKeyCode);
}
public void handleOnPause() {
Cocos2dxRenderer.nativeOnPause();
}
public void handleOnResume() {
Cocos2dxRenderer.nativeOnResume();
}
private static native void nativeInsertText(final String pText);
private static native void nativeDeleteBackward();
private static native String nativeGetContentText();
public void handleInsertText(final String pText) {
Cocos2dxRenderer.nativeInsertText(pText);
}
public void handleDeleteBackward() {
Cocos2dxRenderer.nativeDeleteBackward();
}
public String getContentText() {
return Cocos2dxRenderer.nativeGetContentText();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}

View File

@ -0,0 +1,263 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;
public class Cocos2dxSound {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = "Cocos2dxSound";
// ===========================================================
// Fields
// ===========================================================
private final Context mContext;
private SoundPool mSoundPool;
private float mLeftVolume;
private float mRightVolume;
// sound path and stream ids map
// a file may be played many times at the same time
// so there is an array map to a file path
private final HashMap<String, ArrayList<Integer>> mPathStreamIDsMap = new HashMap<String, ArrayList<Integer>>();
private final HashMap<String, Integer> mPathSoundIDMap = new HashMap<String, Integer>();
private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5;
private static final float SOUND_RATE = 1.0f;
private static final int SOUND_PRIORITY = 1;
private static final int SOUND_QUALITY = 5;
private final static int INVALID_SOUND_ID = -1;
private final static int INVALID_STREAM_ID = -1;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxSound(final Context pContext) {
this.mContext = pContext;
this.initData();
}
private void initData() {
this.mSoundPool = new SoundPool(Cocos2dxSound.MAX_SIMULTANEOUS_STREAMS_DEFAULT, AudioManager.STREAM_MUSIC, Cocos2dxSound.SOUND_QUALITY);
this.mLeftVolume = 0.5f;
this.mRightVolume = 0.5f;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public int preloadEffect(final String pPath) {
Integer soundID = this.mPathSoundIDMap.get(pPath);
if (soundID == null) {
soundID = this.createSoundIDFromAsset(pPath);
this.mPathSoundIDMap.put(pPath, soundID);
}
return soundID;
}
public void unloadEffect(final String pPath) {
// stop effects
final ArrayList<Integer> streamIDs = this.mPathStreamIDsMap.get(pPath);
if (streamIDs != null) {
for (final Integer pStreamID : streamIDs) {
this.mSoundPool.stop(pStreamID);
}
}
this.mPathStreamIDsMap.remove(pPath);
// unload effect
final Integer soundID = this.mPathSoundIDMap.get(pPath);
this.mSoundPool.unload(soundID);
this.mPathSoundIDMap.remove(pPath);
}
public int playEffect(final String pPath, final boolean pLoop) {
Integer soundID = this.mPathSoundIDMap.get(pPath);
int streamID = Cocos2dxSound.INVALID_STREAM_ID;
if (soundID != null) {
// play sound
streamID = this.mSoundPool.play(soundID.intValue(), this.mLeftVolume, this.mRightVolume, Cocos2dxSound.SOUND_PRIORITY, pLoop ? -1 : 0, Cocos2dxSound.SOUND_RATE);
// record stream id
ArrayList<Integer> streamIDs = this.mPathStreamIDsMap.get(pPath);
if (streamIDs == null) {
streamIDs = new ArrayList<Integer>();
this.mPathStreamIDsMap.put(pPath, streamIDs);
}
streamIDs.add(streamID);
} else {
// the effect is not prepared
soundID = this.preloadEffect(pPath);
if (soundID == Cocos2dxSound.INVALID_SOUND_ID) {
// can not preload effect
return Cocos2dxSound.INVALID_SOUND_ID;
}
/*
* Someone reports that, it can not play effect for the first time.
* If you are lucky to meet it. There are two ways to resolve it. 1.
* Add some delay here. I don't know how long it is, so I don't add
* it here. 2. If you use 2.2(API level 8), you can call
* SoundPool.setOnLoadCompleteListener() to play the effect. Because
* the method is supported from 2.2, so I can't use it here.
*/
this.playEffect(pPath, pLoop);
}
return streamID;
}
public void stopEffect(final int pStreamID) {
this.mSoundPool.stop(pStreamID);
// remove record
for (final String pPath : this.mPathStreamIDsMap.keySet()) {
if (this.mPathStreamIDsMap.get(pPath).contains(pStreamID)) {
this.mPathStreamIDsMap.get(pPath).remove(this.mPathStreamIDsMap.get(pPath).indexOf(pStreamID));
break;
}
}
}
public void pauseEffect(final int pStreamID) {
this.mSoundPool.pause(pStreamID);
}
public void resumeEffect(final int pStreamID) {
this.mSoundPool.resume(pStreamID);
}
public void pauseAllEffects() {
this.mSoundPool.autoPause();
}
public void resumeAllEffects() {
// autoPause() is available since level 8
this.mSoundPool.autoResume();
}
@SuppressWarnings("unchecked")
public void stopAllEffects() {
// stop effects
if (!this.mPathStreamIDsMap.isEmpty()) {
final Iterator<?> iter = this.mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Map.Entry<String, ArrayList<Integer>> entry = (Map.Entry<String, ArrayList<Integer>>) iter.next();
for (final int pStreamID : entry.getValue()) {
this.mSoundPool.stop(pStreamID);
}
}
}
// remove records
this.mPathStreamIDsMap.clear();
}
public float getEffectsVolume() {
return (this.mLeftVolume + this.mRightVolume) / 2;
}
public void setEffectsVolume(float pVolume) {
// pVolume should be in [0, 1.0]
if (pVolume < 0) {
pVolume = 0;
}
if (pVolume > 1) {
pVolume = 1;
}
this.mLeftVolume = this.mRightVolume = pVolume;
// change the volume of playing sounds
if (!this.mPathStreamIDsMap.isEmpty()) {
final Iterator<Entry<String, ArrayList<Integer>>> iter = this.mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Entry<String, ArrayList<Integer>> entry = iter.next();
for (final int pStreamID : entry.getValue()) {
this.mSoundPool.setVolume(pStreamID, this.mLeftVolume, this.mRightVolume);
}
}
}
}
public void end() {
this.mSoundPool.release();
this.mPathStreamIDsMap.clear();
this.mPathSoundIDMap.clear();
this.mLeftVolume = 0.5f;
this.mRightVolume = 0.5f;
}
public int createSoundIDFromAsset(final String pPath) {
int soundID = Cocos2dxSound.INVALID_SOUND_ID;
try {
if (pPath.startsWith("/")) {
soundID = this.mSoundPool.load(pPath, 0);
} else {
soundID = this.mSoundPool.load(this.mContext.getAssets().openFd(pPath), 0);
}
} catch (final Exception e) {
soundID = Cocos2dxSound.INVALID_SOUND_ID;
Log.e(Cocos2dxSound.TAG, "error: " + e.getMessage(), e);
}
return soundID;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}

View File

@ -0,0 +1,153 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class Cocos2dxTextInputWraper implements TextWatcher, OnEditorActionListener {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = Cocos2dxTextInputWraper.class.getSimpleName();
// ===========================================================
// Fields
// ===========================================================
private final Cocos2dxGLSurfaceView mCocos2dxGLSurfaceView;
private String mText;
private String mOriginText;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxTextInputWraper(final Cocos2dxGLSurfaceView pCocos2dxGLSurfaceView) {
this.mCocos2dxGLSurfaceView = pCocos2dxGLSurfaceView;
}
// ===========================================================
// Getter & Setter
// ===========================================================
private boolean isFullScreenEdit() {
final TextView textField = this.mCocos2dxGLSurfaceView.getCocos2dxEditText();
final InputMethodManager imm = (InputMethodManager) textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
return imm.isFullscreenMode();
}
public void setOriginText(final String pOriginText) {
this.mOriginText = pOriginText;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void afterTextChanged(final Editable s) {
if (this.isFullScreenEdit()) {
return;
}
if (BuildConfig.DEBUG) {
Log.d(TAG, "afterTextChanged: " + s);
}
int nModified = s.length() - this.mText.length();
if (nModified > 0) {
final String insertText = s.subSequence(this.mText.length(), s.length()).toString();
this.mCocos2dxGLSurfaceView.insertText(insertText);
if (BuildConfig.DEBUG) {
Log.d(TAG, "insertText(" + insertText + ")");
}
} else {
for (; nModified < 0; ++nModified) {
this.mCocos2dxGLSurfaceView.deleteBackward();
if (BuildConfig.DEBUG) {
Log.d(TAG, "deleteBackward");
}
}
}
this.mText = s.toString();
}
@Override
public void beforeTextChanged(final CharSequence pCharSequence, final int start, final int count, final int after) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "beforeTextChanged(" + pCharSequence + ")start: " + start + ",count: " + count + ",after: " + after);
}
this.mText = pCharSequence.toString();
}
@Override
public void onTextChanged(final CharSequence pCharSequence, final int start, final int before, final int count) {
}
@Override
public boolean onEditorAction(final TextView pTextView, final int pActionID, final KeyEvent pKeyEvent) {
if (this.mCocos2dxGLSurfaceView.getCocos2dxEditText() == pTextView && this.isFullScreenEdit()) {
// user press the action button, delete all old text and insert new text
for (int i = this.mOriginText.length(); i > 0; i--) {
this.mCocos2dxGLSurfaceView.deleteBackward();
if (BuildConfig.DEBUG) {
Log.d(TAG, "deleteBackward");
}
}
String text = pTextView.getText().toString();
/* If user input nothing, translate "\n" to engine. */
if (text.compareTo("") == 0) {
text = "\n";
}
if ('\n' != text.charAt(text.length() - 1)) {
text += '\n';
}
final String insertText = text;
this.mCocos2dxGLSurfaceView.insertText(insertText);
if (BuildConfig.DEBUG) {
Log.d(TAG, "insertText(" + insertText + ")");
}
}
return false;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}

View File

@ -0,0 +1,71 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Typeface;
public class Cocos2dxTypefaces {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static final HashMap<String, Typeface> sTypefaceCache = new HashMap<String, Typeface>();
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static synchronized Typeface get(final Context pContext, final String pAssetName) {
if (!Cocos2dxTypefaces.sTypefaceCache.containsKey(pAssetName)) {
final Typeface typeface = Typeface.createFromAsset(pContext.getAssets(), pAssetName);
Cocos2dxTypefaces.sTypefaceCache.put(pAssetName, typeface);
}
return Cocos2dxTypefaces.sTypefaceCache.get(pAssetName);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}

View File

@ -1,107 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
/**
*
* This class is used for controlling the Accelerometer
*
*/
public class Cocos2dxAccelerometer implements SensorEventListener {
private static final String TAG = "Cocos2dxAccelerometer";
private Context mContext;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private int mNaturalOrientation;
public Cocos2dxAccelerometer(Context context){
mContext = context;
//Get an instance of the SensorManager
mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Display display = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
mNaturalOrientation = display.getOrientation();
}
public void enable() {
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
}
public void disable () {
mSensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER){
return;
}
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
/*
* Because the axes are not swapped when the device's screen orientation changes.
* So we should swap it here.
* In tablets such as Motorola Xoom, the default orientation is landscape, so should
* consider this.
*/
int orientation = mContext.getResources().getConfiguration().orientation;
if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (mNaturalOrientation != Surface.ROTATION_0)){
float tmp = x;
x = -y;
y = tmp;
}
else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (mNaturalOrientation != Surface.ROTATION_0))
{
float tmp = x;
x = y;
y = -tmp;
}
onSensorChanged(x, y, z, event.timestamp);
// Log.d(TAG, "x = " + event.values[0] + " y = " + event.values[1] + " z = " + event.values[2]);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private static native void onSensorChanged(float x, float y, float z, long timeStamp);
}

View File

@ -1,346 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import java.lang.ref.WeakReference;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
public class Cocos2dxActivity extends Activity{
protected Cocos2dxGLSurfaceView mGLView;
private static Cocos2dxMusic backgroundMusicPlayer;
private static Cocos2dxSound soundPlayer;
private static Cocos2dxAccelerometer accelerometer;
private static AssetManager assetManager;
private static boolean accelerometerEnabled = false;
private static Handler handler;
private final static int HANDLER_SHOW_DIALOG = 1;
private final static int HANDLER_SHOW_EDITBOX_DIALOG = 2;
private static String packageName;
private static native void nativeSetPaths(String apkPath);
private static native void nativeSetEditboxText(byte[] text);
static class ShowDialogHandler extends Handler {
WeakReference<Cocos2dxActivity> mActivity;
ShowDialogHandler(Cocos2dxActivity activity) {
mActivity = new WeakReference<Cocos2dxActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
Cocos2dxActivity theActivity = mActivity.get();
switch(msg.what) {
case HANDLER_SHOW_DIALOG:
theActivity.showDialog(((DialogMessage)msg.obj).title, ((DialogMessage)msg.obj).message);
break;
case HANDLER_SHOW_EDITBOX_DIALOG:
theActivity.onShowEditBoxDialog((EditBoxMessage)msg.obj);
break;
}
}
};
public Cocos2dxGLSurfaceView getGLView() {
return mGLView;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get frame size
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
accelerometer = new Cocos2dxAccelerometer(this);
// init media player and sound player
backgroundMusicPlayer = new Cocos2dxMusic(this);
soundPlayer = new Cocos2dxSound(this);
// init asset manager for jni call
assetManager = getAssets();
// init bitmap context
Cocos2dxBitmap.setContext(this);
handler = new ShowDialogHandler(this);
}
public static String getDeviceModel(){
return Build.MODEL;
}
public static AssetManager getAssetManager() {
return assetManager;
}
public static String getCurrentLanguage() {
String languageName = java.util.Locale.getDefault().getLanguage();
return languageName;
}
public static void showMessageBox(String title, String message){
Message msg = new Message();
msg.what = HANDLER_SHOW_DIALOG;
msg.obj = new DialogMessage(title, message);
handler.sendMessage(msg);
}
public static void enableAccelerometer() {
accelerometerEnabled = true;
accelerometer.enable();
}
public static void disableAccelerometer() {
accelerometerEnabled = false;
accelerometer.disable();
}
public static void preloadBackgroundMusic(String path){
backgroundMusicPlayer.preloadBackgroundMusic(path);
}
public static void playBackgroundMusic(String path, boolean isLoop){
backgroundMusicPlayer.playBackgroundMusic(path, isLoop);
}
public static void stopBackgroundMusic(){
backgroundMusicPlayer.stopBackgroundMusic();
}
public static void pauseBackgroundMusic(){
backgroundMusicPlayer.pauseBackgroundMusic();
}
public static void resumeBackgroundMusic(){
backgroundMusicPlayer.resumeBackgroundMusic();
}
public static void rewindBackgroundMusic(){
backgroundMusicPlayer.rewindBackgroundMusic();
}
public static boolean isBackgroundMusicPlaying(){
return backgroundMusicPlayer.isBackgroundMusicPlaying();
}
public static float getBackgroundMusicVolume(){
return backgroundMusicPlayer.getBackgroundVolume();
}
public static void setBackgroundMusicVolume(float volume){
backgroundMusicPlayer.setBackgroundVolume(volume);
}
public static int playEffect(String path, boolean isLoop){
return soundPlayer.playEffect(path, isLoop);
}
public static void stopEffect(int soundId){
soundPlayer.stopEffect(soundId);
}
public static void pauseEffect(int soundId){
soundPlayer.pauseEffect(soundId);
}
public static void resumeEffect(int soundId){
soundPlayer.resumeEffect(soundId);
}
public static float getEffectsVolume(){
return soundPlayer.getEffectsVolume();
}
public static void setEffectsVolume(float volume){
soundPlayer.setEffectsVolume(volume);
}
public static void preloadEffect(String path){
soundPlayer.preloadEffect(path);
}
public static void unloadEffect(String path){
soundPlayer.unloadEffect(path);
}
public static void stopAllEffects(){
soundPlayer.stopAllEffects();
}
public static void pauseAllEffects(){
soundPlayer.pauseAllEffects();
}
public static void resumeAllEffects(){
soundPlayer.resumeAllEffects();
}
public static void end(){
backgroundMusicPlayer.end();
soundPlayer.end();
}
public static String getCocos2dxPackageName(){
return packageName;
}
public static void terminateProcess(){
android.os.Process.killProcess(android.os.Process.myPid());
}
@Override
protected void onResume() {
super.onResume();
if (accelerometerEnabled) {
accelerometer.enable();
}
}
@Override
protected void onPause() {
super.onPause();
if (accelerometerEnabled) {
accelerometer.disable();
}
}
protected void setPackageName(String packageName) {
Cocos2dxActivity.packageName = packageName;
String apkFilePath = "";
ApplicationInfo appInfo = null;
PackageManager packMgmr = getApplication().getPackageManager();
try {
appInfo = packMgmr.getApplicationInfo(packageName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
apkFilePath = appInfo.sourceDir;
Log.w("apk path", apkFilePath);
// add this link at the renderer class
nativeSetPaths(apkFilePath);
}
private void showDialog(String title, String message){
Dialog dialog = new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton){
}
}).create();
dialog.show();
}
private static void showEditBoxDialog(String title, String content, int inputMode, int inputFlag, int returnType, int maxLength)
{
Message msg = new Message();
msg.what = HANDLER_SHOW_EDITBOX_DIALOG;
msg.obj = new EditBoxMessage(title, content, inputMode, inputFlag, returnType, maxLength);
handler.sendMessage(msg);
}
private void onShowEditBoxDialog(EditBoxMessage msg)
{
Dialog dialog = new Cocos2dxEditBoxDialog(this, msg);
dialog.show();
}
public void setEditBoxResult(String editResult)
{
Log.i("editbox_content", editResult);
try
{
final byte[] bytesUTF8 = editResult.getBytes("UTF8");
// pass utf8 string from editbox activity to native.
// Should invoke native method in GL thread.
mGLView.queueEvent(new Runnable() {
@Override
public void run() {
nativeSetEditboxText(bytesUTF8);
}
});
}
catch (java.io.UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
class DialogMessage {
public String title;
public String message;
public DialogMessage(String title, String message){
this.message = message;
this.title = title;
}
}
class EditBoxMessage {
public String title;
public String content;
public int inputMode;
public int inputFlag;
public int returnType;
public int maxLength;
public EditBoxMessage(String title, String content, int inputMode, int inputFlag, int returnType, int maxLength){
this.content = content;
this.title = title;
this.inputMode = inputMode;
this.inputFlag = inputFlag;
this.returnType = returnType;
this.maxLength = maxLength;
}
}

View File

@ -1,455 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.LinkedList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
public class Cocos2dxBitmap{
/*
* The values are the same as cocos2dx/platform/CCImage.h.
*/
private static final int HALIGNCENTER = 3;
private static final int HALIGNLEFT = 1;
private static final int HALIGNRIGHT = 2;
// vertical alignment
private static final int VALIGNTOP = 1;
private static final int VALIGNBOTTOM = 2;
private static final int VALIGNCENTER = 3;
private static Context context;
public static void setContext(Context context){
Cocos2dxBitmap.context = context;
}
/*
* @width: the width to draw, it can be 0
* @height: the height to draw, it can be 0
*/
public static void createTextBitmap(String content, String fontName,
int fontSize, int alignment, int width, int height){
content = refactorString(content);
Paint paint = newPaint(fontName, fontSize, alignment);
TextProperty textProperty = computeTextProperty(content, paint, width, height);
int bitmapTotalHeight = (height == 0 ? textProperty.totalHeight:height);
// Draw text to bitmap
Bitmap bitmap = Bitmap.createBitmap(textProperty.maxWidth,
bitmapTotalHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
// Draw string
FontMetricsInt fm = paint.getFontMetricsInt();
int x = 0;
int y = computeY(fm, height, textProperty.totalHeight, alignment);
String[] lines = textProperty.lines;
for (String line : lines){
x = computeX(paint, line, textProperty.maxWidth, alignment);
canvas.drawText(line, x, y, paint);
y += textProperty.heightPerLine;
}
initNativeObject(bitmap);
}
private static int computeX(Paint paint, String content, int w, int alignment){
int ret = 0;
int hAlignment = alignment & 0x0F;
switch (hAlignment){
case HALIGNCENTER:
ret = w / 2;
break;
// ret = 0
case HALIGNLEFT:
break;
case HALIGNRIGHT:
ret = w;
break;
/*
* Default is align left.
* Should be same as newPaint().
*/
default:
break;
}
return ret;
}
private static int computeY(FontMetricsInt fm, int constrainHeight, int totalHeight, int alignment) {
int y = -fm.top;
if (constrainHeight > totalHeight) {
int vAlignment = (alignment >> 4) & 0x0F;
switch (vAlignment) {
case VALIGNTOP:
y = -fm.top;
break;
case VALIGNCENTER:
y = -fm.top + (constrainHeight - totalHeight)/2;
break;
case VALIGNBOTTOM:
y = -fm.top + (constrainHeight - totalHeight);
break;
default:
break;
}
}
return y;
}
private static class TextProperty{
// The max width of lines
int maxWidth;
// The height of all lines
int totalHeight;
int heightPerLine;
String[] lines;
TextProperty(int w, int h, String[] lines){
this.maxWidth = w;
this.heightPerLine = h;
this.totalHeight = h * lines.length;
this.lines = lines;
}
}
private static TextProperty computeTextProperty(String content, Paint paint,
int maxWidth, int maxHeight){
FontMetricsInt fm = paint.getFontMetricsInt();
int h = (int)Math.ceil(fm.bottom - fm.top);
int maxContentWidth = 0;
String[] lines = splitString(content, maxHeight, maxWidth, paint);
if (maxWidth != 0){
maxContentWidth = maxWidth;
}
else {
/*
* Compute the max width
*/
int temp = 0;
for (String line : lines){
temp = (int)Math.ceil(paint.measureText(line, 0, line.length()));
if (temp > maxContentWidth){
maxContentWidth = temp;
}
}
}
return new TextProperty(maxContentWidth, h, lines);
}
/*
* If maxWidth or maxHeight is not 0,
* split the string to fix the maxWidth and maxHeight.
*/
private static String[] splitString(String content, int maxHeight, int maxWidth,
Paint paint){
String[] lines = content.split("\\n");
String[] ret = null;
FontMetricsInt fm = paint.getFontMetricsInt();
int heightPerLine = (int)Math.ceil(fm.bottom - fm.top);
int maxLines = maxHeight / heightPerLine;
if (maxWidth != 0){
LinkedList<String> strList = new LinkedList<String>();
for (String line : lines){
/*
* The width of line is exceed maxWidth, should divide it into
* two or more lines.
*/
int lineWidth = (int)Math.ceil(paint.measureText(line));
if (lineWidth > maxWidth){
strList.addAll(divideStringWithMaxWidth(paint, line, maxWidth));
}
else{
strList.add(line);
}
/*
* Should not exceed the max height;
*/
if (maxLines > 0 && strList.size() >= maxLines){
break;
}
}
/*
* Remove exceeding lines
*/
if (maxLines > 0 && strList.size() > maxLines){
while (strList.size() > maxLines){
strList.removeLast();
}
}
ret = new String[strList.size()];
strList.toArray(ret);
} else
if (maxHeight != 0 && lines.length > maxLines) {
/*
* Remove exceeding lines
*/
LinkedList<String> strList = new LinkedList<String>();
for (int i = 0; i < maxLines; i++){
strList.add(lines[i]);
}
ret = new String[strList.size()];
strList.toArray(ret);
}
else {
ret = lines;
}
return ret;
}
private static LinkedList<String> divideStringWithMaxWidth(Paint paint, String content,
int width){
int charLength = content.length();
int start = 0;
int tempWidth = 0;
LinkedList<String> strList = new LinkedList<String>();
/*
* Break a String into String[] by the width & should wrap the word
*/
for (int i = 1; i <= charLength; ++i){
tempWidth = (int)Math.ceil(paint.measureText(content, start, i));
if (tempWidth >= width){
int lastIndexOfSpace = content.substring(0, i).lastIndexOf(" ");
if (lastIndexOfSpace != -1 && lastIndexOfSpace > start){
/**
* Should wrap the word
*/
strList.add(content.substring(start, lastIndexOfSpace));
i = lastIndexOfSpace;
}
else {
/*
* Should not exceed the width
*/
if (tempWidth > width){
strList.add(content.substring(start, i - 1));
/*
* compute from previous char
*/
--i;
}
else {
strList.add(content.substring(start, i));
}
}
// remove spaces at the beginning of a new line
while(content.indexOf(i++) == ' ') {
}
start = i;
}
}
/*
* Add the last chars
*/
if (start < charLength){
strList.add(content.substring(start));
}
return strList;
}
private static Paint newPaint(String fontName, int fontSize, int alignment){
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(fontSize);
paint.setAntiAlias(true);
/*
* Set type face for paint, now it support .ttf file.
*/
if (fontName.endsWith(".ttf")){
try {
//Typeface typeFace = Typeface.createFromAsset(context.getAssets(), fontName);
Typeface typeFace = Cocos2dxTypefaces.get(context, fontName);
paint.setTypeface(typeFace);
} catch (Exception e){
Log.e("Cocos2dxBitmap",
"error to create ttf type face: " + fontName);
/*
* The file may not find, use system font
*/
paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL));
}
}
else {
paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL));
}
int hAlignment = alignment & 0x0F;
switch (hAlignment){
case HALIGNCENTER:
paint.setTextAlign(Align.CENTER);
break;
case HALIGNLEFT:
paint.setTextAlign(Align.LEFT);
break;
case HALIGNRIGHT:
paint.setTextAlign(Align.RIGHT);
break;
default:
paint.setTextAlign(Align.LEFT);
break;
}
return paint;
}
private static String refactorString(String str){
// Avoid error when content is ""
if (str.compareTo("") == 0){
return " ";
}
/*
* If the font of "\n" is "" or "\n", insert " " in front of it.
*
* For example:
* "\nabc" -> " \nabc"
* "\nabc\n\n" -> " \nabc\n \n"
*/
StringBuilder strBuilder = new StringBuilder(str);
int start = 0;
int index = strBuilder.indexOf("\n");
while (index != -1){
if (index == 0 || strBuilder.charAt(index -1) == '\n'){
strBuilder.insert(start, " ");
start = index + 2;
} else {
start = index + 1;
}
if (start > strBuilder.length() || index == strBuilder.length()){
break;
}
index = strBuilder.indexOf("\n", start);
}
return strBuilder.toString();
}
private static void initNativeObject(Bitmap bitmap){
byte[] pixels = getPixels(bitmap);
if (pixels == null){
return;
}
nativeInitBitmapDC(bitmap.getWidth(), bitmap.getHeight(), pixels);
}
private static byte[] getPixels(Bitmap bitmap){
if (bitmap != null){
byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight() * 4];
ByteBuffer buf = ByteBuffer.wrap(pixels);
buf.order(ByteOrder.nativeOrder());
bitmap.copyPixelsToBuffer(buf);
return pixels;
}
return null;
}
private static native void nativeInitBitmapDC(int width, int height, byte[] pixels);
private static int getFontSizeAccordingHeight(int height)
{
Paint paint = new Paint();
Rect bounds = new Rect();
paint.setTypeface(Typeface.DEFAULT);
int incr_text_size = 1;
boolean found_desired_size = false;
while (!found_desired_size) {
paint.setTextSize(incr_text_size);
String text = "SghMNy";
paint.getTextBounds(text, 0, text.length(), bounds);
incr_text_size++;
if (height - bounds.height() <= 2) {
found_desired_size = true;
}
Log.d("font size", "incr size:" + incr_text_size);
}
return incr_text_size;
}
private static String getStringWithEllipsis(String originalText, float width, float fontSize){
if(TextUtils.isEmpty(originalText)){
return "";
}
TextPaint paint = new TextPaint();
paint.setTypeface(Typeface.DEFAULT);
paint.setTextSize(fontSize);
return TextUtils.ellipsize(originalText, paint, width,
TextUtils.TruncateAt.valueOf("END")).toString();
}
}

View File

@ -1,338 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.InputType;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class Cocos2dxEditBoxDialog extends Dialog {
/**
* The user is allowed to enter any text, including line breaks.
*/
private final int kEditBoxInputModeAny = 0;
/**
* The user is allowed to enter an e-mail address.
*/
private final int kEditBoxInputModeEmailAddr = 1;
/**
* The user is allowed to enter an integer value.
*/
private final int kEditBoxInputModeNumeric = 2;
/**
* The user is allowed to enter a phone number.
*/
private final int kEditBoxInputModePhoneNumber = 3;
/**
* The user is allowed to enter a URL.
*/
private final int kEditBoxInputModeUrl = 4;
/**
* The user is allowed to enter a real number value.
* This extends kEditBoxInputModeNumeric by allowing a decimal point.
*/
private final int kEditBoxInputModeDecimal = 5;
/**
* The user is allowed to enter any text, except for line breaks.
*/
private final int kEditBoxInputModeSingleLine = 6;
/**
* Indicates that the text entered is confidential data that should be
* obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE.
*/
private final int kEditBoxInputFlagPassword = 0;
/**
* Indicates that the text entered is sensitive data that the
* implementation must never store into a dictionary or table for use
* in predictive, auto-completing, or other accelerated input schemes.
* A credit card number is an example of sensitive data.
*/
private final int kEditBoxInputFlagSensitive = 1;
/**
* This flag is a hint to the implementation that during text editing,
* the initial letter of each word should be capitalized.
*/
private final int kEditBoxInputFlagInitialCapsWord = 2;
/**
* This flag is a hint to the implementation that during text editing,
* the initial letter of each sentence should be capitalized.
*/
private final int kEditBoxInputFlagInitialCapsSentence = 3;
/**
* Capitalize all characters automatically.
*/
private final int kEditBoxInputFlagInitialCapsAllCharacters = 4;
private final int kKeyboardReturnTypeDefault = 0;
private final int kKeyboardReturnTypeDone = 1;
private final int kKeyboardReturnTypeSend = 2;
private final int kKeyboardReturnTypeSearch = 3;
private final int kKeyboardReturnTypeGo = 4;
//
private EditText mInputEditText = null;
private TextView mTextViewTitle = null;
private int mInputMode = 0;
private int mInputFlag = 0;
private int mReturnType = 0;
private int mMaxLength = -1;
private int mInputFlagConstraints = 0x00000;
private int mInputModeContraints = 0x00000;
private boolean mIsMultiline = false;
private Cocos2dxActivity mParentActivity = null;
private EditBoxMessage mMsg = null;
public Cocos2dxEditBoxDialog(Context context, EditBoxMessage msg) {
//super(context, R.style.Theme_Translucent);
super(context, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
// TODO Auto-generated constructor stub
mParentActivity = (Cocos2dxActivity)context;
mMsg = msg;
}
// Converting dips to pixels
private int convertDipsToPixels(float dips)
{
float scale = getContext().getResources().getDisplayMetrics().density;
return Math.round(dips * scale);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getWindow().setBackgroundDrawable(new ColorDrawable(0x80000000));
LinearLayout layout = new LinearLayout(mParentActivity);
layout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.
LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT);
mTextViewTitle = new TextView(mParentActivity);
LinearLayout.LayoutParams textviewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
textviewParams.leftMargin = textviewParams.rightMargin = convertDipsToPixels(10);
mTextViewTitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
layout.addView(mTextViewTitle, textviewParams);
mInputEditText = new EditText(mParentActivity);
LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
editTextParams.leftMargin = editTextParams.rightMargin = convertDipsToPixels(10);
layout.addView(mInputEditText, editTextParams);
setContentView(layout, layoutParams);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
mInputMode = mMsg.inputMode;
mInputFlag = mMsg.inputFlag;
mReturnType = mMsg.returnType;
mMaxLength = mMsg.maxLength;
mTextViewTitle.setText(mMsg.title);
mInputEditText.setText(mMsg.content);
int oldImeOptions = mInputEditText.getImeOptions();
mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
oldImeOptions = mInputEditText.getImeOptions();
switch (mInputMode)
{
case kEditBoxInputModeAny:
mInputModeContraints =
InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_FLAG_MULTI_LINE;
break;
case kEditBoxInputModeEmailAddr:
mInputModeContraints =
InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
break;
case kEditBoxInputModeNumeric:
mInputModeContraints =
InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case kEditBoxInputModePhoneNumber:
mInputModeContraints = InputType.TYPE_CLASS_PHONE;
break;
case kEditBoxInputModeUrl:
mInputModeContraints =
InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_URI;
break;
case kEditBoxInputModeDecimal:
mInputModeContraints =
InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_NUMBER_FLAG_DECIMAL |
InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case kEditBoxInputModeSingleLine:
mInputModeContraints = InputType.TYPE_CLASS_TEXT;
break;
default:
break;
}
if ( mIsMultiline ) {
mInputModeContraints |= InputType.TYPE_TEXT_FLAG_MULTI_LINE;
}
mInputEditText.setInputType(mInputModeContraints | mInputFlagConstraints);
switch (mInputFlag)
{
case kEditBoxInputFlagPassword:
mInputFlagConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
break;
case kEditBoxInputFlagSensitive:
mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
break;
case kEditBoxInputFlagInitialCapsWord:
mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_WORDS;
break;
case kEditBoxInputFlagInitialCapsSentence:
mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
break;
case kEditBoxInputFlagInitialCapsAllCharacters:
mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS;
break;
default:
break;
}
mInputEditText.setInputType(mInputFlagConstraints | mInputModeContraints);
switch (mReturnType) {
case kKeyboardReturnTypeDefault:
mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_NONE);
break;
case kKeyboardReturnTypeDone:
mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_DONE);
break;
case kKeyboardReturnTypeSend:
mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_SEND);
break;
case kKeyboardReturnTypeSearch:
mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_SEARCH);
break;
case kKeyboardReturnTypeGo:
mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_GO);
break;
default:
mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_NONE);
break;
}
if (mMaxLength > 0) {
mInputEditText.setFilters(
new InputFilter[] {
new InputFilter.LengthFilter(mMaxLength)
}
);
}
Handler initHandler = new Handler();
initHandler.postDelayed(new Runnable() {
public void run() {
mInputEditText.requestFocus();
mInputEditText.setSelection(mInputEditText.length());
openKeyboard();
}
}, 200);
mInputEditText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// if user didn't set keyboard type,
// this callback will be invoked twice with 'KeyEvent.ACTION_DOWN' and 'KeyEvent.ACTION_UP'
if (actionId != EditorInfo.IME_NULL
|| (actionId == EditorInfo.IME_NULL
&& event != null
&& event.getAction() == KeyEvent.ACTION_DOWN))
{
//Log.d("EditBox", "actionId: "+actionId +",event: "+event);
mParentActivity.setEditBoxResult(mInputEditText.getText().toString());
closeKeyboard();
dismiss();
return true;
}
return false;
}
});
}
private void openKeyboard() {
InputMethodManager imm = (InputMethodManager) mParentActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mInputEditText, 0);
Log.d("Cocos2dxEditBox", "openKeyboard");
}
private void closeKeyboard() {
InputMethodManager imm = (InputMethodManager) mParentActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mInputEditText.getWindowToken(), 0);
Log.d("Cocos2dxEditBox", "closeKeyboard");
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.d("EditBox", "onStop...");
}
}

View File

@ -1,65 +0,0 @@
/****************************************************************************
Copyright (c) 2012 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;
public class Cocos2dxEditText extends EditText {
private Cocos2dxGLSurfaceView mView;
public Cocos2dxEditText(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public Cocos2dxEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Cocos2dxEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setMainView(Cocos2dxGLSurfaceView glSurfaceView) {
mView = glSurfaceView;
}
/*
* Let GlSurfaceView get focus if back key is input
*/
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_BACK) {
mView.requestFocus();
}
return true;
}
}

View File

@ -1,417 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
class TextInputWraper implements TextWatcher, OnEditorActionListener {
private static final Boolean debug = false;
private void LogD(String msg) {
if (debug) Log.d("TextInputFilter", msg);
}
private Cocos2dxGLSurfaceView mMainView;
private String mText;
private String mOriginText;
private Boolean isFullScreenEdit() {
InputMethodManager imm = (InputMethodManager)mMainView.getTextField().getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
return imm.isFullscreenMode();
}
public TextInputWraper(Cocos2dxGLSurfaceView view) {
mMainView = view;
}
public void setOriginText(String text) {
mOriginText = text;
}
@Override
public void afterTextChanged(Editable s) {
if (isFullScreenEdit()) {
return;
}
LogD("afterTextChanged: " + s);
int nModified = s.length() - mText.length();
if (nModified > 0) {
final String insertText = s.subSequence(mText.length(), s.length()).toString();
mMainView.insertText(insertText);
LogD("insertText(" + insertText + ")");
}
else {
for (; nModified < 0; ++nModified) {
mMainView.deleteBackward();
LogD("deleteBackward");
}
}
mText = s.toString();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
LogD("beforeTextChanged(" + s + ")start: " + start + ",count: " + count + ",after: " + after);
mText = s.toString();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (mMainView.getTextField() == v && isFullScreenEdit()) {
// user press the action button, delete all old text and insert new text
for (int i = mOriginText.length(); i > 0; --i) {
mMainView.deleteBackward();
LogD("deleteBackward");
}
String text = v.getText().toString();
/*
* If user input nothing, translate "\n" to engine.
*/
if (text.compareTo("") == 0){
text = "\n";
}
if ('\n' != text.charAt(text.length() - 1)) {
text += '\n';
}
final String insertText = text;
mMainView.insertText(insertText);
LogD("insertText(" + insertText + ")");
}
return false;
}
}
public class Cocos2dxGLSurfaceView extends GLSurfaceView {
static private Cocos2dxGLSurfaceView mainView;
private static final String TAG = Cocos2dxGLSurfaceView.class.getCanonicalName();
private Cocos2dxRenderer mRenderer;
private static final boolean debug = false;
///////////////////////////////////////////////////////////////////////////
// for initialize
///////////////////////////////////////////////////////////////////////////
public Cocos2dxGLSurfaceView(Context context) {
super(context);
initView();
}
public Cocos2dxGLSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public void setCocos2dxRenderer(Cocos2dxRenderer renderer){
mRenderer = renderer;
setRenderer(mRenderer);
}
protected void initView() {
setFocusableInTouchMode(true);
textInputWraper = new TextInputWraper(this);
handler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
case HANDLER_OPEN_IME_KEYBOARD:
if (null != mTextField && mTextField.requestFocus()) {
mTextField.removeTextChangedListener(textInputWraper);
mTextField.setText("");
String text = (String)msg.obj;
mTextField.append(text);
textInputWraper.setOriginText(text);
mTextField.addTextChangedListener(textInputWraper);
InputMethodManager imm = (InputMethodManager)mainView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mTextField, 0);
Log.d("GLSurfaceView", "showSoftInput");
}
break;
case HANDLER_CLOSE_IME_KEYBOARD:
if (null != mTextField) {
mTextField.removeTextChangedListener(textInputWraper);
InputMethodManager imm = (InputMethodManager)mainView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mTextField.getWindowToken(), 0);
Log.d("GLSurfaceView", "HideSoftInput");
}
break;
}
}
};
mainView = this;
}
public void onPause(){
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleOnPause();
}
});
super.onPause();
}
public void onResume(){
super.onResume();
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleOnResume();
}
});
}
///////////////////////////////////////////////////////////////////////////
// for text input
///////////////////////////////////////////////////////////////////////////
private final static int HANDLER_OPEN_IME_KEYBOARD = 2;
private final static int HANDLER_CLOSE_IME_KEYBOARD = 3;
private static Handler handler;
private static TextInputWraper textInputWraper;
private Cocos2dxEditText mTextField;
public TextView getTextField() {
return mTextField;
}
public void setTextField(Cocos2dxEditText view) {
mTextField = view;
if (null != mTextField && null != textInputWraper) {
mTextField.setOnEditorActionListener(textInputWraper);
mTextField.setMainView(this);
this.requestFocus();
}
}
public static void openIMEKeyboard() {
Message msg = new Message();
msg.what = HANDLER_OPEN_IME_KEYBOARD;
msg.obj = mainView.getContentText();
handler.sendMessage(msg);
}
private String getContentText() {
return mRenderer.getContentText();
}
public static void closeIMEKeyboard() {
Message msg = new Message();
msg.what = HANDLER_CLOSE_IME_KEYBOARD;
handler.sendMessage(msg);
}
public void insertText(final String text) {
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleInsertText(text);
}
});
}
public void deleteBackward() {
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleDeleteBackward();
}
});
}
///////////////////////////////////////////////////////////////////////////
// for touch event
///////////////////////////////////////////////////////////////////////////
public boolean onTouchEvent(final MotionEvent event) {
// these data are used in ACTION_MOVE and ACTION_CANCEL
final int pointerNumber = event.getPointerCount();
final int[] ids = new int[pointerNumber];
final float[] xs = new float[pointerNumber];
final float[] ys = new float[pointerNumber];
for (int i = 0; i < pointerNumber; i++) {
ids[i] = event.getPointerId(i);
xs[i] = event.getX(i);
ys[i] = event.getY(i);
}
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_POINTER_DOWN:
final int indexPointerDown = event.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT;
final int idPointerDown = event.getPointerId(indexPointerDown);
final float xPointerDown = event.getX(indexPointerDown);
final float yPointerDown = event.getY(indexPointerDown);
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleActionDown(idPointerDown, xPointerDown, yPointerDown);
}
});
break;
case MotionEvent.ACTION_DOWN:
// there are only one finger on the screen
final int idDown = event.getPointerId(0);
final float xDown = xs[0];
final float yDown = ys[0];
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleActionDown(idDown, xDown, yDown);
}
});
break;
case MotionEvent.ACTION_MOVE:
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleActionMove(ids, xs, ys);
}
});
break;
case MotionEvent.ACTION_POINTER_UP:
final int indexPointUp = event.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT;
final int idPointerUp = event.getPointerId(indexPointUp);
final float xPointerUp = event.getX(indexPointUp);
final float yPointerUp = event.getY(indexPointUp);
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleActionUp(idPointerUp, xPointerUp, yPointerUp);
}
});
break;
case MotionEvent.ACTION_UP:
// there are only one finger on the screen
final int idUp = event.getPointerId(0);
final float xUp = xs[0];
final float yUp = ys[0];
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleActionUp(idUp, xUp, yUp);
}
});
break;
case MotionEvent.ACTION_CANCEL:
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleActionCancel(ids, xs, ys);
}
});
break;
}
if (debug){
dumpEvent(event);
}
return true;
}
/*
* This function is called before Cocos2dxRenderer.nativeInit(), so the width and height is correct.
*/
protected void onSizeChanged(int w, int h, int oldw, int oldh){
this.mRenderer.setScreenWidthAndHeight(w, h);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
final int kc = keyCode;
if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) {
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleKeyDown(kc);
}
});
return true;
}
return super.onKeyDown(keyCode, event);
}
// Show an event in the LogCat view, for debugging
private void dumpEvent(MotionEvent event) {
String names[] = { "DOWN" , "UP" , "MOVE" , "CANCEL" , "OUTSIDE" ,
"POINTER_DOWN" , "POINTER_UP" , "7?" , "8?" , "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_" ).append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN
|| actionCode == MotionEvent.ACTION_POINTER_UP) {
sb.append("(pid " ).append(
action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")" );
}
sb.append("[" );
for (int i = 0; i < event.getPointerCount(); i++) {
sb.append("#" ).append(i);
sb.append("(pid " ).append(event.getPointerId(i));
sb.append(")=" ).append((int) event.getX(i));
sb.append("," ).append((int) event.getY(i));
if (i + 1 < event.getPointerCount())
sb.append(";" );
}
sb.append("]" );
Log.d(TAG, sb.toString());
}
}

View File

@ -1,228 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.util.Log;
/**
*
* This class is used for controlling background music
*
*/
public class Cocos2dxMusic {
private static final String TAG = "Cocos2dxMusic";
private float mLeftVolume;
private float mRightVolume;
private Context mContext;
private MediaPlayer mBackgroundMediaPlayer;
private boolean mIsPaused;
private String mCurrentPath;
public Cocos2dxMusic(Context context){
this.mContext = context;
initData();
}
public void preloadBackgroundMusic(String path){
if ((mCurrentPath == null) || (! mCurrentPath.equals(path))){
// preload new background music
// release old resource and create a new one
if (mBackgroundMediaPlayer != null){
mBackgroundMediaPlayer.release();
}
mBackgroundMediaPlayer = createMediaplayerFromAssets(path);
// record the path
mCurrentPath = path;
}
}
public void playBackgroundMusic(String path, boolean isLoop){
if (mCurrentPath == null){
// it is the first time to play background music
// or end() was called
mBackgroundMediaPlayer = createMediaplayerFromAssets(path);
mCurrentPath = path;
}
else {
if (! mCurrentPath.equals(path)){
// play new background music
// release old resource and create a new one
if (mBackgroundMediaPlayer != null){
mBackgroundMediaPlayer.release();
}
mBackgroundMediaPlayer = createMediaplayerFromAssets(path);
// record the path
mCurrentPath = path;
}
}
if (mBackgroundMediaPlayer == null){
Log.e(TAG, "playBackgroundMusic: background media player is null");
} else {
// if the music is playing or paused, stop it
mBackgroundMediaPlayer.stop();
mBackgroundMediaPlayer.setLooping(isLoop);
try {
mBackgroundMediaPlayer.prepare();
mBackgroundMediaPlayer.seekTo(0);
mBackgroundMediaPlayer.start();
this.mIsPaused = false;
} catch (Exception e){
Log.e(TAG, "playBackgroundMusic: error state");
}
}
}
public void stopBackgroundMusic(){
if (mBackgroundMediaPlayer != null){
mBackgroundMediaPlayer.stop();
// should set the state, if not , the following sequence will be error
// play -> pause -> stop -> resume
this.mIsPaused = false;
}
}
public void pauseBackgroundMusic(){
if (mBackgroundMediaPlayer != null && mBackgroundMediaPlayer.isPlaying()){
mBackgroundMediaPlayer.pause();
this.mIsPaused = true;
}
}
public void resumeBackgroundMusic(){
if (mBackgroundMediaPlayer != null && this.mIsPaused){
mBackgroundMediaPlayer.start();
this.mIsPaused = false;
}
}
public void rewindBackgroundMusic(){
if (mBackgroundMediaPlayer != null){
mBackgroundMediaPlayer.stop();
try {
mBackgroundMediaPlayer.prepare();
mBackgroundMediaPlayer.seekTo(0);
mBackgroundMediaPlayer.start();
this.mIsPaused = false;
} catch (Exception e){
Log.e(TAG, "rewindBackgroundMusic: error state");
}
}
}
public boolean isBackgroundMusicPlaying(){
boolean ret = false;
if (mBackgroundMediaPlayer == null){
ret = false;
} else {
ret = mBackgroundMediaPlayer.isPlaying();
}
return ret;
}
public void end(){
if (mBackgroundMediaPlayer != null){
mBackgroundMediaPlayer.release();
}
initData();
}
public float getBackgroundVolume(){
if (this.mBackgroundMediaPlayer != null){
return (this.mLeftVolume + this.mRightVolume) / 2;
} else {
return 0.0f;
}
}
public void setBackgroundVolume(float volume){
if (volume < 0.0f){
volume = 0.0f;
}
if (volume > 1.0f){
volume = 1.0f;
}
this.mLeftVolume = this.mRightVolume = volume;
if (this.mBackgroundMediaPlayer != null){
this.mBackgroundMediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume);
}
}
private void initData(){
mLeftVolume =0.5f;
mRightVolume = 0.5f;
mBackgroundMediaPlayer = null;
mIsPaused = false;
mCurrentPath = null;
}
/**
* create mediaplayer for music
* @param path the path relative to assets
* @return
*/
private MediaPlayer createMediaplayerFromAssets(String path){
MediaPlayer mediaPlayer = new MediaPlayer();
try{
if (path.startsWith("/")) {
mediaPlayer.setDataSource(path);
}
else {
AssetFileDescriptor assetFileDescritor = mContext.getAssets().openFd(path);
mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(),
assetFileDescritor.getStartOffset(), assetFileDescritor.getLength());
}
mediaPlayer.prepare();
mediaPlayer.setVolume(mLeftVolume, mRightVolume);
}catch (Exception e) {
mediaPlayer = null;
Log.e(TAG, "error: " + e.getMessage(), e);
}
return mediaPlayer;
}
}

View File

@ -1,137 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView;
public class Cocos2dxRenderer implements GLSurfaceView.Renderer {
private final static long NANOSECONDSPERSECOND = 1000000000L;
private final static long NANOSECONDSPERMINISECOND = 1000000;
private static long animationInterval = (long)(1.0 / 60 * NANOSECONDSPERSECOND);
private long last;
private int screenWidth;
private int screenHeight;
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
nativeInit(screenWidth, screenHeight);
last = System.nanoTime();
}
public void setScreenWidthAndHeight(int w, int h){
this.screenWidth = w;
this.screenHeight = h;
}
public void onSurfaceChanged(GL10 gl, int w, int h) {
}
public void onDrawFrame(GL10 gl) {
long now = System.nanoTime();
long interval = now - last;
// should render a frame when onDrawFrame() is called
// or there is a "ghost"
nativeRender();
// fps controlling
if (interval < animationInterval){
try {
// because we render it before, so we should sleep twice time interval
Thread.sleep((animationInterval - interval) * 2 / NANOSECONDSPERMINISECOND);
} catch (Exception e){}
}
last = now;
}
public void handleActionDown(int id, float x, float y)
{
nativeTouchesBegin(id, x, y);
}
public void handleActionUp(int id, float x, float y)
{
nativeTouchesEnd(id, x, y);
}
public void handleActionCancel(int[] id, float[] x, float[] y)
{
nativeTouchesCancel(id, x, y);
}
public void handleActionMove(int[] id, float[] x, float[] y)
{
nativeTouchesMove(id, x, y);
}
public void handleKeyDown(int keyCode)
{
nativeKeyDown(keyCode);
}
public void handleOnPause(){
nativeOnPause();
}
public void handleOnResume(){
nativeOnResume();
}
public static void setAnimationInterval(double interval){
animationInterval = (long)(interval * NANOSECONDSPERSECOND);
}
private static native void nativeTouchesBegin(int id, float x, float y);
private static native void nativeTouchesEnd(int id, float x, float y);
private static native void nativeTouchesMove(int[] id, float[] x, float[] y);
private static native void nativeTouchesCancel(int[] id, float[] x, float[] y);
private static native boolean nativeKeyDown(int keyCode);
private static native void nativeRender();
private static native void nativeInit(int w, int h);
private static native void nativeOnPause();
private static native void nativeOnResume();
/////////////////////////////////////////////////////////////////////////////////
// handle input method edit message
/////////////////////////////////////////////////////////////////////////////////
public void handleInsertText(final String text) {
nativeInsertText(text);
}
public void handleDeleteBackward() {
nativeDeleteBackward();
}
public String getContentText() {
return nativeGetContentText();
}
private static native void nativeInsertText(String text);
private static native void nativeDeleteBackward();
private static native String nativeGetContentText();
}

View File

@ -1,245 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;
/**
*
* This class is used for controlling effect
*
*/
public class Cocos2dxSound {
private Context mContext;
private SoundPool mSoundPool;
private float mLeftVolume;
private float mRightVolume;
// sound path and stream ids map
// a file may be played many times at the same time
// so there is an array map to a file path
private HashMap<String,ArrayList<Integer>> mPathStreamIDsMap;
private HashMap<String, Integer> mPathSoundIdMap;
private static final String TAG = "Cocos2dxSound";
private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5;
private static final float SOUND_RATE = 1.0f;
private static final int SOUND_PRIORITY = 1;
private static final int SOUND_QUALITY = 5;
private final static int INVALID_SOUND_ID = -1;
private final static int INVALID_STREAM_ID = -1;
public Cocos2dxSound(Context context){
this.mContext = context;
initData();
}
public int preloadEffect(String path){
Integer soundID = this.mPathSoundIdMap.get(path);
if (soundID == null) {
soundID = createSoundIdFromAsset(path);
this.mPathSoundIdMap.put(path, soundID);
}
return soundID;
}
public void unloadEffect(String path){
// stop effects
ArrayList<Integer> streamIDs = this.mPathStreamIDsMap.get(path);
if (streamIDs != null) {
for (Integer streamID : streamIDs) {
this.mSoundPool.stop(streamID);
}
}
this.mPathStreamIDsMap.remove(path);
// unload effect
Integer soundID = this.mPathSoundIdMap.get(path);
this.mSoundPool.unload(soundID);
this.mPathSoundIdMap.remove(path);
}
public int playEffect(String path, boolean isLoop){
Integer soundId = this.mPathSoundIdMap.get(path);
int streamId = INVALID_STREAM_ID;
if (soundId != null){
// play sound
streamId = this.mSoundPool.play(soundId.intValue(), this.mLeftVolume,
this.mRightVolume, SOUND_PRIORITY, isLoop ? -1 : 0, SOUND_RATE);
// record stream id
ArrayList<Integer> streamIds = this.mPathStreamIDsMap.get(path);
if (streamIds == null) {
streamIds = new ArrayList<Integer>();
this.mPathStreamIDsMap.put(path, streamIds);
}
streamIds.add(streamId);
} else {
// the effect is not prepared
soundId = preloadEffect(path);
if (soundId == INVALID_SOUND_ID){
// can not preload effect
return INVALID_SOUND_ID;
}
/*
* Someone reports that, it can not play effect for the
* first time. If you are lucky to meet it. There are two
* ways to resolve it.
* 1. Add some delay here. I don't know how long it is, so
* I don't add it here.
* 2. If you use 2.2(API level 8), you can call
* SoundPool.setOnLoadCompleteListener() to play the effect.
* Because the method is supported from 2.2, so I can't use
* it here.
*/
playEffect(path, isLoop);
}
return streamId;
}
public void stopEffect(int streamID){
this.mSoundPool.stop(streamID);
// remove record
for (String path : this.mPathStreamIDsMap.keySet()) {
if (this.mPathStreamIDsMap.get(path).contains(streamID)) {
this.mPathStreamIDsMap.get(path).remove(this.mPathStreamIDsMap.get(path).indexOf(streamID));
break;
}
}
}
public void pauseEffect(int streamID){
this.mSoundPool.pause(streamID);
}
public void resumeEffect(int streamID){
this.mSoundPool.resume(streamID);
}
public void pauseAllEffects(){
this.mSoundPool.autoPause();
}
public void resumeAllEffects(){
// autoPause() is available since level 8
this.mSoundPool.autoResume();
}
@SuppressWarnings("unchecked")
public void stopAllEffects(){
// stop effects
if (! this.mPathStreamIDsMap.isEmpty()) {
Iterator<?> iter = this.mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()){
Map.Entry<String, ArrayList<Integer>> entry = (Map.Entry<String, ArrayList<Integer>>)iter.next();
for (int streamID : entry.getValue()) {
this.mSoundPool.stop(streamID);
}
}
}
// remove records
this.mPathStreamIDsMap.clear();
}
public float getEffectsVolume(){
return (this.mLeftVolume + this.mRightVolume) / 2;
}
@SuppressWarnings("unchecked")
public void setEffectsVolume(float volume){
// volume should be in [0, 1.0]
if (volume < 0){
volume = 0;
}
if (volume > 1){
volume = 1;
}
this.mLeftVolume = this.mRightVolume = volume;
// change the volume of playing sounds
if (! this.mPathStreamIDsMap.isEmpty()) {
Iterator<?> iter = this.mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()){
Map.Entry<String, ArrayList<Integer>> entry = (Map.Entry<String, ArrayList<Integer>>)iter.next();
for (int streamID : entry.getValue()) {
this.mSoundPool.setVolume(streamID, mLeftVolume, mRightVolume);
}
}
}
}
public void end(){
this.mSoundPool.release();
this.mPathStreamIDsMap.clear();
this.mPathSoundIdMap.clear();
initData();
}
public int createSoundIdFromAsset(String path){
int soundId = INVALID_SOUND_ID;
try {
if (path.startsWith("/")){
soundId = mSoundPool.load(path, 0);
}
else {
soundId = mSoundPool.load(mContext.getAssets().openFd(path), 0);
}
} catch(Exception e){
soundId = INVALID_SOUND_ID;
Log.e(TAG, "error: " + e.getMessage(), e);
}
return soundId;
}
private void initData(){
this.mPathStreamIDsMap = new HashMap<String,ArrayList<Integer>>();
this.mPathSoundIdMap = new HashMap<String, Integer>();
mSoundPool = new SoundPool(MAX_SIMULTANEOUS_STREAMS_DEFAULT, AudioManager.STREAM_MUSIC, SOUND_QUALITY);
this.mLeftVolume = 0.5f;
this.mRightVolume = 0.5f;
}
}

View File

@ -1,44 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import java.util.Hashtable;
import android.content.Context;
import android.graphics.Typeface;
public class Cocos2dxTypefaces {
private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
public static Typeface get(Context context, String name){
synchronized(cache){
if (! cache.containsKey(name)){
Typeface t = Typeface.createFromAsset(context.getAssets(), name);
cache.put(name, t);
}
return cache.get(name);
}
}
}

View File

@ -1,170 +0,0 @@
/****************************************************************************
Copyright (c) 2012 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "EditBoxJni.h"
#include "text_input_node/CCIMEDispatcher.h"
#include "JniHelper.h"
#include <android/log.h>
#include <string.h>
#include <jni.h>
#if 0
#define LOG_TAG "EditBoxJni"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#else
#define LOGD(...)
#endif
using namespace cocos2d;
static EditBoxCallback s_pfEditBoxCB = NULL;
static void* s_ctx = NULL;
extern "C"
{
//////////////////////////////////////////////////////////////////////////
// handle EditBox message
//////////////////////////////////////////////////////////////////////////
void showEditBoxDialogJni(const char* pszTitle,
const char* pszContent,
int nInputMode,
int nInputFlag,
int nReturnType,
int nMaxLength,
EditBoxCallback pfEditBoxCB,
void* ctx)
{
LOGD("showEditBoxDialogJni...");
if (pszContent == NULL) {
return;
}
s_pfEditBoxCB = pfEditBoxCB;
s_ctx = ctx;
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t
, "org/cocos2dx/lib/Cocos2dxActivity"
, "showEditBoxDialog"
, "(Ljava/lang/String;Ljava/lang/String;IIII)V"))
{
jstring stringArg1;
if (!pszTitle)
{
stringArg1 = t.env->NewStringUTF("");
}
else
{
stringArg1 = t.env->NewStringUTF(pszTitle);
}
jstring stringArg2 = t.env->NewStringUTF(pszContent);
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg1, stringArg2, nInputMode, nInputFlag, nReturnType, nMaxLength);
t.env->DeleteLocalRef(stringArg1);
t.env->DeleteLocalRef(stringArg2);
t.env->DeleteLocalRef(t.classID);
}
}
void JNICALL Java_org_cocos2dx_lib_Cocos2dxActivity_nativeSetEditboxText(JNIEnv * env, jobject obj, jbyteArray text)
{
jsize size = env->GetArrayLength(text);
if (size > 0)
{
jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0);
char* pBuf = (char*)malloc(size+1);
if (pBuf != NULL)
{
memcpy(pBuf, data, size);
pBuf[size] = '\0';
// pass data to editbox's delegate
if (s_pfEditBoxCB) s_pfEditBoxCB(pBuf, s_ctx);
free(pBuf);
}
env->ReleaseByteArrayElements(text, data, 0);
}
else
{
if (s_pfEditBoxCB) s_pfEditBoxCB("", s_ctx);
}
}
int getFontSizeAccordingHeightJni(int height)
{
int ret = 0;
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t
, "org/cocos2dx/lib/Cocos2dxBitmap"
, "getFontSizeAccordingHeight"
, "(I)I"))
{
ret = t.env->CallStaticIntMethod(t.classID, t.methodID, height);
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
std::string getStringWithEllipsisJni(const char* pszText, float width, float fontSize)
{
std::string ret;
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t
, "org/cocos2dx/lib/Cocos2dxBitmap"
, "getStringWithEllipsis"
, "(Ljava/lang/String;FF)Ljava/lang/String;"))
{
jstring stringArg1;
if (!pszText)
{
stringArg1 = t.env->NewStringUTF("");
}
else
{
stringArg1 = t.env->NewStringUTF(pszText);
}
jstring retFromJava = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID, stringArg1, width, fontSize);
const char* str = t.env->GetStringUTFChars(retFromJava, 0);
ret = str;
t.env->ReleaseStringUTFChars(retFromJava, str);
t.env->DeleteLocalRef(stringArg1);
t.env->DeleteLocalRef(t.classID);
}
LOGD("getStringWithEllipsisJni 07");
return ret;
}
} // end of extern "C"

View File

@ -1,47 +0,0 @@
/****************************************************************************
Copyright (c) 2012 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __EDITBOX_JNI_H__
#define __EDITBOX_JNI_H__
#include <string>
typedef void (*EditBoxCallback)(const char* pText, void* ctx);
extern "C"
{
void showEditBoxDialogJni(const char* pszTitle,
const char* pszContent,
int nInputMode,
int nInputFlag,
int nReturnType,
int nMaxLength,
EditBoxCallback pfEditBoxCB,
void* ctx);
int getFontSizeAccordingHeightJni(int height);
std::string getStringWithEllipsisJni(const char* pszText, float width, float fontSize);
} // end of extern "C"
#endif // __EDITBOX_JNI_H__

View File

@ -29,56 +29,32 @@ THE SOFTWARE.
#include <string.h>
#include <jni.h>
#if 0
#define LOG_TAG "IMEJni"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#else
#define LOGD(...)
#endif
using namespace cocos2d;
extern "C"
{
//////////////////////////////////////////////////////////////////////////
// handle IME message
//////////////////////////////////////////////////////////////////////////
extern "C" {
void setKeyboardStateJNI(int bOpen) {
if (bOpen) {
openKeyboardJNI();
} else {
closeKeyboardJNI();
}
}
void setKeyboardStateJNI(int bOpen)
{
void openKeyboardJNI() {
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t,
"org/cocos2dx/lib/Cocos2dxGLSurfaceView",
(bOpen) ? "openIMEKeyboard" : "closeIMEKeyboard",
"()V"))
{
if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxGLSurfaceView", "openIMEKeyboard", "()V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
}
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInsertText(JNIEnv* env, jobject thiz, jstring text)
{
const char* pszText = env->GetStringUTFChars(text, NULL);
cocos2d::CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(pszText, strlen(pszText));
env->ReleaseStringUTFChars(text, pszText);
}
void closeKeyboardJNI() {
JniMethodInfo t;
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeDeleteBackward(JNIEnv* env, jobject thiz)
{
cocos2d::CCIMEDispatcher::sharedDispatcher()->dispatchDeleteBackward();
}
jstring Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeGetContentText()
{
JNIEnv * env = 0;
if (JniHelper::getJavaVM()->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK || ! env)
{
return 0;
if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxGLSurfaceView", "closeIMEKeyboard", "()V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
const char * pszText = cocos2d::CCIMEDispatcher::sharedDispatcher()->getContentText();
return env->NewStringUTF(pszText);
}
}

View File

@ -24,10 +24,10 @@ THE SOFTWARE.
#ifndef __ANDROID_IME_JNI_H__
#define __ANDROID_IME_JNI_H__
extern "C"
{
extern "C" {
extern void setKeyboardStateJNI(int bOpen);
extern void openKeyboardJNI();
extern void closeKeyboardJNI();
}
#endif // __ANDROID_IME_JNI_H__

View File

@ -0,0 +1,15 @@
#include "cocoa/CCGeometry.h"
#include "platform/android/CCAccelerometer.h"
#include "../CCEGLView.h"
#include "JniHelper.h"
#include <jni.h>
#include "CCDirector.h"
using namespace cocos2d;
extern "C" {
void Java_org_cocos2dx_lib_Cocos2dxAccelerometer_onSensorChanged(JNIEnv* env, jobject thiz, jfloat x, jfloat y, jfloat z, jlong timeStamp) {
CCDirector* pDirector = CCDirector::sharedDirector();
pDirector->getAccelerometer()->update(x, y, z, timeStamp);
}
}

View File

@ -0,0 +1,48 @@
#include "JniHelper.h"
#include <string.h>
#include "CCDirector.h"
#include "../CCApplication.h"
#include "platform/CCFileUtils.h"
#include "CCEventType.h"
#include "support/CCNotificationCenter.h"
#include <jni.h>
using namespace cocos2d;
extern "C" {
int getFontSizeAccordingHeightJni(int height) {
int ret = 0;
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxBitmap", "getFontSizeAccordingHeight", "(I)I")) {
ret = t.env->CallStaticIntMethod(t.classID, t.methodID, height);
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
std::string getStringWithEllipsisJni(const char* pszText, float width, float fontSize) {
std::string ret;
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxBitmap", "getStringWithEllipsis", "(Ljava/lang/String;FF)Ljava/lang/String;")) {
jstring stringArg1;
if (!pszText) {
stringArg1 = t.env->NewStringUTF("");
} else {
stringArg1 = t.env->NewStringUTF(pszText);
}
jstring retFromJava = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID, stringArg1, width, fontSize);
const char* str = t.env->GetStringUTFChars(retFromJava, 0);
ret = str;
t.env->ReleaseStringUTFChars(retFromJava, str);
t.env->DeleteLocalRef(stringArg1);
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
}

View File

@ -0,0 +1,177 @@
#include <stdlib.h>
#include <jni.h>
#include <android/log.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include "JniHelper.h"
#include "cocoa/CCString.h"
#include "Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#define LOG_TAG "Java_org_cocos2dx_lib_Cocos2dxHelper.cpp"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define CLASS_NAME "org/cocos2dx/lib/Cocos2dxHelper"
static EditTextCallback s_pfEditTextCallback = NULL;
static void* s_ctx = NULL;
using namespace cocos2d;
extern "C" {
const char * g_pApkPath;
void Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetApkPath(JNIEnv* env, jobject thiz, jstring apkPath) {
g_pApkPath = env->GetStringUTFChars(apkPath, NULL);
}
const char * getApkPath() {
return g_pApkPath;
}
void Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetAssetManager(JNIEnv* env, jobject thiz, jobject java_assetmanager) {
AAssetManager* assetmanager = AAssetManager_fromJava(env, java_assetmanager);
if (assetmanager == NULL) {
LOGD("ERROR: assetmanager == NULL");
return;
}
cocos2d::JniHelper::setAssetManager(assetmanager);
}
void Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetExternalAssetPath(JNIEnv* env, jobject thiz, jstring externalAssetPath) {
const char* externalAssetPathChars = env->GetStringUTFChars(externalAssetPath, NULL);
cocos2d::JniHelper::setExternalAssetPath(externalAssetPathChars);
env->ReleaseStringUTFChars(externalAssetPath, externalAssetPathChars);
}
void showDialogJNI(const char * pszMsg, const char * pszTitle) {
if (!pszMsg) {
return;
}
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "showDialog", "(Ljava/lang/String;Ljava/lang/String;)V")) {
jstring stringArg1;
if (!pszTitle) {
stringArg1 = t.env->NewStringUTF("");
} else {
stringArg1 = t.env->NewStringUTF(pszTitle);
}
jstring stringArg2 = t.env->NewStringUTF(pszMsg);
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg1, stringArg2);
t.env->DeleteLocalRef(stringArg1);
t.env->DeleteLocalRef(stringArg2);
t.env->DeleteLocalRef(t.classID);
}
}
void showEditTextDialogJNI(const char* pszTitle, const char* pszMessage, int nInputMode, int nInputFlag, int nReturnType, int nMaxLength, EditTextCallback pfEditTextCallback, void* ctx) {
if (pszMessage == NULL) {
return;
}
s_pfEditTextCallback = pfEditTextCallback;
s_ctx = ctx;
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "showEditTextDialog", "(Ljava/lang/String;Ljava/lang/String;IIII)V")) {
jstring stringArg1;
if (!pszTitle) {
stringArg1 = t.env->NewStringUTF("");
} else {
stringArg1 = t.env->NewStringUTF(pszTitle);
}
jstring stringArg2 = t.env->NewStringUTF(pszMessage);
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg1, stringArg2, nInputMode, nInputFlag, nReturnType, nMaxLength);
t.env->DeleteLocalRef(stringArg1);
t.env->DeleteLocalRef(stringArg2);
t.env->DeleteLocalRef(t.classID);
}
}
void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv * env, jobject obj, jbyteArray text) {
jsize size = env->GetArrayLength(text);
if (size > 0) {
jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0);
char* pBuf = (char*)malloc(size+1);
if (pBuf != NULL) {
memcpy(pBuf, data, size);
pBuf[size] = '\0';
// pass data to edittext's delegate
if (s_pfEditTextCallback) s_pfEditTextCallback(pBuf, s_ctx);
free(pBuf);
}
env->ReleaseByteArrayElements(text, data, 0);
} else {
if (s_pfEditTextCallback) s_pfEditTextCallback("", s_ctx);
}
}
void terminateProcessJNI() {
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "terminateProcess", "()V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
}
const char* getPackageNameJNI() {
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getCocos2dxPackageName", "()Ljava/lang/String;")) {
jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
CCString *ret = new CCString(JniHelper::jstring2string(str).c_str());
ret->autorelease();
t.env->DeleteLocalRef(str);
return ret->m_sString.c_str();
}
return 0;
}
const char* getCurrentLanguageJNI() {
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getCurrentLanguage", "()Ljava/lang/String;")) {
jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
CCString *ret = new CCString(JniHelper::jstring2string(str).c_str());
ret->autorelease();
t.env->DeleteLocalRef(str);
return ret->m_sString.c_str();
}
return 0;
}
void enableAccelerometerJNI() {
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "enableAccelerometer", "()V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
}
void disableAccelerometerJNI() {
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "disableAccelerometer", "()V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
}
}

View File

@ -21,14 +21,22 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __ANDROID_SENSOR_JNI_H__
#define __ANDROID_SENSOR_JNI_H__
#ifndef __Java_org_cocos2dx_lib_Cocos2dxHelper_H__
#define __Java_org_cocos2dx_lib_Cocos2dxHelper_H__
extern "C"
#include <string>
{
typedef void (*EditTextCallback)(const char* pText, void* ctx);
extern "C" {
extern const char * getApkPath();
extern void showDialogJNI(const char * pszMsg, const char * pszTitle);
extern void showEditTextDialogJNI(const char* pszTitle, const char* pszContent, int nInputMode, int nInputFlag, int nReturnType, int nMaxLength, EditTextCallback pfEditTextCallback, void* ctx);
extern void terminateProcessJNI();
extern const char * getCurrentLanguageJNI();
extern const char * getPackageNameJNI();
extern void enableAccelerometerJNI();
extern void disableAccelerometerJNI();
}
#endif // __ANDROID_SENSOR_JNI_H__
#endif

View File

@ -0,0 +1,48 @@
#include "text_input_node/CCIMEDispatcher.h"
#include "CCDirector.h"
#include "../CCApplication.h"
#include "platform/CCFileUtils.h"
#include "CCEventType.h"
#include "support/CCNotificationCenter.h"
#include "JniHelper.h"
#include <jni.h>
using namespace cocos2d;
extern "C" {
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeRender(JNIEnv* env) {
cocos2d::CCDirector::sharedDirector()->mainLoop();
}
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnPause() {
CCApplication::sharedApplication()->applicationDidEnterBackground();
CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_COME_TO_BACKGROUND, NULL);
}
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnResume() {
if (CCDirector::sharedDirector()->getOpenGLView()) {
CCApplication::sharedApplication()->applicationWillEnterForeground();
}
}
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInsertText(JNIEnv* env, jobject thiz, jstring text) {
const char* pszText = env->GetStringUTFChars(text, NULL);
cocos2d::CCIMEDispatcher::sharedDispatcher()->dispatchInsertText(pszText, strlen(pszText));
env->ReleaseStringUTFChars(text, pszText);
}
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeDeleteBackward(JNIEnv* env, jobject thiz) {
cocos2d::CCIMEDispatcher::sharedDispatcher()->dispatchDeleteBackward();
}
jstring Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeGetContentText() {
JNIEnv * env = 0;
if (JniHelper::getJavaVM()->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK || ! env) {
return 0;
}
const char * pszText = cocos2d::CCIMEDispatcher::sharedDispatcher()->getContentText();
return env->NewStringUTF(pszText);
}
}

View File

@ -23,6 +23,8 @@ THE SOFTWARE.
****************************************************************************/
#include "JniHelper.h"
#include <android/log.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <string.h>
#if 1
@ -193,6 +195,26 @@ void JniHelper::setJavaVM(JavaVM *javaVM)
m_psJavaVM = javaVM;
}
AAssetManager* JniHelper::m_assetmanager = NULL;
AAssetManager* JniHelper::getAssetManager() {
return m_assetmanager;
}
void JniHelper::setAssetManager(AAssetManager* am) {
m_assetmanager = am;
}
string JniHelper::m_externalAssetPath;
const char* JniHelper::getExternalAssetPath() {
return m_externalAssetPath.c_str();
}
void JniHelper::setExternalAssetPath(const char * externalAssetPath) {
m_externalAssetPath = externalAssetPath;
}
jclass JniHelper::getClassID(const char *className, JNIEnv *env)
{
return getClassID_(className, env);

View File

@ -27,6 +27,7 @@ THE SOFTWARE.
#include <jni.h>
#include <string>
#include "platform/CCPlatformMacros.h"
#include <android/asset_manager.h>
NS_CC_BEGIN
@ -42,6 +43,10 @@ class CC_DLL JniHelper
public:
static JavaVM* getJavaVM();
static void setJavaVM(JavaVM *javaVM);
static AAssetManager* getAssetManager();
static void setAssetManager(AAssetManager* am);
static const char* getExternalAssetPath();
static void setExternalAssetPath(const char* externalAssetPath);
static jclass getClassID(const char *className, JNIEnv *env=0);
static bool getStaticMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode);
static bool getMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode);
@ -49,6 +54,8 @@ public:
private:
static JavaVM *m_psJavaVM;
static AAssetManager *m_assetmanager;
static std::string m_externalAssetPath;
};
NS_CC_END

View File

@ -1,141 +0,0 @@
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "MessageJni.h"
#include "CCDirector.h"
#include "JniHelper.h"
#include "../CCApplication.h"
#include "platform/CCFileUtils.h"
#include "CCEventType.h"
#include "support/CCNotificationCenter.h"
#include <android/log.h>
#include <jni.h>
#if 0
#define LOG_TAG "MessageJni"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#else
#define LOGD(...)
#endif
using namespace cocos2d;
extern "C"
{
char *g_pApkPath;
//////////////////////////////////////////////////////////////////////////
// native renderer
//////////////////////////////////////////////////////////////////////////
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeRender(JNIEnv* env)
{
cocos2d::CCDirector::sharedDirector()->mainLoop();
}
// handle onPause and onResume
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnPause()
{
CCApplication::sharedApplication()->applicationDidEnterBackground();
CCNotificationCenter::sharedNotificationCenter()->postNotification(EVENT_COME_TO_BACKGROUND, NULL);
}
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnResume()
{
// Shared OpenGL View instance doesn't exist yet when Activity.onResume is first called
if (CCDirector::sharedDirector()->getOpenGLView())
{
CCApplication::sharedApplication()->applicationWillEnterForeground();
}
}
void showMessageBoxJNI(const char * pszMsg, const char * pszTitle)
{
if (! pszMsg)
{
return;
}
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t
, "org/cocos2dx/lib/Cocos2dxActivity"
, "showMessageBox"
, "(Ljava/lang/String;Ljava/lang/String;)V"))
{
jstring stringArg1;
if (! pszTitle)
{
stringArg1 = t.env->NewStringUTF("");
}
else
{
stringArg1 = t.env->NewStringUTF(pszTitle);
}
jstring stringArg2 = t.env->NewStringUTF(pszMsg);
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg1, stringArg2);
t.env->DeleteLocalRef(stringArg1);
t.env->DeleteLocalRef(stringArg2);
t.env->DeleteLocalRef(t.classID);
}
}
//////////////////////////////////////////////////////////////////////////
// terminate the process
//////////////////////////////////////////////////////////////////////////
void terminateProcessJNI()
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t
, "org/cocos2dx/lib/Cocos2dxActivity"
, "terminateProcess"
, "()V"))
{
t.env->CallStaticVoidMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
}
//////////////////////////////////////////////////////////////////////////
// set apk path
//////////////////////////////////////////////////////////////////////////
void Java_org_cocos2dx_lib_Cocos2dxActivity_nativeSetPaths(JNIEnv* env, jobject thiz, jstring apkPath)
{
g_pApkPath = (char*)env->GetStringUTFChars(apkPath, NULL);
// don't release it, we will use it later
//env->ReleaseStringUTFChars(apkPath, str);
}
char* getApkPath()
{
return g_pApkPath;
}
}

View File

@ -1,35 +0,0 @@
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __ANDROID_MESSAGE_JNI_H__
#define __ANDROID_MESSAGE_JNI_H__
extern "C"
{
extern void showMessageBoxJNI(const char * pszMsg, const char * pszTitle);
extern void terminateProcessJNI();
extern char* getApkPath();
}
#endif // __ANDROID_MESSAGE_JNI_H__

View File

@ -1,83 +0,0 @@
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "SensorJni.h"
#include "cocoa/CCGeometry.h"
#include "platform/android/CCAccelerometer.h"
#include "../CCEGLView.h"
#include "JniHelper.h"
#include <android/log.h>
#include <jni.h>
#include "CCDirector.h"
#if 0
#define LOG_TAG "SensorJni"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#else
#define LOGD(...)
#endif
using namespace cocos2d;
extern "C"
{
//////////////////////////////////////////////////////////////////////////
// handle accelerometer changes
//////////////////////////////////////////////////////////////////////////
void Java_org_cocos2dx_lib_Cocos2dxAccelerometer_onSensorChanged(JNIEnv* env, jobject thiz, jfloat x, jfloat y, jfloat z, jlong timeStamp)
{
// We need to invert to make it compatible with iOS.
CCDirector* pDirector = CCDirector::sharedDirector();
pDirector->getAccelerometer()->update(x, y, z, timeStamp);
}
void enableAccelerometerJNI()
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t,
"org/cocos2dx/lib/Cocos2dxActivity",
"enableAccelerometer",
"()V"))
{
t.env->CallStaticVoidMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
}
void disableAccelerometerJNI()
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t,
"org/cocos2dx/lib/Cocos2dxActivity",
"disableAccelerometer",
"()V"))
{
t.env->CallStaticVoidMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
}
}

View File

@ -1,91 +0,0 @@
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "SystemInfoJni.h"
#include "JniHelper.h"
#include "cocoa/CCString.h"
#include <android/log.h>
#include <jni.h>
#if 0
#define LOG_TAG "SystemInfoJni"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#else
#define LOGD(...)
#endif
using namespace cocos2d;
extern "C"
{
const char* getPackageNameJNI()
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t,
"org/cocos2dx/lib/Cocos2dxActivity",
"getCocos2dxPackageName",
"()Ljava/lang/String;"))
{
jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
CCString *ret = new CCString(JniHelper::jstring2string(str).c_str());
ret->autorelease();
t.env->DeleteLocalRef(str);
LOGD("package name %s", ret->m_sString.c_str());
return ret->m_sString.c_str();
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
// handle get current language
//////////////////////////////////////////////////////////////////////////
const char* getCurrentLanguageJNI()
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t
, "org/cocos2dx/lib/Cocos2dxActivity"
, "getCurrentLanguage"
, "()Ljava/lang/String;"))
{
jstring str = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID);
t.env->DeleteLocalRef(t.classID);
CCString *ret = new CCString(JniHelper::jstring2string(str).c_str());
ret->autorelease();
t.env->DeleteLocalRef(str);
LOGD("language name %s", ret.c_str());
return ret->m_sString.c_str();
}
return 0;
}
}

View File

@ -1,36 +0,0 @@
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __ANDROID_SYSTEM_INFO_JNI_H__
#define __ANDROID_SYSTEM_INFO_JNI_H__
#include <jni.h>
extern "C"
{
extern const char* getCurrentLanguageJNI();
extern const char* getPackageNameJNI();
}
#endif // __ANDROID_SYSTEM_INFO_JNI_H__

View File

@ -31,79 +31,60 @@ THE SOFTWARE.
#include <android/log.h>
#include <jni.h>
#if 0
#define LOG_TAG "NativeTouchesJni"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#else
#define LOGD(...)
#endif
using namespace cocos2d;
extern "C"
{
extern "C" {
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesBegin(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y) {
cocos2d::CCDirector::sharedDirector()->getOpenGLView()->handleTouchesBegin(1, &id, &x, &y);
}
// handle touch event
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesBegin(JNIEnv* env, jobject thiz, jint id, jfloat x, jfloat y)
{
cocos2d::CCDirector::sharedDirector()->getOpenGLView()->handleTouchesBegin(1, &id, &x, &y);
}
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesEnd(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y) {
cocos2d::CCDirector::sharedDirector()->getOpenGLView()->handleTouchesEnd(1, &id, &x, &y);
}
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesEnd(JNIEnv* env, jobject thiz, jint id, jfloat x, jfloat y)
{
cocos2d::CCDirector::sharedDirector()->getOpenGLView()->handleTouchesEnd(1, &id, &x, &y);
}
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesMove(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys) {
int size = env->GetArrayLength(ids);
jint id[size];
jfloat x[size];
jfloat y[size];
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesMove(JNIEnv* env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys)
{
int size = env->GetArrayLength(ids);
jint id[size];
jfloat x[size];
jfloat y[size];
env->GetIntArrayRegion(ids, 0, size, id);
env->GetFloatArrayRegion(xs, 0, size, x);
env->GetFloatArrayRegion(ys, 0, size, y);
env->GetIntArrayRegion(ids, 0, size, id);
env->GetFloatArrayRegion(xs, 0, size, x);
env->GetFloatArrayRegion(ys, 0, size, y);
cocos2d::CCDirector::sharedDirector()->getOpenGLView()->handleTouchesMove(size, id, x, y);
}
cocos2d::CCDirector::sharedDirector()->getOpenGLView()->handleTouchesMove(size, id, x, y);
}
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesCancel(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys) {
int size = env->GetArrayLength(ids);
jint id[size];
jfloat x[size];
jfloat y[size];
void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesCancel(JNIEnv* env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys)
{
int size = env->GetArrayLength(ids);
jint id[size];
jfloat x[size];
jfloat y[size];
env->GetIntArrayRegion(ids, 0, size, id);
env->GetFloatArrayRegion(xs, 0, size, x);
env->GetFloatArrayRegion(ys, 0, size, y);
env->GetIntArrayRegion(ids, 0, size, id);
env->GetFloatArrayRegion(xs, 0, size, x);
env->GetFloatArrayRegion(ys, 0, size, y);
cocos2d::CCDirector::sharedDirector()->getOpenGLView()->handleTouchesCancel(size, id, x, y);
}
cocos2d::CCDirector::sharedDirector()->getOpenGLView()->handleTouchesCancel(size, id, x, y);
}
#define KEYCODE_BACK 0x04
#define KEYCODE_MENU 0x52
#define KEYCODE_BACK 0x04
#define KEYCODE_MENU 0x52
// handle keydown event
jboolean Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeKeyDown(JNIEnv* env, jobject thiz, jint keyCode)
{
CCDirector* pDirector = CCDirector::sharedDirector();
switch (keyCode)
{
case KEYCODE_BACK:
if (pDirector->getKeypadDispatcher()->dispatchKeypadMSG(kTypeBackClicked))
return JNI_TRUE;
break;
case KEYCODE_MENU:
if (pDirector->getKeypadDispatcher()->dispatchKeypadMSG(kTypeMenuClicked))
return JNI_TRUE;
break;
default:
jboolean Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeKeyDown(JNIEnv * env, jobject thiz, jint keyCode) {
CCDirector* pDirector = CCDirector::sharedDirector();
switch (keyCode) {
case KEYCODE_BACK:
if (pDirector->getKeypadDispatcher()->dispatchKeypadMSG(kTypeBackClicked))
return JNI_TRUE;
break;
case KEYCODE_MENU:
if (pDirector->getKeypadDispatcher()->dispatchKeypadMSG(kTypeMenuClicked))
return JNI_TRUE;
break;
default:
return JNI_FALSE;
}
return JNI_FALSE;
}
return JNI_FALSE;
}
}

View File

@ -31,6 +31,6 @@ LOCAL_LDLIBS += -llog
include $(BUILD_STATIC_LIBRARY)
$(call import-module,scripting/javascript/spidermonkey-android/android)
$(call import-module,scripting/javascript/spidermonkey-android)
$(call import-module,cocos2dx)
$(call import-module,external/chipmunk)

View File

@ -3,8 +3,8 @@ LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := spidermonkey_static
LOCAL_MODULE_FILENAME := js_static
LOCAL_SRC_FILES := ../dist/lib/libjs_static.a
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../dist/include
LOCAL_SRC_FILES := ./lib/libjs_static.a
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_CPPFLAGS := -D__STDC_LIMIT_MACROS=1
LOCAL_EXPORT_CPPFLAGS := -D__STDC_LIMIT_MACROS=1
include $(PREBUILT_STATIC_LIBRARY)

Some files were not shown because too many files have changed in this diff Show More