Skip to content

Commit 32d1b94

Browse files
authored
Cocos2d x 3.1 oh (#20896)
* 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]> * Keyboard optimization Signed-off-by: 冰冰冰 <[email protected]> * mainability optimization Signed-off-by: 冰冰冰 <[email protected]> --------- Signed-off-by: 冰冰冰 <[email protected]>
1 parent c2c4811 commit 32d1b94

Some content is hidden

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

59 files changed

+578
-404
lines changed

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

cocos/platform/ohos/napi/plugin_manager.cpp

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

6060
int64_t value;
6161
NAPI_CALL(env, napi_get_value_int64(env, args[0], &value));
62-
62+
napi_handle_scope scope = nullptr;
63+
NAPI_CALL(env, napi_open_handle_scope(env, &scope));
64+
if(scope == nullptr){
65+
return nullptr;
66+
}
6367
NAPI_CALL(env, napi_create_object(env, &exports));
6468

6569
switch (value) {
@@ -160,6 +164,7 @@ napi_value NapiManager::GetContext(napi_env env, napi_callback_info info) {
160164
default:
161165
OHOS_LOGE("unknown type");
162166
}
167+
NAPI_CALL(env, napi_close_handle_scope(env, scope));
163168
return exports;
164169
}
165170

cocos/platform/ohos/napi/render/plugin_render.cpp

+22-4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#include <ace/xcomponent/native_xcomponent_key_event.h>
12
#include <stdint.h>
23
#include <unistd.h>
34

@@ -30,7 +31,7 @@ float mousePositionY = -1;
3031
bool isMouseLeftActive = false;
3132
double scrollDistance = 0;
3233

33-
std::unordered_map<int, cocos2d::EventKeyboard::KeyCode> ohKeyMap = {
34+
const std::unordered_map<OH_NativeXComponent_KeyCode, cocos2d::EventKeyboard::KeyCode> ohKeyMap = {
3435
{KEY_ESCAPE, cocos2d::EventKeyboard::KeyCode::KEY_ESCAPE},
3536
{KEY_GRAVE, cocos2d::EventKeyboard::KeyCode::KEY_GRAVE},
3637
{KEY_MINUS, cocos2d::EventKeyboard::KeyCode::KEY_MINUS},
@@ -60,7 +61,23 @@ std::unordered_map<int, cocos2d::EventKeyboard::KeyCode> ohKeyMap = {
6061
{KEY_DPAD_UP, cocos2d::EventKeyboard::KeyCode::KEY_DPAD_UP},
6162
{KEY_SYSRQ, cocos2d::EventKeyboard::KeyCode::KEY_PRINT},
6263
{KEY_INSERT, cocos2d::EventKeyboard::KeyCode::KEY_INSERT},
63-
{KEY_FORWARD_DEL, cocos2d::EventKeyboard::KeyCode::KEY_DELETE}
64+
{KEY_FORWARD_DEL, cocos2d::EventKeyboard::KeyCode::KEY_DELETE},
65+
{KEY_SCROLL_LOCK, cocos2d::EventKeyboard::KeyCode::KEY_SCROLL_LOCK},
66+
{KEY_MINUS, cocos2d::EventKeyboard::KeyCode::KEY_MINUS},
67+
{KEY_AT, cocos2d::EventKeyboard::KeyCode::KEY_AT},
68+
{KEY_PLUS, cocos2d::EventKeyboard::KeyCode::KEY_PLUS},
69+
{KEY_MENU, cocos2d::EventKeyboard::KeyCode::KEY_MENU},
70+
{KEY_BREAK, cocos2d::EventKeyboard::KeyCode::KEY_PAUSE},
71+
{KEY_MOVE_HOME, cocos2d::EventKeyboard::KeyCode::KEY_HOME},
72+
{KEY_MOVE_END, cocos2d::EventKeyboard::KeyCode::KEY_END},
73+
{KEY_PAGE_UP, cocos2d::EventKeyboard::KeyCode::KEY_PG_UP},
74+
{KEY_PAGE_DOWN, cocos2d::EventKeyboard::KeyCode::KEY_PG_DOWN},
75+
{KEY_NUMPAD_ADD, cocos2d::EventKeyboard::KeyCode::KEY_KP_PLUS},
76+
{KEY_NUMPAD_SUBTRACT, cocos2d::EventKeyboard::KeyCode::KEY_KP_MINUS},
77+
{KEY_NUMPAD_MULTIPLY, cocos2d::EventKeyboard::KeyCode::KEY_KP_MULTIPLY},
78+
{KEY_NUMPAD_DIVIDE, cocos2d::EventKeyboard::KeyCode::KEY_KP_DIVIDE},
79+
{KEY_NUMPAD_ENTER, cocos2d::EventKeyboard::KeyCode::KEY_KP_ENTER}
80+
6481
};
6582

6683
cocos2d::EventKeyboard::KeyCode ohKeyCodeToCocosKeyCode(OH_NativeXComponent_KeyCode ohKeyCode)
@@ -80,8 +97,9 @@ cocos2d::EventKeyboard::KeyCode ohKeyCodeToCocosKeyCode(OH_NativeXComponent_KeyC
8097
if (ohKeyCode >= KEY_A && ohKeyCode <= KEY_Z) {
8198
// A - Z
8299
return cocos2d::EventKeyboard::KeyCode(int(cocos2d::EventKeyboard::KeyCode::KEY_A) + (ohKeyCode - KEY_A));
83-
}
84-
return cocos2d::EventKeyboard::KeyCode(ohKeyCode);
100+
}
101+
OHOS_LOGW("Unmapped OH key code: %d", ohKeyCode);
102+
return cocos2d::EventKeyboard::KeyCode::KEY_NONE;
85103
}
86104

87105
void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window)

