Commit bfabb962 bfabb962900dbf3ff83cd53779d6737d44a41170 by jinwawa

0802

1 parent fe27a2a7
Showing 313 changed files with 3747 additions and 8 deletions
...@@ -9,6 +9,6 @@ ...@@ -9,6 +9,6 @@
9 <isEffect>1</isEffect> 9 <isEffect>1</isEffect>
10 <fanpai_best>10</fanpai_best> 10 <fanpai_best>10</fanpai_best>
11 <candy_best>2391</candy_best> 11 <candy_best>2391</candy_best>
12 <candy_game_play_cnt>33</candy_game_play_cnt> 12 <candy_game_play_cnt>34</candy_game_play_cnt>
13 <is_game_vip>1</is_game_vip> 13 <is_game_vip>1</is_game_vip>
14 </userDefaultRoot> 14 </userDefaultRoot>
......
...@@ -5,8 +5,7 @@ ...@@ -5,8 +5,7 @@
5 <SchemaVersion>2.0</SchemaVersion> 5 <SchemaVersion>2.0</SchemaVersion>
6 <ProjectGuid>E439935D-B2A2-46AE-856D-2AA408428F33</ProjectGuid> 6 <ProjectGuid>E439935D-B2A2-46AE-856D-2AA408428F33</ProjectGuid>
7 <!--$guid1$--> 7 <!--$guid1$-->
8 <ProjectHome> 8 <ProjectHome>.</ProjectHome>
9 </ProjectHome>
10 <StartupFile> 9 <StartupFile>
11 </StartupFile> 10 </StartupFile>
12 <SearchPath> 11 <SearchPath>
......
...@@ -185,7 +185,7 @@ function GameScene:createBoomFun() ...@@ -185,7 +185,7 @@ function GameScene:createBoomFun()
185 self:createCandy(1,-_info.boom_speed); 185 self:createCandy(1,-_info.boom_speed);
186 end 186 end
187 end 187 end
188 188 --防护罩
189 function GameScene:createShieldFun() 189 function GameScene:createShieldFun()
190 local _info = game_data.get_info_by_score(self.score); 190 local _info = game_data.get_info_by_score(self.score);
191 191
......
...@@ -33,12 +33,9 @@ ...@@ -33,12 +33,9 @@
33 <OpenedDocuments> 33 <OpenedDocuments>
34 <FilePathData Path="ui/candy/LoadingScene.csd" /> 34 <FilePathData Path="ui/candy/LoadingScene.csd" />
35 <FilePathData Path="ui/candy/GameStartLayer.csd" /> 35 <FilePathData Path="ui/candy/GameStartLayer.csd" />
36 <FilePathData Path="ui/candy/GameStartLayer_shdx.csd" />
37 <FilePathData Path="ui/candy/LoadingScene_shdx.csd" /> 36 <FilePathData Path="ui/candy/LoadingScene_shdx.csd" />
38 <FilePathData Path="ui/candy/GameScene.csd" />
39 <FilePathData Path="ui/candy/Girl.csd" />
40 </OpenedDocuments> 37 </OpenedDocuments>
41 <ActiveDocument Path="ui/candy/Girl.csd" /> 38 <ActiveDocument Path="ui/candy/GameStartLayer.csd" />
42 </Value> 39 </Value>
43 </Item> 40 </Item>
44 </Properties> 41 </Properties>
......
1 {
2 "engine_type": "prebuilt",
3 "engine_version": "cocos2d-x-3.10",
4 "has_native": true,
5 "project_type": "lua"
6 }
...\ No newline at end of file ...\ No newline at end of file
1 <?xml version="1.0" encoding="UTF-8"?>
2 <projectDescription>
3 <name>rubbish</name>
4 <comment></comment>
5 <projects>
6 </projects>
7 <buildSpec>
8 </buildSpec>
9 <natures>
10 <nature>org.ccdt.cocosproject</nature>
11 <nature>org.eclipse.koneki.ldt.nature</nature>
12 </natures>
13 </projectDescription>
1 {
2 "engineVersion": "cocos2d-x-3.10",
3 "runtimeVersion": "2.0",
4 "templateVersion": "2.0"
5 }
...\ No newline at end of file ...\ No newline at end of file
1 <?xml version="1.0" encoding="UTF-8"?>
2 <userDefaultRoot>
3 <Account>wwj0728112</Account>
4 <exp>-5</exp>
5 <versionnum>201801291657</versionnum>
6 <best>4186</best>
7 <guess_best>89</guess_best>
8 <isMusic>1</isMusic>
9 <isEffect>1</isEffect>
10 <fanpai_best>10</fanpai_best>
11 <candy_best>2391</candy_best>
12 <candy_game_play_cnt>34</candy_game_play_cnt>
13 <is_game_vip>1</is_game_vip>
14 </userDefaultRoot>
1 {
2 "init_cfg": {
3 "isLandscape": true,
4 "isWindowTop": false,
5 "name": "rubbish",
6 "width": 960,
7 "height": 640,
8 "entry": "src/main.lua",
9 "consolePort": 6050,
10 "uploadPort": 6060
11 },
12 "simulator_screen_size": [
13 {
14 "title": "iPhone 3Gs (480x320)",
15 "width": 480,
16 "height": 320
17 },
18 {
19 "title": "iPhone 4 (960x640)",
20 "width": 960,
21 "height": 640
22 },
23 {
24 "title": "iPhone 5 (1136x640)",
25 "width": 1136,
26 "height": 640
27 },
28 {
29 "title": "iPad (1024x768)",
30 "width": 1024,
31 "height": 768
32 },
33 {
34 "title": "iPad Retina (2048x1536)",
35 "width": 2048,
36 "height": 1536
37 },
38 {
39 "title": "Android (800x480)",
40 "width": 800,
41 "height": 480
42 },
43 {
44 "title": "Android (854x480)",
45 "width": 854,
46 "height": 480
47 },
48 {
49 "title": "Android (1280x720)",
50 "width": 1280,
51 "height": 720
52 },
53 {
54 "title": "Android (1920x1080)",
55 "width": 1920,
56 "height": 1080
57 }
58 ]
59 }
...\ No newline at end of file ...\ No newline at end of file
No preview for this file type
1 <?xml version="1.0" encoding="utf-8"?>
2 <Project ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3 <PropertyGroup>
4 <ProjectView>ShowAllFiles</ProjectView>
5 </PropertyGroup>
6 </Project>
...\ No newline at end of file ...\ No newline at end of file
1 
2 Microsoft Visual Studio Solution File, Format Version 12.00
3 # Visual Studio 2013
4 VisualStudioVersion = 12.0.30501.0
5 MinimumVisualStudioVersion = 10.0.40219.1
6 Project("{5697748A-77EF-44CA-8824-4F5637E5945B}") = "rubbish", "rubbish.luaproj", "{E439935D-B2A2-46AE-856D-2AA408428F33}"
7 EndProject
8 Global
9 GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 Debug|Any CPU = Debug|Any CPU
11 Release|Any CPU = Release|Any CPU
12 EndGlobalSection
13 GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 {E439935D-B2A2-46AE-856D-2AA408428F33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 {E439935D-B2A2-46AE-856D-2AA408428F33}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 {E439935D-B2A2-46AE-856D-2AA408428F33}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 {E439935D-B2A2-46AE-856D-2AA408428F33}.Release|Any CPU.Build.0 = Release|Any CPU
18 EndGlobalSection
19 GlobalSection(SolutionProperties) = preSolution
20 HideSolutionNode = FALSE
21 EndGlobalSection
22 EndGlobal
No preview for this file type
1 #include "AppDelegate.h"
2 #include "CCLuaEngine.h"
3 #include "SimpleAudioEngine.h"
4 #include "cocos2d.h"
5 #include "lua_module_register.h"
6
7 #if (CC_TARGET_PLATFORM != CC_PLATFORM_LINUX)
8 #include "ide-support/CodeIDESupport.h"
9 #endif
10
11 #if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
12 #include "runtime/Runtime.h"
13 #include "ide-support/RuntimeLuaImpl.h"
14 #endif
15
16 using namespace CocosDenshion;
17
18 USING_NS_CC;
19 using namespace std;
20
21 AppDelegate::AppDelegate()
22 {
23 }
24
25 AppDelegate::~AppDelegate()
26 {
27 SimpleAudioEngine::end();
28
29 #if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
30 // NOTE:Please don't remove this call if you want to debug with Cocos Code IDE
31 RuntimeEngine::getInstance()->end();
32 #endif
33
34 }
35
36 //if you want a different context,just modify the value of glContextAttrs
37 //it will takes effect on all platforms
38 void AppDelegate::initGLContextAttrs()
39 {
40 //set OpenGL context attributions,now can only set six attributions:
41 //red,green,blue,alpha,depth,stencil
42 GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
43
44 GLView::setGLContextAttrs(glContextAttrs);
45 }
46
47 // If you want to use packages manager to install more packages,
48 // don't modify or remove this function
49 static int register_all_packages()
50 {
51 return 0; //flag for packages manager
52 }
53
54 bool AppDelegate::applicationDidFinishLaunching()
55 {
56 // set default FPS
57 Director::getInstance()->setAnimationInterval(1.0 / 60.0f);
58
59 // register lua module
60 auto engine = LuaEngine::getInstance();
61 ScriptEngineManager::getInstance()->setScriptEngine(engine);
62 lua_State* L = engine->getLuaStack()->getLuaState();
63 lua_module_register(L);
64
65 register_all_packages();
66
67 LuaStack* stack = engine->getLuaStack();
68 stack->setXXTEAKeyAndSign("2dxLua", strlen("2dxLua"), "XXTEA", strlen("XXTEA"));
69
70 //register custom function
71 //LuaStack* stack = engine->getLuaStack();
72 //register_custom_function(stack->getLuaState());
73
74 #if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
75 // NOTE:Please don't remove this call if you want to debug with Cocos Code IDE
76 auto runtimeEngine = RuntimeEngine::getInstance();
77 runtimeEngine->addRuntime(RuntimeLuaImpl::create(), kRuntimeEngineLua);
78 runtimeEngine->start();
79 #else
80 if (engine->executeScriptFile("src/main.lua"))
81 {
82 return false;
83 }
84 #endif
85
86 return true;
87 }
88
89 // This function will be called when the app is inactive. When comes a phone call,it's be invoked too
90 void AppDelegate::applicationDidEnterBackground()
91 {
92 Director::getInstance()->stopAnimation();
93
94 SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
95 }
96
97 // this function will be called when the app is active again
98 void AppDelegate::applicationWillEnterForeground()
99 {
100 Director::getInstance()->startAnimation();
101
102 SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
103 }
1 #ifndef __APP_DELEGATE_H__
2 #define __APP_DELEGATE_H__
3
4 #include "cocos2d.h"
5
6 /**
7 @brief The cocos2d Application.
8
9 The reason for implement as private inheritance is to hide some interface call by Director.
10 */
11 class AppDelegate : private cocos2d::Application
12 {
13 public:
14 AppDelegate();
15 virtual ~AppDelegate();
16
17 virtual void initGLContextAttrs();
18
19 /**
20 @brief Implement Director and Scene init code here.
21 @return true Initialize success, app continue.
22 @return false Initialize failed, app terminate.
23 */
24 virtual bool applicationDidFinishLaunching();
25
26 /**
27 @brief The function be called when the application enter background
28 @param the pointer of the application
29 */
30 virtual void applicationDidEnterBackground();
31
32 /**
33 @brief The function be called when the application enter foreground
34 @param the pointer of the application
35 */
36 virtual void applicationWillEnterForeground();
37 };
38
39 #endif // __APP_DELEGATE_H__
40
1 #ifndef __CODE_IDE_SUPPORT_H__
2 #define __CODE_IDE_SUPPORT_H__
3
4 // define 1 to open Cocos Code IDE support, 0 to disable
5 #define CC_CODE_IDE_DEBUG_SUPPORT 0
6
7 #endif /* __CODE_IDE_SUPPORT_H__ */
1 //
2 // RuntimeLuaImpl.h
3 // Simulator
4 //
5 //
6
7 #ifndef __Simulator__RuntimeLuaImpl__
8 #define __Simulator__RuntimeLuaImpl__
9
10 #include "CodeIDESupport.h"
11 #include "cocos2d.h"
12
13 #if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
14
15 #include "runtime/RuntimeProtocol.h"
16
17 class RuntimeLuaImpl : public RuntimeProtocol
18 {
19 public:
20 static RuntimeLuaImpl *create();
21
22 void onStartDebuger(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse);
23 void onReload(const rapidjson::Document& dArgParse, rapidjson::Document& dReplyParse);
24 void startScript(const std::string& strDebugArg);
25
26 private:
27 void init();
28 };
29
30 #endif // (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
31
32 #endif /* defined(__Simulator__RuntimeLua__) */
1
2 #include "json/document.h"
3 #include "json/filestream.h"
4 #include "json/stringbuffer.h"
5 #include "json/writer.h"
6 #include "SimpleConfigParser.h"
7
8 // SimpleConfigParser
9 SimpleConfigParser *SimpleConfigParser::s_sharedSimpleConfigParserInstance = NULL;
10 SimpleConfigParser *SimpleConfigParser::getInstance(void)
11 {
12 if (!s_sharedSimpleConfigParserInstance)
13 {
14 s_sharedSimpleConfigParserInstance = new SimpleConfigParser();
15 s_sharedSimpleConfigParserInstance->readConfig();
16 }
17 return s_sharedSimpleConfigParserInstance;
18 }
19
20 void SimpleConfigParser::purge()
21 {
22 CC_SAFE_DELETE(s_sharedSimpleConfigParserInstance);
23 }
24
25 void SimpleConfigParser::readConfig(const string &filepath)
26 {
27 string fullPathFile = filepath;
28
29 // read config file
30 if (fullPathFile.empty())
31 {
32 fullPathFile = FileUtils::getInstance()->fullPathForFilename(CONFIG_FILE);
33 }
34 string fileContent = FileUtils::getInstance()->getStringFromFile(fullPathFile);
35
36 if(fileContent.empty())
37 return;
38
39 if (_docRootjson.Parse<0>(fileContent.c_str()).HasParseError()) {
40 cocos2d::log("read json file %s failed because of %d", fullPathFile.c_str(), _docRootjson.GetParseError());
41 return;
42 }
43
44 if (_docRootjson.HasMember("init_cfg"))
45 {
46 if(_docRootjson["init_cfg"].IsObject())
47 {
48 const rapidjson::Value& objectInitView = _docRootjson["init_cfg"];
49 if (objectInitView.HasMember("isLandscape") && objectInitView["isLandscape"].IsBool())
50 {
51 _isLandscape = objectInitView["isLandscape"].GetBool();
52 }
53 }
54 }
55 }
56
57 SimpleConfigParser::SimpleConfigParser(void) :
58 _isLandscape(true)
59 {
60 }
61
62 rapidjson::Document& SimpleConfigParser::getConfigJsonRoot()
63 {
64 return _docRootjson;
65 }
66
67 bool SimpleConfigParser::isLanscape()
68 {
69 return _isLandscape;
70 }
1 #ifndef __SIMPLE_CONFIG_PARSER_H__
2 #define __SIMPLE_CONFIG_PARSER_H__
3
4 #include <string>
5 #include <vector>
6 #include "cocos2d.h"
7 #include "json/document.h"
8 using namespace std;
9 USING_NS_CC;
10
11 #define CONFIG_FILE "config.json"
12
13 class SimpleConfigParser
14 {
15 public:
16 static SimpleConfigParser *getInstance(void);
17 static void purge();
18
19 void readConfig(const string &filepath = "");
20 bool isLanscape();
21 rapidjson::Document& getConfigJsonRoot();
22 private:
23 SimpleConfigParser(void);
24 static SimpleConfigParser *s_sharedSimpleConfigParserInstance;
25 bool _isLandscape;
26
27 rapidjson::Document _docRootjson;
28 };
29
30 #endif // __SIMPLE_CONFIG_PARSER_H__
31
1 {
2 "zh-CN": {
3 "View": "视图(&V)",
4 "Exit": "退出(&X)",
5 "File": "文件(&F)",
6 "Portrait": "竖屏",
7 "Landscape": "横屏",
8 "Refresh": "刷新(重启)",
9 "Zoom Out": "缩放",
10 "Simulator": "模拟器",
11 "Open File": "打开文件",
12 "Open Project": "打开工程",
13 "Error": "错误",
14 "Help": "帮助(&H)",
15 "About": "关于(&A)"
16 },
17 "zh-Hans": {
18 "View": "视图",
19 "Exit": "退出",
20 "File": "文件",
21 "Portrait": "竖屏",
22 "Landscape": "横屏",
23 "Refresh": "刷新(重启)",
24 "Zoom Out": "缩放",
25 "Simulator": "模拟器",
26 "Help": "帮助(&H)",
27 "About": "关于(&A)"
28 }
29 }
...\ No newline at end of file ...\ No newline at end of file
This diff could not be displayed because it is too large.
1
2 /* lua_debugger.h.h */
3
4 #ifndef __LUA_MODULES_049C000C96FE547176CCBB7690BA01B6_H_
5 #define __LUA_MODULES_049C000C96FE547176CCBB7690BA01B6_H_
6
7 #if __cplusplus
8 extern "C" {
9 #endif
10
11 #include "lua.h"
12
13 void luaopen_lua_debugger(lua_State* L);
14
15 /*
16 int luaopen_lua_m_debugger(lua_State* L);
17 */
18
19 #if __cplusplus
20 }
21 #endif
22
23 #endif /* __LUA_MODULES_049C000C96FE547176CCBB7690BA01B6_H_ */
1 #ifndef __LUA_TEMPLATE_RUNTIME_FRAMEWORKS_RUNTIME_SRC_CLASSES_LUA_MODULE_REGISTER_H__
2 #define __LUA_TEMPLATE_RUNTIME_FRAMEWORKS_RUNTIME_SRC_CLASSES_LUA_MODULE_REGISTER_H__
3
4 #include "lua.h"
5 #include "Lua-BindingsExport.h"
6
7 CC_LUA_DLL int lua_module_register(lua_State* L);
8
9 #endif // __LUA_TEMPLATE_RUNTIME_FRAMEWORKS_RUNTIME_SRC_CLASSES_LUA_MODULE_REGISTER_H__
10
1 <?xml version="1.0" encoding="UTF-8"?>
2 <classpath>
3 <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
4 <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
5 <classpathentry kind="src" path="src"/>
6 <classpathentry kind="src" path="gen"/>
7 <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
8 <classpathentry kind="output" path="bin/classes"/>
9 </classpath>
1 <?xml version="1.0" encoding="UTF-8"?>
2 <projectDescription>
3 <name>rubbish</name>
4 <comment></comment>
5 <projects>
6 </projects>
7 <buildSpec>
8 <buildCommand>
9 <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
10 <arguments>
11 </arguments>
12 </buildCommand>
13 <buildCommand>
14 <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
15 <arguments>
16 </arguments>
17 </buildCommand>
18 <buildCommand>
19 <name>org.eclipse.jdt.core.javabuilder</name>
20 <arguments>
21 </arguments>
22 </buildCommand>
23 <buildCommand>
24 <name>com.android.ide.eclipse.adt.ApkBuilder</name>
25 <arguments>
26 </arguments>
27 </buildCommand>
28 </buildSpec>
29 <natures>
30 <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
31 <nature>org.eclipse.jdt.core.javanature</nature>
32 </natures>
33 </projectDescription>
1 eclipse.preferences.version=1
2 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
3 org.eclipse.jdt.core.compiler.compliance=1.6
4 org.eclipse.jdt.core.compiler.source=1.6
1 <?xml version="1.0" encoding="utf-8"?>
2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3 package="org.cocos2dx.rubbish"
4 android:versionCode="1"
5 android:versionName="1.0"
6 android:installLocation="auto">
7
8 <uses-sdk android:minSdkVersion="9"/>
9 <uses-feature android:glEsVersion="0x00020000" />
10
11 <application android:label="@string/app_name"
12 android:icon="@drawable/icon">
13
14 <!-- Tell Cocos2dxActivity the name of our .so -->
15 <meta-data android:name="android.app.lib_name"
16 android:value="cocos2dlua" />
17
18 <activity android:name="org.cocos2dx.lua.AppActivity"
19 android:label="@string/app_name"
20 android:screenOrientation="landscape"
21 android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
22 android:configChanges="orientation">
23 <intent-filter>
24 <action android:name="android.intent.action.MAIN" />
25 <category android:name="android.intent.category.LAUNCHER" />
26 </intent-filter>
27 </activity>
28 </application>
29
30 <supports-screens android:anyDensity="true"
31 android:smallScreens="true"
32 android:normalScreens="true"
33 android:largeScreens="true"
34 android:xlargeScreens="true"/>
35 <uses-permission android:name="android.permission.INTERNET"/>
36 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
37 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
38 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
39 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
40
41 <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
42 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
43 </manifest>
1 # This file is used to override default values used by the Ant build system.
2 #
3 # This file must be checked into Version Control Systems, as it is
4 # integral to the build system of your project.
5
6 # This file is only used by the Ant script.
7
8 # You can use this to override default values such as
9 # 'source.dir' for the location of your java source folder and
10 # 'out.dir' for the location of your output folder.
11
12 # You can also use it define how the release builds are signed by declaring
13 # the following properties:
14 # 'key.store' for the location of your keystore and
15 # 'key.alias' for the name of the key to use.
16 # The password will be asked during the build when you use the 'release' target.
17
1 {
2 "ndk_module_path" :[
3 "${COCOS_X_ROOT}/cocos2d-x-3.10",
4 "${COCOS_X_ROOT}/cocos2d-x-3.10/cocos/",
5 "${COCOS_X_ROOT}/cocos2d-x-3.10/external",
6 "${COCOS_X_ROOT}/cocos2d-x-3.10/cocos/scripting"
7 ],
8 "copy_resources": [
9 {
10 "from": "../../../src",
11 "to": "src"
12 },
13 {
14 "from": "../../../res",
15 "to": "res"
16 }
17 ],
18 "must_copy_resources": [
19 {
20 "from": "../../../config.json",
21 "to": ""
22 }
23 ]
24 }
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project name="rubbish" default="debug">
3
4 <!-- The local.properties file is created and updated by the 'android' tool.
5 It contains the path to the SDK. It should *NOT* be checked into
6 Version Control Systems. -->
7 <property file="local.properties" />
8
9 <!-- The ant.properties file can be created by you. It is only edited by the
10 'android' tool to add properties to it.
11 This is the place to change some Ant specific build properties.
12 Here are some properties you may want to change/update:
13
14 source.dir
15 The name of the source directory. Default is 'src'.
16 out.dir
17 The name of the output directory. Default is 'bin'.
18
19 For other overridable properties, look at the beginning of the rules
20 files in the SDK, at tools/ant/build.xml
21
22 Properties related to the SDK location or the project target should
23 be updated using the 'android' tool with the 'update' action.
24
25 This file is an integral part of the build system for your
26 application and should be checked into Version Control Systems.
27
28 -->
29 <property file="ant.properties" />
30
31 <!-- The project.properties file is created and updated by the 'android'
32 tool, as well as ADT.
33
34 This contains project specific properties such as project target, and library
35 dependencies. Lower level build properties are stored in ant.properties
36 (or in .classpath for Eclipse projects).
37
38 This file is an integral part of the build system for your
39 application and should be checked into Version Control Systems. -->
40 <loadproperties srcFile="project.properties" />
41
42 <!-- quick check on sdk.dir -->
43 <fail
44 message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through an env var"
45 unless="sdk.dir"
46 />
47
48 <!--
49 Import per project custom build rules if present at the root of the project.
50 This is the place to put custom intermediary targets such as:
51 -pre-build
52 -pre-compile
53 -post-compile (This is typically used for code obfuscation.
54 Compiled code location: ${out.classes.absolute.dir}
55 If this is not done in place, override ${out.dex.input.absolute.dir})
56 -post-package
57 -post-build
58 -pre-clean
59 -->
60 <import file="custom_rules.xml" optional="true" />
61
62 <!-- Import the actual build file.
63
64 To customize existing targets, there are two options:
65 - Customize only one target:
66 - copy/paste the target into this file, *before* the
67 <import> task.
68 - customize it to your needs.
69 - Customize the whole content of build.xml
70 - copy/paste the content of the rules files (minus the top node)
71 into this file, replacing the <import> task.
72 - customize to your needs.
73
74 ***********************
75 ****** IMPORTANT ******
76 ***********************
77 In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
78 in order to avoid having your file be overridden by tools such as "android update project"
79 -->
80 <!-- version-tag: 1 -->
81 <import file="${sdk.dir}/tools/ant/build.xml" />
82
83 </project>
1 LOCAL_PATH := $(call my-dir)
2
3 include $(CLEAR_VARS)
4
5 LOCAL_MODULE := cocos2dlua_shared
6
7 LOCAL_MODULE_FILENAME := libcocos2dlua
8
9 LOCAL_SRC_FILES := \
10 ../../Classes/AppDelegate.cpp \
11 ../../Classes/ide-support/SimpleConfigParser.cpp \
12 ../../Classes/ide-support/RuntimeLuaImpl.cpp \
13 ../../Classes/ide-support/lua_debugger.c \
14 hellolua/main.cpp
15
16 LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes
17
18 # _COCOS_HEADER_ANDROID_BEGIN
19 # _COCOS_HEADER_ANDROID_END
20
21 LOCAL_STATIC_LIBRARIES := cocos2d_lua_static
22 LOCAL_STATIC_LIBRARIES += cocos2d_simulator_static
23
24 # _COCOS_LIB_ANDROID_BEGIN
25 # _COCOS_LIB_ANDROID_END
26
27 include $(BUILD_SHARED_LIBRARY)
28
29 $(call import-module,scripting/lua-bindings/proj.android/prebuilt-mk)
30 $(call import-module,tools/simulator/libsimulator/proj.android/prebuilt-mk)
31
32 # _COCOS_LIB_IMPORT_ANDROID_BEGIN
33 # _COCOS_LIB_IMPORT_ANDROID_END
1 APP_STL := gnustl_static
2
3 APP_CPPFLAGS := -frtti -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -std=c++11 -fsigned-char
4 APP_LDFLAGS := -latomic
5
6
7 ifeq ($(NDK_DEBUG),1)
8 APP_CPPFLAGS += -DCOCOS2D_DEBUG=1
9 APP_OPTIM := debug
10 else
11 APP_CPPFLAGS += -DNDEBUG
12 APP_OPTIM := release
13 endif
1 #include "AppDelegate.h"
2 #include "cocos2d.h"
3 #include "platform/android/jni/JniHelper.h"
4 #include <jni.h>
5 #include <android/log.h>
6 #include "ide-support/SimpleConfigParser.h"
7 #include "ide-support/CodeIDESupport.h"
8
9 #define LOG_TAG "main"
10 #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
11
12 using namespace cocos2d;
13
14 void cocos_android_app_init (JNIEnv* env) {
15 LOGD("cocos_android_app_init");
16 AppDelegate *pAppDelegate = new AppDelegate();
17 }
18
19 extern "C"
20 {
21 bool Java_org_cocos2dx_lua_AppActivity_nativeIsLandScape(JNIEnv *env, jobject thisz)
22 {
23 return SimpleConfigParser::getInstance()->isLanscape();
24 }
25
26 bool Java_org_cocos2dx_lua_AppActivity_nativeIsDebug(JNIEnv *env, jobject thisz)
27 {
28 #if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)
29 return true;
30 #else
31 return false;
32 #endif
33 }
34 }
35
1 # To enable ProGuard in your project, edit project.properties
2 # to define the proguard.config property as described in that file.
3 #
4 # Add project specific ProGuard rules here.
5 # By default, the flags in this file are appended to flags specified
6 # in ${sdk.dir}/tools/proguard/proguard-android.txt
7 # You can edit the include path and order by changing the ProGuard
8 # include property in project.properties.
9 #
10 # For more details, see
11 # http://developer.android.com/guide/developing/tools/proguard.html
12
13 # Add any project specific keep options here:
14
15 # If your project uses WebView with JS, uncomment the following
16 # and specify the fully qualified class name to the JavaScript interface
17 # class:
18 #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
19 # public *;
20 #}
1 # This file is automatically generated by Android Tools.
2 # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
3 #
4 # This file must be checked in Version Control Systems.
5 #
6 # To customize properties used by the Ant build system use,
7 # "ant.properties", and override values to adapt the script to your
8 # project structure.
9
10 # Project target.
11 target=android-10
12
1 <?xml version="1.0" encoding="utf-8"?>
2 <resources>
3 <string name="app_name">rubbish</string>
4 </resources>
1 /****************************************************************************
2 Copyright (c) 2015 Chukong Technologies Inc.
3
4 http://www.cocos2d-x.org
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in
14 all copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 THE SOFTWARE.
23 ****************************************************************************/
24 package com.chukong.cocosplay.client;
25
26 import android.app.Activity;
27
28 public class CocosPlayClient {
29
30 public static boolean init(Activity activity, boolean isDemo) {
31 return false;
32 }
33
34 public static boolean isEnabled() {
35 return false;
36 }
37
38 public static boolean isDemo() {
39 return false;
40 }
41
42 public static boolean isNotifyFileLoadedEnabled() {
43 return false;
44 }
45
46 public static void notifyFileLoaded(String filePath) {
47
48 }
49
50 public static void updateAssets(String filePath) {
51
52 }
53
54 public static String getGameRoot() {
55 return "";
56 }
57
58 public static native String[] getSearchPaths();
59 }
1 package com.enhance.gameservice;
2
3 interface IGameTuningService
4 {
5 int setPreferredResolution(int resolution);
6 int setFramePerSecond(int fps);
7 int boostUp(int seconds);
8 int getAbstractTemperature();
9 int setGamePowerSaving(boolean enable);
10 }
...\ No newline at end of file ...\ No newline at end of file
1 /****************************************************************************
2 Copyright (c) 2010-2011 cocos2d-x.org
3
4 http://www.cocos2d-x.org
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in
14 all copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 THE SOFTWARE.
23 ****************************************************************************/
24 package org.cocos2dx.lib;
25
26 import android.content.Context;
27 import android.content.res.Configuration;
28 import android.hardware.Sensor;
29 import android.hardware.SensorEvent;
30 import android.hardware.SensorEventListener;
31 import android.hardware.SensorManager;
32 import android.view.Display;
33 import android.view.Surface;
34 import android.view.WindowManager;
35
36 public class Cocos2dxAccelerometer implements SensorEventListener {
37 // ===========================================================
38 // Constants
39 // ===========================================================
40
41 private static final String TAG = Cocos2dxAccelerometer.class.getSimpleName();
42
43 // ===========================================================
44 // Fields
45 // ===========================================================
46
47 private final Context mContext;
48 private final SensorManager mSensorManager;
49 private final Sensor mAccelerometer;
50 private final int mNaturalOrientation;
51
52 // ===========================================================
53 // Constructors
54 // ===========================================================
55
56 public Cocos2dxAccelerometer(final Context context) {
57 this.mContext = context;
58
59 this.mSensorManager = (SensorManager) this.mContext.getSystemService(Context.SENSOR_SERVICE);
60 this.mAccelerometer = this.mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
61
62 final Display display = ((WindowManager) this.mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
63 this.mNaturalOrientation = display.getOrientation();
64 }
65
66 // ===========================================================
67 // Getter & Setter
68 // ===========================================================
69
70 public void enable() {
71 this.mSensorManager.registerListener(this, this.mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
72 }
73
74 public void setInterval(float interval) {
75 // Honeycomb version is 11
76 if(android.os.Build.VERSION.SDK_INT < 11) {
77 this.mSensorManager.registerListener(this, this.mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
78 } else {
79 //convert seconds to microseconds
80 this.mSensorManager.registerListener(this, this.mAccelerometer, (int)(interval*100000));
81 }
82 }
83
84 public void disable() {
85 this.mSensorManager.unregisterListener(this);
86 }
87
88 // ===========================================================
89 // Methods for/from SuperClass/Interfaces
90 // ===========================================================
91
92 @Override
93 public void onSensorChanged(final SensorEvent sensorEvent) {
94 if (sensorEvent.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
95 return;
96 }
97
98 float x = sensorEvent.values[0];
99 float y = sensorEvent.values[1];
100 final float z = sensorEvent.values[2];
101
102 /*
103 * Because the axes are not swapped when the device's screen orientation
104 * changes. So we should swap it here. In tablets such as Motorola Xoom,
105 * the default orientation is landscape, so should consider this.
106 */
107 final int orientation = this.mContext.getResources().getConfiguration().orientation;
108
109 if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (this.mNaturalOrientation != Surface.ROTATION_0)) {
110 final float tmp = x;
111 x = -y;
112 y = tmp;
113 } else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (this.mNaturalOrientation != Surface.ROTATION_0)) {
114 final float tmp = x;
115 x = y;
116 y = -tmp;
117 }
118
119 Cocos2dxGLSurfaceView.queueAccelerometer(x,y,z,sensorEvent.timestamp);
120
121 /*
122 if(BuildConfig.DEBUG) {
123 Log.d(TAG, "x = " + sensorEvent.values[0] + " y = " + sensorEvent.values[1] + " z = " + pSensorEvent.values[2]);
124 }
125 */
126 }
127
128 @Override
129 public void onAccuracyChanged(final Sensor sensor, final int accuracy) {
130 }
131
132 // ===========================================================
133 // Methods
134 // Native method called from Cocos2dxGLSurfaceView (To be in the same thread)
135 // ===========================================================
136
137 public static native void onSensorChanged(final float x, final float y, final float z, final long timestamp);
138
139 // ===========================================================
140 // Inner and Anonymous Classes
141 // ===========================================================
142 }
1 /****************************************************************************
2 Copyright (c) 2010-2012 cocos2d-x.org
3 Copyright (c) 2013-2015 Chukong Technologies Inc.
4
5 http://www.cocos2d-x.org
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE.
24 ****************************************************************************/
25 package org.cocos2dx.lib;
26
27 import android.content.Context;
28 import android.graphics.Bitmap;
29 import android.graphics.Canvas;
30 import android.graphics.Rect;
31 import android.graphics.Typeface;
32 import android.text.Layout;
33 import android.text.StaticLayout;
34 import android.text.TextPaint;
35 import android.text.TextUtils;
36 import android.util.Log;
37
38 import java.nio.ByteBuffer;
39 import java.nio.ByteOrder;
40
41 public final class Cocos2dxBitmap {
42 // ===========================================================
43 // Constants
44 // ===========================================================
45
46 /* The values are the same as cocos2dx/platform/CCImage.h. */
47 private static final int HORIZONTAL_ALIGN_LEFT = 1;
48 private static final int HORIZONTAL_ALIGN_RIGHT = 2;
49 private static final int HORIZONTAL_ALIGN_CENTER = 3;
50 private static final int VERTICAL_ALIGN_TOP = 1;
51 private static final int VERTICAL_ALIGN_BOTTOM = 2;
52 private static final int VERTICAL_ALIGN_CENTER = 3;
53
54 // ===========================================================
55 // Fields
56 // ===========================================================
57
58 private static Context sContext;
59
60 // ===========================================================
61 // Getter & Setter
62 // ===========================================================
63
64 public static void setContext(final Context context) {
65 Cocos2dxBitmap.sContext = context;
66 }
67
68 // ===========================================================
69 // Methods for/from SuperClass/Interfaces
70 // ===========================================================
71
72 // ===========================================================
73 // Methods
74 // ===========================================================
75
76 private static native void nativeInitBitmapDC(final int width,
77 final int height, final byte[] pixels);
78
79 public static boolean createTextBitmapShadowStroke(byte[] bytes, final String fontName, int fontSize,
80 int fontTintR, int fontTintG, int fontTintB, int fontTintA,
81 int alignment, int width, int height,
82 boolean shadow, float shadowDX, float shadowDY, float shadowBlur, float shadowOpacity,
83 boolean stroke, int strokeR, int strokeG, int strokeB, int strokeA, float strokeSize) {
84 String string;
85 if (bytes == null || bytes.length == 0) {
86 return false;
87 } else {
88 string = new String(bytes);
89 }
90
91 Layout.Alignment hAlignment = Layout.Alignment.ALIGN_NORMAL;
92 int horizontalAlignment = alignment & 0x0F;
93 switch (horizontalAlignment) {
94 case HORIZONTAL_ALIGN_CENTER:
95 hAlignment = Layout.Alignment.ALIGN_CENTER;
96 break;
97 case HORIZONTAL_ALIGN_RIGHT:
98 hAlignment = Layout.Alignment.ALIGN_OPPOSITE;
99 break;
100 case HORIZONTAL_ALIGN_LEFT:
101 break;
102 default:
103 break;
104 }
105
106 TextPaint paint = Cocos2dxBitmap.newPaint(fontName, fontSize);
107 if (stroke) {
108 paint.setStyle(TextPaint.Style.STROKE);
109 paint.setStrokeWidth(strokeSize);
110 }
111
112 int maxWidth = width;
113 if (maxWidth <= 0) {
114 maxWidth = (int)Math.ceil( StaticLayout.getDesiredWidth(string, paint));
115 }
116 StaticLayout staticLayout = new StaticLayout(string, paint, maxWidth , hAlignment,1.0f,0.0f,false);
117 int layoutWidth = staticLayout.getWidth();
118 int layoutHeight = staticLayout.getLineTop(staticLayout.getLineCount());
119
120 int bitmapWidth = Math.max(layoutWidth, width);
121 int bitmapHeight = layoutHeight;
122 if (height > 0) {
123 bitmapHeight = height;
124 }
125
126 if (bitmapWidth == 0 || bitmapHeight == 0) {
127 return false;
128 }
129
130 int offsetX = 0;
131 if (horizontalAlignment == HORIZONTAL_ALIGN_CENTER) {
132 offsetX = (bitmapWidth - layoutWidth) / 2;
133 }
134 else if (horizontalAlignment == HORIZONTAL_ALIGN_RIGHT) {
135 offsetX = bitmapWidth - layoutWidth;
136 }
137
138 int offsetY = 0;
139 int verticalAlignment = (alignment >> 4) & 0x0F;
140 switch (verticalAlignment)
141 {
142 case VERTICAL_ALIGN_CENTER:
143 offsetY = (bitmapHeight - layoutHeight) / 2;
144 break;
145 case VERTICAL_ALIGN_BOTTOM:
146 offsetY = bitmapHeight - layoutHeight;
147 break;
148 }
149
150 Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
151 Canvas canvas = new Canvas(bitmap);
152 canvas.translate(offsetX, offsetY);
153 if ( stroke )
154 {
155 paint.setARGB(strokeA, strokeR, strokeG, strokeB);
156 staticLayout.draw(canvas);
157 }
158 paint.setStyle(TextPaint.Style.FILL);
159 paint.setARGB(fontTintA, fontTintR, fontTintG, fontTintB);
160 staticLayout.draw(canvas);
161
162 Cocos2dxBitmap.initNativeObject(bitmap);
163 return true;
164 }
165
166 private static TextPaint newPaint(final String fontName, final int fontSize) {
167 final TextPaint paint = new TextPaint();
168 paint.setTextSize(fontSize);
169 paint.setAntiAlias(true);
170
171 // Set type face for paint, now it support .ttf file.
172 if (fontName.endsWith(".ttf")) {
173 try {
174 final Typeface typeFace = Cocos2dxTypefaces.get(
175 Cocos2dxBitmap.sContext, fontName);
176 paint.setTypeface(typeFace);
177 } catch (final Exception e) {
178 Log.e("Cocos2dxBitmap", "error to create ttf type face: "
179 + fontName);
180
181 // The file may not find, use system font.
182 paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL));
183 }
184 } else {
185 paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL));
186 }
187
188 return paint;
189 }
190
191 private static void initNativeObject(final Bitmap bitmap) {
192 final byte[] pixels = Cocos2dxBitmap.getPixels(bitmap);
193 if (pixels == null) {
194 return;
195 }
196
197 Cocos2dxBitmap.nativeInitBitmapDC(bitmap.getWidth(),
198 bitmap.getHeight(), pixels);
199 }
200
201 private static byte[] getPixels(final Bitmap bitmap) {
202 if (bitmap != null) {
203 final byte[] pixels = new byte[bitmap.getWidth()
204 * bitmap.getHeight() * 4];
205 final ByteBuffer buf = ByteBuffer.wrap(pixels);
206 buf.order(ByteOrder.nativeOrder());
207 bitmap.copyPixelsToBuffer(buf);
208 return pixels;
209 }
210
211 return null;
212 }
213
214 public static int getFontSizeAccordingHeight(int height) {
215 TextPaint paint = new TextPaint();
216 Rect bounds = new Rect();
217
218 paint.setTypeface(Typeface.DEFAULT);
219 int text_size = 1;
220 boolean found_desired_size = false;
221
222 while (!found_desired_size) {
223 paint.setTextSize(text_size);
224 String text = "SghMNy";
225 paint.getTextBounds(text, 0, text.length(), bounds);
226
227 text_size++;
228
229 if (height - bounds.height() <= 2) {
230 found_desired_size = true;
231 }
232 }
233 return text_size;
234 }
235
236 private static String getStringWithEllipsis(String string, float width,
237 float fontSize) {
238 if (TextUtils.isEmpty(string)) {
239 return "";
240 }
241
242 TextPaint paint = new TextPaint();
243 paint.setTypeface(Typeface.DEFAULT);
244 paint.setTextSize(fontSize);
245
246 return TextUtils.ellipsize(string, paint, width,
247 TextUtils.TruncateAt.END).toString();
248 }
249 }
1 /****************************************************************************
2 Copyright (c) 2010-2012 cocos2d-x.org
3 Copyright (c) 2013-2015 Chukong Technologies Inc.
4
5 http://www.cocos2d-x.org
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE.
24 ****************************************************************************/
25 package org.cocos2dx.lib;
26
27 import android.content.Context;
28 import android.graphics.Color;
29 import android.graphics.Typeface;
30 import android.text.InputFilter;
31 import android.text.InputType;
32 import android.text.method.PasswordTransformationMethod;
33 import android.util.Log;
34 import android.view.Gravity;
35 import android.view.KeyEvent;
36 import android.view.View;
37 import android.view.inputmethod.EditorInfo;
38 import android.widget.EditText;
39 import android.widget.FrameLayout;
40
41 public class Cocos2dxEditBox extends EditText {
42 /**
43 * The user is allowed to enter any text, including line breaks.
44 */
45 private final int kEditBoxInputModeAny = 0;
46
47 /**
48 * The user is allowed to enter an e-mail address.
49 */
50 private final int kEditBoxInputModeEmailAddr = 1;
51
52 /**
53 * The user is allowed to enter an integer value.
54 */
55 private final int kEditBoxInputModeNumeric = 2;
56
57 /**
58 * The user is allowed to enter a phone number.
59 */
60 private final int kEditBoxInputModePhoneNumber = 3;
61
62 /**
63 * The user is allowed to enter a URL.
64 */
65 private final int kEditBoxInputModeUrl = 4;
66
67 /**
68 * The user is allowed to enter a real number value. This extends kEditBoxInputModeNumeric by allowing a decimal point.
69 */
70 private final int kEditBoxInputModeDecimal = 5;
71
72 /**
73 * The user is allowed to enter any text, except for line breaks.
74 */
75 private final int kEditBoxInputModeSingleLine = 6;
76
77 /**
78 * Indicates that the text entered is confidential data that should be obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE.
79 */
80 private final int kEditBoxInputFlagPassword = 0;
81
82 /**
83 * 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.
84 */
85 private final int kEditBoxInputFlagSensitive = 1;
86
87 /**
88 * This flag is a hint to the implementation that during text editing, the initial letter of each word should be capitalized.
89 */
90 private final int kEditBoxInputFlagInitialCapsWord = 2;
91
92 /**
93 * This flag is a hint to the implementation that during text editing, the initial letter of each sentence should be capitalized.
94 */
95 private final int kEditBoxInputFlagInitialCapsSentence = 3;
96
97 /**
98 * Capitalize all characters automatically.
99 */
100 private final int kEditBoxInputFlagInitialCapsAllCharacters = 4;
101
102 private final int kKeyboardReturnTypeDefault = 0;
103 private final int kKeyboardReturnTypeDone = 1;
104 private final int kKeyboardReturnTypeSend = 2;
105 private final int kKeyboardReturnTypeSearch = 3;
106 private final int kKeyboardReturnTypeGo = 4;
107
108 private int mInputFlagConstraints;
109 private int mInputModeConstraints;
110 private int mMaxLength;
111
112 //OpenGL view scaleX
113 private float mScaleX;
114
115
116
117
118 public Cocos2dxEditBox(Context context){
119 super(context);
120 }
121
122 public void setEditBoxViewRect(int left, int top, int maxWidth, int maxHeight) {
123 FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
124 FrameLayout.LayoutParams.WRAP_CONTENT);
125 layoutParams.leftMargin = left;
126 layoutParams.topMargin = top;
127 layoutParams.width = maxWidth;
128 layoutParams.height = maxHeight;
129 layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
130 this.setLayoutParams(layoutParams);
131 }
132
133 public float getOpenGLViewScaleX() {
134 return mScaleX;
135 }
136
137 public void setOpenGLViewScaleX(float mScaleX) {
138 this.mScaleX = mScaleX;
139 }
140
141
142 public void setMaxLength(int maxLength){
143 this.mMaxLength = maxLength;
144
145 this.setFilters(new InputFilter[]{new InputFilter.LengthFilter(this.mMaxLength) });
146 }
147
148 public void setMultilineEnabled(boolean flag){
149 this.mInputModeConstraints |= InputType.TYPE_TEXT_FLAG_MULTI_LINE;
150 }
151
152 public void setReturnType(int returnType) {
153 switch (returnType) {
154 case kKeyboardReturnTypeDefault:
155 this.setImeOptions(EditorInfo.IME_ACTION_NONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
156 break;
157 case kKeyboardReturnTypeDone:
158 this.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
159 break;
160 case kKeyboardReturnTypeSend:
161 this.setImeOptions(EditorInfo.IME_ACTION_SEND | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
162 break;
163 case kKeyboardReturnTypeSearch:
164 this.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
165 break;
166 case kKeyboardReturnTypeGo:
167 this.setImeOptions(EditorInfo.IME_ACTION_GO | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
168 break;
169 default:
170 this.setImeOptions(EditorInfo.IME_ACTION_NONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
171 break;
172 }
173 }
174
175 public void setInputMode(int inputMode){
176
177 switch (inputMode) {
178 case kEditBoxInputModeAny:
179 this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE;
180 break;
181 case kEditBoxInputModeEmailAddr:
182 this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
183 break;
184 case kEditBoxInputModeNumeric:
185 this.mInputModeConstraints = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED;
186 break;
187 case kEditBoxInputModePhoneNumber:
188 this.mInputModeConstraints = InputType.TYPE_CLASS_PHONE;
189 break;
190 case kEditBoxInputModeUrl:
191 this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI;
192 break;
193 case kEditBoxInputModeDecimal:
194 this.mInputModeConstraints = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED;
195 break;
196 case kEditBoxInputModeSingleLine:
197 this.mInputModeConstraints = InputType.TYPE_CLASS_TEXT;
198 break;
199 default:
200
201 break;
202 }
203
204 this.setInputType(this.mInputModeConstraints | this.mInputFlagConstraints);
205
206 }
207
208 @Override
209 public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
210 switch (pKeyCode) {
211 case KeyEvent.KEYCODE_BACK:
212 Cocos2dxActivity activity = (Cocos2dxActivity)this.getContext();
213 //To prevent program from going to background
214 activity.getGLSurfaceView().requestFocus();
215 return true;
216 default:
217 return super.onKeyDown(pKeyCode, pKeyEvent);
218 }
219 }
220
221 @Override
222 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
223 return super.onKeyPreIme(keyCode, event);
224 }
225
226 public void setInputFlag(int inputFlag) {
227
228 switch (inputFlag) {
229 case kEditBoxInputFlagPassword:
230 this.mInputFlagConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
231 this.setTypeface(Typeface.DEFAULT);
232 this.setTransformationMethod(new PasswordTransformationMethod());
233 break;
234 case kEditBoxInputFlagSensitive:
235 this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
236 break;
237 case kEditBoxInputFlagInitialCapsWord:
238 this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_WORDS;
239 break;
240 case kEditBoxInputFlagInitialCapsSentence:
241 this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
242 break;
243 case kEditBoxInputFlagInitialCapsAllCharacters:
244 this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS;
245 break;
246 default:
247 break;
248 }
249
250 this.setInputType(this.mInputFlagConstraints | this.mInputModeConstraints);
251 }
252 }
1 /****************************************************************************
2 Copyright (c) 2010-2011 cocos2d-x.org
3
4 http://www.cocos2d-x.org
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in
14 all copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 THE SOFTWARE.
23 ****************************************************************************/
24
25 package org.cocos2dx.lib;
26
27 import android.app.AlertDialog;
28 import android.content.DialogInterface;
29 import android.os.Handler;
30 import android.os.Message;
31
32 import java.lang.ref.WeakReference;
33
34 public class Cocos2dxHandler extends Handler {
35 // ===========================================================
36 // Constants
37 // ===========================================================
38 public final static int HANDLER_SHOW_DIALOG = 1;
39
40 // ===========================================================
41 // Fields
42 // ===========================================================
43 private WeakReference<Cocos2dxActivity> mActivity;
44
45 // ===========================================================
46 // Constructors
47 // ===========================================================
48 public Cocos2dxHandler(Cocos2dxActivity activity) {
49 this.mActivity = new WeakReference<Cocos2dxActivity>(activity);
50 }
51
52 // ===========================================================
53 // Getter & Setter
54 // ===========================================================
55
56 // ===========================================================
57 // Methods for/from SuperClass/Interfaces
58 // ===========================================================
59
60 // ===========================================================
61 // Methods
62 // ===========================================================
63
64 public void handleMessage(Message msg) {
65 switch (msg.what) {
66 case Cocos2dxHandler.HANDLER_SHOW_DIALOG:
67 showDialog(msg);
68 break;
69 }
70 }
71
72 private void showDialog(Message msg) {
73 Cocos2dxActivity theActivity = this.mActivity.get();
74 DialogMessage dialogMessage = (DialogMessage)msg.obj;
75 new AlertDialog.Builder(theActivity)
76 .setTitle(dialogMessage.titile)
77 .setMessage(dialogMessage.message)
78 .setPositiveButton("Ok",
79 new DialogInterface.OnClickListener() {
80
81 @Override
82 public void onClick(DialogInterface dialog, int which) {
83 // TODO Auto-generated method stub
84
85 }
86 }).create().show();
87 }
88
89
90 // ===========================================================
91 // Inner and Anonymous Classes
92 // ===========================================================
93
94 public static class DialogMessage {
95 public String titile;
96 public String message;
97
98 public DialogMessage(String title, String message) {
99 this.titile = title;
100 this.message = message;
101 }
102 }
103 }
1 /*
2 * Copyright (c) 2013-2014 Chukong Technologies Inc.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 * THE SOFTWARE.
21 */
22
23 package org.cocos2dx.lib;
24
25 public class Cocos2dxJavascriptJavaBridge {
26 public static native int evalString(String value);
27 }
1 /****************************************************************************
2 Copyright (c) 2013-2014 Chukong Technologies Inc.
3
4 http://www.cocos2d-x.org
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in
14 all copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 THE SOFTWARE.
23 ****************************************************************************/
24 package org.cocos2dx.lib;
25
26 import android.content.Context;
27 import android.database.Cursor;
28 import android.database.sqlite.SQLiteDatabase;
29 import android.database.sqlite.SQLiteOpenHelper;
30 import android.util.Log;
31
32
33 public class Cocos2dxLocalStorage {
34
35 private static final String TAG = "Cocos2dxLocalStorage";
36
37 private static String DATABASE_NAME = "jsb.sqlite";
38 private static String TABLE_NAME = "data";
39 private static final int DATABASE_VERSION = 1;
40
41 private static DBOpenHelper mDatabaseOpenHelper = null;
42 private static SQLiteDatabase mDatabase = null;
43 /**
44 * Constructor
45 * @param context The Context within which to work, used to create the DB
46 * @return
47 */
48 public static boolean init(String dbName, String tableName) {
49 if (Cocos2dxActivity.getContext() != null) {
50 DATABASE_NAME = dbName;
51 TABLE_NAME = tableName;
52 mDatabaseOpenHelper = new DBOpenHelper(Cocos2dxActivity.getContext());
53 mDatabase = mDatabaseOpenHelper.getWritableDatabase();
54 return true;
55 }
56 return false;
57 }
58
59 public static void destory() {
60 if (mDatabase != null) {
61 mDatabase.close();
62 }
63 }
64
65 public static void setItem(String key, String value) {
66 try {
67 String sql = "replace into "+TABLE_NAME+"(key,value)values(?,?)";
68 mDatabase.execSQL(sql, new Object[] { key, value });
69 } catch (Exception e) {
70 e.printStackTrace();
71 }
72 }
73
74 public static String getItem(String key) {
75 String ret = null;
76 try {
77 String sql = "select value from "+TABLE_NAME+" where key=?";
78 Cursor c = mDatabase.rawQuery(sql, new String[]{key});
79 while (c.moveToNext()) {
80 // only return the first value
81 if (ret != null)
82 {
83 Log.e(TAG, "The key contains more than one value.");
84 break;
85 }
86 ret = c.getString(c.getColumnIndex("value"));
87 }
88 c.close();
89 } catch (Exception e) {
90 e.printStackTrace();
91 }
92 return ret == null ? "" : ret;
93 }
94
95 public static void removeItem(String key) {
96 try {
97 String sql = "delete from "+TABLE_NAME+" where key=?";
98 mDatabase.execSQL(sql, new Object[] {key});
99 } catch (Exception e) {
100 e.printStackTrace();
101 }
102 }
103
104 public static void clear() {
105 try {
106 String sql = "delete from "+TABLE_NAME;
107 mDatabase.execSQL(sql);
108 } catch (Exception e) {
109 e.printStackTrace();
110 }
111 }
112
113
114 /**
115 * This creates/opens the database.
116 */
117 private static class DBOpenHelper extends SQLiteOpenHelper {
118
119 DBOpenHelper(Context context) {
120 super(context, DATABASE_NAME, null, DATABASE_VERSION);
121 }
122
123 @Override
124 public void onCreate(SQLiteDatabase db) {
125 db.execSQL("CREATE TABLE IF NOT EXISTS "+TABLE_NAME+"(key TEXT PRIMARY KEY,value TEXT);");
126 }
127
128 @Override
129 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
130 Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
131 + newVersion + ", which will destroy all old data");
132 //db.execSQL("DROP TABLE IF EXISTS " + VIRTUAL_TABLE);
133 //onCreate(db);
134 }
135 }
136 }
1 /****************************************************************************
2 Copyright (c) 2013-2014 Chukong Technologies Inc.
3
4 http://www.cocos2d-x.org
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in
14 all copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 THE SOFTWARE.
23 ****************************************************************************/
24
25 package org.cocos2dx.lib;
26
27 public class Cocos2dxLuaJavaBridge
28 {
29 public static native int callLuaFunctionWithString(int luaFunctionId, String value);
30 public static native int callLuaGlobalFunctionWithString(String luaFunctionName, String value);
31 public static native int retainLuaFunction(int luaFunctionId);
32 public static native int releaseLuaFunction(int luaFunctionId);
33 }
1 /****************************************************************************
2 Copyright (c) 2010-2012 cocos2d-x.org
3 Copyright (c) 2013-2014 Chukong Technologies Inc.
4
5 http://www.cocos2d-x.org
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE.
24 ****************************************************************************/
25
26 package org.cocos2dx.lib;
27
28 import android.content.Context;
29 import android.content.res.AssetFileDescriptor;
30 import android.media.MediaPlayer;
31 import android.util.Log;
32
33 import com.chukong.cocosplay.client.CocosPlayClient;
34
35 import java.io.FileInputStream;
36
37 public class Cocos2dxMusic {
38 // ===========================================================
39 // Constants
40 // ===========================================================
41
42 private static final String TAG = Cocos2dxMusic.class.getSimpleName();
43
44 // ===========================================================
45 // Fields
46 // ===========================================================
47
48 private final Context mContext;
49 private MediaPlayer mBackgroundMediaPlayer;
50 private float mLeftVolume;
51 private float mRightVolume;
52 private boolean mPaused; // whether music is paused state.
53 private boolean mIsLoop = false;
54 private boolean mManualPaused = false; // whether music is paused manually before the program is switched to the background.
55 private String mCurrentPath;
56
57 // ===========================================================
58 // Constructors
59 // ===========================================================
60
61 public Cocos2dxMusic(final Context context) {
62 this.mContext = context;
63
64 this.initData();
65 }
66
67 // ===========================================================
68 // Getter & Setter
69 // ===========================================================
70
71 // ===========================================================
72 // Methods for/from SuperClass/Interfaces
73 // ===========================================================
74
75 // ===========================================================
76 // Methods
77 // ===========================================================
78
79 public void preloadBackgroundMusic(final String path) {
80 if ((this.mCurrentPath == null) || (!this.mCurrentPath.equals(path))) {
81 // preload new background music
82
83 // release old resource and create a new one
84 if (this.mBackgroundMediaPlayer != null) {
85 this.mBackgroundMediaPlayer.release();
86 }
87
88 this.mBackgroundMediaPlayer = this.createMediaplayer(path);
89
90 // record the path
91 this.mCurrentPath = path;
92 }
93 }
94
95 public void playBackgroundMusic(final String path, final boolean isLoop) {
96 if (mCurrentPath == null) {
97 // it is the first time to play background music or end() was called
98 mBackgroundMediaPlayer = createMediaplayer(path);
99 mCurrentPath = path;
100 } else {
101 if (!mCurrentPath.equals(path)) {
102 // play new background music
103
104 // release old resource and create a new one
105 if (mBackgroundMediaPlayer != null) {
106 mBackgroundMediaPlayer.release();
107 }
108 mBackgroundMediaPlayer = createMediaplayer(path);
109
110 // record the path
111 mCurrentPath = path;
112 }
113 }
114
115 if (mBackgroundMediaPlayer == null) {
116 Log.e(Cocos2dxMusic.TAG, "playBackgroundMusic: background media player is null");
117 } else {
118 try {
119 // if the music is playing or paused, stop it
120 if (mPaused) {
121 mBackgroundMediaPlayer.seekTo(0);
122 mBackgroundMediaPlayer.start();
123 } else if (mBackgroundMediaPlayer.isPlaying()) {
124 mBackgroundMediaPlayer.seekTo(0);
125 } else {
126 mBackgroundMediaPlayer.start();
127 }
128 mBackgroundMediaPlayer.setLooping(isLoop);
129 mPaused = false;
130 mIsLoop = isLoop;
131 } catch (final Exception e) {
132 Log.e(Cocos2dxMusic.TAG, "playBackgroundMusic: error state");
133 }
134 }
135 }
136
137 public void stopBackgroundMusic() {
138 if (this.mBackgroundMediaPlayer != null) {
139 mBackgroundMediaPlayer.release();
140 mBackgroundMediaPlayer = createMediaplayer(mCurrentPath);
141
142 /**
143 * should set the state, if not, the following sequence will be error
144 * play -> pause -> stop -> resume
145 */
146 this.mPaused = false;
147 }
148 }
149
150 public void pauseBackgroundMusic() {
151 if (this.mBackgroundMediaPlayer != null && this.mBackgroundMediaPlayer.isPlaying()) {
152 this.mBackgroundMediaPlayer.pause();
153 this.mPaused = true;
154 this.mManualPaused = true;
155 }
156 }
157
158 public void resumeBackgroundMusic() {
159 if (this.mBackgroundMediaPlayer != null && this.mPaused) {
160 this.mBackgroundMediaPlayer.start();
161 this.mPaused = false;
162 this.mManualPaused = false;
163 }
164 }
165
166 public void rewindBackgroundMusic() {
167 if (this.mBackgroundMediaPlayer != null) {
168 playBackgroundMusic(mCurrentPath, mIsLoop);
169 }
170 }
171
172 public boolean isBackgroundMusicPlaying() {
173 boolean ret = false;
174
175 if (this.mBackgroundMediaPlayer == null) {
176 ret = false;
177 } else {
178 ret = this.mBackgroundMediaPlayer.isPlaying();
179 }
180
181 return ret;
182 }
183
184 public void end() {
185 if (this.mBackgroundMediaPlayer != null) {
186 this.mBackgroundMediaPlayer.release();
187 }
188
189 this.initData();
190 }
191
192 public float getBackgroundVolume() {
193 if (this.mBackgroundMediaPlayer != null) {
194 return (this.mLeftVolume + this.mRightVolume) / 2;
195 } else {
196 return 0.0f;
197 }
198 }
199
200 public void setBackgroundVolume(float volume) {
201 if (volume < 0.0f) {
202 volume = 0.0f;
203 }
204
205 if (volume > 1.0f) {
206 volume = 1.0f;
207 }
208
209 this.mLeftVolume = this.mRightVolume = volume;
210 if (this.mBackgroundMediaPlayer != null) {
211 this.mBackgroundMediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume);
212 }
213 }
214
215 public void onEnterBackground(){
216 if (this.mBackgroundMediaPlayer != null && this.mBackgroundMediaPlayer.isPlaying()) {
217 this.mBackgroundMediaPlayer.pause();
218 this.mPaused = true;
219 }
220 }
221
222 public void onEnterForeground(){
223 if(!this.mManualPaused){
224 if (this.mBackgroundMediaPlayer != null && this.mPaused) {
225 this.mBackgroundMediaPlayer.start();
226 this.mPaused = false;
227 }
228 }
229 }
230
231 private void initData() {
232 this.mLeftVolume = 0.5f;
233 this.mRightVolume = 0.5f;
234 this.mBackgroundMediaPlayer = null;
235 this.mPaused = false;
236 this.mCurrentPath = null;
237 }
238
239 /**
240 * create mediaplayer for music
241 *
242 * @param pPath
243 * the pPath relative to assets
244 * @return
245 */
246 private MediaPlayer createMediaplayer(final String path) {
247 MediaPlayer mediaPlayer = new MediaPlayer();
248
249 try {
250 if (CocosPlayClient.isEnabled() && !CocosPlayClient.isDemo()) {
251 CocosPlayClient.updateAssets(path);
252 }
253 CocosPlayClient.notifyFileLoaded(path);
254 if (path.startsWith("/")) {
255 final FileInputStream fis = new FileInputStream(path);
256 mediaPlayer.setDataSource(fis.getFD());
257 fis.close();
258 } else {
259 final AssetFileDescriptor assetFileDescritor = this.mContext.getAssets().openFd(path);
260 mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength());
261 }
262
263 mediaPlayer.prepare();
264
265 mediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume);
266 } catch (final Exception e) {
267 mediaPlayer = null;
268 Log.e(Cocos2dxMusic.TAG, "error: " + e.getMessage(), e);
269 }
270
271 return mediaPlayer;
272 }
273
274 // ===========================================================
275 // Inner and Anonymous Classes
276 // ===========================================================
277 }
1 /****************************************************************************
2 Copyright (c) 2010-2011 cocos2d-x.org
3
4 http://www.cocos2d-x.org
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in
14 all copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 THE SOFTWARE.
23 ****************************************************************************/
24 package org.cocos2dx.lib;
25
26 import android.opengl.GLSurfaceView;
27
28 import javax.microedition.khronos.egl.EGLConfig;
29 import javax.microedition.khronos.opengles.GL10;
30 public class Cocos2dxRenderer implements GLSurfaceView.Renderer {
31 // ===========================================================
32 // Constants
33 // ===========================================================
34
35 private final static long NANOSECONDSPERSECOND = 1000000000L;
36 private final static long NANOSECONDSPERMICROSECOND = 1000000;
37
38 private static long sAnimationInterval = (long) (1.0 / 60 * Cocos2dxRenderer.NANOSECONDSPERSECOND);
39
40 // ===========================================================
41 // Fields
42 // ===========================================================
43
44 private long mLastTickInNanoSeconds;
45 private int mScreenWidth;
46 private int mScreenHeight;
47 private boolean mNativeInitCompleted = false;
48
49 // ===========================================================
50 // Constructors
51 // ===========================================================
52
53 // ===========================================================
54 // Getter & Setter
55 // ===========================================================
56
57 public static void setAnimationInterval(final float animationInterval) {
58 Cocos2dxRenderer.sAnimationInterval = (long) (animationInterval * Cocos2dxRenderer.NANOSECONDSPERSECOND);
59 }
60
61 public void setScreenWidthAndHeight(final int surfaceWidth, final int surfaceHeight) {
62 this.mScreenWidth = surfaceWidth;
63 this.mScreenHeight = surfaceHeight;
64 }
65
66 // ===========================================================
67 // Methods for/from SuperClass/Interfaces
68 // ===========================================================
69
70 @Override
71 public void onSurfaceCreated(final GL10 GL10, final EGLConfig EGLConfig) {
72 Cocos2dxRenderer.nativeInit(this.mScreenWidth, this.mScreenHeight);
73 this.mLastTickInNanoSeconds = System.nanoTime();
74 mNativeInitCompleted = true;
75 }
76
77 @Override
78 public void onSurfaceChanged(final GL10 GL10, final int width, final int height) {
79 Cocos2dxRenderer.nativeOnSurfaceChanged(width, height);
80 }
81
82 @Override
83 public void onDrawFrame(final GL10 gl) {
84 /*
85 * No need to use algorithm in default(60 FPS) situation,
86 * since onDrawFrame() was called by system 60 times per second by default.
87 */
88 if (sAnimationInterval <= 1.0 / 60 * Cocos2dxRenderer.NANOSECONDSPERSECOND) {
89 Cocos2dxRenderer.nativeRender();
90 } else {
91 final long now = System.nanoTime();
92 final long interval = now - this.mLastTickInNanoSeconds;
93
94 if (interval < Cocos2dxRenderer.sAnimationInterval) {
95 try {
96 Thread.sleep((Cocos2dxRenderer.sAnimationInterval - interval) / Cocos2dxRenderer.NANOSECONDSPERMICROSECOND);
97 } catch (final Exception e) {
98 }
99 }
100 /*
101 * Render time MUST be counted in, or the FPS will slower than appointed.
102 */
103 this.mLastTickInNanoSeconds = System.nanoTime();
104 Cocos2dxRenderer.nativeRender();
105 }
106 }
107
108 // ===========================================================
109 // Methods
110 // ===========================================================
111
112 private static native void nativeTouchesBegin(final int id, final float x, final float y);
113 private static native void nativeTouchesEnd(final int id, final float x, final float y);
114 private static native void nativeTouchesMove(final int[] ids, final float[] xs, final float[] ys);
115 private static native void nativeTouchesCancel(final int[] ids, final float[] xs, final float[] ys);
116 private static native boolean nativeKeyEvent(final int keyCode,boolean isPressed);
117 private static native void nativeRender();
118 private static native void nativeInit(final int width, final int height);
119 private static native void nativeOnSurfaceChanged(final int width, final int height);
120 private static native void nativeOnPause();
121 private static native void nativeOnResume();
122
123 public void handleActionDown(final int id, final float x, final float y) {
124 Cocos2dxRenderer.nativeTouchesBegin(id, x, y);
125 }
126
127 public void handleActionUp(final int id, final float x, final float y) {
128 Cocos2dxRenderer.nativeTouchesEnd(id, x, y);
129 }
130
131 public void handleActionCancel(final int[] ids, final float[] xs, final float[] ys) {
132 Cocos2dxRenderer.nativeTouchesCancel(ids, xs, ys);
133 }
134
135 public void handleActionMove(final int[] ids, final float[] xs, final float[] ys) {
136 Cocos2dxRenderer.nativeTouchesMove(ids, xs, ys);
137 }
138
139 public void handleKeyDown(final int keyCode) {
140 Cocos2dxRenderer.nativeKeyEvent(keyCode, true);
141 }
142
143 public void handleKeyUp(final int keyCode) {
144 Cocos2dxRenderer.nativeKeyEvent(keyCode, false);
145 }
146
147 public void handleOnPause() {
148 /**
149 * onPause may be invoked before onSurfaceCreated,
150 * and engine will be initialized correctly after
151 * onSurfaceCreated is invoked. Can not invoke any
152 * native method before onSurfaceCreated is invoked
153 */
154 if (! mNativeInitCompleted)
155 return;
156
157 Cocos2dxHelper.onEnterBackground();
158 Cocos2dxRenderer.nativeOnPause();
159 }
160
161 public void handleOnResume() {
162 Cocos2dxHelper.onEnterForeground();
163 Cocos2dxRenderer.nativeOnResume();
164 }
165
166 private static native void nativeInsertText(final String text);
167 private static native void nativeDeleteBackward();
168 private static native String nativeGetContentText();
169
170 public void handleInsertText(final String text) {
171 Cocos2dxRenderer.nativeInsertText(text);
172 }
173
174 public void handleDeleteBackward() {
175 Cocos2dxRenderer.nativeDeleteBackward();
176 }
177
178 public String getContentText() {
179 return Cocos2dxRenderer.nativeGetContentText();
180 }
181
182 // ===========================================================
183 // Inner and Anonymous Classes
184 // ===========================================================
185 }
1 /****************************************************************************
2 Copyright (c) 2010-2011 cocos2d-x.org
3
4 http://www.cocos2d-x.org
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in
14 all copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 THE SOFTWARE.
23 ****************************************************************************/
24 package org.cocos2dx.lib;
25
26 import android.content.Context;
27 import android.text.Editable;
28 import android.text.TextWatcher;
29 import android.util.Log;
30 import android.view.KeyEvent;
31 import android.view.inputmethod.EditorInfo;
32 import android.view.inputmethod.InputMethodManager;
33 import android.widget.TextView;
34 import android.widget.TextView.OnEditorActionListener;
35
36 public class Cocos2dxTextInputWraper implements TextWatcher, OnEditorActionListener {
37 // ===========================================================
38 // Constants
39 // ===========================================================
40
41 private static final String TAG = Cocos2dxTextInputWraper.class.getSimpleName();
42
43 // ===========================================================
44 // Fields
45 // ===========================================================
46
47 private final Cocos2dxGLSurfaceView mCocos2dxGLSurfaceView;
48 private String mText;
49 private String mOriginText;
50
51 // ===========================================================
52 // Constructors
53 // ===========================================================
54
55 public Cocos2dxTextInputWraper(final Cocos2dxGLSurfaceView pCocos2dxGLSurfaceView) {
56 this.mCocos2dxGLSurfaceView = pCocos2dxGLSurfaceView;
57 }
58
59 // ===========================================================
60 // Getter & Setter
61 // ===========================================================
62
63 private boolean isFullScreenEdit() {
64 final TextView textField = this.mCocos2dxGLSurfaceView.getCocos2dxEditText();
65 final InputMethodManager imm = (InputMethodManager) textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
66 return imm.isFullscreenMode();
67 }
68
69 public void setOriginText(final String pOriginText) {
70 this.mOriginText = pOriginText;
71 }
72
73 // ===========================================================
74 // Methods for/from SuperClass/Interfaces
75 // ===========================================================
76
77 @Override
78 public void afterTextChanged(final Editable s) {
79 if (this.isFullScreenEdit()) {
80 return;
81 }
82 int old_i = 0;
83 int new_i = 0;
84 while (old_i < this.mText.length() && new_i < s.length()) {
85 if (this.mText.charAt(old_i) != s.charAt(new_i)) {
86 break;
87 }
88 old_i += 1;
89 new_i += 1;
90 }
91
92 for (; old_i < this.mText.length(); ++old_i) {
93 this.mCocos2dxGLSurfaceView.deleteBackward();
94 }
95
96 int nModified = s.length() - new_i;
97 if (nModified > 0) {
98 final String insertText = s.subSequence(new_i, s.length()).toString();
99 this.mCocos2dxGLSurfaceView.insertText(insertText);
100 }
101
102 this.mText = s.toString();
103 }
104
105 @Override
106 public void beforeTextChanged(final CharSequence pCharSequence, final int start, final int count, final int after) {
107 this.mText = pCharSequence.toString();
108 }
109
110 @Override
111 public void onTextChanged(final CharSequence pCharSequence, final int start, final int before, final int count) {
112
113 }
114
115 @Override
116 public boolean onEditorAction(final TextView pTextView, final int pActionID, final KeyEvent pKeyEvent) {
117 if (this.mCocos2dxGLSurfaceView.getCocos2dxEditText() == pTextView && this.isFullScreenEdit()) {
118 // user press the action button, delete all old text and insert new text
119 if (null != mOriginText) {
120 for (int i = this.mOriginText.length(); i > 0; i--) {
121 this.mCocos2dxGLSurfaceView.deleteBackward();
122 }
123 }
124
125 String text = pTextView.getText().toString();
126
127 if (text != null) {
128 /* If user input nothing, translate "\n" to engine. */
129 if ( text.compareTo("") == 0) {
130 text = "\n";
131 }
132
133 if ( '\n' != text.charAt(text.length() - 1)) {
134 text += '\n';
135 }
136 }
137
138 final String insertText = text;
139 this.mCocos2dxGLSurfaceView.insertText(insertText);
140
141 }
142
143 if (pActionID == EditorInfo.IME_ACTION_DONE) {
144 this.mCocos2dxGLSurfaceView.requestFocus();
145 }
146 return false;
147 }
148
149 }
...\ No newline at end of file ...\ No newline at end of file
1 /****************************************************************************
2 Copyright (c) 2010-2012 cocos2d-x.org
3 Copyright (c) 2013-2014 Chukong Technologies Inc.
4
5 http://www.cocos2d-x.org
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE.
24 ****************************************************************************/
25 package org.cocos2dx.lib;
26
27 import android.content.Context;
28 import android.graphics.Typeface;
29
30 import java.util.HashMap;
31
32 public class Cocos2dxTypefaces {
33 // ===========================================================
34 // Constants
35 // ===========================================================
36
37 // ===========================================================
38 // Fields
39 // ===========================================================
40
41 private static final HashMap<String, Typeface> sTypefaceCache = new HashMap<String, Typeface>();
42
43 // ===========================================================
44 // Constructors
45 // ===========================================================
46
47 // ===========================================================
48 // Getter & Setter
49 // ===========================================================
50
51 // ===========================================================
52 // Methods for/from SuperClass/Interfaces
53 // ===========================================================
54
55 // ===========================================================
56 // Methods
57 // ===========================================================
58
59 public static synchronized Typeface get(final Context context, final String assetName) {
60 if (!Cocos2dxTypefaces.sTypefaceCache.containsKey(assetName)) {
61 Typeface typeface = null;
62 if (assetName.startsWith("/"))
63 {
64 typeface = Typeface.createFromFile(assetName);
65 }
66 else
67 {
68 typeface = Typeface.createFromAsset(context.getAssets(), assetName);
69 }
70 Cocos2dxTypefaces.sTypefaceCache.put(assetName, typeface);
71 }
72
73 return Cocos2dxTypefaces.sTypefaceCache.get(assetName);
74 }
75
76 // ===========================================================
77 // Inner and Anonymous Classes
78 // ===========================================================
79
80 }
1 package org.cocos2dx.lib;
2
3 import android.annotation.SuppressLint;
4 import android.content.Context;
5 import android.util.Log;
6 import android.view.Gravity;
7 import android.webkit.WebChromeClient;
8 import android.webkit.WebView;
9 import android.webkit.WebViewClient;
10 import android.widget.FrameLayout;
11
12 import java.lang.reflect.Method;
13 import java.net.URI;
14 import java.util.concurrent.CountDownLatch;
15
16 class ShouldStartLoadingWorker implements Runnable {
17 private CountDownLatch mLatch;
18 private boolean[] mResult;
19 private final int mViewTag;
20 private final String mUrlString;
21
22 ShouldStartLoadingWorker(CountDownLatch latch, boolean[] result, int viewTag, String urlString) {
23 this.mLatch = latch;
24 this.mResult = result;
25 this.mViewTag = viewTag;
26 this.mUrlString = urlString;
27 }
28
29 @Override
30 public void run() {
31 this.mResult[0] = Cocos2dxWebViewHelper._shouldStartLoading(mViewTag, mUrlString);
32 this.mLatch.countDown(); // notify that result is ready
33 }
34 }
35
36 public class Cocos2dxWebView extends WebView {
37 private static final String TAG = Cocos2dxWebViewHelper.class.getSimpleName();
38
39 private int mViewTag;
40 private String mJSScheme;
41
42 public Cocos2dxWebView(Context context) {
43 this(context, -1);
44 }
45
46 @SuppressLint("SetJavaScriptEnabled")
47 public Cocos2dxWebView(Context context, int viewTag) {
48 super(context);
49 this.mViewTag = viewTag;
50 this.mJSScheme = "";
51
52 this.setFocusable(true);
53 this.setFocusableInTouchMode(true);
54
55 this.getSettings().setSupportZoom(false);
56
57 this.getSettings().setJavaScriptEnabled(true);
58
59 // `searchBoxJavaBridge_` has big security risk. http://jvn.jp/en/jp/JVN53768697
60 try {
61 Method method = this.getClass().getMethod("removeJavascriptInterface", new Class[]{String.class});
62 method.invoke(this, "searchBoxJavaBridge_");
63 } catch (Exception e) {
64 Log.d(TAG, "This API level do not support `removeJavascriptInterface`");
65 }
66
67 this.setWebViewClient(new Cocos2dxWebViewClient());
68 this.setWebChromeClient(new WebChromeClient());
69 }
70
71 public void setJavascriptInterfaceScheme(String scheme) {
72 this.mJSScheme = scheme != null ? scheme : "";
73 }
74
75 public void setScalesPageToFit(boolean scalesPageToFit) {
76 this.getSettings().setSupportZoom(scalesPageToFit);
77 }
78
79 class Cocos2dxWebViewClient extends WebViewClient {
80 @Override
81 public boolean shouldOverrideUrlLoading(WebView view, final String urlString) {
82 Cocos2dxActivity activity = (Cocos2dxActivity)getContext();
83
84 try {
85 URI uri = URI.create(urlString);
86 if (uri != null && uri.getScheme().equals(mJSScheme)) {
87 activity.runOnGLThread(new Runnable() {
88 @Override
89 public void run() {
90 Cocos2dxWebViewHelper._onJsCallback(mViewTag, urlString);
91 }
92 });
93 return true;
94 }
95 } catch (Exception e) {
96 Log.d(TAG, "Failed to create URI from url");
97 }
98
99 boolean[] result = new boolean[] { true };
100 CountDownLatch latch = new CountDownLatch(1);
101
102 // run worker on cocos thread
103 activity.runOnGLThread(new ShouldStartLoadingWorker(latch, result, mViewTag, urlString));
104
105 // wait for result from cocos thread
106 try {
107 latch.await();
108 } catch (InterruptedException ex) {
109 Log.d(TAG, "'shouldOverrideUrlLoading' failed");
110 }
111
112 return result[0];
113 }
114
115 @Override
116 public void onPageFinished(WebView view, final String url) {
117 super.onPageFinished(view, url);
118 Cocos2dxActivity activity = (Cocos2dxActivity)getContext();
119 activity.runOnGLThread(new Runnable() {
120 @Override
121 public void run() {
122 Cocos2dxWebViewHelper._didFinishLoading(mViewTag, url);
123 }
124 });
125 }
126
127 @Override
128 public void onReceivedError(WebView view, int errorCode, String description, final String failingUrl) {
129 super.onReceivedError(view, errorCode, description, failingUrl);
130 Cocos2dxActivity activity = (Cocos2dxActivity)getContext();
131 activity.runOnGLThread(new Runnable() {
132 @Override
133 public void run() {
134 Cocos2dxWebViewHelper._didFailLoading(mViewTag, failingUrl);
135 }
136 });
137 }
138 }
139
140 public void setWebViewRect(int left, int top, int maxWidth, int maxHeight) {
141 FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
142 FrameLayout.LayoutParams.WRAP_CONTENT);
143 layoutParams.leftMargin = left;
144 layoutParams.topMargin = top;
145 layoutParams.width = maxWidth;
146 layoutParams.height = maxHeight;
147 layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
148 this.setLayoutParams(layoutParams);
149 }
150 }
1 package org.cocos2dx.lib;
2
3 import android.os.Handler;
4 import android.os.Looper;
5 import android.util.SparseArray;
6 import android.view.View;
7 import android.widget.FrameLayout;
8
9 import com.chukong.cocosplay.client.CocosPlayClient;
10
11 import java.util.concurrent.Callable;
12 import java.util.concurrent.ExecutionException;
13 import java.util.concurrent.FutureTask;
14
15
16 public class Cocos2dxWebViewHelper {
17 private static final String TAG = Cocos2dxWebViewHelper.class.getSimpleName();
18 private static Handler sHandler;
19 private static Cocos2dxActivity sCocos2dxActivity;
20 private static FrameLayout sLayout;
21
22 private static SparseArray<Cocos2dxWebView> webViews;
23 private static int viewTag = 0;
24
25 public Cocos2dxWebViewHelper(FrameLayout layout) {
26 Cocos2dxWebViewHelper.sLayout = layout;
27 Cocos2dxWebViewHelper.sHandler = new Handler(Looper.myLooper());
28
29 Cocos2dxWebViewHelper.sCocos2dxActivity = (Cocos2dxActivity) Cocos2dxActivity.getContext();
30 Cocos2dxWebViewHelper.webViews = new SparseArray<Cocos2dxWebView>();
31 }
32
33 private static native boolean shouldStartLoading(int index, String message);
34
35 public static boolean _shouldStartLoading(int index, String message) {
36 return !shouldStartLoading(index, message);
37 }
38
39 private static native void didFinishLoading(int index, String message);
40
41 public static void _didFinishLoading(int index, String message) {
42 didFinishLoading(index, message);
43 }
44
45 private static native void didFailLoading(int index, String message);
46
47 public static void _didFailLoading(int index, String message) {
48 didFailLoading(index, message);
49 }
50
51 private static native void onJsCallback(int index, String message);
52
53 public static void _onJsCallback(int index, String message) {
54 onJsCallback(index, message);
55 }
56
57 public static int createWebView() {
58 final int index = viewTag;
59 sCocos2dxActivity.runOnUiThread(new Runnable() {
60 @Override
61 public void run() {
62 Cocos2dxWebView webView = new Cocos2dxWebView(sCocos2dxActivity, index);
63 FrameLayout.LayoutParams lParams = new FrameLayout.LayoutParams(
64 FrameLayout.LayoutParams.WRAP_CONTENT,
65 FrameLayout.LayoutParams.WRAP_CONTENT);
66 sLayout.addView(webView, lParams);
67
68 webViews.put(index, webView);
69 }
70 });
71 return viewTag++;
72 }
73
74 public static void removeWebView(final int index) {
75 sCocos2dxActivity.runOnUiThread(new Runnable() {
76 @Override
77 public void run() {
78 Cocos2dxWebView webView = webViews.get(index);
79 if (webView != null) {
80 webViews.remove(index);
81 sLayout.removeView(webView);
82 }
83 }
84 });
85 }
86
87 public static void setVisible(final int index, final boolean visible) {
88 sCocos2dxActivity.runOnUiThread(new Runnable() {
89 @Override
90 public void run() {
91 Cocos2dxWebView webView = webViews.get(index);
92 if (webView != null) {
93 webView.setVisibility(visible ? View.VISIBLE : View.GONE);
94 }
95 }
96 });
97 }
98
99 public static void setWebViewRect(final int index, final int left, final int top, final int maxWidth, final int maxHeight) {
100 sCocos2dxActivity.runOnUiThread(new Runnable() {
101 @Override
102 public void run() {
103 Cocos2dxWebView webView = webViews.get(index);
104 if (webView != null) {
105 webView.setWebViewRect(left, top, maxWidth, maxHeight);
106 }
107 }
108 });
109 }
110
111 public static void setJavascriptInterfaceScheme(final int index, final String scheme) {
112 sCocos2dxActivity.runOnUiThread(new Runnable() {
113 @Override
114 public void run() {
115 Cocos2dxWebView webView = webViews.get(index);
116 if (webView != null) {
117 webView.setJavascriptInterfaceScheme(scheme);
118 }
119 }
120 });
121 }
122
123 public static void loadData(final int index, final String data, final String mimeType, final String encoding, final String baseURL) {
124 sCocos2dxActivity.runOnUiThread(new Runnable() {
125 @Override
126 public void run() {
127 Cocos2dxWebView webView = webViews.get(index);
128 if (webView != null) {
129 webView.loadDataWithBaseURL(baseURL, data, mimeType, encoding, null);
130 }
131 }
132 });
133 }
134
135 public static void loadHTMLString(final int index, final String data, final String baseUrl) {
136 sCocos2dxActivity.runOnUiThread(new Runnable() {
137 @Override
138 public void run() {
139 Cocos2dxWebView webView = webViews.get(index);
140 if (webView != null) {
141 webView.loadDataWithBaseURL(baseUrl, data, null, null, null);
142 }
143 }
144 });
145 }
146
147 public static void loadUrl(final int index, final String url) {
148 sCocos2dxActivity.runOnUiThread(new Runnable() {
149 @Override
150 public void run() {
151 Cocos2dxWebView webView = webViews.get(index);
152 if (webView != null) {
153 webView.loadUrl(url);
154 }
155 }
156 });
157 }
158
159 public static void loadFile(final int index, final String filePath) {
160 if (CocosPlayClient.isEnabled() && !CocosPlayClient.isDemo()) {
161 CocosPlayClient.updateAssets(filePath);
162 }
163 CocosPlayClient.notifyFileLoaded(filePath);
164 sCocos2dxActivity.runOnUiThread(new Runnable() {
165 @Override
166 public void run() {
167 Cocos2dxWebView webView = webViews.get(index);
168 if (webView != null) {
169 webView.loadUrl(filePath);
170 }
171 }
172 });
173 }
174
175 public static void stopLoading(final int index) {
176 sCocos2dxActivity.runOnUiThread(new Runnable() {
177 @Override
178 public void run() {
179 Cocos2dxWebView webView = webViews.get(index);
180 if (webView != null) {
181 webView.stopLoading();
182 }
183 }
184 });
185
186 }
187
188 public static void reload(final int index) {
189 sCocos2dxActivity.runOnUiThread(new Runnable() {
190 @Override
191 public void run() {
192 Cocos2dxWebView webView = webViews.get(index);
193 if (webView != null) {
194 webView.reload();
195 }
196 }
197 });
198 }
199
200 public static <T> T callInMainThread(Callable<T> call) throws ExecutionException, InterruptedException {
201 FutureTask<T> task = new FutureTask<T>(call);
202 sHandler.post(task);
203 return task.get();
204 }
205
206 public static boolean canGoBack(final int index) {
207 Callable<Boolean> callable = new Callable<Boolean>() {
208 @Override
209 public Boolean call() throws Exception {
210 Cocos2dxWebView webView = webViews.get(index);
211 return webView != null && webView.canGoBack();
212 }
213 };
214 try {
215 return callInMainThread(callable);
216 } catch (ExecutionException e) {
217 return false;
218 } catch (InterruptedException e) {
219 return false;
220 }
221 }
222
223 public static boolean canGoForward(final int index) {
224 Callable<Boolean> callable = new Callable<Boolean>() {
225 @Override
226 public Boolean call() throws Exception {
227 Cocos2dxWebView webView = webViews.get(index);
228 return webView != null && webView.canGoForward();
229 }
230 };
231 try {
232 return callInMainThread(callable);
233 } catch (ExecutionException e) {
234 return false;
235 } catch (InterruptedException e) {
236 return false;
237 }
238 }
239
240 public static void goBack(final int index) {
241 sCocos2dxActivity.runOnUiThread(new Runnable() {
242 @Override
243 public void run() {
244 Cocos2dxWebView webView = webViews.get(index);
245 if (webView != null) {
246 webView.goBack();
247 }
248 }
249 });
250 }
251
252 public static void goForward(final int index) {
253 sCocos2dxActivity.runOnUiThread(new Runnable() {
254 @Override
255 public void run() {
256 Cocos2dxWebView webView = webViews.get(index);
257 if (webView != null) {
258 webView.goForward();
259 }
260 }
261 });
262 }
263
264 public static void evaluateJS(final int index, final String js) {
265 sCocos2dxActivity.runOnUiThread(new Runnable() {
266 @Override
267 public void run() {
268 Cocos2dxWebView webView = webViews.get(index);
269 if (webView != null) {
270 webView.loadUrl("javascript:" + js);
271 }
272 }
273 });
274 }
275
276 public static void setScalesPageToFit(final int index, final boolean scalesPageToFit) {
277 sCocos2dxActivity.runOnUiThread(new Runnable() {
278 @Override
279 public void run() {
280 Cocos2dxWebView webView = webViews.get(index);
281 if (webView != null) {
282 webView.setScalesPageToFit(scalesPageToFit);
283 }
284 }
285 });
286 }
287 }
1 package org.cocos2dx.lib;
2
3 import java.util.ArrayList;
4
5 public class GameControllerAdapter {
6 private static ArrayList<Runnable> sRunnableFrameStartList = null;
7
8 public static void addRunnableToFrameStartList(Runnable runnable) {
9 if (sRunnableFrameStartList == null)
10 sRunnableFrameStartList = new ArrayList<Runnable>();
11 sRunnableFrameStartList.add(runnable);
12 }
13
14 public static void removeRunnableFromFrameStartList(Runnable runnable) {
15 if (sRunnableFrameStartList != null)
16 sRunnableFrameStartList.remove(runnable);
17 }
18
19 public static void onDrawFrameStart() {
20 if (sRunnableFrameStartList != null)
21 {
22 int size = sRunnableFrameStartList.size();
23 for (int i = 0; i < size; ++i) {
24 sRunnableFrameStartList.get(i).run();
25 }
26 }
27 }
28
29 public static void onConnected(final String vendorName, final int controller)
30 {
31 Cocos2dxHelper.runOnGLThread(new Runnable() {
32
33 @Override
34 public void run() {
35 nativeControllerConnected(vendorName, controller);
36 }
37 });
38 }
39
40 public static void onDisconnected(final String vendorName, final int controller)
41 {
42 Cocos2dxHelper.runOnGLThread(new Runnable() {
43
44 @Override
45 public void run() {
46 nativeControllerDisconnected(vendorName, controller);
47 }
48 });
49 }
50
51 public static void onButtonEvent(final String vendorName, final int controller, final int button, final boolean isPressed, final float value, final boolean isAnalog)
52 {
53 Cocos2dxHelper.runOnGLThread(new Runnable() {
54
55 @Override
56 public void run() {
57 nativeControllerButtonEvent(vendorName, controller, button, isPressed, value, isAnalog);
58 }
59 });
60 }
61
62 public static void onAxisEvent(final String vendorName, final int controller, final int axisID, final float value, final boolean isAnalog)
63 {
64 Cocos2dxHelper.runOnGLThread(new Runnable() {
65
66 @Override
67 public void run() {
68 nativeControllerAxisEvent(vendorName, controller, axisID, value, isAnalog);
69 }
70 });
71 }
72
73 private static native void nativeControllerConnected(final String vendorName, final int controller);
74 private static native void nativeControllerDisconnected(final String vendorName, final int controller);
75 private static native void nativeControllerButtonEvent(final String vendorName, final int controller, final int button, final boolean isPressed, final float value, final boolean isAnalog);
76 private static native void nativeControllerAxisEvent(final String vendorName, final int controller, final int axisID, final float value, final boolean isAnalog);
77 }
1 package org.cocos2dx.lib;
2
3 import android.content.Context;
4 import android.view.KeyEvent;
5 import android.view.MotionEvent;
6
7 public interface GameControllerDelegate {
8
9 static final int KEY_BASE = 1000;
10
11 public static final int THUMBSTICK_LEFT_X = KEY_BASE;
12 public static final int THUMBSTICK_LEFT_Y = KEY_BASE + 1;
13 public static final int THUMBSTICK_RIGHT_X = KEY_BASE + 2;
14 public static final int THUMBSTICK_RIGHT_Y = KEY_BASE + 3;
15
16 public static final int BUTTON_A = KEY_BASE + 4;
17 public static final int BUTTON_B = KEY_BASE + 5;
18 public static final int BUTTON_C = KEY_BASE + 6;
19 public static final int BUTTON_X = KEY_BASE + 7;
20 public static final int BUTTON_Y = KEY_BASE + 8;
21 public static final int BUTTON_Z = KEY_BASE + 9;
22
23 public static final int BUTTON_DPAD_UP = KEY_BASE + 10;
24 public static final int BUTTON_DPAD_DOWN = KEY_BASE + 11;
25 public static final int BUTTON_DPAD_LEFT = KEY_BASE + 12;
26 public static final int BUTTON_DPAD_RIGHT = KEY_BASE + 13;
27 public static final int BUTTON_DPAD_CENTER = KEY_BASE + 14;
28
29 public static final int BUTTON_LEFT_SHOULDER = KEY_BASE + 15;
30 public static final int BUTTON_RIGHT_SHOULDER = KEY_BASE + 16;
31 public static final int BUTTON_LEFT_TRIGGER = KEY_BASE + 17;
32 public static final int BUTTON_RIGHT_TRIGGER = KEY_BASE + 18;
33
34 public static final int BUTTON_LEFT_THUMBSTICK = KEY_BASE + 19;
35 public static final int BUTTON_RIGHT_THUMBSTICK = KEY_BASE + 20;
36
37 public static final int BUTTON_START = KEY_BASE + 21;
38 public static final int BUTTON_SELECT = KEY_BASE + 22;
39
40 void onCreate(Context context);
41 void onPause();
42 void onResume();
43 void onDestroy();
44
45 boolean dispatchKeyEvent(KeyEvent event);
46 boolean dispatchGenericMotionEvent(MotionEvent event);
47
48 void setControllerEventListener(ControllerEventListener listener);
49
50 public interface ControllerEventListener {
51 void onButtonEvent(String vendorName, int controller, int button, boolean isPressed, float value, boolean isAnalog);
52 void onAxisEvent(String vendorName, int controller, int axisID, float value, boolean isAnalog);
53
54 void onConnected(String vendorName, int controller);
55 void onDisconnected(String vendorName, int controller);
56 }
57 }
1 package org.cocos2dx.lib;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5
6 public class GameControllerUtils {
7
8 public static void ensureDirectoryExist(String path){
9
10 File sdkDir = new File(path);
11 if(!sdkDir.exists()){
12 sdkDir.mkdirs();
13 }
14 }
15
16 public static String readJsonFile(String filePath) {
17
18 File file = new File(filePath);
19
20 if (!file.exists()){
21 return null;
22 }
23
24 try {
25
26 FileInputStream is = new FileInputStream(file);;
27
28 int size = is.available();
29 byte[] buffer = new byte[size];
30
31 is.read(buffer);
32 is.close();
33
34 String jsonstr = new String(buffer, "UTF-8");
35
36 return jsonstr;
37 } catch (Exception e) {
38 e.printStackTrace();
39 }
40
41 return null;
42 }
43 }
1 /****************************************************************************
2 Copyright (c) 2010-2013 cocos2d-x.org
3
4 http://www.cocos2d-x.org
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in
14 all copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 THE SOFTWARE.
23 ****************************************************************************/
24 package org.cocos2dx.lib;
25
26 import android.content.Context;
27 import android.os.Handler;
28 import android.util.AttributeSet;
29 import android.widget.FrameLayout;
30
31 public class ResizeLayout extends FrameLayout {
32 private boolean mEnableForceDoLayout = false;
33
34 public ResizeLayout(Context context){
35 super(context);
36 }
37
38 public ResizeLayout(Context context, AttributeSet attrs) {
39 super(context, attrs);
40 }
41
42 public void setEnableForceDoLayout(boolean flag){
43 mEnableForceDoLayout = flag;
44 }
45
46 @Override
47 protected void onLayout(boolean changed, int l, int t, int r, int b) {
48 super.onLayout(changed, l, t, r, b);
49 if(mEnableForceDoLayout){
50 /*This is a hot-fix for some android devices which don't do layout when the main window
51 * is paned. We refersh the layout in 24 frames per seconds.
52 * When the editBox is lose focus or when user begin to type, the do layout is disabled.
53 */
54 final Handler handler = new Handler();
55 handler.postDelayed(new Runnable() {
56 @Override
57 public void run() {
58 //Do something after 100ms
59 requestLayout();
60 invalidate();
61 }
62 }, 1000 / 24);
63
64 }
65
66 }
67
68 }
1 /****************************************************************************
2 Copyright (c) 2008-2010 Ricardo Quesada
3 Copyright (c) 2010-2012 cocos2d-x.org
4 Copyright (c) 2011 Zynga Inc.
5 Copyright (c) 2013-2014 Chukong Technologies Inc.
6
7 http://www.cocos2d-x.org
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notice and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 THE SOFTWARE.
26 ****************************************************************************/
27 package org.cocos2dx.lua;
28
29 import java.net.InetAddress;
30 import java.net.NetworkInterface;
31 import java.net.SocketException;
32 import java.util.Enumeration;
33 import java.util.ArrayList;
34
35 import org.cocos2dx.lib.Cocos2dxActivity;
36
37 import android.app.AlertDialog;
38 import android.content.Context;
39 import android.content.DialogInterface;
40 import android.content.Intent;
41 import android.content.pm.ApplicationInfo;
42 import android.content.pm.ActivityInfo;
43 import android.net.ConnectivityManager;
44 import android.net.NetworkInfo;
45 import android.net.wifi.WifiInfo;
46 import android.net.wifi.WifiManager;
47 import android.os.Bundle;
48 import android.provider.Settings;
49 import android.text.format.Formatter;
50 import android.util.Log;
51 import android.view.WindowManager;
52 import android.widget.Toast;
53
54
55 public class AppActivity extends Cocos2dxActivity{
56
57 static String hostIPAdress = "0.0.0.0";
58 @Override
59 protected void onCreate(Bundle savedInstanceState) {
60 super.onCreate(savedInstanceState);
61
62 if(nativeIsLandScape()) {
63 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
64 } else {
65 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
66 }
67
68 //2.Set the format of window
69
70 // Check the wifi is opened when the native is debug.
71 if(nativeIsDebug())
72 {
73 getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
74 if(!isNetworkConnected())
75 {
76 AlertDialog.Builder builder=new AlertDialog.Builder(this);
77 builder.setTitle("Warning");
78 builder.setMessage("Please open WIFI for debuging...");
79 builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
80
81 @Override
82 public void onClick(DialogInterface dialog, int which) {
83 startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
84 finish();
85 System.exit(0);
86 }
87 });
88
89 builder.setNegativeButton("Cancel", null);
90 builder.setCancelable(true);
91 builder.show();
92 }
93 hostIPAdress = getHostIpAddress();
94 }
95 }
96 private boolean isNetworkConnected() {
97 ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
98 if (cm != null) {
99 NetworkInfo networkInfo = cm.getActiveNetworkInfo();
100 ArrayList networkTypes = new ArrayList();
101 networkTypes.add(ConnectivityManager.TYPE_WIFI);
102 try {
103 networkTypes.add(ConnectivityManager.class.getDeclaredField("TYPE_ETHERNET").getInt(null));
104 } catch (NoSuchFieldException nsfe) {
105 }
106 catch (IllegalAccessException iae) {
107 throw new RuntimeException(iae);
108 }
109 if (networkInfo != null && networkTypes.contains(networkInfo.getType())) {
110 return true;
111 }
112 }
113 return false;
114 }
115
116 public String getHostIpAddress() {
117 WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
118 WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
119 int ip = wifiInfo.getIpAddress();
120 return ((ip & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF));
121 }
122
123 public static String getLocalIpAddress() {
124 return hostIPAdress;
125 }
126
127 private static native boolean nativeIsLandScape();
128 private static native boolean nativeIsDebug();
129
130 }
1 /****************************************************************************
2 Copyright (c) 2010-2013 cocos2d-x.org
3 Copyright (c) 2013-2014 Chukong Technologies Inc.
4
5 http://www.cocos2d-x.org
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE.
24 ****************************************************************************/
25
26 @class RootViewController;
27
28 @interface AppController : NSObject <UIApplicationDelegate>
29 {
30 UIWindow *window;
31 RootViewController *viewController;
32 }
33
34 @end
35
1 /****************************************************************************
2 Copyright (c) 2010-2013 cocos2d-x.org
3 Copyright (c) 2013-2014 Chukong Technologies Inc.
4
5 http://www.cocos2d-x.org
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE.
24 ****************************************************************************/
25
26 #import <UIKit/UIKit.h>
27 #import "cocos2d.h"
28
29 #import "AppController.h"
30 #import "AppDelegate.h"
31 #import "RootViewController.h"
32 #import "platform/ios/CCEAGLView-ios.h"
33
34 @implementation AppController
35
36 #pragma mark -
37 #pragma mark Application lifecycle
38
39 // cocos2d application instance
40 static AppDelegate s_sharedApplication;
41
42 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
43 {
44
45 cocos2d::Application *app = cocos2d::Application::getInstance();
46 app->initGLContextAttrs();
47 cocos2d::GLViewImpl::convertAttrs();
48
49 // Override point for customization after application launch.
50
51 // Add the view controller's view to the window and display.
52 window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
53 CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds]
54 pixelFormat: (NSString*)cocos2d::GLViewImpl::_pixelFormat
55 depthFormat: cocos2d::GLViewImpl::_depthFormat
56 preserveBackbuffer: NO
57 sharegroup: nil
58 multiSampling: NO
59 numberOfSamples: 0 ];
60
61 [eaglView setMultipleTouchEnabled:YES];
62
63 // Use RootViewController manage CCEAGLView
64 viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
65 viewController.wantsFullScreenLayout = YES;
66 viewController.view = eaglView;
67
68 // Set RootViewController to window
69 if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)
70 {
71 // warning: addSubView doesn't work on iOS6
72 [window addSubview: viewController.view];
73 }
74 else
75 {
76 // use this method on ios6
77 [window setRootViewController:viewController];
78 }
79
80 [window makeKeyAndVisible];
81
82 [[UIApplication sharedApplication] setStatusBarHidden: YES];
83
84 // IMPORTANT: Setting the GLView should be done after creating the RootViewController
85 cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView(eaglView);
86 cocos2d::Director::getInstance()->setOpenGLView(glview);
87
88 app->run();
89 return YES;
90 }
91
92
93 - (void)applicationWillResignActive:(UIApplication *)application {
94 /*
95 Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
96 Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
97 */
98 cocos2d::Director::getInstance()->pause();
99 }
100
101 - (void)applicationDidBecomeActive:(UIApplication *)application {
102 /*
103 Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
104 */
105 cocos2d::Director::getInstance()->resume();
106 }
107
108 - (void)applicationDidEnterBackground:(UIApplication *)application {
109 /*
110 Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
111 If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
112 */
113 cocos2d::Application::getInstance()->applicationDidEnterBackground();
114 }
115
116 - (void)applicationWillEnterForeground:(UIApplication *)application {
117 /*
118 Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
119 */
120 cocos2d::Application::getInstance()->applicationWillEnterForeground();
121 }
122
123 - (void)applicationWillTerminate:(UIApplication *)application {
124 /*
125 Called when the application is about to terminate.
126 See also applicationDidEnterBackground:.
127 */
128 }
129
130
131 #pragma mark -
132 #pragma mark Memory management
133
134 - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
135 /*
136 Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
137 */
138 cocos2d::Director::getInstance()->purgeCachedData();
139 }
140
141
142 - (void)dealloc {
143 [super dealloc];
144 }
145
146
147 @end
148
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3 <plist version="1.0">
4 <dict>
5 <key>CFBundleDevelopmentRegion</key>
6 <string>English</string>
7 <key>CFBundleDisplayName</key>
8 <string>${PRODUCT_NAME}</string>
9 <key>CFBundleExecutable</key>
10 <string>${EXECUTABLE_NAME}</string>
11 <key>CFBundleIdentifier</key>
12 <string>org.cocos2dx.rubbish</string>
13 <key>CFBundleIconFile</key>
14 <string>Icon-57.png</string>
15 <key>CFBundleIconFiles</key>
16 <array>
17 <string>Icon-29</string>
18 <string>Icon-40</string>
19 <string>Icon-50</string>
20 <string>Icon-57</string>
21 <string>Icon-58</string>
22 <string>Icon-72</string>
23 <string>Icon-76</string>
24 <string>Icon-80</string>
25 <string>Icon-87</string>
26 <string>Icon-100</string>
27 <string>Icon-114</string>
28 <string>Icon-120</string>
29 <string>Icon-144</string>
30 <string>Icon-152</string>
31 <string>Icon-180</string>
32 </array>
33 <key>CFBundleIconFiles~ipad</key>
34 <array>
35 <string>Icon-29</string>
36 <string>Icon-40</string>
37 <string>Icon-50</string>
38 <string>Icon-57</string>
39 <string>Icon-58</string>
40 <string>Icon-72</string>
41 <string>Icon-76</string>
42 <string>Icon-80</string>
43 <string>Icon-87</string>
44 <string>Icon-100</string>
45 <string>Icon-114</string>
46 <string>Icon-120</string>
47 <string>Icon-144</string>
48 <string>Icon-152</string>
49 <string>Icon-180</string>
50 </array>
51 <key>CFBundleInfoDictionaryVersion</key>
52 <string>6.0</string>
53 <key>CFBundleName</key>
54 <string>${PRODUCT_NAME}</string>
55 <key>CFBundlePackageType</key>
56 <string>APPL</string>
57 <key>CFBundleSignature</key>
58 <string>????</string>
59 <key>CFBundleVersion</key>
60 <string>1.0</string>
61 <key>LSRequiresIPhoneOS</key>
62 <true/>
63 <key>UIPrerenderedIcon</key>
64 <true/>
65 <key>UIRequiredDeviceCapabilities</key>
66 <dict>
67 <key>accelerometer</key>
68 <true/>
69 <key>opengles-1</key>
70 <true/>
71 </dict>
72 <key>UIStatusBarHidden</key>
73 <true/>
74 <key>UISupportedInterfaceOrientations</key>
75 <array>
76 <string>UIInterfaceOrientationLandscapeRight</string>
77 <string>UIInterfaceOrientationLandscapeLeft</string>
78 </array>
79 </dict>
80 </plist>
1 /****************************************************************************
2 Copyright (c) 2010-2011 cocos2d-x.org
3 Copyright (c) 2010 Ricardo Quesada
4
5 http://www.cocos2d-x.org
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE.
24 ****************************************************************************/
25
26 #import <UIKit/UIKit.h>
27
28
29 @interface RootViewController : UIViewController {
30
31 }
32 - (BOOL)prefersStatusBarHidden;
33 @end
1 /****************************************************************************
2 Copyright (c) 2010-2011 cocos2d-x.org
3 Copyright (c) 2010 Ricardo Quesada
4
5 http://www.cocos2d-x.org
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE.
24 ****************************************************************************/
25
26 #import "RootViewController.h"
27 #import "cocos2d.h"
28 #import "platform/ios/CCEAGLView-ios.h"
29 #include "ide-support/SimpleConfigParser.h"
30
31 @implementation RootViewController
32
33 /*
34 // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
35 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
36 if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
37 // Custom initialization
38 }
39 return self;
40 }
41 */
42
43 /*
44 // Implement loadView to create a view hierarchy programmatically, without using a nib.
45 - (void)loadView {
46 }
47 */
48
49 /*
50 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
51 - (void)viewDidLoad {
52 [super viewDidLoad];
53 }
54
55 */
56 // Override to allow orientations other than the default portrait orientation.
57 // This method is deprecated on ios6
58 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
59 if (SimpleConfigParser::getInstance()->isLanscape()) {
60 return UIInterfaceOrientationIsLandscape( interfaceOrientation );
61 }else{
62 return UIInterfaceOrientationIsPortrait( interfaceOrientation );
63 }
64 }
65
66 // For ios6, use supportedInterfaceOrientations & shouldAutorotate instead
67 - (NSUInteger) supportedInterfaceOrientations{
68 #ifdef __IPHONE_6_0
69 if (SimpleConfigParser::getInstance()->isLanscape()) {
70 return UIInterfaceOrientationMaskLandscape;
71 }else{
72 return UIInterfaceOrientationMaskPortrait;
73 }
74 #endif
75 }
76
77 - (BOOL) shouldAutorotate {
78 if (SimpleConfigParser::getInstance()->isLanscape()) {
79 return YES;
80 }else{
81 return NO;
82 }
83 }
84
85 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
86 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
87
88 cocos2d::GLView *glview = cocos2d::Director::getInstance()->getOpenGLView();
89
90 if (glview)
91 {
92 CCEAGLView *eaglview = (CCEAGLView*) glview->getEAGLView();
93
94 if (eaglview)
95 {
96 CGSize s = CGSizeMake([eaglview getWidth], [eaglview getHeight]);
97 cocos2d::Application::getInstance()->applicationScreenSizeChanged((int) s.width, (int) s.height);
98 }
99 }
100 }
101
102 //fix not hide status on ios7
103 - (BOOL)prefersStatusBarHidden
104 {
105 return YES;
106 }
107
108 - (void)didReceiveMemoryWarning {
109 // Releases the view if it doesn't have a superview.
110 [super didReceiveMemoryWarning];
111
112 // Release any cached data, images, etc that aren't in use.
113 }
114
115 - (void)viewDidUnload {
116 [super viewDidUnload];
117 // Release any retained subviews of the main view.
118 // e.g. self.myOutlet = nil;
119 }
120
121
122 - (void)dealloc {
123 [super dealloc];
124 }
125
126
127 @end

13.4 KB | W: | H:

12.4 KB | W: | H:

  • 2-up
  • Swipe
  • Onion skin

17.3 KB | W: | H:

15.8 KB | W: | H:

  • 2-up
  • Swipe
  • Onion skin

12.6 KB | W: | H:

11.5 KB | W: | H:

  • 2-up
  • Swipe
  • Onion skin

11.9 KB | W: | H:

10.7 KB | W: | H:

  • 2-up
  • Swipe
  • Onion skin

9.91 KB | W: | H:

9.68 KB | W: | H:

  • 2-up
  • Swipe
  • Onion skin