Skip to content

Commit 6d137c8

Browse files
authored
Cocos2d x 2.2.6 oh (#20894)
* 2.2.6 version OHOS adaptation Signed-off-by: 冰冰冰 <[email protected]> * Review and revise based on feedback Signed-off-by: 冰冰冰 <[email protected]> * Review and revise based on feedback Signed-off-by: 冰冰冰 <[email protected]> * Review and revise based on feedback Signed-off-by: 冰冰冰 <[email protected]> * Review and revise based on feedback Signed-off-by: 冰冰冰 <[email protected]> * Review and revise based on feedback Signed-off-by: 冰冰冰 <[email protected]> * ohos code optimization Signed-off-by: 冰冰冰 <[email protected]> * ohos code optimization Signed-off-by: 冰冰冰 <[email protected]> * Change the ts file to ets; API15 upgrade; Napi call return value exception scenario handling; Napi Interactive Use Scope to Prevent Memory Leakage Signed-off-by: 冰冰冰 <[email protected]> * Macro definition capitalized Signed-off-by: 冰冰冰 <[email protected]> * mainability optimization Signed-off-by: 冰冰冰 <[email protected]> --------- Signed-off-by: 冰冰冰 <[email protected]>
1 parent 59f8512 commit 6d137c8

File tree

67 files changed

+556
-492
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

67 files changed

+556
-492
lines changed

CocosDenshion/ohos/CMakeLists.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ include_directories(${COCOSDENSHION_HEADER}
2929

3030
#set(CMAKE_C_FLAGS -Wno-psabi -Wno-absolute-value -Wno-extra)
3131
#set(CMAKE_CXX_FLAGS -Wno-overloaded-virtual -Wno-unused-function -Wno-unused-private-field -Wno-reorder-ctor -Wno-unsequenced -Wno-extra)
32-
target_compile_definitions(${PROJECT_NAME} PUBLIC -DHarmonyOS_Next=1)
32+
target_compile_definitions(${PROJECT_NAME} PUBLIC -DHARMONYOS_NEXT=1)
3333
target_compile_options(${PROJECT_NAME} PUBLIC -Wno-psabi -Wno-absolute-value -Wno-extra -Wno-overloaded-virtual -Wno-unused-function -Wno-unused-private-field -Wno-reorder-ctor -Wno-unsequenced -Wno-extra -Wno-unused-command-line-argument -Wno-ignored-qualifiers)
3434
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../include
3535
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../../cocos2dx

cocos2dx/CMakeLists.txt

+2-2
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ if(OHOS)
189189
-Wno-unsequenced
190190
-Wno-extra
191191
-Wno-c++11-narrowing
192-
-DHarmonyOS_Next
192+
-DHARMONYOS_NEXT
193193
)
194194

195195
add_library(${PROJECT_NAME} STATIC ${COCOS2DX_SRC})
@@ -200,7 +200,7 @@ if(OHOS)
200200

201201
target_link_libraries(${PROJECT_NAME} PUBLIC ext_png ext_zlib libtiff ext_jpeg)
202202
target_include_directories(${PROJECT_NAME} PUBLIC ${COCOS2DX_HEADER_PUBLIC})
203-
target_compile_definitions(${PROJECT_NAME} PUBLIC -DUSE_FILE32API -DHarmonyOS_Next)
203+
target_compile_definitions(${PROJECT_NAME} PUBLIC -DUSE_FILE32API -DHARMONYOS_NEXT)
204204
target_compile_options(${PROJECT_NAME} PUBLIC -Wno-psabi)
205205

206206
find_library( # Sets the name of the path variable.

cocos2dx/platform/ohos/napi/helper/NapiHelper.h

+20-1
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,11 @@ class JSFunction {
114114
napi_value jsArgs[sizeof...(Args)] = {NapiValueConverter::ToNapiValue(env, args)...};
115115
napi_value return_val;
116116
status = napi_call_function(env, global, func, sizeof...(Args), jsArgs, &return_val);
117-
117+
if (status == napi_pending_exception) {
118+
LOGI("Caught invoke exception: napi_pending_exception");
119+
napi_value exception;
120+
napi_get_and_clear_last_exception(env, &exception);
121+
}
118122
ReturnType value;
119123
if (!NapiValueConverter::ToCppValue(env, return_val, value)) {
120124
// Handle error here
@@ -136,6 +140,11 @@ class JSFunction {
136140
napi_value jsArgs[sizeof...(Args)] = {NapiValueConverter::ToNapiValue(env, args)...};
137141
napi_value return_val;
138142
status = napi_call_function(env, global, func, sizeof...(Args), jsArgs, &return_val);
143+
if (status == napi_pending_exception) {
144+
LOGI("Caught invoke exception: napi_pending_exception");
145+
napi_value exception;
146+
napi_get_and_clear_last_exception(env, &exception);
147+
}
139148
}
140149

141150
static void callFunctionWithParams(WorkParam *param) {
@@ -167,6 +176,11 @@ class JSFunction {
167176
}
168177
if (status != napi_ok) {
169178
LOGI("XXXXXX:napi_call_function getClassObject != napi_ok %{public}d", status);
179+
if (status == napi_pending_exception) {
180+
LOGI("Caught invoke exception: napi_pending_exception");
181+
napi_value exception;
182+
napi_get_and_clear_last_exception(env, &exception);
183+
}
170184
}
171185

172186
napi_value thenFunc = nullptr;
@@ -187,6 +201,11 @@ class JSFunction {
187201
status = napi_call_function(env, promise, thenFunc, 1, &successFunc, &ret);
188202
if (status != napi_ok) {
189203
LOGI("XXXXXX:napi_call_function thenFunc failed, ret: %{public}d", status);
204+
if (status == napi_pending_exception) {
205+
LOGI("Caught invoke exception: napi_pending_exception");
206+
napi_value exception;
207+
napi_get_and_clear_last_exception(env, &exception);
208+
}
190209
}
191210
}
192211
// Callback Function Type

cocos2dx/platform/ohos/napi/plugin_manager.cpp

+6-1
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,11 @@ napi_value NapiManager::GetContext(napi_env env, napi_callback_info info)
7373

7474
int64_t value;
7575
NAPI_CALL(env, napi_get_value_int64(env, args[0], &value));
76-
76+
napi_handle_scope scope = nullptr;
77+
NAPI_CALL(env, napi_open_handle_scope(env, &scope));
78+
if(scope == nullptr){
79+
return nullptr;
80+
}
7781
NAPI_CALL(env, napi_create_object(env, &exports));
7882

7983
switch (value) {
@@ -181,6 +185,7 @@ napi_value NapiManager::GetContext(napi_env env, napi_callback_info info)
181185
default:
182186
OHOS_LOGE("unknown type");
183187
}
188+
NAPI_CALL(env, napi_close_handle_scope(env, scope));
184189
return exports;
185190
}
186191

extensions/CMakeLists.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ if(OHOS)
156156
add_library(${PROJECT_NAME} STATIC ${EXTENSION_SRC})
157157
target_link_libraries(${PROJECT_NAME} box2d chipmunk cocosdenshion)
158158
set(CMAKE_C_FLAGS -fexceptions)
159-
target_compile_options(${PROJECT_NAME} PUBLIC -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DHarmonyOS_Next=1)
159+
target_compile_options(${PROJECT_NAME} PUBLIC -DCC_ENABLE_CHIPMUNK_INTEGRATION=1 -DHARMONYOS_NEXT=1)
160160
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/
161161
${CMAKE_CURRENT_SOURCE_DIR}/CCBReader
162162
${CMAKE_CURRENT_SOURCE_DIR}/GUI/CCControlExtension

samples/Cpp/TestCpp/CMakeLists.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ if(OHOS)
186186

187187
)
188188
list(APPEND TEST_COMMON_SRC proj.ohos/entry/src/main/cpp/main.cpp)
189-
add_definitions("-DHarmonyOS_Next")
189+
add_definitions("-DHARMONYOS_NEXT")
190190
add_definitions("-DCOCOS2D_DEBUG=3")
191191

192192
include_directories(${COCOS2DX_HEADER}

samples/Cpp/TestCpp/proj.ohos/.clang-format

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
Language: Cpp
22
# BasedOnStyle: LLVM
33
ColumnLimit: 120
4-
SortIncludes: false
4+
SortIncludes: CaseSensitive
55
TabWidth: 4
66
IndentWidth: 4
77
UseTab: Never

samples/Cpp/TestCpp/proj.ohos/build-profile.json5

+1-3
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,8 @@
44
{
55
"name": "default",
66
"signingConfig": "default",
7-
"compatibleSdkVersion": "5.0.0(12)",
8-
//指定HarmonyOS应用/服务目标版本。若没有设置,默认为compatibleSdkVersion
7+
"compatibleSdkVersion": "5.0.3(15)",
98
"runtimeOS": "HarmonyOS"
10-
//指定为HarmonyOS/OpenHarmony
119
}
1210
],
1311
"signingConfigs": [

samples/Cpp/TestCpp/proj.ohos/entry/build-profile.json5

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
},
1313
"sourceOption": {
1414
"workers": [
15-
'./src/main/ets/workers/CocosWorker.ts'
15+
'./src/main/ets/workers/CocosWorker.ets'
1616
]
1717
}
1818
},
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import window from '@ohos.window';
2+
import UIAbility from '@ohos.app.ability.UIAbility';
3+
import nativeRender from "libnativerender.so";
4+
import { ContextType, DeviceUtils } from "@ohos/libSysCapabilities"
5+
import { GlobalContext,GlobalContextConstants} from "@ohos/libSysCapabilities"
6+
import { BusinessError } from '@kit.BasicServicesKit';
7+
import { WorkerManager } from '../workers/WorkerManager';
8+
import Want from '@ohos.app.ability.Want';
9+
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
10+
11+
const nativeAppLifecycle: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.APP_LIFECYCLE);
12+
const rawFileUtils: nativeRender.CPPFunctions = nativeRender.getContext(ContextType.RAW_FILE_UTILS);
13+
let cocosWorker = WorkerManager.getInstance().getWorker();
14+
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_SHOW_FLAG, true);
15+
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_HIDE_FLAG, true);
16+
export default class MainAbility extends UIAbility {
17+
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
18+
nativeAppLifecycle.onCreate();
19+
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT, this.context);
20+
console.info('[LIFECYCLE-App] onCreate')
21+
}
22+
23+
onDestroy() {
24+
nativeAppLifecycle.onDestroy();
25+
console.info('[LIFECYCLE-App] onDestroy')
26+
}
27+
28+
onWindowStageCreate(windowStage: window.WindowStage): void {
29+
// Main window is created, set main page for this ability
30+
windowStage.loadContent('pages/Index', (err:BusinessError, data) => {
31+
if (err.code) {
32+
return;
33+
}
34+
rawFileUtils.nativeResourceManagerInit(this.context.resourceManager);
35+
rawFileUtils.writablePathInit(this.context.filesDir);
36+
});
37+
38+
windowStage.getMainWindow().then((windowIns: window.Window) => {
39+
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_MAIN_WINDOW, windowIns);
40+
// Set whether to display the status bar and navigation bar. If they are not displayed, [] is displayed.
41+
let systemBarPromise = windowIns.setWindowSystemBarEnable([]);
42+
// Whether the window layout is displayed in full screen mode
43+
let fullScreenPromise = windowIns.setWindowLayoutFullScreen(true);
44+
// Sets whether the screen is always on.
45+
let keepScreenOnPromise = windowIns.setWindowKeepScreenOn(true);
46+
Promise.all([systemBarPromise, fullScreenPromise, keepScreenOnPromise]).then(() => {
47+
console.info('Succeeded in setting the window');
48+
}).catch((err: BusinessError) => {
49+
console.error('Failed to set the window, cause ', err.code, err.message);
50+
});
51+
52+
try {
53+
DeviceUtils.calculateSafeArea(cocosWorker, windowIns.getWindowAvoidArea(window.AvoidAreaType.TYPE_CUTOUT), windowIns.getWindowProperties().windowRect);
54+
windowIns.on('avoidAreaChange', (data) => {
55+
console.info('getSafeAreaRect Succeeded in enabling the listener for system avoid area changes. type:' +
56+
JSON.stringify(data.type) + ', area: ' + JSON.stringify(data.area));
57+
58+
if(data.type == window.AvoidAreaType.TYPE_SYSTEM_GESTURE || data.type == window.AvoidAreaType.TYPE_KEYBOARD) {
59+
return;
60+
}
61+
62+
let mainWindow: window.Window = GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_MAIN_WINDOW);
63+
DeviceUtils.calculateSafeArea(cocosWorker, data.area, mainWindow.getWindowProperties().windowRect);
64+
});
65+
} catch (exception) {
66+
console.error(`Failed to enable the listener for system avoid area changes. Cause code: ${exception.code}, message: ${exception.message}`);
67+
}
68+
})
69+
70+
windowStage.on("windowStageEvent", (data:window.WindowStageEventType) => {
71+
let stageEventType: window.WindowStageEventType = data;
72+
switch (stageEventType) {
73+
case window.WindowStageEventType.RESUMED:
74+
console.info('[LIFECYCLE-App] onShow_RESUMED')
75+
if(GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_SHOW_FLAG)){
76+
nativeAppLifecycle.onShow();
77+
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_SHOW_FLAG, false);
78+
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_HIDE_FLAG, true);
79+
}
80+
break;
81+
case window.WindowStageEventType.PAUSED:
82+
if(GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_HIDE_FLAG)){
83+
console.info('[LIFECYCLE-App] onHide_PAUSED')
84+
nativeAppLifecycle.onHide();
85+
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_HIDE_FLAG, false);
86+
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_SHOW_FLAG, true);
87+
}
88+
break;
89+
default:
90+
break;
91+
}
92+
});
93+
}
94+
95+
onWindowStageDestroy() {
96+
// Main window is destroyed, release UI related resources
97+
}
98+
99+
onForeground() {
100+
if(GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_SHOW_FLAG)){
101+
// Ability has brought to foreground
102+
console.info('[LIFECYCLE-App] onShow')
103+
nativeAppLifecycle.onShow();
104+
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_SHOW_FLAG, false);
105+
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_HIDE_FLAG, true);
106+
}
107+
}
108+
109+
onBackground() {
110+
if(GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_HIDE_FLAG)){
111+
// Ability has back to background
112+
console.info('[LIFECYCLE-App] onHide')
113+
nativeAppLifecycle.onHide();
114+
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_HIDE_FLAG, false);
115+
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_SHOW_FLAG, true);
116+
}
117+
}
118+
};