tests/cpp-tests/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

tests/cpp-tests/proj.ohos/build-profile.json5

+6-7
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@
44
{
55
"name": "default",
66
"signingConfig": "default",
7-
"compatibleSdkVersion": "5.0.0(12)",
8-
"targetSdkVersion": "5.0.0(12)",
7+
"compatibleSdkVersion": "5.0.3(15)",
98
"runtimeOS": "HarmonyOS"
109
}
1110
],
@@ -14,13 +13,13 @@
1413
"name": "default",
1514
"type": "HarmonyOS",
1615
"material": {
17-
"certpath": "C:\\Users\\cocos\\.ohos\\config\\default_proj.ohos_bDUQ21cu36Hb_T3jW1UCUliZUhDOg-slWObojAZ01aE=.cer",
18-
"storePassword": "0000001B42DE88211EE39411DFDEC8296FC1F89A1E03E0A0E155C6E2D9282E6FDCEA4C39E34EB9C3D38AA3",
16+
"certpath": "C:\\Users\\cocos\\.ohos\\config\\default_proj.ohos_Sn00X7CKuPjypPJX7h9NSE93VEZdoZLgQH01I4cTSMw=.cer",
1917
"keyAlias": "debugKey",
20-
"keyPassword": "0000001B85EB0DEC53BFE80C21BD062A5180A3CAA3DFBBB1B13B8F29130E2CF6DD6A2B2E4EABBABA095CC6",
21-
"profile": "C:\\Users\\cocos\\.ohos\\config\\default_proj.ohos_bDUQ21cu36Hb_T3jW1UCUliZUhDOg-slWObojAZ01aE=.p7b",
18+
"keyPassword": "0000001A142B209FF7D2A7268F3273851288B08854AD9E09D57A0F77AEA8C1488ACD59F3BF5F880ABE47",
19+
"profile": "C:\\Users\\cocos\\.ohos\\config\\default_proj.ohos_Sn00X7CKuPjypPJX7h9NSE93VEZdoZLgQH01I4cTSMw=.p7b",
2220
"signAlg": "SHA256withECDSA",
23-
"storeFile": "C:\\Users\\cocos\\.ohos\\config\\default_proj.ohos_bDUQ21cu36Hb_T3jW1UCUliZUhDOg-slWObojAZ01aE=.p12"
21+
"storeFile": "C:\\Users\\cocos\\.ohos\\config\\default_proj.ohos_Sn00X7CKuPjypPJX7h9NSE93VEZdoZLgQH01I4cTSMw=.p12",
22+
"storePassword": "0000001A11A855F8A13953CDE22713662FC55157E78C6847EDF97963892A7BDC05A0C5B554C6528FB69D"
2423
}
2524
}
2625
]

tests/cpp-tests/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+
};

tests/cpp-tests/proj.ohos/entry/src/main/ets/MainAbility/MainAbility.ts

-80
This file was deleted.

tests/cpp-tests/proj.ohos/entry/src/main/ets/pages/Index.ets

+1-1
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ struct Index {
109109
}
110110

111111
build() {
112-
Stack(){
112+
Stack() {
113113
XComponent({
114114
id: 'xcomponentId',
115115
type: 'surface',

0 commit comments

Comments
 (0)