Merge branch 'develop' of github.com:cocos-creator/cocos2d-x-lite into develop

This commit is contained in:
Nan Wang
2016-05-17 10:48:44 +08:00
25 changed files with 18 additions and 5695 deletions
+13 -3
View File
@@ -923,18 +923,28 @@ void FileUtils::setWritablePath(const std::string& writablePath)
void FileUtils::setDefaultResourceRootPath(const std::string& resRootPath)
{
if (_defaultResRootPath == resRootPath)
if (resRootPath.empty() || _defaultResRootPath == resRootPath)
return;
if (!_searchPathArray.empty() && !_defaultResRootPath.empty())
{
auto tmp = _defaultResRootPath.length();
std::vector<std::string> newSearchPathArray;
for (auto& iter : _searchPathArray)
{
iter = iter.substr(tmp);
if (iter.find(_defaultResRootPath) == 0)
{
if (iter.length() == tmp)
newSearchPathArray.push_back("");
else
newSearchPathArray.push_back(iter.substr(tmp));
}
else
newSearchPathArray.push_back(iter);
}
_defaultResRootPath = resRootPath;
setSearchPaths(_searchPathArray);
setSearchPaths(newSearchPathArray);
}
else
{
@@ -669,7 +669,7 @@ bool jsval_to_TTFConfig(JSContext *cx, JS::HandleValue v, cocos2d::TTFConfig* re
if (JS_GetProperty(cx, tmp, "glyphs", &js_glyphs) && !js_glyphs.isUndefined())
{
if (JS::ToNumber(cx, js_glyphs, &glyphs))
ret->glyphs = (GlyphCollection)glyphs;
ret->glyphs = (GlyphCollection)((int)glyphs);
}
if (JS_GetProperty(cx, tmp, "customGlyphs", &js_customGlyphs) && !js_customGlyphs.isUndefined())
@@ -54,6 +54,10 @@
"include":[
"tojs"
]
},
{
"from":"cocos/platform/android/java/src/org/cocos2dx/lib",
"to":"frameworks/runtime-src/proj.android/src/org/cocos2dx/lib"
}
],
"project_rename":{
@@ -1,130 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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;
public class Cocos2dxAccelerometer implements SensorEventListener {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = "Cocos2dxAccelerometer";
// ===========================================================
// Fields
// ===========================================================
private final Context mContext;
private final SensorManager mSensorManager;
private final Sensor mAccelerometer;
private final int mNaturalOrientation;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxAccelerometer(final Context context) {
mContext = context;
mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
final 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 setInterval(float interval) {
// Honeycomb version is 11
if(android.os.Build.VERSION.SDK_INT < 11) {
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
} else {
//convert seconds to microseconds
mSensorManager.registerListener(this, mAccelerometer, (int)(interval*100000));
}
}
public void disable() {
mSensorManager.unregisterListener(this);
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onSensorChanged(final SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return;
}
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
final float z = sensorEvent.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 = mContext.getResources().getConfiguration().orientation;
if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (mNaturalOrientation != Surface.ROTATION_0)) {
final float tmp = x;
x = -y;
y = tmp;
} else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (mNaturalOrientation != Surface.ROTATION_0)) {
final float tmp = x;
x = y;
y = -tmp;
}
Cocos2dxGLSurfaceView.queueAccelerometer(x,y,z,sensorEvent.timestamp);
}
@Override
public void onAccuracyChanged(final Sensor sensor, final int accuracy) {
}
// ===========================================================
// Methods
// Native method called from Cocos2dxGLSurfaceView (To be in the same thread)
// ===========================================================
public static native void onSensorChanged(final float x, final float y, final float z, final long timestamp);
}
@@ -1,398 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.preference.PreferenceManager.OnActivityResultListener;
import android.util.Log;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;
public abstract class Cocos2dxActivity extends Activity {
private final static String TAG = "Cocos2dxActivity";
// ===========================================================
// Fields
// ===========================================================
static ResizeLayout ROOT_LAYOUT = null;
private Cocos2dxGLSurfaceView mGLSurfaceView = null;
private int[] mGLContextAttrs = null;
private Cocos2dxHandler mHandler = null;
static Cocos2dxActivity COCOS_ACTIVITY = null;
private Cocos2dxVideoHelper mVideoHelper = null;
private Cocos2dxEditBoxHelper mEditBoxHelper = null;
private boolean isHasFocus = true;
public Cocos2dxGLSurfaceView getGLSurfaceView(){
return mGLSurfaceView;
}
public class Cocos2dxEGLConfigChooser implements GLSurfaceView.EGLConfigChooser
{
protected int[] configAttributes;
public Cocos2dxEGLConfigChooser(int[] attributes)
{
configAttributes = attributes;
}
private int findConfigAttrib(EGL10 egl, EGLDisplay display,
EGLConfig config, int attribute, int defaultValue) {
int[] value = new int[1];
if (egl.eglGetConfigAttrib(display, config, attribute, value)) {
return value[0];
}
return defaultValue;
}
class ConfigValue implements Comparable<ConfigValue> {
public EGLConfig config = null;
public int[] configAttribs = null;
public int value = 0;
private void calcValue() {
// depth factor 29bit and [6,12)bit
if (configAttribs[4] > 0) {
value = value + (1 << 29) + ((configAttribs[4]%64) << 6);
}
// stencil factor 28bit and [0, 6)bit
if (configAttribs[5] > 0) {
value = value + (1 << 28) + ((configAttribs[5]%64));
}
// alpha factor 30bit and [24, 28)bit
if (configAttribs[3] > 0) {
value = value + (1 << 30) + ((configAttribs[3]%16) << 24);
}
// green factor [20, 24)bit
if (configAttribs[1] > 0) {
value = value + ((configAttribs[1]%16) << 20);
}
// blue factor [16, 20)bit
if (configAttribs[2] > 0) {
value = value + ((configAttribs[2]%16) << 16);
}
// red factor [12, 16)bit
if (configAttribs[0] > 0) {
value = value + ((configAttribs[0]%16) << 12);
}
}
public ConfigValue(int[] attribs) {
configAttribs = attribs;
calcValue();
}
public ConfigValue(EGL10 egl, EGLDisplay display, EGLConfig config) {
this.config = config;
configAttribs = new int[6];
configAttribs[0] = findConfigAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0);
configAttribs[1] = findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0);
configAttribs[2] = findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0);
configAttribs[3] = findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0);
configAttribs[4] = findConfigAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0);
configAttribs[5] = findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0);
calcValue();
}
@Override
public int compareTo(ConfigValue another) {
if (value < another.value) {
return -1;
} else if (value > another.value) {
return 1;
} else {
return 0;
}
}
@Override
public String toString() {
return "{ color: " + configAttribs[3] + configAttribs[2] + configAttribs[1] + configAttribs[0] +
"; depth: " + configAttribs[4] + "; stencil: " + configAttribs[5] + ";}";
}
}
@Override
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display)
{
int[] EGLattribs = {
EGL10.EGL_RED_SIZE, configAttributes[0],
EGL10.EGL_GREEN_SIZE, configAttributes[1],
EGL10.EGL_BLUE_SIZE, configAttributes[2],
EGL10.EGL_ALPHA_SIZE, configAttributes[3],
EGL10.EGL_DEPTH_SIZE, configAttributes[4],
EGL10.EGL_STENCIL_SIZE,configAttributes[5],
EGL10.EGL_RENDERABLE_TYPE, 4, //EGL_OPENGL_ES2_BIT
EGL10.EGL_NONE
};
EGLConfig[] configs = new EGLConfig[1];
int[] numConfigs = new int[1];
boolean eglChooseResult = egl.eglChooseConfig(display, EGLattribs, configs, 1, numConfigs);
if (eglChooseResult && numConfigs[0] > 0)
{
return configs[0];
}
// there's no config match the specific configAttribs, we should choose a closest one
int[] EGLV2attribs = {
EGL10.EGL_RENDERABLE_TYPE, 4, //EGL_OPENGL_ES2_BIT
EGL10.EGL_NONE
};
eglChooseResult = egl.eglChooseConfig(display, EGLV2attribs, null, 0, numConfigs);
if(eglChooseResult && numConfigs[0] > 0) {
int num = numConfigs[0];
ConfigValue[] cfgVals = new ConfigValue[num];
// convert all config to ConfigValue
configs = new EGLConfig[num];
egl.eglChooseConfig(display, EGLV2attribs, configs, num, numConfigs);
for (int i = 0; i < num; ++i) {
cfgVals[i] = new ConfigValue(egl, display, configs[i]);
}
ConfigValue e = new ConfigValue(configAttributes);
// bin search
int lo = 0;
int hi = num;
int mi;
while (lo < hi - 1) {
mi = (lo + hi) / 2;
if (e.compareTo(cfgVals[mi]) < 0) {
hi = mi;
} else {
lo = mi;
}
}
if (lo != num - 1) {
lo = lo + 1;
}
Log.w("cocos2d", "Can't find EGLConfig match: " + e + ", instead of closest one:" + cfgVals[lo]);
return cfgVals[lo].config;
}
Log.e(DEVICE_POLICY_SERVICE, "Can not select an EGLConfig for rendering.");
return null;
}
}
public static Context getContext() {
return COCOS_ACTIVITY;
}
public void setKeepScreenOn(boolean value) {
final boolean newValue = value;
runOnUiThread(new Runnable() {
@Override
public void run() {
mGLSurfaceView.setKeepScreenOn(newValue);
}
});
}
protected void onLoadNativeLibraries() {
try {
ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
String libName = bundle.getString("android.app.lib_name");
System.loadLibrary(libName);
} catch (Exception e) {
e.printStackTrace();
}
}
// ===========================================================
// Constructors
// ===========================================================
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onLoadNativeLibraries();
COCOS_ACTIVITY = this;
mHandler = new Cocos2dxHandler(this);
Cocos2dxHelper.init(this);
mGLContextAttrs = getGLContextAttrs();
init();
if (mVideoHelper == null) {
mVideoHelper = new Cocos2dxVideoHelper();
}
if(mEditBoxHelper == null){
mEditBoxHelper = new Cocos2dxEditBoxHelper();
}
Cocos2dxWebViewHelper.init();
Window window = getWindow();
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
//native method,call GLViewImpl::getGLContextAttrs() to get the OpenGL ES context attributions
private static native int[] getGLContextAttrs();
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected void onResume() {
Log.d(TAG, "onResume()");
super.onResume();
resumeIfHasFocus();
}
@Override
public void onWindowFocusChanged(boolean isHasFocus) {
Log.d(TAG, "onWindowFocusChanged() hasFocus=" + isHasFocus);
super.onWindowFocusChanged(isHasFocus);
COCOS_ACTIVITY.isHasFocus = isHasFocus;
resumeIfHasFocus();
}
private void resumeIfHasFocus() {
if(isHasFocus) {
Cocos2dxHelper.onResume();
mGLSurfaceView.onResume();
}
}
@Override
protected void onPause() {
Log.d(TAG, "onPause()");
super.onPause();
Cocos2dxHelper.onPause();
mGLSurfaceView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
Cocos2dxEditBoxHelper.reset();
Cocos2dxHelper.reset();
Cocos2dxWebViewHelper.reset();
COCOS_ACTIVITY = null;
ROOT_LAYOUT = null;
}
public void showDialog(final String title, final String message) {
Message msg = Message.obtain();
msg.what = Cocos2dxHandler.HANDLER_SHOW_DIALOG;
msg.obj = new Cocos2dxHandler.DialogMessage(title, message);
mHandler.sendMessageDelayed(msg, 0);
}
public void runOnGLThread(final Runnable runnable) {
mGLSurfaceView.queueEvent(runnable);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
for (OnActivityResultListener listener : Cocos2dxHelper.getOnActivityResultListeners()) {
listener.onActivityResult(requestCode, resultCode, data);
}
super.onActivityResult(requestCode, resultCode, data);
}
public void init() {
ViewGroup.LayoutParams framelayout_params =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
ROOT_LAYOUT = null;
ROOT_LAYOUT = new ResizeLayout(this);
ROOT_LAYOUT.setLayoutParams(framelayout_params);
// Cocos2dxEditText layout
ViewGroup.LayoutParams editTextLayoutParams =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
Cocos2dxEditBox editText = new Cocos2dxEditBox(this);
editText.setLayoutParams(editTextLayoutParams);
ROOT_LAYOUT.addView(editText);
// Cocos2dxGLSurfaceView
mGLSurfaceView = this.onCreateView();
ROOT_LAYOUT.addView(mGLSurfaceView);
// Switch to supported OpenGL (ARGB888) mode on emulator
if (isAndroidEmulator())
this.mGLSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
mGLSurfaceView.setCocos2dxRenderer(new Cocos2dxRenderer());
mGLSurfaceView.setCocos2dxEditText(editText);
setContentView(ROOT_LAYOUT);
}
public Cocos2dxGLSurfaceView onCreateView() {
Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
//this line is need on some device if we specify an alpha bits
if(this.mGLContextAttrs[3] > 0) glSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
Cocos2dxEGLConfigChooser chooser = new Cocos2dxEGLConfigChooser(mGLContextAttrs);
glSurfaceView.setEGLConfigChooser(chooser);
return glSurfaceView;
}
private static boolean isAndroidEmulator() {
String model = Build.MODEL;
Log.d(TAG, "model=" + model);
String product = Build.PRODUCT;
Log.d(TAG, "product=" + product);
boolean isEmulator = false;
if (product != null) {
isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_");
}
Log.d(TAG, "isEmulator=" + isEmulator);
return isEmulator;
}
}
@@ -1,225 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public final class Cocos2dxBitmap {
// ===========================================================
// Constants
// ===========================================================
/* The values are the same as cocos2dx/platform/CCImage.h. */
private static final int HORIZONTAL_ALIGN_LEFT = 1;
private static final int HORIZONTAL_ALIGN_RIGHT = 2;
private static final int HORIZONTAL_ALIGN_CENTER = 3;
private static final int VERTICAL_ALIGN_TOP = 1;
private static final int VERTICAL_ALIGN_BOTTOM = 2;
private static final int VERTICAL_ALIGN_CENTER = 3;
// ===========================================================
// Methods
// ===========================================================
private static native void nativeInitBitmapDC(final int width,
final int height, final byte[] pixels);
public static boolean createTextBitmapShadowStroke(final String string, final String fontName, int fontSize,
int fontTintR, int fontTintG, int fontTintB, int fontTintA,
int alignment, int width, int height,
boolean shadow, float shadowDX, float shadowDY, float shadowBlur, float shadowOpacity,
boolean stroke, int strokeR, int strokeG, int strokeB, int strokeA, float strokeSize)
{
Layout.Alignment hAlignment = Layout.Alignment.ALIGN_NORMAL;
int horizontalAlignment = alignment & 0x0F;
switch (horizontalAlignment) {
case HORIZONTAL_ALIGN_CENTER:
hAlignment = Layout.Alignment.ALIGN_CENTER;
break;
case HORIZONTAL_ALIGN_RIGHT:
hAlignment = Layout.Alignment.ALIGN_OPPOSITE;
break;
case HORIZONTAL_ALIGN_LEFT:
break;
default:
break;
}
TextPaint paint = Cocos2dxBitmap.newPaint(fontName, fontSize);
if (stroke) {
paint.setStyle(TextPaint.Style.STROKE);
paint.setStrokeWidth(strokeSize);
}
int maxWidth = width;
if (maxWidth <= 0) {
maxWidth = (int)Math.ceil( StaticLayout.getDesiredWidth(string, paint));
}
StaticLayout staticLayout = new StaticLayout(string, paint, maxWidth , hAlignment,1.0f,0.0f,false);
int layoutWidth = staticLayout.getWidth();
int layoutHeight = staticLayout.getLineTop(staticLayout.getLineCount());
int bitmapWidth = Math.max(layoutWidth, width);
int bitmapHeight = layoutHeight;
if (height > 0) {
bitmapHeight = height;
}
if (bitmapWidth == 0 || bitmapHeight == 0) {
return false;
}
int offsetX = 0;
if (horizontalAlignment == HORIZONTAL_ALIGN_CENTER) {
offsetX = (bitmapWidth - layoutWidth) / 2;
}
else if (horizontalAlignment == HORIZONTAL_ALIGN_RIGHT) {
offsetX = bitmapWidth - layoutWidth;
}
int offsetY = 0;
int verticalAlignment = (alignment >> 4) & 0x0F;
switch (verticalAlignment)
{
case VERTICAL_ALIGN_CENTER:
offsetY = (bitmapHeight - layoutHeight) / 2;
break;
case VERTICAL_ALIGN_BOTTOM:
offsetY = bitmapHeight - layoutHeight;
break;
}
Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.translate(offsetX, offsetY);
if ( stroke )
{
paint.setARGB(strokeA, strokeR, strokeG, strokeB);
staticLayout.draw(canvas);
}
paint.setStyle(TextPaint.Style.FILL);
paint.setARGB(fontTintA, fontTintR, fontTintG, fontTintB);
staticLayout.draw(canvas);
Cocos2dxBitmap.initNativeObject(bitmap);
return true;
}
private static TextPaint newPaint(final String fontName, final int fontSize) {
final TextPaint paint = new TextPaint();
paint.setTextSize(fontSize);
paint.setAntiAlias(true);
// Set type face for paint, now it support .ttf file.
if (fontName.endsWith(".ttf")) {
try {
final Typeface typeFace = Cocos2dxTypefaces.get(
Cocos2dxActivity.COCOS_ACTIVITY, fontName);
paint.setTypeface(typeFace);
} catch (final 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));
}
return paint;
}
private static void initNativeObject(final Bitmap bitmap) {
final byte[] pixels = Cocos2dxBitmap.getPixels(bitmap);
if (pixels == null) {
return;
}
Cocos2dxBitmap.nativeInitBitmapDC(bitmap.getWidth(),
bitmap.getHeight(), pixels);
}
private static byte[] getPixels(final Bitmap bitmap) {
if (bitmap != null) {
final byte[] pixels = new byte[bitmap.getWidth()
* bitmap.getHeight() * 4];
final ByteBuffer buf = ByteBuffer.wrap(pixels);
buf.order(ByteOrder.nativeOrder());
bitmap.copyPixelsToBuffer(buf);
return pixels;
}
return null;
}
public static int getFontSizeAccordingHeight(int height) {
TextPaint paint = new TextPaint();
Rect bounds = new Rect();
paint.setTypeface(Typeface.DEFAULT);
int text_size = 1;
boolean found_desired_size = false;
while (!found_desired_size) {
paint.setTextSize(text_size);
String text = "SghMNy";
paint.getTextBounds(text, 0, text.length(), bounds);
text_size++;
if (height - bounds.height() <= 2) {
found_desired_size = true;
}
}
return text_size;
}
private static String getStringWithEllipsis(String string, float width,
float fontSize) {
if (TextUtils.isEmpty(string)) {
return "";
}
TextPaint paint = new TextPaint();
paint.setTypeface(Typeface.DEFAULT);
paint.setTextSize(fontSize);
return TextUtils.ellipsize(string, paint, width,
TextUtils.TruncateAt.END).toString();
}
}
@@ -1,249 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.graphics.Color;
import android.graphics.Typeface;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
public class Cocos2dxEditBox extends EditText {
/**
* 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 int mInputFlagConstraints;
private int mInputModeConstraints;
private int mMaxLength;
//OpenGL view scaleX
private float mScaleX;
public Cocos2dxEditBox(Context context){
super(context);
}
public void setEditBoxViewRect(int left, int top, int maxWidth, int maxHeight) {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = left;
layoutParams.topMargin = top;
layoutParams.width = maxWidth;
layoutParams.height = maxHeight;
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
this.setLayoutParams(layoutParams);
}
public float getOpenGLViewScaleX() {
return mScaleX;
}
public void setOpenGLViewScaleX(float mScaleX) {
this.mScaleX = mScaleX;
}
public void setMaxLength(int maxLength){
this.mMaxLength = maxLength;
this.setFilters(new InputFilter[]{new InputFilter.LengthFilter(this.mMaxLength) });
}
public void setMultilineEnabled(boolean flag){
this.mInputModeConstraints |= InputType.TYPE_TEXT_FLAG_MULTI_LINE;
}
public void setReturnType(int returnType) {
switch (returnType) {
case kKeyboardReturnTypeDefault:
this.setImeOptions(EditorInfo.IME_ACTION_NONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
case kKeyboardReturnTypeDone:
this.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
case kKeyboardReturnTypeSend:
this.setImeOptions(EditorInfo.IME_ACTION_SEND | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
case kKeyboardReturnTypeSearch:
this.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
case kKeyboardReturnTypeGo:
this.setImeOptions(EditorInfo.IME_ACTION_GO | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
default:
this.setImeOptions(EditorInfo.IME_ACTION_NONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
}
}
public void setInputMode(int inputMode){
switch (inputMode) {
case kEditBoxInputModeAny:
this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE;
break;
case kEditBoxInputModeEmailAddr:
this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
break;
case kEditBoxInputModeNumeric:
this.mInputModeConstraints = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case kEditBoxInputModePhoneNumber:
this.mInputModeConstraints = InputType.TYPE_CLASS_PHONE;
break;
case kEditBoxInputModeUrl:
this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI;
break;
case kEditBoxInputModeDecimal:
this.mInputModeConstraints = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case kEditBoxInputModeSingleLine:
this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT;
break;
default:
break;
}
this.setInputType(this.mInputModeConstraints | this.mInputFlagConstraints);
}
@Override
public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
switch (pKeyCode) {
case KeyEvent.KEYCODE_BACK:
//To prevent program from going to background
Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().requestFocus();
return true;
default:
return super.onKeyDown(pKeyCode, pKeyEvent);
}
}
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
return super.onKeyPreIme(keyCode, event);
}
public void setInputFlag(int inputFlag) {
switch (inputFlag) {
case kEditBoxInputFlagPassword:
this.mInputFlagConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
this.setTypeface(Typeface.DEFAULT);
this.setTransformationMethod(new PasswordTransformationMethod());
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.setInputType(this.mInputFlagConstraints | this.mInputModeConstraints);
}
}
@@ -1,401 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.TextView;
public class Cocos2dxEditBoxHelper {
private static final String TAG = "Cocos2dxEditBoxHelper";
private static SparseArray<Cocos2dxEditBox> sEditBoxArray = null;
private static int sViewTag = 0;
static void reset() {
if (sEditBoxArray != null) {
sEditBoxArray.clear();
sEditBoxArray = null;
sViewTag = 0;
}
}
//Call native methods
private static native void editBoxEditingDidBegin(int index);
public static void __editBoxEditingDidBegin(int index){
editBoxEditingDidBegin(index);
}
private static native void editBoxEditingChanged(int index, String text);
public static void __editBoxEditingChanged(int index, String text){
editBoxEditingChanged(index, text);
}
private static native void editBoxEditingDidEnd(int index, String text);
public static void __editBoxEditingDidEnd(int index, String text){
editBoxEditingDidEnd(index, text);
}
public Cocos2dxEditBoxHelper() {
sEditBoxArray = new SparseArray<Cocos2dxEditBox>();
}
public static int convertToSP(float point){
Resources r = Cocos2dxActivity.COCOS_ACTIVITY.getResources();
int convertedValue = (int)TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, point, r.getDisplayMetrics());
return convertedValue;
}
public static int createEditBox(final int left, final int top, final int width, final int height, final float scaleX) {
final int index = sViewTag;
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
final Cocos2dxEditBox editBox = new Cocos2dxEditBox(Cocos2dxActivity.COCOS_ACTIVITY);
editBox.setFocusable(true);
editBox.setFocusableInTouchMode(true);
editBox.setInputFlag(4); //kEditBoxInputFlagInitialCapsAllCharacters
editBox.setInputMode(6); //kEditBoxInputModeSingleLine
editBox.setReturnType(0); //kKeyboardReturnTypeDefault
editBox.setHintTextColor(Color.GRAY);
editBox.setVisibility(View.INVISIBLE);
editBox.setBackgroundColor(Color.TRANSPARENT);
editBox.setTextColor(Color.WHITE);
editBox.setSingleLine();
editBox.setOpenGLViewScaleX(scaleX);
Resources r = Cocos2dxActivity.COCOS_ACTIVITY.getResources();
float density = r.getDisplayMetrics().density;
int paddingBottom = (int)(height * 0.33f / density);
paddingBottom = convertToSP(paddingBottom - 5 * scaleX / density);
paddingBottom = paddingBottom / 2;
int paddingTop = paddingBottom;
int paddingLeft = (int)(5 * scaleX / density);
paddingLeft = convertToSP(paddingLeft);
editBox.setPadding(paddingLeft,paddingTop, 0, paddingBottom);
FrameLayout.LayoutParams lParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
lParams.leftMargin = left;
lParams.topMargin = top;
lParams.width = width;
lParams.height = height;
lParams.gravity = Gravity.TOP | Gravity.LEFT;
Cocos2dxActivity.ROOT_LAYOUT.addView(editBox, lParams);
editBox.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
//The optimization can't be turn on due to unknown keyboard hide in some custom keyboard
// Cocos2dxActivity.ROOT_LAYOUT.setEnableForceDoLayout(false);
Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBoxHelper.__editBoxEditingChanged(index, s.toString());
}
});
}
@Override
public void afterTextChanged(Editable s) {
}
});
editBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBoxHelper.__editBoxEditingDidBegin(index);
}
});
editBox.setSelection(editBox.getText().length());
Cocos2dxActivity.ROOT_LAYOUT.setEnableForceDoLayout(true);
Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().setSoftKeyboardShown(true);
Log.d(TAG, "edit box get focus");
} else {
editBox.setVisibility(View.GONE);
Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBoxHelper.__editBoxEditingDidEnd(index, editBox.getText().toString());
}
});
Cocos2dxActivity.ROOT_LAYOUT.setEnableForceDoLayout(false);
Log.d(TAG, "edit box lose focus");
}
}
});
editBox.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
//if editbox doesn't support multiline, just hide the keyboard
if ((editBox.getInputType() & InputType.TYPE_TEXT_FLAG_MULTI_LINE) != InputType.TYPE_TEXT_FLAG_MULTI_LINE) {
Cocos2dxEditBoxHelper.closeKeyboard(index);
Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().requestFocus();
return true;
}
}
return false;
}
});
editBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
Cocos2dxEditBoxHelper.closeKeyboard(index);
Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().requestFocus();
}
return false;
}
});
sEditBoxArray.put(index, editBox);
}
});
return sViewTag++;
}
public static void removeEditBox(final int index) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (editBox != null) {
sEditBoxArray.remove(index);
Cocos2dxActivity.ROOT_LAYOUT.removeView(editBox);
}
}
});
}
public static void setFont(final int index, final String fontName, final float fontSize){
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (editBox != null) {
Typeface tf;
if (!fontName.isEmpty()) {
tf = Typeface.create(fontName, Typeface.NORMAL);
}else{
tf = Typeface.DEFAULT;
}
//TODO: The font size is not the same across all the anroid devices...
if (fontSize >= 0){
float density = Cocos2dxActivity.COCOS_ACTIVITY.getResources().getDisplayMetrics().density;
editBox.setTextSize(TypedValue.COMPLEX_UNIT_SP,
fontSize / density );
}
editBox.setTypeface(tf);
}
}
});
}
public static void setFontColor(final int index, final int red, final int green, final int blue, final int alpha){
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (editBox != null) {
editBox.setTextColor(Color.argb(alpha, red, green, blue));
}
}
});
}
public static void setPlaceHolderText(final int index, final String text){
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (editBox != null) {
editBox.setHint(text);
}
}
});
}
public static void setPlaceHolderTextColor(final int index, final int red, final int green, final int blue, final int alpha){
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (editBox != null) {
editBox.setHintTextColor(Color.argb(alpha, red, green, blue));
}
}
});
}
public static void setMaxLength(final int index, final int maxLength) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (editBox != null) {
editBox.setMaxLength(maxLength);
}
}
});
}
public static void setVisible(final int index, final boolean visible) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (editBox != null) {
editBox.setVisibility(visible ? View.VISIBLE : View.GONE);
if (visible) {
editBox.requestFocus();
Cocos2dxEditBoxHelper.openKeyboard(index);
}else{
Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().requestFocus();
Cocos2dxEditBoxHelper.closeKeyboard(index);
}
}
}
});
}
public static void setText(final int index, final String text){
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (editBox != null) {
editBox.setText(text);
}
}
});
}
public static void setReturnType(final int index, final int returnType) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (editBox != null) {
editBox.setReturnType(returnType);
}
}
});
}
public static void setInputMode(final int index, final int inputMode) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (editBox != null) {
editBox.setInputMode(inputMode);
}
}
});
}
public static void setInputFlag(final int index, final int inputFlag) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (editBox != null) {
editBox.setInputFlag(inputFlag);
}
}
});
}
public static void setEditBoxViewRect(final int index, final int left, final int top, final int maxWidth, final int maxHeight) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (editBox != null) {
editBox.setEditBoxViewRect(left, top, maxWidth, maxHeight);
}
}
});
}
public static void openKeyboard(int index) {
final InputMethodManager imm = (InputMethodManager) Cocos2dxActivity.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (null != editBox) {
imm.showSoftInput(editBox, 0);
Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().setSoftKeyboardShown(true);
}
}
public static void closeKeyboard(int index) {
final InputMethodManager imm = (InputMethodManager) Cocos2dxActivity.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
Cocos2dxEditBox editBox = sEditBoxArray.get(index);
if (null != editBox) {
imm.hideSoftInputFromWindow(editBox.getWindowToken(), 0);
Cocos2dxActivity.COCOS_ACTIVITY.getGLSurfaceView().setSoftKeyboardShown(false);
}
}
}
@@ -1,389 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.Activity;
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.View;
import android.view.inputmethod.InputMethodManager;
public class Cocos2dxGLSurfaceView extends GLSurfaceView {
// ===========================================================
// Constants
// ===========================================================
private static final String TAG = "Cocos2dxGLSurfaceView";
private final static int HANDLER_OPEN_IME_KEYBOARD = 2;
private final static int HANDLER_CLOSE_IME_KEYBOARD = 3;
// ===========================================================
// Fields
// ===========================================================
private static IMEHandler sIMEHandler;
private static Cocos2dxGLSurfaceView sGLSurfaceView;
private static Cocos2dxTextInputWrapper sTextInputWrapper;
private Cocos2dxRenderer mCocosRenderer;
private Cocos2dxEditBox mCocosEditText;
private boolean mSoftKeyboardShown = false;
public boolean isSoftKeyboardShown() {
return mSoftKeyboardShown;
}
public void setSoftKeyboardShown(boolean softKeyboardShown) {
mSoftKeyboardShown = softKeyboardShown;
}
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxGLSurfaceView(final Context context) {
super(context);
initView();
}
public Cocos2dxGLSurfaceView(final Context context, final AttributeSet attrs) {
super(context, attrs);
initView();
}
static class IMEHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case HANDLER_OPEN_IME_KEYBOARD:
if (null != sGLSurfaceView.mCocosEditText && sGLSurfaceView.mCocosEditText.requestFocus()) {
sGLSurfaceView.mCocosEditText.removeTextChangedListener(Cocos2dxGLSurfaceView.sTextInputWrapper);
sGLSurfaceView.mCocosEditText.setText("");
final String text = (String) msg.obj;
sGLSurfaceView.mCocosEditText.append(text);
Cocos2dxGLSurfaceView.sTextInputWrapper.setOriginText(text);
sGLSurfaceView.mCocosEditText.addTextChangedListener(Cocos2dxGLSurfaceView.sTextInputWrapper);
InputMethodManager imm = (InputMethodManager) Cocos2dxActivity.COCOS_ACTIVITY.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(sGLSurfaceView.mCocosEditText, 0);
Log.d(TAG, "showSoftInput");
}
break;
case HANDLER_CLOSE_IME_KEYBOARD:
if (null != sGLSurfaceView.mCocosEditText) {
sGLSurfaceView.mCocosEditText.removeTextChangedListener(Cocos2dxGLSurfaceView.sTextInputWrapper);
InputMethodManager imm = (InputMethodManager) Cocos2dxActivity.COCOS_ACTIVITY.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(sGLSurfaceView.mCocosEditText.getWindowToken(), 0);
sGLSurfaceView.requestFocus();
Log.d(TAG, "HideSoftInput");
}
break;
}
}
}
protected void initView() {
setEGLContextClientVersion(2);
setFocusableInTouchMode(true);
sGLSurfaceView = this;
sTextInputWrapper = new Cocos2dxTextInputWrapper(this);
sIMEHandler = new IMEHandler();
}
// ===========================================================
// Getter & Setter
// ===========================================================
public static Cocos2dxGLSurfaceView getInstance() {
return sGLSurfaceView;
}
public static void queueAccelerometer(final float x, final float y, final float z, final long timestamp) {
sGLSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
Cocos2dxAccelerometer.onSensorChanged(x, y, z, timestamp);
}
});
}
public void setCocos2dxRenderer(final Cocos2dxRenderer renderer) {
mCocosRenderer = renderer;
setRenderer(mCocosRenderer);
}
public Cocos2dxRenderer getCocos2dxRenderer() {
return mCocosRenderer;
}
private String getContentText() {
return mCocosRenderer.getContentText();
}
public Cocos2dxEditBox getCocos2dxEditText() {
return mCocosEditText;
}
public void setCocos2dxEditText(final Cocos2dxEditBox cocos2dxEditText) {
mCocosEditText = cocos2dxEditText;
if (null != mCocosEditText && null != sTextInputWrapper) {
mCocosEditText.setOnEditorActionListener(sTextInputWrapper);
requestFocus();
}
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onResume() {
super.onResume();
setRenderMode(RENDERMODE_CONTINUOUSLY);
queueEvent(new Runnable() {
@Override
public void run() {
sGLSurfaceView.mCocosRenderer.handleOnResume();
}
});
}
@Override
public void onPause() {
queueEvent(new Runnable() {
@Override
public void run() {
sGLSurfaceView.mCocosRenderer.handleOnPause();
}
});
setRenderMode(RENDERMODE_WHEN_DIRTY);
//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];
if (mSoftKeyboardShown){
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
View view = ((Activity)getContext()).getCurrentFocus();
if (view != null)
imm.hideSoftInputFromWindow(view.getWindowToken(),0);
requestFocus();
mSoftKeyboardShown = false;
}
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_INDEX_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() {
sGLSurfaceView.mCocosRenderer.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() {
sGLSurfaceView.mCocosRenderer.handleActionDown(idDown, xDown, yDown);
}
});
break;
case MotionEvent.ACTION_MOVE:
this.queueEvent(new Runnable() {
@Override
public void run() {
sGLSurfaceView.mCocosRenderer.handleActionMove(ids, xs, ys);
}
});
break;
case MotionEvent.ACTION_POINTER_UP:
final int indexPointUp = pMotionEvent.getAction() >> MotionEvent.ACTION_POINTER_INDEX_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() {
sGLSurfaceView.mCocosRenderer.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() {
sGLSurfaceView.mCocosRenderer.handleActionUp(idUp, xUp, yUp);
}
});
break;
case MotionEvent.ACTION_CANCEL:
this.queueEvent(new Runnable() {
@Override
public void run() {
sGLSurfaceView.mCocosRenderer.handleActionCancel(ids, xs, ys);
}
});
break;
}
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(!isInEditMode()) {
mCocosRenderer.setScreenWidthAndHeight(pNewSurfaceWidth, pNewSurfaceHeight);
}
}
@Override
public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
switch (pKeyCode) {
case KeyEvent.KEYCODE_BACK:
Cocos2dxVideoHelper.sVideoHandler.sendEmptyMessage(Cocos2dxVideoHelper.KeyEventBack);
case KeyEvent.KEYCODE_MENU:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_DPAD_CENTER:
this.queueEvent(new Runnable() {
@Override
public void run() {
sGLSurfaceView.mCocosRenderer.handleKeyDown(pKeyCode);
}
});
return true;
default:
return super.onKeyDown(pKeyCode, pKeyEvent);
}
}
@Override
public boolean onKeyUp(final int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
case KeyEvent.KEYCODE_MENU:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_DPAD_CENTER:
this.queueEvent(new Runnable() {
@Override
public void run() {
sGLSurfaceView.mCocosRenderer.handleKeyUp(keyCode);
}
});
return true;
default:
return super.onKeyUp(keyCode, event);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static void openIMEKeyboard() {
Message msg = Message.obtain();
msg.what = HANDLER_OPEN_IME_KEYBOARD;
msg.obj = sGLSurfaceView.getContentText();
sIMEHandler.sendMessage(msg);
}
public static void closeIMEKeyboard() {
Message msg = Message.obtain();
msg.what = HANDLER_CLOSE_IME_KEYBOARD;
sIMEHandler.sendMessage(msg);
}
public void insertText(final String text) {
this.queueEvent(new Runnable() {
@Override
public void run() {
sGLSurfaceView.mCocosRenderer.handleInsertText(text);
}
});
}
public void deleteBackward() {
this.queueEvent(new Runnable() {
@Override
public void run() {
sGLSurfaceView.mCocosRenderer.handleDeleteBackward();
}
});
}
}
@@ -1,97 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import java.lang.ref.WeakReference;
public class Cocos2dxHandler extends Handler {
// ===========================================================
// Constants
// ===========================================================
public final static int HANDLER_SHOW_DIALOG = 1;
// ===========================================================
// Fields
// ===========================================================
private WeakReference<Activity> mActivityReference;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxHandler(Activity activity) {
mActivityReference = new WeakReference<Activity>(activity);
}
// ===========================================================
// Methods
// ===========================================================
public void handleMessage(Message msg) {
switch (msg.what) {
case Cocos2dxHandler.HANDLER_SHOW_DIALOG:
showDialog(msg);
break;
}
}
private void showDialog(Message msg) {
Activity theActivity = mActivityReference.get();
DialogMessage dialogMessage = (DialogMessage)msg.obj;
new AlertDialog.Builder(theActivity)
.setTitle(dialogMessage.mTitle)
.setMessage(dialogMessage.mMessage)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).create().show();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static class DialogMessage {
public String mTitle;
public String mMessage;
public DialogMessage(String title, String message) {
mTitle = title;
mMessage = message;
}
}
}
@@ -1,526 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;
import android.preference.PreferenceManager.OnActivityResultListener;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
public class Cocos2dxHelper {
private static final String PREFS_NAME = "Cocos2dxPrefsFile";
private static final int RUNNABLES_PER_FRAME = 5;
// ===========================================================
// Fields
// ===========================================================
private static Cocos2dxMusic sCocosMusic;
private static Cocos2dxSound sCocosSound;
private static AssetManager sAssetManager;
private static Cocos2dxAccelerometer sAccelerometer;
private static boolean sAccelerometerEnabled;
private static boolean sActivityVisible;
private static String sPackageName;
private static String sFileDirectory;
private static Set<OnActivityResultListener> onActivityResultListeners = new LinkedHashSet<OnActivityResultListener>();
private static Vibrator sVibrateService = null;
public static void runOnGLThread(final Runnable r) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(r);
}
private static boolean sInited = false;
public static void init(final Activity activity) {
if (!sInited) {
final ApplicationInfo applicationInfo = activity.getApplicationInfo();
sPackageName = applicationInfo.packageName;
sFileDirectory = activity.getFilesDir().getAbsolutePath();
nativeSetApkPath(applicationInfo.sourceDir);
sAccelerometer = new Cocos2dxAccelerometer(activity);
sCocosMusic = new Cocos2dxMusic(activity);
sCocosSound = new Cocos2dxSound(activity);
sAssetManager = activity.getAssets();
nativeSetContext(activity.getClass().getClassLoader(), sAssetManager);
sVibrateService = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);
sInited = true;
}
}
public static Activity getActivity() {
return Cocos2dxActivity.COCOS_ACTIVITY;
}
public static void addOnActivityResultListener(OnActivityResultListener listener) {
onActivityResultListeners.add(listener);
}
public static Set<OnActivityResultListener> getOnActivityResultListeners() {
return onActivityResultListeners;
}
public static boolean isActivityVisible(){
return sActivityVisible;
}
// ===========================================================
// Methods
// ===========================================================
private static native void nativeSetApkPath(final String pApkPath);
private static native void nativeSetEditTextDialogResult(final byte[] pBytes);
private static native void nativeSetContext(final ClassLoader classLoader, final AssetManager pAssetManager);
public static String getCocos2dxPackageName() {
return Cocos2dxHelper.sPackageName;
}
public static String getCocos2dxWritablePath() {
return Cocos2dxHelper.sFileDirectory;
}
public static String getCurrentLanguage() {
return Locale.getDefault().getLanguage();
}
public static String getDeviceModel(){
return Build.MODEL;
}
public static int getSDKVersion() {
return Build.VERSION.SDK_INT;
}
public static AssetManager getAssetManager() {
return Cocos2dxHelper.sAssetManager;
}
public static void enableAccelerometer() {
if (sAccelerometer != null) {
sAccelerometerEnabled = true;
sAccelerometer.enable();
}
}
public static void setAccelerometerInterval(float interval) {
if (sAccelerometer != null) {
sAccelerometer.setInterval(interval);
}
}
public static void disableAccelerometer() {
if (sAccelerometer != null) {
sAccelerometerEnabled = false;
sAccelerometer.disable();
}
}
public static void setKeepScreenOn(boolean value) {
Cocos2dxActivity.COCOS_ACTIVITY.setKeepScreenOn(value);
}
public static void vibrate(float duration) {
if (sVibrateService != null)
sVibrateService.vibrate((long)(duration * 1000));
}
public static boolean openURL(String url) {
boolean ret = false;
try {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
Cocos2dxActivity.COCOS_ACTIVITY.startActivity(i);
ret = true;
} catch (Exception e) {
}
return ret;
}
public static void preloadBackgroundMusic(final String pPath) {
sCocosMusic.preloadBackgroundMusic(pPath);
}
public static void playBackgroundMusic(final String pPath, final boolean isLoop) {
sCocosMusic.playBackgroundMusic(pPath, isLoop);
}
public static void resumeBackgroundMusic() {
sCocosMusic.resumeBackgroundMusic();
}
public static void pauseBackgroundMusic() {
sCocosMusic.pauseBackgroundMusic();
}
public static void stopBackgroundMusic() {
sCocosMusic.stopBackgroundMusic();
}
public static void rewindBackgroundMusic() {
sCocosMusic.rewindBackgroundMusic();
}
public static boolean isBackgroundMusicPlaying() {
return sCocosMusic.isBackgroundMusicPlaying();
}
public static float getBackgroundMusicVolume() {
return sCocosMusic.getBackgroundVolume();
}
public static void setBackgroundMusicVolume(final float volume) {
sCocosMusic.setBackgroundVolume(volume);
}
public static void preloadEffect(final String path) {
sCocosSound.preloadEffect(path);
}
public static int playEffect(final String path, final boolean isLoop, final float pitch, final float pan, final float gain) {
return sCocosSound.playEffect(path, isLoop, pitch, pan, gain);
}
public static void resumeEffect(final int soundId) {
sCocosSound.resumeEffect(soundId);
}
public static void pauseEffect(final int soundId) {
sCocosSound.pauseEffect(soundId);
}
public static void stopEffect(final int soundId) {
sCocosSound.stopEffect(soundId);
}
public static float getEffectsVolume() {
return sCocosSound.getEffectsVolume();
}
public static void setEffectsVolume(final float volume) {
sCocosSound.setEffectsVolume(volume);
}
public static void unloadEffect(final String path) {
sCocosSound.unloadEffect(path);
}
public static void pauseAllEffects() {
sCocosSound.pauseAllEffects();
}
public static void resumeAllEffects() {
sCocosSound.resumeAllEffects();
}
public static void stopAllEffects() {
sCocosSound.stopAllEffects();
}
public static void destoryAudioEngine() {
if (sCocosMusic != null)
{
sCocosMusic.end();
sCocosMusic = null;
}
if (sCocosSound != null)
{
sCocosSound.end();
sCocosSound = null;
}
}
public static void reset() {
destoryAudioEngine();
onActivityResultListeners.clear();
if (sAccelerometer != null) {
disableAccelerometer();
sAccelerometer = null;
}
sVibrateService = null;
}
public static void onResume() {
sActivityVisible = true;
if (sAccelerometerEnabled) {
sAccelerometer.enable();
}
}
public static void onPause() {
sActivityVisible = false;
if (sAccelerometerEnabled) {
sAccelerometer.disable();
}
}
public static void onEnterBackground() {
if (sCocosSound != null) {
sCocosSound.onEnterBackground();
}
if (sCocosMusic != null) {
sCocosMusic.onEnterBackground();
}
}
public static void onEnterForeground() {
if (sCocosSound != null) {
sCocosSound.onEnterForeground();
}
if (sCocosMusic != null) {
sCocosMusic.onEnterForeground();
}
}
public static void terminateProcess() {
android.os.Process.killProcess(android.os.Process.myPid());
}
private static void showDialog(final String pTitle, final String pMessage) {
Cocos2dxActivity.COCOS_ACTIVITY.showDialog(pTitle, pMessage);
}
public static void setEditTextDialogResult(final String pResult) {
try {
final byte[] bytesUTF8 = pResult.getBytes("UTF8");
Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxHelper.nativeSetEditTextDialogResult(bytesUTF8);
}
});
} catch (UnsupportedEncodingException pUnsupportedEncodingException) {
/* Nothing. */
}
}
public static int getDPI()
{
if (Cocos2dxActivity.COCOS_ACTIVITY != null)
{
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = Cocos2dxActivity.COCOS_ACTIVITY.getWindowManager();
if (wm != null)
{
Display d = wm.getDefaultDisplay();
if (d != null)
{
d.getMetrics(metrics);
return (int)(metrics.density*160.0f);
}
}
}
return -1;
}
// ===========================================================
// Functions for CCUserDefault
// ===========================================================
public static boolean getBoolForKey(String key, boolean defaultValue) {
SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
try {
return settings.getBoolean(key, defaultValue);
}
catch (Exception ex) {
ex.printStackTrace();
Map allValues = settings.getAll();
Object value = allValues.get(key);
if ( value instanceof String)
{
return Boolean.parseBoolean(value.toString());
}
else if (value instanceof Integer)
{
int intValue = ((Integer) value).intValue();
return (intValue != 0) ;
}
else if (value instanceof Float)
{
float floatValue = ((Float) value).floatValue();
return (floatValue != 0.0f);
}
}
return false;
}
public static int getIntegerForKey(String key, int defaultValue) {
SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
try {
return settings.getInt(key, defaultValue);
}
catch (Exception ex) {
ex.printStackTrace();
Map allValues = settings.getAll();
Object value = allValues.get(key);
if ( value instanceof String) {
return Integer.parseInt(value.toString());
}
else if (value instanceof Float)
{
return ((Float) value).intValue();
}
else if (value instanceof Boolean)
{
boolean booleanValue = ((Boolean) value).booleanValue();
if (booleanValue)
return 1;
}
}
return 0;
}
public static float getFloatForKey(String key, float defaultValue) {
SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
try {
return settings.getFloat(key, defaultValue);
}
catch (Exception ex) {
ex.printStackTrace();;
Map allValues = settings.getAll();
Object value = allValues.get(key);
if ( value instanceof String) {
return Float.parseFloat(value.toString());
}
else if (value instanceof Integer)
{
return ((Integer) value).floatValue();
}
else if (value instanceof Boolean)
{
boolean booleanValue = ((Boolean) value).booleanValue();
if (booleanValue)
return 1.0f;
}
}
return 0.0f;
}
public static double getDoubleForKey(String key, double defaultValue) {
// SharedPreferences doesn't support saving double value
return getFloatForKey(key, (float) defaultValue);
}
public static String getStringForKey(String key, String defaultValue) {
SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
try {
return settings.getString(key, defaultValue);
}
catch (Exception ex) {
ex.printStackTrace();
return settings.getAll().get(key).toString();
}
}
public static void setBoolForKey(String key, boolean value) {
SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static void setIntegerForKey(String key, int value) {
SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(key, value);
editor.commit();
}
public static void setFloatForKey(String key, float value) {
SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putFloat(key, value);
editor.commit();
}
public static void setDoubleForKey(String key, double value) {
// SharedPreferences doesn't support recording double value
SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putFloat(key, (float)value);
editor.commit();
}
public static void setStringForKey(String key, String value) {
SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor.commit();
}
public static void deleteValueForKey(String key) {
SharedPreferences settings = Cocos2dxActivity.COCOS_ACTIVITY.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.remove(key);
editor.commit();
}
public static byte[] conversionEncoding(byte[] text, String fromCharset,String newCharset)
{
try {
String str = new String(text,fromCharset);
return str.getBytes(newCharset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
@@ -1,405 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2014 cocos2d-x.org
Copyright (c) 2014-2016 Chukong Technologies Inc.
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.util.Log;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
public class Cocos2dxHttpURLConnection
{
private static final String POST_METHOD = "POST" ;
private static final String PUT_METHOD = "PUT" ;
static HttpURLConnection createHttpURLConnection(String linkURL) {
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(linkURL);
urlConnection = (HttpURLConnection) url.openConnection();
//Accept-Encoding
urlConnection.setRequestProperty("Accept-Encoding", "identity");
urlConnection.setDoInput(true);
} catch (Exception e) {
Log.e("URLConnection exception", e.toString());
return null;
}
return urlConnection;
}
static void setReadAndConnectTimeout(HttpURLConnection urlConnection, int readMiliseconds, int connectMiliseconds) {
urlConnection.setReadTimeout(readMiliseconds);
urlConnection.setConnectTimeout(connectMiliseconds);
}
static void setRequestMethod(HttpURLConnection urlConnection, String method){
try {
urlConnection.setRequestMethod(method);
if(method.equalsIgnoreCase(POST_METHOD) || method.equalsIgnoreCase(PUT_METHOD)) {
urlConnection.setDoOutput(true);
}
} catch (ProtocolException e) {
Log.e("URLConnection exception", e.toString());
}
}
static void setVerifySSL(HttpURLConnection urlConnection, String sslFilename) {
if(!(urlConnection instanceof HttpsURLConnection))
return;
HttpsURLConnection httpsURLConnection = (HttpsURLConnection)urlConnection;
try {
InputStream caInput = null;
if (sslFilename.startsWith("/")) {
caInput = new BufferedInputStream(new FileInputStream(sslFilename));
}else {
String assetString = "assets/";
String assetsFileName = sslFilename.substring(assetString.length());
caInput = new BufferedInputStream(Cocos2dxActivity.COCOS_ACTIVITY.getAssets().open(assetsFileName));
}
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate ca;
ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
caInput.close();
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
httpsURLConnection.setSSLSocketFactory(context.getSocketFactory());
} catch (Exception e) {
Log.e("URLConnection exception", e.toString());
}
}
//Add header
static void addRequestHeader(HttpURLConnection urlConnection, String key, String value) {
urlConnection.setRequestProperty(key, value);
}
static int connect(HttpURLConnection http) {
int suc = 0;
try {
http.connect();
} catch (IOException e) {
Log.e("cocos2d-x debug info", "come in connect");
Log.e("cocos2d-x debug info", e.toString());
suc = 1;
}
return suc;
}
static void disconnect(HttpURLConnection http) {
http.disconnect();
}
static void sendRequest(HttpURLConnection http, byte[] byteArray) {
try {
OutputStream out = http.getOutputStream();
if(null != byteArray) {
out.write(byteArray);
out.flush();
}
out.close();
} catch (IOException e) {
Log.e("URLConnection exception", e.toString());
}
}
static String getResponseHeaders(HttpURLConnection http) {
Map<String, List<String>> headers = http.getHeaderFields();
if (null == headers) {
return null;
}
String header = "";
for (Entry<String, List<String>> entry: headers.entrySet()) {
String key = entry.getKey();
if (null == key) {
header += listToString(entry.getValue(), ",") + "\n";
} else {
header += key + ":" + listToString(entry.getValue(), ",") + "\n";
}
}
return header;
}
static String getResponseHeaderByIdx(HttpURLConnection http, int idx) {
Map<String, List<String>> headers = http.getHeaderFields();
if (null == headers) {
return null;
}
String header = null;
int counter = 0;
for (Entry<String, List<String>> entry: headers.entrySet()) {
if (counter == idx) {
String key = entry.getKey();
if (null == key) {
header = listToString(entry.getValue(), ",") + "\n";
} else {
header = key + ":" + listToString(entry.getValue(), ",") + "\n";
}
break;
}
counter++;
}
return header;
}
static String getResponseHeaderByKey(HttpURLConnection http, String key) {
if (null == key) {
return null;
}
Map<String, List<String>> headers = http.getHeaderFields();
if (null == headers) {
return null;
}
String header = null;
for (Entry<String, List<String>> entry: headers.entrySet()) {
if (key.equalsIgnoreCase(entry.getKey())) {
if ("set-cookie".equalsIgnoreCase(key)) {
header = combinCookies(entry.getValue(), http.getURL().getHost());
} else {
header = listToString(entry.getValue(), ",");
}
break;
}
}
return header;
}
static int getResponseHeaderByKeyInt(HttpURLConnection http, String key) {
String value = http.getHeaderField(key);
if (null == value) {
return 0;
} else {
return Integer.parseInt(value);
}
}
static byte[] getResponseContent(HttpURLConnection http) {
InputStream in;
try {
in = http.getInputStream();
String contentEncoding = http.getContentEncoding();
if (contentEncoding != null) {
if(contentEncoding.equalsIgnoreCase("gzip")){
in = new GZIPInputStream(http.getInputStream()); //reads 2 bytes to determine GZIP stream!
}
else if(contentEncoding.equalsIgnoreCase("deflate")){
in = new InflaterInputStream(http.getInputStream());
}
}
} catch (IOException e) {
in = http.getErrorStream();
} catch (Exception e) {
Log.e("URLConnection exception", e.toString());
return null;
}
try {
byte[] buffer = new byte[1024];
int size = 0;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
while((size = in.read(buffer, 0 , 1024)) != -1)
{
byteStream.write(buffer, 0, size);
}
byte retBuffer[] = byteStream.toByteArray();
byteStream.close();
return retBuffer;
} catch (Exception e) {
Log.e("URLConnection exception", e.toString());
}
return null;
}
static int getResponseCode(HttpURLConnection http) {
int code = 0;
try {
code = http.getResponseCode();
} catch (IOException e) {
Log.e("URLConnection exception", e.toString());
}
return code;
}
static String getResponseMessage(HttpURLConnection http) {
String msg;
try {
msg = http.getResponseMessage();
} catch (IOException e) {
msg = e.toString();
Log.e("URLConnection exception", msg);
}
return msg;
}
public static String listToString(List<String> list, String strInterVal) {
if (list == null) {
return null;
}
StringBuilder result = new StringBuilder();
boolean flag = false;
for (String str : list) {
if (flag) {
result.append(strInterVal);
}
if (null == str) {
str = "";
}
result.append(str);
flag = true;
}
return result.toString();
}
public static String combinCookies(List<String> list, String hostDomain) {
StringBuilder sbCookies = new StringBuilder();
String domain = hostDomain;
String tailMatch = "FALSE";
String path = "/";
String secure = "FALSE";
String key = null;
String value = null;
String expires = null;
for (String str : list) {
String[] parts = str.split(";");
for (String part : parts) {
int firstIndex = part.indexOf("=");
if (-1 == firstIndex)
continue;
String[] item = {part.substring(0, firstIndex), part.substring(firstIndex + 1)};
if ("expires".equalsIgnoreCase(item[0].trim())) {
expires = str2Seconds(item[1].trim());
} else if("path".equalsIgnoreCase(item[0].trim())) {
path = item[1];
} else if("secure".equalsIgnoreCase(item[0].trim())) {
secure = item[1];
} else if("domain".equalsIgnoreCase(item[0].trim())) {
domain = item[1];
} else if("version".equalsIgnoreCase(item[0].trim()) || "max-age".equalsIgnoreCase(item[0].trim())) {
//do nothing
} else {
key = item[0];
value = item[1];
}
}
if (null == domain) {
domain = "none";
}
sbCookies.append(domain);
sbCookies.append('\t');
sbCookies.append(tailMatch); //access
sbCookies.append('\t');
sbCookies.append(path); //path
sbCookies.append('\t');
sbCookies.append(secure); //secure
sbCookies.append('\t');
sbCookies.append(expires); //expires
sbCookies.append("\t");
sbCookies.append(key); //key
sbCookies.append("\t");
sbCookies.append(value); //value
sbCookies.append('\n');
}
return sbCookies.toString();
}
private static String str2Seconds(String strTime) {
Calendar c = Calendar.getInstance();
long millisSecond = 0;
try {
c.setTime(new SimpleDateFormat("EEE, dd-MMM-yy hh:mm:ss zzz", Locale.US).parse(strTime));
millisSecond = c.getTimeInMillis()/1000;
} catch (ParseException e) {
Log.e("URLConnection exception", e.toString());
}
return Long.toString(millisSecond);
}
}
@@ -1,128 +0,0 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Cocos2dxLocalStorage {
private static final String TAG = "Cocos2dxLocalStorage";
private static String DATABASE_NAME = "jsb.sqlite";
private static String TABLE_NAME = "data";
private static final int DATABASE_VERSION = 1;
private static DBOpenHelper mDatabaseOpenHelper = null;
private static SQLiteDatabase mDatabase = null;
public static boolean init(String dbName, String tableName) {
if (Cocos2dxActivity.COCOS_ACTIVITY != null) {
DATABASE_NAME = dbName;
TABLE_NAME = tableName;
mDatabaseOpenHelper = new DBOpenHelper(Cocos2dxActivity.COCOS_ACTIVITY);
mDatabase = mDatabaseOpenHelper.getWritableDatabase();
return true;
}
return false;
}
public static void destory() {
if (mDatabase != null) {
mDatabase.close();
}
}
public static void setItem(String key, String value) {
try {
String sql = "replace into "+TABLE_NAME+"(key,value)values(?,?)";
mDatabase.execSQL(sql, new Object[] { key, value });
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getItem(String key) {
String ret = null;
try {
String sql = "select value from "+TABLE_NAME+" where key=?";
Cursor c = mDatabase.rawQuery(sql, new String[]{key});
while (c.moveToNext()) {
// only return the first value
if (ret != null)
{
Log.e(TAG, "The key contains more than one value.");
break;
}
ret = c.getString(c.getColumnIndex("value"));
}
c.close();
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
public static void removeItem(String key) {
try {
String sql = "delete from "+TABLE_NAME+" where key=?";
mDatabase.execSQL(sql, new Object[] {key});
} catch (Exception e) {
e.printStackTrace();
}
}
public static void clear() {
try {
String sql = "delete from "+TABLE_NAME;
mDatabase.execSQL(sql);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This creates/opens the database.
*/
private static class DBOpenHelper extends SQLiteOpenHelper {
DBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS "+TABLE_NAME+"(key TEXT PRIMARY KEY,value TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
@@ -1,238 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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;
import java.io.FileInputStream;
public class Cocos2dxMusic {
private static final String TAG = "Cocos2dxMusic";
// ===========================================================
// Fields
// ===========================================================
private final Context mContext;
private MediaPlayer mBackgroundMediaPlayer;
private float mLeftVolume;
private float mRightVolume;
private boolean mPaused; // whether music is paused state.
private boolean mIsLoop = false;
private boolean mManualPaused = false; // whether music is paused manually before the program is switched to the background.
private String mCurrentPath;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxMusic(final Context context) {
mContext = context;
initData();
}
public void preloadBackgroundMusic(final String path) {
if ((this.mCurrentPath == null) || (!this.mCurrentPath.equals(path))) {
// release old resource and create a new one
if (mBackgroundMediaPlayer != null) {
mBackgroundMediaPlayer.release();
}
mBackgroundMediaPlayer = createMediaPlayer(path);
mCurrentPath = path;
}
}
public void playBackgroundMusic(final String path, final boolean isLoop) {
if (mCurrentPath == null) {
// it is the first time to play background music or end() was called
mBackgroundMediaPlayer = createMediaPlayer(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 = createMediaPlayer(path);
// record the path
mCurrentPath = path;
}
}
if (mBackgroundMediaPlayer == null) {
Log.e(Cocos2dxMusic.TAG, "playBackgroundMusic: background media player is null");
} else {
try {
// if the music is playing or paused, stop it
if (mPaused) {
mBackgroundMediaPlayer.seekTo(0);
mBackgroundMediaPlayer.start();
} else if (mBackgroundMediaPlayer.isPlaying()) {
mBackgroundMediaPlayer.seekTo(0);
} else {
mBackgroundMediaPlayer.start();
}
mBackgroundMediaPlayer.setLooping(isLoop);
mPaused = false;
mIsLoop = isLoop;
} catch (final Exception e) {
Log.e(Cocos2dxMusic.TAG, "playBackgroundMusic: error state");
}
}
}
public void stopBackgroundMusic() {
if (mBackgroundMediaPlayer != null) {
mBackgroundMediaPlayer.release();
mBackgroundMediaPlayer = createMediaPlayer(mCurrentPath);
/**
* should set the state, if not, the following sequence will be error
* play -> pause -> stop -> resume
*/
this.mPaused = false;
}
}
public void pauseBackgroundMusic() {
if (mBackgroundMediaPlayer != null && mBackgroundMediaPlayer.isPlaying()) {
mBackgroundMediaPlayer.pause();
mPaused = true;
mManualPaused = true;
}
}
public void resumeBackgroundMusic() {
if (mBackgroundMediaPlayer != null && this.mPaused) {
mBackgroundMediaPlayer.start();
mPaused = false;
mManualPaused = false;
}
}
public void rewindBackgroundMusic() {
if (mBackgroundMediaPlayer != null) {
playBackgroundMusic(mCurrentPath, mIsLoop);
}
}
public boolean isBackgroundMusicPlaying() {
boolean ret = false;
if (mBackgroundMediaPlayer != null) {
ret = mBackgroundMediaPlayer.isPlaying();
}
return ret;
}
public void end() {
if (mBackgroundMediaPlayer != null) {
mBackgroundMediaPlayer.release();
}
initData();
}
public float getBackgroundVolume() {
if (mBackgroundMediaPlayer != null) {
return (mLeftVolume + 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;
}
mLeftVolume = mRightVolume = volume;
if (mBackgroundMediaPlayer != null) {
mBackgroundMediaPlayer.setVolume(mLeftVolume, mRightVolume);
}
}
public void onEnterBackground(){
if (mBackgroundMediaPlayer != null && mBackgroundMediaPlayer.isPlaying()) {
mBackgroundMediaPlayer.pause();
mPaused = true;
}
}
public void onEnterForeground(){
if(!mManualPaused){
if (mBackgroundMediaPlayer != null && mPaused) {
mBackgroundMediaPlayer.start();
mPaused = false;
}
}
}
private void initData() {
mLeftVolume = 0.5f;
mRightVolume = 0.5f;
mBackgroundMediaPlayer = null;
mPaused = false;
mCurrentPath = null;
}
private MediaPlayer createMediaPlayer(final String path) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
if (path.startsWith("/")) {
final FileInputStream fis = new FileInputStream(path);
mediaPlayer.setDataSource(fis.getFD());
fis.close();
} else {
final AssetFileDescriptor assetFileDescritor = this.mContext.getAssets().openFd(path);
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;
}
}
@@ -1,178 +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.opengl.GLSurfaceView;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
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 = 0;
private int mScreenWidth = 0;
private int mScreenHeight = 0;
private boolean mNativeInitCompleted = false;
// ===========================================================
// Getter & Setter
// ===========================================================
public static void setAnimationInterval(final float animationInterval) {
Cocos2dxRenderer.sAnimationInterval = (long) (animationInterval * Cocos2dxRenderer.NANOSECONDSPERSECOND);
}
public void setScreenWidthAndHeight(final int surfaceWidth, final int surfaceHeight) {
mScreenWidth = surfaceWidth;
mScreenHeight = surfaceHeight;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onSurfaceCreated(final GL10 GL10, final EGLConfig EGLConfig) {
Cocos2dxRenderer.nativeInit(mScreenWidth, mScreenHeight);
mLastTickInNanoSeconds = System.nanoTime();
mNativeInitCompleted = true;
}
@Override
public void onSurfaceChanged(final GL10 GL10, final int width, final int height) {
Cocos2dxRenderer.nativeOnSurfaceChanged(width, height);
}
@Override
public void onDrawFrame(final GL10 gl) {
/*
* No need to use algorithm in default(60 FPS) situation,
* since onDrawFrame() was called by system 60 times per second by default.
*/
if (sAnimationInterval <= 1.0 / 60 * Cocos2dxRenderer.NANOSECONDSPERSECOND) {
Cocos2dxRenderer.nativeRender();
} else {
final long now = System.nanoTime();
final long interval = now - this.mLastTickInNanoSeconds;
if (interval < Cocos2dxRenderer.sAnimationInterval) {
try {
Thread.sleep((Cocos2dxRenderer.sAnimationInterval - interval) / Cocos2dxRenderer.NANOSECONDSPERMICROSECOND);
} catch (final Exception e) {
}
}
/*
* Render time MUST be counted in, or the FPS will slower than appointed.
*/
mLastTickInNanoSeconds = System.nanoTime();
Cocos2dxRenderer.nativeRender();
}
}
// ===========================================================
// Methods
// ===========================================================
private static native void nativeTouchesBegin(final int id, final float x, final float y);
private static native void nativeTouchesEnd(final int id, final float x, final float y);
private static native void nativeTouchesMove(final int[] ids, final float[] xs, final float[] ys);
private static native void nativeTouchesCancel(final int[] ids, final float[] xs, final float[] ys);
private static native boolean nativeKeyEvent(final int keyCode,boolean isPressed);
private static native void nativeRender();
private static native void nativeInit(final int width, final int height);
private static native void nativeOnSurfaceChanged(final int width, final int height);
private static native void nativeOnPause();
private static native void nativeOnResume();
public void handleActionDown(final int id, final float x, final float y) {
Cocos2dxRenderer.nativeTouchesBegin(id, x, y);
}
public void handleActionUp(final int id, final float x, final float y) {
Cocos2dxRenderer.nativeTouchesEnd(id, x, y);
}
public void handleActionCancel(final int[] ids, final float[] xs, final float[] ys) {
Cocos2dxRenderer.nativeTouchesCancel(ids, xs, ys);
}
public void handleActionMove(final int[] ids, final float[] xs, final float[] ys) {
Cocos2dxRenderer.nativeTouchesMove(ids, xs, ys);
}
public void handleKeyDown(final int keyCode) {
Cocos2dxRenderer.nativeKeyEvent(keyCode, true);
}
public void handleKeyUp(final int keyCode) {
Cocos2dxRenderer.nativeKeyEvent(keyCode, false);
}
public void handleOnPause() {
/**
* onPause may be invoked before onSurfaceCreated,
* and engine will be initialized correctly after
* onSurfaceCreated is invoked. Can not invoke any
* native method before onSurfaceCreated is invoked
*/
if (! mNativeInitCompleted)
return;
Cocos2dxHelper.onEnterBackground();
Cocos2dxRenderer.nativeOnPause();
}
public void handleOnResume() {
Cocos2dxHelper.onEnterForeground();
Cocos2dxRenderer.nativeOnResume();
}
private static native void nativeInsertText(final String text);
private static native void nativeDeleteBackward();
private static native String nativeGetContentText();
public void handleInsertText(final String text) {
Cocos2dxRenderer.nativeInsertText(text);
}
public void handleDeleteBackward() {
Cocos2dxRenderer.nativeDeleteBackward();
}
public String getContentText() {
return Cocos2dxRenderer.nativeGetContentText();
}
}
@@ -1,360 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
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 ConcurrentHashMap<Integer, SoundInfoForLoadedCompleted> mPlayWhenLoadedEffects =
new ConcurrentHashMap<Integer, SoundInfoForLoadedCompleted>();
private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5;
private static final int MAX_SIMULTANEOUS_STREAMS_I9100 = 3;
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;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxSound(final Context context) {
mContext = context;
initData();
}
private void initData() {
if (Cocos2dxHelper.getDeviceModel().contains("GT-I9100")) {
mSoundPool = new SoundPool(Cocos2dxSound.MAX_SIMULTANEOUS_STREAMS_I9100, AudioManager.STREAM_MUSIC, Cocos2dxSound.SOUND_QUALITY);
}
else {
mSoundPool = new SoundPool(Cocos2dxSound.MAX_SIMULTANEOUS_STREAMS_DEFAULT, AudioManager.STREAM_MUSIC, Cocos2dxSound.SOUND_QUALITY);
}
mSoundPool.setOnLoadCompleteListener(new OnLoadCompletedListener());
mLeftVolume = 0.5f;
mRightVolume = 0.5f;
}
public int preloadEffect(final String path) {
Integer soundID = mPathSoundIDMap.get(path);
if (soundID == null) {
soundID = createSoundIDFromAsset(path);
// save value just in case if file is really loaded
if (soundID != Cocos2dxSound.INVALID_SOUND_ID) {
mPathSoundIDMap.put(path, soundID);
}
}
return soundID;
}
public void unloadEffect(final String path) {
// stop effects
final ArrayList<Integer> streamIDs = mPathStreamIDsMap.get(path);
if (streamIDs != null) {
for (final Integer steamID : streamIDs) {
mSoundPool.stop(steamID);
}
}
mPathStreamIDsMap.remove(path);
// unload effect
final Integer soundID = mPathSoundIDMap.get(path);
if(soundID != null){
mSoundPool.unload(soundID);
mPathSoundIDMap.remove(path);
}
}
private static final int LOAD_TIME_OUT = 500;
public int playEffect(final String path, final boolean loop, float pitch, float pan, float gain)
{
int streamID;
Integer soundID = mPathSoundIDMap.get(path);
if (soundID != null) {
// parameters; pan = -1 for left channel, 1 for right channel, 0 for both channels
// play sound
streamID = doPlayEffect(path, soundID, loop, pitch, pan, gain);
} else {
// the effect is not prepared
soundID = preloadEffect(path);
if (soundID == Cocos2dxSound.INVALID_SOUND_ID) {
// can not preload effect
return Cocos2dxSound.INVALID_SOUND_ID;
}
SoundInfoForLoadedCompleted info = new SoundInfoForLoadedCompleted(path, loop, pitch, pan, gain);
mPlayWhenLoadedEffects.putIfAbsent(soundID, info);
synchronized(info) {
try {
info.wait(LOAD_TIME_OUT);
}
catch (Exception e) {
e.printStackTrace();
}
}
streamID = info.effectID;
mPlayWhenLoadedEffects.remove(soundID);
}
return streamID;
}
public void stopEffect(final int steamID) {
mSoundPool.stop(steamID);
// remove record
for (final String path : mPathStreamIDsMap.keySet()) {
if (mPathStreamIDsMap.get(path).contains(steamID)) {
mPathStreamIDsMap.get(path).remove(mPathStreamIDsMap.get(path).indexOf(steamID));
break;
}
}
}
public void pauseEffect(final int steamID) {
mSoundPool.pause(steamID);
}
public void resumeEffect(final int steamID) {
mSoundPool.resume(steamID);
}
public void pauseAllEffects() {
if (!mPathStreamIDsMap.isEmpty()) {
final Iterator<Entry<String, ArrayList<Integer>>> iter = mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Entry<String, ArrayList<Integer>> entry = iter.next();
for (final int steamID : entry.getValue()) {
mSoundPool.pause(steamID);
}
}
}
}
public void resumeAllEffects() {
// can not only invoke SoundPool.autoResume() here, because
// it only resumes all effects paused by pauseAllEffects()
if (!mPathStreamIDsMap.isEmpty()) {
final Iterator<Entry<String, ArrayList<Integer>>> iter = mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Entry<String, ArrayList<Integer>> entry = iter.next();
for (final int steamID : entry.getValue()) {
mSoundPool.resume(steamID);
}
}
}
}
@SuppressWarnings("unchecked")
public void stopAllEffects() {
// stop effects
if (!mPathStreamIDsMap.isEmpty()) {
final Iterator<?> iter = mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Map.Entry<String, ArrayList<Integer>> entry = (Map.Entry<String, ArrayList<Integer>>) iter.next();
for (final int steamID : entry.getValue()) {
mSoundPool.stop(steamID);
}
}
}
// remove records
mPathStreamIDsMap.clear();
}
public float getEffectsVolume() {
return (mLeftVolume + mRightVolume) / 2;
}
public void setEffectsVolume(float volume) {
// volume should be in [0, 1.0]
if (volume < 0) {
volume = 0;
}
if (volume > 1) {
volume = 1;
}
mLeftVolume = mRightVolume = volume;
// change the volume of playing sounds
if (!mPathStreamIDsMap.isEmpty()) {
final Iterator<Entry<String, ArrayList<Integer>>> iter = mPathStreamIDsMap.entrySet().iterator();
while (iter.hasNext()) {
final Entry<String, ArrayList<Integer>> entry = iter.next();
for (final int steamID : entry.getValue()) {
mSoundPool.setVolume(steamID, mLeftVolume, mRightVolume);
}
}
}
}
public void end() {
mSoundPool.release();
mPathStreamIDsMap.clear();
mPathSoundIDMap.clear();
mPlayWhenLoadedEffects.clear();
mLeftVolume = 0.5f;
mRightVolume = 0.5f;
initData();
}
public int createSoundIDFromAsset(final String path) {
int soundID;
try {
if (path.startsWith("/")) {
soundID = mSoundPool.load(path, 0);
} else {
soundID = mSoundPool.load(mContext.getAssets().openFd(path), 0);
}
} catch (final Exception e) {
soundID = Cocos2dxSound.INVALID_SOUND_ID;
Log.e(Cocos2dxSound.TAG, "error: " + e.getMessage(), e);
}
// mSoundPool.load returns 0 if something goes wrong, for example a file does not exist
if (soundID == 0) {
soundID = Cocos2dxSound.INVALID_SOUND_ID;
}
return soundID;
}
private float clamp(float value, float min, float max) {
return Math.max(min, (Math.min(value, max)));
}
private int doPlayEffect(final String path, final int soundId, final boolean loop, float pitch, float pan, float gain) {
float leftVolume = mLeftVolume * gain * (1.0f - clamp(pan, 0.0f, 1.0f));
float rightVolume = mRightVolume * gain * (1.0f - clamp(-pan, 0.0f, 1.0f));
float soundRate = clamp(SOUND_RATE * pitch, 0.5f, 2.0f);
// play sound
int streamID = mSoundPool.play(soundId, clamp(leftVolume, 0.0f, 1.0f), clamp(rightVolume, 0.0f, 1.0f), Cocos2dxSound.SOUND_PRIORITY, loop ? -1 : 0, soundRate);
// record stream id
ArrayList<Integer> streamIDs = mPathStreamIDsMap.get(path);
if (streamIDs == null) {
streamIDs = new ArrayList<Integer>();
mPathStreamIDsMap.put(path, streamIDs);
}
streamIDs.add(streamID);
return streamID;
}
public void onEnterBackground(){
mSoundPool.autoPause();
}
public void onEnterForeground(){
mSoundPool.autoResume();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public class SoundInfoForLoadedCompleted {
public boolean isLoop;
public float pitch;
public float pan;
public float gain;
public String path;
public int effectID;
public SoundInfoForLoadedCompleted(String path, boolean isLoop, float pitch, float pan, float gain) {
this.path = path;
this.isLoop = isLoop;
this.pitch = pitch;
this.pan = pan;
this.gain = gain;
effectID = Cocos2dxSound.INVALID_SOUND_ID;
}
}
public class OnLoadCompletedListener implements SoundPool.OnLoadCompleteListener {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
if (status == 0)
{
SoundInfoForLoadedCompleted info = mPlayWhenLoadedEffects.get(sampleId);
if (info != null) {
info.effectID = doPlayEffect(info.path, sampleId, info.isLoop, info.pitch, info.pan, info.gain);
synchronized (info) {
info.notifyAll();
}
}
}
}
}
}
@@ -1,56 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.graphics.Typeface;
import java.util.HashMap;
public class Cocos2dxTypefaces {
private static final HashMap<String, Typeface> sTypefaceCache = new HashMap<String, Typeface>();
// ===========================================================
// Methods
// ===========================================================
public static synchronized Typeface get(final Context context, final String assetName) {
if (!Cocos2dxTypefaces.sTypefaceCache.containsKey(assetName)) {
Typeface typeface;
if (assetName.startsWith("/"))
{
typeface = Typeface.createFromFile(assetName);
}
else
{
typeface = Typeface.createFromAsset(context.getAssets(), assetName);
}
Cocos2dxTypefaces.sTypefaceCache.put(assetName, typeface);
}
return Cocos2dxTypefaces.sTypefaceCache.get(assetName);
}
}
@@ -1,417 +0,0 @@
/****************************************************************************
Copyright (c) 2014-2016 Chukong Technologies Inc.
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.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.SparseArray;
import android.view.View;
import android.widget.FrameLayout;
import org.cocos2dx.lib.Cocos2dxVideoView.OnVideoEventListener;
import java.lang.ref.WeakReference;
public class Cocos2dxVideoHelper {
static VideoHandler sVideoHandler = null;
private SparseArray<Cocos2dxVideoView> mVideoViews = null;
Cocos2dxVideoHelper()
{
sVideoHandler = new VideoHandler(this);
mVideoViews = new SparseArray<Cocos2dxVideoView>();
}
private static int videoTag = 0;
private final static int VideoTaskCreate = 0;
private final static int VideoTaskRemove = 1;
private final static int VideoTaskSetSource = 2;
private final static int VideoTaskSetRect = 3;
private final static int VideoTaskStart = 4;
private final static int VideoTaskPause = 5;
private final static int VideoTaskResume = 6;
private final static int VideoTaskStop = 7;
private final static int VideoTaskSeek = 8;
private final static int VideoTaskSetVisible = 9;
private final static int VideoTaskRestart = 10;
private final static int VideoTaskKeepRatio = 11;
private final static int VideoTaskFullScreen = 12;
final static int KeyEventBack = 1000;
static class VideoHandler extends Handler{
WeakReference<Cocos2dxVideoHelper> mReference;
VideoHandler(Cocos2dxVideoHelper helper){
mReference = new WeakReference<Cocos2dxVideoHelper>(helper);
}
@Override
public void handleMessage(Message msg) {
Cocos2dxVideoHelper helper = mReference.get();
switch (msg.what) {
case VideoTaskCreate: {
helper._createVideoView(msg.arg1);
break;
}
case VideoTaskRemove: {
helper._removeVideoView(msg.arg1);
break;
}
case VideoTaskSetSource: {
helper._setVideoURL(msg.arg1, msg.arg2, (String)msg.obj);
break;
}
case VideoTaskStart: {
helper._startVideo(msg.arg1);
break;
}
case VideoTaskSetRect: {
Rect rect = (Rect)msg.obj;
helper._setVideoRect(msg.arg1, rect.left, rect.top, rect.right, rect.bottom);
break;
}
case VideoTaskFullScreen:{
Rect rect = (Rect)msg.obj;
if (msg.arg2 == 1) {
helper._setFullScreenEnabled(msg.arg1, true, rect.right, rect.bottom);
} else {
helper._setFullScreenEnabled(msg.arg1, false, rect.right, rect.bottom);
}
break;
}
case VideoTaskPause: {
helper._pauseVideo(msg.arg1);
break;
}
case VideoTaskResume: {
helper._resumeVideo(msg.arg1);
break;
}
case VideoTaskStop: {
helper._stopVideo(msg.arg1);
break;
}
case VideoTaskSeek: {
helper._seekVideoTo(msg.arg1, msg.arg2);
break;
}
case VideoTaskSetVisible: {
if (msg.arg2 == 1) {
helper._setVideoVisible(msg.arg1, true);
} else {
helper._setVideoVisible(msg.arg1, false);
}
break;
}
case VideoTaskRestart: {
helper._restartVideo(msg.arg1);
break;
}
case VideoTaskKeepRatio: {
if (msg.arg2 == 1) {
helper._setVideoKeepRatio(msg.arg1, true);
} else {
helper._setVideoKeepRatio(msg.arg1, false);
}
break;
}
case KeyEventBack: {
helper.onBackKeyEvent();
break;
}
default:
break;
}
super.handleMessage(msg);
}
}
private class VideoEventRunnable implements Runnable
{
private int mVideoTag;
private int mVideoEvent;
public VideoEventRunnable(int tag,int event) {
mVideoTag = tag;
mVideoEvent = event;
}
@Override
public void run() {
nativeExecuteVideoCallback(mVideoTag, mVideoEvent);
}
}
public static native void nativeExecuteVideoCallback(int index,int event);
OnVideoEventListener videoEventListener = new OnVideoEventListener() {
@Override
public void onVideoEvent(int tag,int event) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new VideoEventRunnable(tag, event));
}
};
public static int createVideoWidget() {
Message msg = Message.obtain();
msg.what = VideoTaskCreate;
msg.arg1 = videoTag;
sVideoHandler.sendMessageDelayed(msg, 0);
return videoTag++;
}
private void _createVideoView(int index) {
Cocos2dxVideoView videoView = new Cocos2dxVideoView(Cocos2dxActivity.COCOS_ACTIVITY,index);
mVideoViews.put(index, videoView);
FrameLayout.LayoutParams lParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
Cocos2dxActivity.ROOT_LAYOUT.addView(videoView, lParams);
videoView.setZOrderOnTop(true);
videoView.setOnCompletionListener(videoEventListener);
}
public static void removeVideoWidget(int index){
Message msg = Message.obtain();
msg.what = VideoTaskRemove;
msg.arg1 = index;
sVideoHandler.sendMessageDelayed(msg, 0);
}
private void _removeVideoView(int index) {
Cocos2dxVideoView view = mVideoViews.get(index);
if (view != null) {
view.stopPlayback();
mVideoViews.remove(index);
Cocos2dxActivity.ROOT_LAYOUT.removeView(view);
}
}
public static void setVideoUrl(int index, int videoSource, String videoUrl) {
Message msg = Message.obtain();
msg.what = VideoTaskSetSource;
msg.arg1 = index;
msg.arg2 = videoSource;
msg.obj = videoUrl;
sVideoHandler.sendMessageDelayed(msg, 0);
}
private void _setVideoURL(int index, int videoSource, String videoUrl) {
Cocos2dxVideoView videoView = mVideoViews.get(index);
if (videoView != null) {
switch (videoSource) {
case 0:
videoView.setVideoFileName(videoUrl);
break;
case 1:
videoView.setVideoURL(videoUrl);
break;
default:
break;
}
}
}
public static void setVideoRect(int index, int left, int top, int maxWidth, int maxHeight) {
Message msg = Message.obtain();
msg.what = VideoTaskSetRect;
msg.arg1 = index;
msg.obj = new Rect(left, top, maxWidth, maxHeight);
sVideoHandler.sendMessageDelayed(msg, 0);
}
private void _setVideoRect(int index, int left, int top, int maxWidth, int maxHeight) {
Cocos2dxVideoView videoView = mVideoViews.get(index);
if (videoView != null) {
videoView.setVideoRect(left,top,maxWidth,maxHeight);
}
}
public static void setFullScreenEnabled(int index, boolean enabled, int width, int height) {
Message msg = Message.obtain();
msg.what = VideoTaskFullScreen;
msg.arg1 = index;
if (enabled) {
msg.arg2 = 1;
} else {
msg.arg2 = 0;
}
msg.obj = new Rect(0, 0, width, height);
sVideoHandler.sendMessageDelayed(msg, 0);
}
private void _setFullScreenEnabled(int index, boolean enabled, int width,int height) {
Cocos2dxVideoView videoView = mVideoViews.get(index);
if (videoView != null) {
videoView.setFullScreenEnabled(enabled, width, height);
}
}
private void onBackKeyEvent() {
int viewCount = mVideoViews.size();
for (int i = 0; i < viewCount; i++) {
int key = mVideoViews.keyAt(i);
Cocos2dxVideoView videoView = mVideoViews.get(key);
if (videoView != null) {
videoView.setFullScreenEnabled(false, 0, 0);
Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new VideoEventRunnable(key, KeyEventBack));
}
}
}
public static void startVideo(int index) {
Message msg = Message.obtain();
msg.what = VideoTaskStart;
msg.arg1 = index;
sVideoHandler.sendMessageDelayed(msg, 0);
}
private void _startVideo(int index) {
Cocos2dxVideoView videoView = mVideoViews.get(index);
if (videoView != null) {
videoView.start();
}
}
public static void pauseVideo(int index) {
Message msg = Message.obtain();
msg.what = VideoTaskPause;
msg.arg1 = index;
sVideoHandler.sendMessageDelayed(msg, 0);
}
private void _pauseVideo(int index) {
Cocos2dxVideoView videoView = mVideoViews.get(index);
if (videoView != null) {
videoView.pause();
}
}
public static void resumeVideo(int index) {
Message msg = Message.obtain();
msg.what = VideoTaskResume;
msg.arg1 = index;
sVideoHandler.sendMessageDelayed(msg, 0);
}
private void _resumeVideo(int index) {
Cocos2dxVideoView videoView = mVideoViews.get(index);
if (videoView != null) {
videoView.resume();
}
}
public static void stopVideo(int index) {
Message msg = Message.obtain();
msg.what = VideoTaskStop;
msg.arg1 = index;
sVideoHandler.sendMessageDelayed(msg, 0);
}
private void _stopVideo(int index) {
Cocos2dxVideoView videoView = mVideoViews.get(index);
if (videoView != null) {
videoView.stop();
}
}
public static void restartVideo(int index) {
Message msg = Message.obtain();
msg.what = VideoTaskRestart;
msg.arg1 = index;
sVideoHandler.sendMessageDelayed(msg, 0);
}
private void _restartVideo(int index) {
Cocos2dxVideoView videoView = mVideoViews.get(index);
if (videoView != null) {
videoView.restart();
}
}
public static void seekVideoTo(int index,int msec) {
Message msg = Message.obtain();
msg.what = VideoTaskSeek;
msg.arg1 = index;
msg.arg2 = msec;
sVideoHandler.sendMessageDelayed(msg, 0);
}
private void _seekVideoTo(int index,int msec) {
Cocos2dxVideoView videoView = mVideoViews.get(index);
if (videoView != null) {
videoView.seekTo(msec);
}
}
public static void setVideoVisible(int index, boolean visible) {
Message msg = Message.obtain();
msg.what = VideoTaskSetVisible;
msg.arg1 = index;
if (visible) {
msg.arg2 = 1;
} else {
msg.arg2 = 0;
}
sVideoHandler.sendMessageDelayed(msg, 0);
}
private void _setVideoVisible(int index, boolean visible) {
Cocos2dxVideoView videoView = mVideoViews.get(index);
if (videoView != null) {
if (visible) {
videoView.fixSize();
videoView.setVisibility(View.VISIBLE);
} else {
videoView.setVisibility(View.INVISIBLE);
}
}
}
public static void setVideoKeepRatioEnabled(int index, boolean enable) {
Message msg = Message.obtain();
msg.what = VideoTaskKeepRatio;
msg.arg1 = index;
if (enable) {
msg.arg2 = 1;
} else {
msg.arg2 = 0;
}
sVideoHandler.sendMessageDelayed(msg, 0);
}
private void _setVideoKeepRatio(int index, boolean enable) {
Cocos2dxVideoView videoView = mVideoViews.get(index);
if (videoView != null) {
videoView.setKeepRatio(enable);
}
}
}
@@ -1,691 +0,0 @@
package org.cocos2dx.lib;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.FrameLayout;
import android.widget.MediaController.MediaPlayerControl;
import java.io.IOException;
import java.util.Map;
public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl {
private String TAG = "Cocos2dxVideoView";
private Uri mVideoUri;
private int mDuration;
// all possible internal states
private static final int STATE_ERROR = -1;
private static final int STATE_IDLE = 0;
private static final int STATE_PREPARING = 1;
private static final int STATE_PREPARED = 2;
private static final int STATE_PLAYING = 3;
private static final int STATE_PAUSED = 4;
private static final int STATE_PLAYBACK_COMPLETED = 5;
/**
* mCurrentState is a VideoView object's current state.
* mTargetState is the state that a method caller intends to reach.
* For instance, regardless the VideoView object's current state,
* calling pause() intends to bring the object to a target state
* of STATE_PAUSED.
*/
private int mCurrentState = STATE_IDLE;
private int mTargetState = STATE_IDLE;
// All the stuff we need for playing and showing a video
private SurfaceHolder mSurfaceHolder = null;
private MediaPlayer mMediaPlayer = null;
private int mVideoWidth = 0;
private int mVideoHeight = 0;
private OnVideoEventListener mOnVideoEventListener;
private MediaPlayer.OnPreparedListener mOnPreparedListener;
private int mCurrentBufferPercentage;
private OnErrorListener mOnErrorListener;
// recording the seek position while preparing
private int mSeekWhenPrepared;
protected Activity mActivity = null;
protected int mViewLeft = 0;
protected int mViewTop = 0;
protected int mViewWidth = 0;
protected int mViewHeight = 0;
protected int mVisibleLeft = 0;
protected int mVisibleTop = 0;
protected int mVisibleWidth = 0;
protected int mVisibleHeight = 0;
protected boolean mFullScreenEnabled = false;
protected int mFullScreenWidth = 0;
protected int mFullScreenHeight = 0;
private int mViewTag = 0;
public Cocos2dxVideoView(Context context,int tag) {
super(context);
mViewTag = tag;
mActivity = Cocos2dxActivity.COCOS_ACTIVITY;
initVideoView();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mVideoWidth == 0 || mVideoHeight == 0) {
setMeasuredDimension(mViewWidth, mViewHeight);
Log.i(TAG, ""+mViewWidth+ ":" +mViewHeight);
}
else {
setMeasuredDimension(mVisibleWidth, mVisibleHeight);
Log.i(TAG, ""+mVisibleWidth+ ":" +mVisibleHeight);
}
}
public void setVideoRect(int left, int top, int maxWidth, int maxHeight) {
mViewLeft = left;
mViewTop = top;
mViewWidth = maxWidth;
mViewHeight = maxHeight;
fixSize(mViewLeft, mViewTop, mViewWidth, mViewHeight);
}
public void setFullScreenEnabled(boolean enabled, int width, int height) {
if (mFullScreenEnabled != enabled) {
mFullScreenEnabled = enabled;
if (width != 0 && height != 0) {
mFullScreenWidth = width;
mFullScreenHeight = height;
}
fixSize();
}
}
public int resolveAdjustedSize(int desiredSize, int measureSpec) {
int result = desiredSize;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
/* Parent says we can be as big as we want. Just don't be larger
* than max size imposed on ourselves.
*/
result = desiredSize;
break;
case MeasureSpec.AT_MOST:
/* Parent says we can be as big as we want, up to specSize.
* Don't be larger than specSize, and don't be larger than
* the max size imposed on ourselves.
*/
result = Math.min(desiredSize, specSize);
break;
case MeasureSpec.EXACTLY:
// No choice. Do what we are told.
result = specSize;
break;
}
return result;
}
private boolean mNeedResume = false;
@Override
public void setVisibility(int visibility) {
if (visibility == INVISIBLE) {
mNeedResume = isPlaying();
if (mNeedResume) {
mSeekWhenPrepared = getCurrentPosition();
}
}
else if (mNeedResume){
start();
mNeedResume = false;
}
super.setVisibility(visibility);
}
private void initVideoView() {
mVideoWidth = 0;
mVideoHeight = 0;
getHolder().addCallback(mSHCallback);
//Fix issue#11516:Can't play video on Android 2.3.x
getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
setFocusable(true);
setFocusableInTouchMode(true);
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP)
{
if (isPlaying()) {
pause();
} else if(mCurrentState == STATE_PAUSED){
resume();
}
}
return true;
}
private boolean mIsAssetRouse = false;
private String mVideoFilePath = null;
private static final String AssetResourceRoot = "assets/";
public void setVideoFileName(String path) {
if (path.startsWith(AssetResourceRoot)) {
path = path.substring(AssetResourceRoot.length());
}
if (path.startsWith("/")) {
mIsAssetRouse = false;
setVideoURI(Uri.parse(path),null);
}
else {
mVideoFilePath = path;
mIsAssetRouse = true;
setVideoURI(Uri.parse(path),null);
}
}
public void setVideoURL(String url) {
mIsAssetRouse = false;
setVideoURI(Uri.parse(url), null);
}
/**
* @hide
*/
private void setVideoURI(Uri uri, Map<String, String> headers) {
mVideoUri = uri;
mSeekWhenPrepared = 0;
mVideoWidth = 0;
mVideoHeight = 0;
openVideo();
requestLayout();
invalidate();
}
public void stopPlayback() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
}
private void openVideo() {
if (mSurfaceHolder == null) {
// not ready for playback just yet, will try again later
return;
}
if (mIsAssetRouse) {
if(mVideoFilePath == null)
return;
} else if(mVideoUri == null) {
return;
}
// Tell the music playback service to pause
// TODO: these constants need to be published somewhere in the framework.
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
mActivity.sendBroadcast(i);
// we shouldn't clear the target state, because somebody might have
// called start() previously
release(false);
try {
//if (mMediaPlayer == null) {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnPreparedListener(mPreparedListener);
mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
mMediaPlayer.setOnCompletionListener(mCompletionListener);
mMediaPlayer.setOnErrorListener(mErrorListener);
mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setScreenOnWhilePlaying(true);
//}
mDuration = -1;
mCurrentBufferPercentage = 0;
if (mIsAssetRouse) {
AssetFileDescriptor afd = mActivity.getAssets().openFd(mVideoFilePath);
mMediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
} else {
mMediaPlayer.setDataSource(mActivity, mVideoUri);
}
mMediaPlayer.prepareAsync();
/**
* Don't set the target state here either, but preserve the target state that was there before.
*/
mCurrentState = STATE_PREPARING;
} catch (IOException ex) {
Log.w(TAG, "Unable to open content: " + mVideoUri, ex);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
}
}
private boolean mKeepRatio = false;
public void setKeepRatio(boolean enabled) {
mKeepRatio = enabled;
fixSize();
}
public void fixSize() {
if (mFullScreenEnabled) {
fixSize(0, 0, mFullScreenWidth, mFullScreenHeight);
} else {
fixSize(mViewLeft, mViewTop, mViewWidth, mViewHeight);
}
}
public void fixSize(int left, int top, int width, int height) {
if (mVideoWidth == 0 || mVideoHeight == 0) {
mVisibleLeft = left;
mVisibleTop = top;
mVisibleWidth = width;
mVisibleHeight = height;
}
else if (width != 0 && height != 0) {
if (mKeepRatio) {
if ( mVideoWidth * height > width * mVideoHeight ) {
mVisibleWidth = width;
mVisibleHeight = width * mVideoHeight / mVideoWidth;
} else if ( mVideoWidth * height < width * mVideoHeight ) {
mVisibleWidth = height * mVideoWidth / mVideoHeight;
mVisibleHeight = height;
}
mVisibleLeft = left + (width - mVisibleWidth) / 2;
mVisibleTop = top + (height - mVisibleHeight) / 2;
} else {
mVisibleLeft = left;
mVisibleTop = top;
mVisibleWidth = width;
mVisibleHeight = height;
}
}
else {
mVisibleLeft = left;
mVisibleTop = top;
mVisibleWidth = mVideoWidth;
mVisibleHeight = mVideoHeight;
}
getHolder().setFixedSize(mVisibleWidth, mVisibleHeight);
FrameLayout.LayoutParams lParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
lParams.leftMargin = mVisibleLeft;
lParams.topMargin = mVisibleTop;
lParams.gravity = Gravity.TOP | Gravity.LEFT;
setLayoutParams(lParams);
}
protected
MediaPlayer.OnVideoSizeChangedListener mSizeChangedListener =
new MediaPlayer.OnVideoSizeChangedListener() {
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
if (mVideoWidth != 0 && mVideoHeight != 0) {
getHolder().setFixedSize(mVideoWidth, mVideoHeight);
}
}
};
MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mCurrentState = STATE_PREPARED;
if (mOnPreparedListener != null) {
mOnPreparedListener.onPrepared(mMediaPlayer);
}
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
// mSeekWhenPrepared may be changed after seekTo() call
int seekToPosition = mSeekWhenPrepared;
if (seekToPosition != 0) {
seekTo(seekToPosition);
}
if (mVideoWidth != 0 && mVideoHeight != 0) {
fixSize();
}
if (mTargetState == STATE_PLAYING) {
start();
}
}
};
private MediaPlayer.OnCompletionListener mCompletionListener =
new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mCurrentState = STATE_PLAYBACK_COMPLETED;
mTargetState = STATE_PLAYBACK_COMPLETED;
release(true);
if (mOnVideoEventListener != null) {
mOnVideoEventListener.onVideoEvent(mViewTag,EVENT_COMPLETED);
}
}
};
private static final int EVENT_PLAYING = 0;
private static final int EVENT_PAUSED = 1;
private static final int EVENT_STOPPED = 2;
private static final int EVENT_COMPLETED = 3;
public interface OnVideoEventListener
{
void onVideoEvent(int tag,int event);
}
private MediaPlayer.OnErrorListener mErrorListener =
new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
Log.d(TAG, "Error: " + framework_err + "," + impl_err);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
/* If an error handler has been supplied, use it and finish. */
if (mOnErrorListener != null) {
if (mOnErrorListener.onError(mMediaPlayer, framework_err, impl_err)) {
return true;
}
}
/* Otherwise, pop up an error dialog so the user knows that
* something bad has happened. Only try and pop up the dialog
* if we're attached to a window. When we're going away and no
* longer have a window, don't bother showing the user an error.
*/
if (getWindowToken() != null) {
Resources r = mActivity.getResources();
int messageId;
if (framework_err == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
// messageId = com.android.internal.R.string.VideoView_error_text_invalid_progressive_playback;
messageId = r.getIdentifier("VideoView_error_text_invalid_progressive_playback", "string", "android");
} else {
// messageId = com.android.internal.R.string.VideoView_error_text_unknown;
messageId = r.getIdentifier("VideoView_error_text_unknown", "string", "android");
}
int titleId = r.getIdentifier("VideoView_error_title", "string", "android");
int buttonStringId = r.getIdentifier("VideoView_error_button", "string", "android");
new AlertDialog.Builder(mActivity)
.setTitle(r.getString(titleId))
.setMessage(messageId)
.setPositiveButton(r.getString(buttonStringId),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* If we get here, there is no onError listener, so
* at least inform them that the video is over.
*/
if (mOnVideoEventListener != null) {
mOnVideoEventListener.onVideoEvent(mViewTag,EVENT_COMPLETED);
}
}
})
.setCancelable(false)
.show();
}
return true;
}
};
private MediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener =
new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
mCurrentBufferPercentage = percent;
}
};
/**
* Register a callback to be invoked when the media file
* is loaded and ready to go.
*
* @param l The callback that will be run
*/
public void setOnPreparedListener(MediaPlayer.OnPreparedListener l)
{
mOnPreparedListener = l;
}
/**
* Register a callback to be invoked when the end of a media file
* has been reached during play back.
*
* @param l The callback that will be run
*/
public void setOnCompletionListener(OnVideoEventListener l)
{
mOnVideoEventListener = l;
}
/**
* Register a callback to be invoked when an error occurs
* during play back or setup. If no listener is specified,
* or if the listener returned false, VideoView will inform
* the user of any errors.
*
* @param l The callback that will be run
*/
public void setOnErrorListener(OnErrorListener l)
{
mOnErrorListener = l;
}
SurfaceHolder.Callback mSHCallback = new SurfaceHolder.Callback()
{
public void surfaceChanged(SurfaceHolder holder, int format,
int w, int h)
{
boolean isValidState = (mTargetState == STATE_PLAYING);
boolean hasValidSize = (mVideoWidth == w && mVideoHeight == h);
if (mMediaPlayer != null && isValidState && hasValidSize) {
if (mSeekWhenPrepared != 0) {
seekTo(mSeekWhenPrepared);
}
start();
}
}
public void surfaceCreated(SurfaceHolder holder)
{
mSurfaceHolder = holder;
openVideo();
}
public void surfaceDestroyed(SurfaceHolder holder)
{
// after we return from this we can't use the surface any more
mSurfaceHolder = null;
release(true);
}
};
/*
* release the media player in any state
*/
private void release(boolean cleartargetstate) {
if (mMediaPlayer != null) {
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
if (cleartargetstate) {
mTargetState = STATE_IDLE;
}
}
}
public void start() {
if (isInPlaybackState()) {
mMediaPlayer.start();
mCurrentState = STATE_PLAYING;
if (mOnVideoEventListener != null) {
mOnVideoEventListener.onVideoEvent(mViewTag, EVENT_PLAYING);
}
}
mTargetState = STATE_PLAYING;
}
public void pause() {
if (isInPlaybackState()) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mCurrentState = STATE_PAUSED;
if (mOnVideoEventListener != null) {
mOnVideoEventListener.onVideoEvent(mViewTag, EVENT_PAUSED);
}
}
}
mTargetState = STATE_PAUSED;
}
public void stop() {
if (isInPlaybackState()) {
if (mMediaPlayer.isPlaying()) {
stopPlayback();
if (mOnVideoEventListener != null) {
mOnVideoEventListener.onVideoEvent(mViewTag, EVENT_STOPPED);
}
}
}
}
public void suspend() {
release(false);
}
public void resume() {
if (isInPlaybackState()) {
if (mCurrentState == STATE_PAUSED) {
mMediaPlayer.start();
mCurrentState = STATE_PLAYING;
if (mOnVideoEventListener != null) {
mOnVideoEventListener.onVideoEvent(mViewTag, EVENT_PLAYING);
}
}
}
}
public void restart() {
if (isInPlaybackState()) {
mMediaPlayer.seekTo(0);
mMediaPlayer.start();
mCurrentState = STATE_PLAYING;
mTargetState = STATE_PLAYING;
}
}
// cache duration as mDuration for faster access
public int getDuration() {
if (isInPlaybackState()) {
if (mDuration > 0) {
return mDuration;
}
mDuration = mMediaPlayer.getDuration();
return mDuration;
}
mDuration = -1;
return mDuration;
}
public int getCurrentPosition() {
if (isInPlaybackState()) {
return mMediaPlayer.getCurrentPosition();
}
return 0;
}
public void seekTo(int msec) {
if (isInPlaybackState()) {
mMediaPlayer.seekTo(msec);
mSeekWhenPrepared = 0;
} else {
mSeekWhenPrepared = msec;
}
}
public boolean isPlaying() {
return isInPlaybackState() && mMediaPlayer.isPlaying();
}
public int getBufferPercentage() {
if (mMediaPlayer != null) {
return mCurrentBufferPercentage;
}
return 0;
}
public boolean isInPlaybackState() {
return (mMediaPlayer != null &&
mCurrentState != STATE_ERROR &&
mCurrentState != STATE_IDLE &&
mCurrentState != STATE_PREPARING);
}
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
public int getAudioSessionId () {
return mMediaPlayer.getAudioSessionId();
}
}
@@ -1,150 +0,0 @@
package org.cocos2dx.lib;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.concurrent.CountDownLatch;
public class Cocos2dxWebView extends WebView {
private static final String TAG = Cocos2dxWebViewHelper.class.getSimpleName();
private int mViewTag;
private String mJSScheme;
public Cocos2dxWebView(Context context) {
this(context, -1);
}
@SuppressLint("SetJavaScriptEnabled")
public Cocos2dxWebView(Context context, int viewTag) {
super(context);
this.mViewTag = viewTag;
this.mJSScheme = "";
this.setFocusable(true);
this.setFocusableInTouchMode(true);
this.getSettings().setSupportZoom(false);
this.getSettings().setJavaScriptEnabled(true);
// `searchBoxJavaBridge_` has big security risk. http://jvn.jp/en/jp/JVN53768697
try {
Method method = this.getClass().getMethod("removeJavascriptInterface", new Class[]{String.class});
method.invoke(this, "searchBoxJavaBridge_");
} catch (Exception e) {
Log.d(TAG, "This API level do not support `removeJavascriptInterface`");
}
this.setWebViewClient(new Cocos2dxWebViewClient());
this.setWebChromeClient(new WebChromeClient());
}
public void setJavascriptInterfaceScheme(String scheme) {
this.mJSScheme = scheme != null ? scheme : "";
}
public void setScalesPageToFit(boolean scalesPageToFit) {
this.getSettings().setSupportZoom(scalesPageToFit);
}
class Cocos2dxWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, final String urlString) {
Cocos2dxActivity activity = Cocos2dxActivity.COCOS_ACTIVITY;
try {
URI uri = URI.create(urlString);
if (uri.getScheme().equals(mJSScheme)) {
activity.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebViewHelper._onJsCallback(mViewTag, urlString);
}
});
return true;
}
} catch (Exception e) {
Log.d(TAG, "Failed to create URI from url");
}
boolean[] result = new boolean[] { true };
CountDownLatch latch = new CountDownLatch(1);
// run worker on cocos thread
activity.runOnGLThread(new ShouldStartLoadingWorker(latch, result, mViewTag, urlString));
// wait for result from cocos thread
try {
latch.await();
} catch (InterruptedException ex) {
Log.d(TAG, "'shouldOverrideUrlLoading' failed");
}
return result[0];
}
@Override
public void onPageFinished(WebView view, final String url) {
super.onPageFinished(view, url);
Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebViewHelper._didFinishLoading(mViewTag, url);
}
});
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, final String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Cocos2dxActivity.COCOS_ACTIVITY.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebViewHelper._didFailLoading(mViewTag, failingUrl);
}
});
}
}
public void setWebViewRect(int left, int top, int maxWidth, int maxHeight) {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = left;
layoutParams.topMargin = top;
layoutParams.width = maxWidth;
layoutParams.height = maxHeight;
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
this.setLayoutParams(layoutParams);
}
class ShouldStartLoadingWorker implements Runnable {
private CountDownLatch mLatch;
private boolean[] mResult;
private final int mViewTag;
private final String mUrlString;
ShouldStartLoadingWorker(CountDownLatch latch, boolean[] result, int viewTag, String urlString) {
this.mLatch = latch;
this.mResult = result;
this.mViewTag = viewTag;
this.mUrlString = urlString;
}
@Override
public void run() {
this.mResult[0] = Cocos2dxWebViewHelper._shouldStartLoading(mViewTag, mUrlString);
this.mLatch.countDown(); // notify that result is ready
}
}
}
@@ -1,313 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.os.Handler;
import android.os.Looper;
import android.util.SparseArray;
import android.view.View;
import android.widget.FrameLayout;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Cocos2dxWebViewHelper {
private static final String TAG = "Cocos2dxWebViewHelper";
private static Handler sHandler = null;
private static SparseArray<Cocos2dxWebView> sWebViews = null;
private static int viewTag = 0;
static void init()
{
if (sWebViews == null)
{
sWebViews = new SparseArray<Cocos2dxWebView>();
sHandler = new Handler(Looper.myLooper());
}
}
static void reset()
{
if (sWebViews != null)
sWebViews.clear();
sWebViews = null;
sHandler = null;
}
private static native boolean shouldStartLoading(int index, String message);
public static boolean _shouldStartLoading(int index, String message) {
return !shouldStartLoading(index, message);
}
private static native void didFinishLoading(int index, String message);
public static void _didFinishLoading(int index, String message) {
didFinishLoading(index, message);
}
private static native void didFailLoading(int index, String message);
public static void _didFailLoading(int index, String message) {
didFailLoading(index, message);
}
private static native void onJsCallback(int index, String message);
public static void _onJsCallback(int index, String message) {
onJsCallback(index, message);
}
public static int createWebView() {
final int index = viewTag;
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = new Cocos2dxWebView(Cocos2dxActivity.COCOS_ACTIVITY, index);
FrameLayout.LayoutParams lParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
Cocos2dxActivity.ROOT_LAYOUT.addView(webView, lParams);
sWebViews.put(index, webView);
}
});
return viewTag++;
}
public static void removeWebView(final int index) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
sWebViews.remove(index);
Cocos2dxActivity.ROOT_LAYOUT.removeView(webView);
}
}
});
}
public static void setVisible(final int index, final boolean visible) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
webView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
}
});
}
public static void setWebViewRect(final int index, final int left, final int top, final int maxWidth, final int maxHeight) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
webView.setWebViewRect(left, top, maxWidth, maxHeight);
}
}
});
}
public static void setJavascriptInterfaceScheme(final int index, final String scheme) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
webView.setJavascriptInterfaceScheme(scheme);
}
}
});
}
public static void loadData(final int index, final String data, final String mimeType, final String encoding, final String baseURL) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
webView.loadDataWithBaseURL(baseURL, data, mimeType, encoding, null);
}
}
});
}
public static void loadHTMLString(final int index, final String data, final String baseUrl) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
webView.loadDataWithBaseURL(baseUrl, data, null, null, null);
}
}
});
}
public static void loadUrl(final int index, final String url) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
webView.loadUrl(url);
}
}
});
}
public static void loadFile(final int index, final String filePath) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
webView.loadUrl(filePath);
}
}
});
}
public static void stopLoading(final int index) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
webView.stopLoading();
}
}
});
}
public static void reload(final int index) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
webView.reload();
}
}
});
}
public static <T> T callInMainThread(Callable<T> call) throws ExecutionException, InterruptedException {
FutureTask<T> task = new FutureTask<T>(call);
sHandler.post(task);
return task.get();
}
public static boolean canGoBack(final int index) {
Callable<Boolean> callable = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Cocos2dxWebView webView = sWebViews.get(index);
return webView != null && webView.canGoBack();
}
};
try {
return callInMainThread(callable);
} catch (ExecutionException e) {
return false;
} catch (InterruptedException e) {
return false;
}
}
public static boolean canGoForward(final int index) {
Callable<Boolean> callable = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Cocos2dxWebView webView = sWebViews.get(index);
return webView != null && webView.canGoForward();
}
};
try {
return callInMainThread(callable);
} catch (ExecutionException e) {
return false;
} catch (InterruptedException e) {
return false;
}
}
public static void goBack(final int index) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
webView.goBack();
}
}
});
}
public static void goForward(final int index) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
webView.goForward();
}
}
});
}
public static void evaluateJS(final int index, final String js) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
webView.loadUrl("javascript:" + js);
}
}
});
}
public static void setScalesPageToFit(final int index, final boolean scalesPageToFit) {
Cocos2dxActivity.COCOS_ACTIVITY.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxWebView webView = sWebViews.get(index);
if (webView != null) {
webView.setScalesPageToFit(scalesPageToFit);
}
}
});
}
}
@@ -1,102 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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;
public class GameControllerAdapter {
private static ArrayList<Runnable> sRunnableFrameStartList = null;
public static void addRunnableToFrameStartList(Runnable runnable) {
if (sRunnableFrameStartList == null)
sRunnableFrameStartList = new ArrayList<Runnable>();
sRunnableFrameStartList.add(runnable);
}
public static void removeRunnableFromFrameStartList(Runnable runnable) {
if (sRunnableFrameStartList != null)
sRunnableFrameStartList.remove(runnable);
}
public static void onDrawFrameStart() {
if (sRunnableFrameStartList != null)
{
int size = sRunnableFrameStartList.size();
for (int i = 0; i < size; ++i) {
sRunnableFrameStartList.get(i).run();
}
}
}
public static void onConnected(final String vendorName, final int controller)
{
Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override
public void run() {
nativeControllerConnected(vendorName, controller);
}
});
}
public static void onDisconnected(final String vendorName, final int controller)
{
Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override
public void run() {
nativeControllerDisconnected(vendorName, controller);
}
});
}
public static void onButtonEvent(final String vendorName, final int controller, final int button, final boolean isPressed, final float value, final boolean isAnalog)
{
Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override
public void run() {
nativeControllerButtonEvent(vendorName, controller, button, isPressed, value, isAnalog);
}
});
}
public static void onAxisEvent(final String vendorName, final int controller, final int axisID, final float value, final boolean isAnalog)
{
Cocos2dxHelper.runOnGLThread(new Runnable() {
@Override
public void run() {
nativeControllerAxisEvent(vendorName, controller, axisID, value, isAnalog);
}
});
}
private static native void nativeControllerConnected(final String vendorName, final int controller);
private static native void nativeControllerDisconnected(final String vendorName, final int controller);
private static native void nativeControllerButtonEvent(final String vendorName, final int controller, final int button, final boolean isPressed, final float value, final boolean isAnalog);
private static native void nativeControllerAxisEvent(final String vendorName, final int controller, final int axisID, final float value, final boolean isAnalog);
}
@@ -1,82 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.view.KeyEvent;
import android.view.MotionEvent;
public interface GameControllerDelegate {
static final int KEY_BASE = 1000;
public static final int THUMBSTICK_LEFT_X = KEY_BASE;
public static final int THUMBSTICK_LEFT_Y = KEY_BASE + 1;
public static final int THUMBSTICK_RIGHT_X = KEY_BASE + 2;
public static final int THUMBSTICK_RIGHT_Y = KEY_BASE + 3;
public static final int BUTTON_A = KEY_BASE + 4;
public static final int BUTTON_B = KEY_BASE + 5;
public static final int BUTTON_C = KEY_BASE + 6;
public static final int BUTTON_X = KEY_BASE + 7;
public static final int BUTTON_Y = KEY_BASE + 8;
public static final int BUTTON_Z = KEY_BASE + 9;
public static final int BUTTON_DPAD_UP = KEY_BASE + 10;
public static final int BUTTON_DPAD_DOWN = KEY_BASE + 11;
public static final int BUTTON_DPAD_LEFT = KEY_BASE + 12;
public static final int BUTTON_DPAD_RIGHT = KEY_BASE + 13;
public static final int BUTTON_DPAD_CENTER = KEY_BASE + 14;
public static final int BUTTON_LEFT_SHOULDER = KEY_BASE + 15;
public static final int BUTTON_RIGHT_SHOULDER = KEY_BASE + 16;
public static final int BUTTON_LEFT_TRIGGER = KEY_BASE + 17;
public static final int BUTTON_RIGHT_TRIGGER = KEY_BASE + 18;
public static final int BUTTON_LEFT_THUMBSTICK = KEY_BASE + 19;
public static final int BUTTON_RIGHT_THUMBSTICK = KEY_BASE + 20;
public static final int BUTTON_START = KEY_BASE + 21;
public static final int BUTTON_SELECT = KEY_BASE + 22;
void onCreate(Context context);
void onPause();
void onResume();
void onDestroy();
boolean dispatchKeyEvent(KeyEvent event);
boolean dispatchGenericMotionEvent(MotionEvent event);
void setControllerEventListener(ControllerEventListener listener);
public interface ControllerEventListener {
void onButtonEvent(String vendorName, int controller, int button, boolean isPressed, float value, boolean isAnalog);
void onAxisEvent(String vendorName, int controller, int axisID, float value, boolean isAnalog);
void onConnected(String vendorName, int controller);
void onDisconnected(String vendorName, int controller);
}
}
@@ -1,68 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.File;
import java.io.FileInputStream;
public class GameControllerUtils {
public static void ensureDirectoryExist(String path){
File sdkDir = new File(path);
if(!sdkDir.exists()){
sdkDir.mkdirs();
}
}
public static String readJsonFile(String filePath) {
File file = new File(filePath);
if (!file.exists()){
return null;
}
try {
FileInputStream is = new FileInputStream(file);;
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String jsonstr = new String(buffer, "UTF-8");
return jsonstr;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
@@ -1,88 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
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.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import java.lang.ref.WeakReference;
public class ResizeLayout extends FrameLayout {
private boolean mEnableForceDoLayout = false;
private MyLayoutHandler myLayoutHandler = null;
public ResizeLayout(Context context){
super(context);
myLayoutHandler = new MyLayoutHandler(this);
}
public ResizeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setEnableForceDoLayout(boolean flag){
mEnableForceDoLayout = flag;
}
static class MyLayoutHandler extends Handler {
WeakReference<ResizeLayout> mReference;
MyLayoutHandler(ResizeLayout layout)
{
mReference = new WeakReference<ResizeLayout>(layout);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1024: {
ResizeLayout layout = mReference.get();
layout.requestLayout();
layout.invalidate();
break;
}
default:
break;
}
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if(mEnableForceDoLayout){
/*This is a hot-fix for some android devices which don't do layout when the main window
* is paned. We refresh the layout in 24 frames per seconds.
* When the editBox is lose focus or when user begin to type, the do layout is disabled.
*/
myLayoutHandler.sendEmptyMessageDelayed(1024, 1000 / 24);
}
}
}