samples/Cpp/TestCpp/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts

-80
This file was deleted.

samples/Cpp/TestCpp/proj.ohos/entry/src/main/ets/components/CocosVideoPlayer.ets

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ export struct CocosVideoPlayer {
1212
Video({
1313
src: this.videoPlayerInfo.isUrl ? this.videoPlayerInfo.url : this.videoPlayerInfo.rawfile,
1414
controller: this.videoPlayerInfo.controller
15-
}).position({ x: this.videoPlayerInfo.x, y: this.videoPlayerInfo.y })
15+
})
1616
.width(this.videoPlayerInfo.w)
1717
.height(this.videoPlayerInfo.h)
1818
.visibility(this.videoPlayerInfo.visible ? Visibility.Visible : Visibility.None)

samples/Cpp/TestCpp/proj.ohos/entry/src/main/ets/pages/Index.ets

+7-7
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ import promptAction from '@ohos.promptAction';
1717
import process from '@ohos.process';
1818
const nativePageLifecycle:nativeRender.CPPFunctions = nativeRender.getContext(ContextType.JSPAGE_LIFECYCLE);
1919

20+
let cocosWorker = WorkerManager.getInstance().getWorker();
21+
2022
@Entry
2123
@Component
2224
struct Index {
23-
24-
cocosWorker = WorkerManager.getInstance().getWorker();
2525
xcomponentController: XComponentController = new XComponentController();
2626

2727
processMgr = new process.ProcessManager();
@@ -53,7 +53,7 @@ struct Index {
5353
console.log('[LIFECYCLE-Page] onPageShow');
5454
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_ARRAY, this.editBoxArray);
5555
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_EDIT_BOX_INDEX_MAP, this.editBoxIndexMap);
56-
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_COCOS_WORKER, this.cocosWorker);
56+
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_COCOS_WORKER, cocosWorker);
5757
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_ARRAY, this.webViewArray);
5858
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_WEB_VIEW_INDEX_MAP, this.webViewIndexMap);
5959
GlobalContext.storeGlobalThis(GlobalContextConstants.COCOS2DX_VIDEO_PLAYER_ARRAY, this.videoPlayerInfoArray);
@@ -102,7 +102,7 @@ struct Index {
102102
}
103103

104104
build() {
105-
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
105+
Stack() {
106106
XComponent({
107107
id: 'xcomponentId',
108108
type: 'surface',
@@ -113,9 +113,9 @@ struct Index {
113113
.focusOnTouch(true)
114114
.onLoad((context) => {
115115
console.log('[cocos] XComponent.onLoad Callback');
116-
this.cocosWorker.postMessage({ type: "abilityContextInit", data: GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT)});
117-
this.cocosWorker.postMessage({ type: "onXCLoad", data: "XComponent" });
118-
this.cocosWorker.onmessage = WorkerMsgUtils.recvWorkerThreadMessage;
116+
cocosWorker.postMessage({ type: "abilityContextInit", data: GlobalContext.loadGlobalThis(GlobalContextConstants.COCOS2DX_ABILITY_CONTEXT)});
117+
cocosWorker.postMessage({ type: "onXCLoad", data: "XComponent" });
118+
cocosWorker.onmessage = WorkerMsgUtils.recvWorkerThreadMessage;
119119
})
120120
.onDestroy(() => {
121121
})

0 commit comments

Comments
 (0)