merge refactory h2dts

Signed-off-by: wangshi <wangshi@kaihong.com>
This commit is contained in:
wangshi 2024-10-29 17:12:31 +08:00
commit 520ce30585
22 changed files with 1147 additions and 149 deletions

View File

@ -66,6 +66,12 @@ add_library(entry SHARED
javascriptapi/jsvalues/napicreateint32.cpp
javascriptapi/jsvalues/napicreateuint32.cpp
javascriptapi/jsvalues/napicreateint64.cpp
javascriptapi/jsfunctions/jsFunctionsInit.cpp
javascriptapi/jsfunctions/napicallfunction.cpp
javascriptapi/jsfunctions/napicreatefunction.cpp
javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp
javascriptapi/jsobjectwrap/napiwrap.cpp
javascriptapi/jsobjectwrap/napiunwrap.cpp
ncpp/ffmpegcase/render/egl_core.cpp
ncpp/ffmpegcase/render/plugin_render.cpp
ncpp/ffmpegcase/manager/plugin_manager.cpp

View File

@ -58,4 +58,13 @@ napi_value testNapiCreateInt32(napi_env env, napi_callback_info info);
napi_value testNapiCreateUInt32(napi_env env, napi_callback_info info);
napi_value testNapiCreateInt64(napi_env env, napi_callback_info info);
napi_value jsFunctionsInit(napi_env env, napi_value exports);
napi_value testNapiCallFunction(napi_env env, napi_callback_info info);
napi_value SayHello(napi_env env, napi_callback_info info);
napi_value testNapiCreateFunction(napi_env env, napi_callback_info info);
napi_value jsObjectWrapInit(napi_env env, napi_value exports);
napi_value testNapiWrap(napi_env env, napi_callback_info info);
napi_value testNapiUnwrap(napi_env env, napi_callback_info info);
#endif //NAPITUTORIALS_JAVASCRIPTAPI_H

View File

@ -114,6 +114,12 @@ static napi_value Init(napi_env env, napi_value exports)
// 对应 javascriptapi/jsproperty/jsPropertyInit.cpp
jsPropertyInit(env, exports);
// 对应 javascriptapi/jsfunctions/jsFunctionsInit.cpp
jsFunctionsInit(env, exports);
// 对应 javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp
jsObjectWrapInit(env, exports);
napi_property_descriptor descArr[] = {
{"add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr},
{"getTestCase", nullptr, getTestCase, nullptr, nullptr, nullptr, napi_default, nullptr},

View File

@ -0,0 +1,27 @@
/*
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
#include "javascriptapi.h"
napi_value jsFunctionsInit(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
{"testNapiCallFunction", nullptr, testNapiCallFunction, nullptr, nullptr, nullptr, napi_default, nullptr},
{"testNapiCreateFunction", nullptr, testNapiCreateFunction, nullptr, nullptr, nullptr, napi_default, nullptr},
};
napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc);
return exports;
}

View File

@ -0,0 +1,63 @@
/*
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
#include "javascriptapi.h"
static const char *TAG = "[javascriptapi_function]";
napi_value testNapiCallFunction(napi_env env, napi_callback_info info)
{
// pages/javascript/jsfunctions/napicallfunction
// 获取参数数量
size_t argc = PARAM2;
// 准备接收参数的变量
napi_value argv[PARAM2];
napi_value func;
napi_value result;
napi_status status;
const napi_extended_error_info *extended_error_info;
// 获取回调函数的参数信息
status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL);
if (status != napi_ok) {
getErrMsg(status, env, extended_error_info, "Failed to get callback info", TAG);
return NULL;
}
// 检查参数数量是否符合预期
if (argc != PARAM2) {
napi_throw_error(env, NULL, "Expected exactly one argument");
return NULL;
}
// 检查传入参数是否为function
napi_valuetype resultType;
napi_typeof(env, argv[0], &resultType);
if (resultType != napi_function) {
napi_throw_error(env, NULL, "The incoming parameter is not a function");
return NULL;
}
func = argv[PARAM0];
status = napi_call_function(env, NULL, func, PARAM1, &argv[PARAM1], &result);
if (status != napi_ok) {
getErrMsg(status, env, extended_error_info, "call function", TAG);
return NULL;
}
return result;
}

View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
#include "javascriptapi.h"
static const char *TAG = "[javascriptapi_function]";
napi_value SayHello(napi_env env, napi_callback_info info)
{
printf("Hello\n");
return NULL;
}
napi_value testNapiCreateFunction(napi_env env, napi_callback_info info)
{
// pages/javascript/jsfunctions/napicreatefunction
napi_value func;
napi_status status;
napi_value obj;
const napi_extended_error_info *extended_error_info;
status = napi_create_object(env, &obj);
if (status != napi_ok) {
// 错误处理
return NULL;
}
status = napi_create_function(env, NULL, 0, SayHello, NULL, &func);
if (status != napi_ok) {
getErrMsg(status, env, extended_error_info, "create function", TAG);
return NULL;
}
return func;
}

View File

@ -0,0 +1,27 @@
/*
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
#include "javascriptapi.h"
napi_value jsObjectWrapInit(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
{"testNapiWrap", nullptr, testNapiWrap, nullptr, nullptr, nullptr, napi_default, nullptr},
{"testNapiUnwrap", nullptr, testNapiUnwrap, nullptr, nullptr, nullptr, napi_default, nullptr}};
napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc);
return exports;
}

View File

@ -0,0 +1,90 @@
/*
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
#include "javascriptapi.h"
#include "hilog/log.h"
static const char *TAG = "[javascriptapi_object_wrap]";
class MyNode {
public:
napi_status status;
napi_valuetype result;
napi_value resultStr;
const napi_extended_error_info *extended_error_info;
MyNode(napi_env env, napi_value val)
{
// Call napi_typeof(), any -> napi_valuetype
status = napi_typeof(env, val, &result);
if (status != napi_ok) {
getErrMsg(status, env, extended_error_info, "call napi_typeof()", TAG);
}
// napi_valuetype -> string
status = napiValueType2Str(env, result, &resultStr);
if (status != napi_ok) {
std::string errMsg = "Failed to convert napi_valuetype " + std::to_string(status) + " to string";
napi_throw_error(env, NULL, errMsg.c_str());
}
}
napi_value GetResult(napi_env env)
{
return resultStr;
}
};
napi_value testNapiUnwrap(napi_env env, napi_callback_info info)
{
size_t argc = PARAM1;
napi_value argv[PARAM1];
napi_value thisObj;
void *data = nullptr;
napi_status status;
napi_value cons;
const napi_extended_error_info *extended_error_info;
// 获取回调函数的参数信息
status = napi_get_cb_info(env, info, &argc, argv, &thisObj, &data);
if (status != napi_ok) {
getErrMsg(status, env, extended_error_info, "Failed to get callback info", TAG);
return NULL;
}
auto instance = new MyNode(env, argv[PARAM0]);
status = napi_wrap(
env, thisObj, instance,
[](napi_env environment, void *data, void *hint) {
auto objInfo = reinterpret_cast<MyNode *>(data);
if (objInfo != nullptr) {
delete objInfo;
}
}, NULL, NULL);
if (status != napi_ok) {
getErrMsg(status, env, extended_error_info, "wrap", TAG);
return NULL;
}
MyNode *obj;
status = napi_unwrap(env, thisObj, reinterpret_cast<void **>(&obj));
if (status != napi_ok) {
getErrMsg(status, env, extended_error_info, "unwrap", TAG);
return NULL;
}
napi_value resultStrValue = obj->GetResult(env);
if (resultStrValue == nullptr) {
// 处理错误情况
napi_throw_error(env, NULL, "Failed to get result string");
return NULL;
}
return resultStrValue;
}

View File

@ -0,0 +1,74 @@
/*
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
#include "javascriptapi.h"
static const char *TAG = "[javascriptapi_object_wrap]";
static const int MAX_BUFFER_SIZE = 128;
class Node {
public:
Node(napi_env env, napi_value id)
{
// 将 JavaScript 字符串转换为 C++ 字符串
size_t idLength = MAX_BUFFER_SIZE;
char buf[MAX_BUFFER_SIZE];
char *buffer = buf;
napi_get_value_string_utf8(env, id, buffer, idLength, nullptr);
// 将 C++ 字符串转换为 std::string
_id = std::string(buffer);
}
std::string GetId() { return _id; }
private:
std::string _id; // 成员变量,存储 id
};
napi_value testNapiWrap(napi_env env, napi_callback_info info)
{
size_t argc = PARAM1;
napi_value argv[PARAM1] = {0};
napi_value thisObj = nullptr;
void *data = nullptr;
napi_status status;
napi_value cons;
const napi_extended_error_info *extended_error_info;
// 获取回调函数的参数信息
status = napi_get_cb_info(env, info, &argc, argv, &thisObj, &data);
if (status != napi_ok) {
getErrMsg(status, env, extended_error_info, "Failed to get callback info", TAG);
return NULL;
}
napi_valuetype resultType;
napi_typeof(env, argv[PARAM0], &resultType);
if (resultType != napi_string) {
std::string res = "Expected a string, got " + std::to_string(resultType);
napi_throw_error(env, NULL, res.c_str());
return NULL;
}
auto instance = new Node(env, argv[PARAM0]);
status = napi_wrap(env, thisObj, instance,
[](napi_env environment, void *data, void *hint) {
auto objInfo = reinterpret_cast<Node *>(data);
if (objInfo != nullptr) {
delete objInfo;
}
}, NULL, NULL);
if (status != napi_ok) {
getErrMsg(status, env, extended_error_info, "wrap", TAG);
return NULL;
}
return thisObj;
}

View File

@ -65,3 +65,11 @@ export const testNapiStrictEquals: (a: any, b: any) => boolean;
export const testNapiCreateInt32: (number) => number;
export const testNapiCreateUInt32: (number) => number;
export const testNapiCreateInt64: (number) => number;
/* work_with_javascript_functions */
export const testNapiCallFunction: (a: Function, b: number) => number;
export const testNapiCreateFunction: () => any;
/* work_with_javascript_objectwrap */
export const testNapiWrap: (a: string) => any;
export const testNapiUnwrap: (a: any) => string;

View File

@ -400,11 +400,11 @@ const WORK_WITH_JAVASCRIPT_FUNCTIONS: ThirdLevelCategory =
childNodes: [
{
title: $r('app.string.napi_call_function'),
url: 'pages/image/basicSample/image2Gray'
url: 'pages/javascript/jsfunctions/napicallfunction'
},
{
title: $r('app.string.napi_create_function'),
url: 'pages/image/basicSample/image2Gray'
url: 'pages/javascript/jsfunctions/napicreatefunction'
},
{
title: $r('app.string.napi_get_cb_info'),
@ -432,11 +432,11 @@ const OBJECT_WRAP: ThirdLevelCategory =
},
{
title: $r('app.string.napi_wrap'),
url: 'pages/image/basicSample/image2Gray'
url: 'pages/javascript/jsobjectwrap/napiwrap'
},
{
title: $r('app.string.napi_unwrap'),
url: 'pages/image/basicSample/image2Gray'
url: 'pages/javascript/jsobjectwrap/napiunwrap'
},
{
title: $r('app.string.napi_remove_wrap'),

View File

@ -0,0 +1,109 @@
/*
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import router from '@ohos.router';
import image from '@ohos.multimedia.image';
import Logger from '../../../util/Logger';
import testNapi, { testNapiValue } from 'libentry.so';
import { TitleBar } from '../../../common/TitleBar'
import hilog from '@ohos.hilog';
const TAG: string = 'napi_call_function';
function AddTwo(num: number) {
return num + 2;
}
@Entry
@Component
struct napiCallFunction {
private btnFontColor: Resource = $r('app.color.white');
private pixelMapFormat: image.PixelMapFormat = 3;
@State isSetInstance: Boolean = false;
@State imagePixelMap: PixelMap | undefined = undefined;
@State textcont: string = 'napi_call_function用于从原生附加组件调用 JavaScript 函数对象。'
+ '这是从加载项的原生代码回调到 JavaScript 的主要机制。';
@State testcont: string = ' // 测试 N-API napi_call_function \n'
+ ' let fun = function AddTwo(num) {return num + 2;} \n'
+ ' const result = testNapi.testNapiCallFunction(fun, 7); \n'
+ ' console.log(result); \n'
controller: TextAreaController = new TextAreaController()
build() {
Column() {
// 标题
TitleBar({ title: $r('app.string.napi_call_function') })
Column() {
Column() {
TextArea({
text: this.textcont,
placeholder: '',
})
.placeholderFont({ size: 16, weight: 400 })
.width('90%')
.margin(10)
.fontSize(16)
.fontColor($r('app.color.sub_title_color'))
.backgroundColor($r('app.color.white'))
.enabled(false)
TextArea({
text: this.testcont,
placeholder: '',
})
.placeholderFont({ size: 16, weight: 400 })
.width('90%')
.margin(10)
.fontSize(16)
.fontColor($r('app.color.textarea_font_color'))
.backgroundColor($r('app.color.white'))
.enabled(false)
}
.width('100%')
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Start)
Row() {
Button($r('app.string.napi_call_function'), { type: ButtonType.Capsule })
.backgroundColor(Color.Blue)
.width('80%')
.height(48)
.fontSize(16)
.fontWeight(500)
.fontColor(this.btnFontColor)
.margin({ left: 24 })
.id('napi_call_function')
.onClick(() => {
let fun: Function = AddTwo;
let ret: number = testNapi.testNapiCallFunction(fun, 7);
this.testcont = this.testcont.replace('log(result)', 'log(## ' + ret + ' ##)');
})
}
.width('100%')
.height(48)
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.SpaceBetween)
}
.width('100%')
}
.height('100%')
.width('100%')
.backgroundColor($r('app.color.background_shallow_grey'))
}
}

View File

@ -0,0 +1,103 @@
/*
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import router from '@ohos.router';
import image from '@ohos.multimedia.image';
import Logger from '../../../util/Logger';
import testNapi, { testNapiValue } from 'libentry.so';
import { TitleBar } from '../../../common/TitleBar'
import hilog from '@ohos.hilog';
const TAG: string = 'napi_create_function';
@Entry
@Component
struct napiCreateFunction {
private btnFontColor: Resource = $r('app.color.white');
private pixelMapFormat: image.PixelMapFormat = 3;
@State isSetInstance: Boolean = false;
@State imagePixelMap: PixelMap | undefined = undefined;
@State textcont: string = 'napi_create_function允许插件作者以原生代码创建函数对象。'
+ '这是允许从 JavaScript 调用加载项的原生代码的主要机制。';
@State testcont: string = ' // 测试 N-API napi_create_function \n'
+ ' const result = testNapi.testNapiCreateFunction(); \n'
+ ' console.log(result); \n'
controller: TextAreaController = new TextAreaController()
build() {
Column() {
// 标题
TitleBar({ title: $r('app.string.napi_create_function') })
Column() {
Column() {
TextArea({
text: this.textcont,
placeholder: '',
})
.placeholderFont({ size: 16, weight: 400 })
.width('90%')
.margin(10)
.fontSize(16)
.fontColor($r('app.color.sub_title_color'))
.backgroundColor($r('app.color.white'))
.enabled(false)
TextArea({
text: this.testcont,
placeholder: '',
})
.placeholderFont({ size: 16, weight: 400 })
.width('90%')
.margin(10)
.fontSize(16)
.fontColor($r('app.color.textarea_font_color'))
.backgroundColor($r('app.color.white'))
.enabled(false)
}
.width('100%')
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Start)
Row() {
Button($r('app.string.napi_create_function'), { type: ButtonType.Capsule })
.backgroundColor(Color.Blue)
.width('80%')
.height(48)
.fontSize(16)
.fontWeight(500)
.fontColor(this.btnFontColor)
.margin({ left: 24 })
.id('napi_create_function')
.onClick(() => {
console.log(`result is ${testNapi.testNapiCreateFunction()}`);
this.testcont = this.testcont.replace('log(result)', 'log(## typeof result is ' + typeof (testNapi.testNapiCreateFunction()) + ' ##)');
})
}
.width('100%')
.height(48)
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.SpaceBetween)
}
.width('100%')
}
.height('100%')
.width('100%')
.backgroundColor($r('app.color.background_shallow_grey'))
}
}

View File

@ -0,0 +1,102 @@
/*
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import router from '@ohos.router';
import image from '@ohos.multimedia.image';
import Logger from '../../../util/Logger';
import testNapi, { testNapiValue } from 'libentry.so';
import { TitleBar } from '../../../common/TitleBar'
import hilog from '@ohos.hilog';
const TAG: string = 'napi_unwrap';
@Entry
@Component
struct napiunwrap {
private btnFontColor: Resource = $r('app.color.white');
private pixelMapFormat: image.PixelMapFormat = 3;
@State isSetInstance: Boolean = false;
@State imagePixelMap: PixelMap | undefined = undefined;
@State textcont: string = 'napi_unwrap解除封装在 JavaScript 对象中的原生实例。';
@State testcont: string = ' // 测试 N-API napi_unwrap \n'
+ ' const result = testNapi.testNapiUnwrap(true); \n'
+ ' console.log(result); \n'
controller: TextAreaController = new TextAreaController()
build() {
Column() {
// 标题
TitleBar({ title: $r('app.string.napi_unwrap') })
Column() {
Column() {
TextArea({
text: this.textcont,
placeholder: '',
})
.placeholderFont({ size: 16, weight: 400 })
.width('90%')
.margin(10)
.fontSize(16)
.fontColor($r('app.color.sub_title_color'))
.backgroundColor($r('app.color.white'))
.enabled(false)
TextArea({
text: this.testcont,
placeholder: '',
})
.placeholderFont({ size: 16, weight: 400 })
.width('90%')
.margin(10)
.fontSize(16)
.fontColor($r('app.color.textarea_font_color'))
.backgroundColor($r('app.color.white'))
.enabled(false)
}
.width('100%')
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Start)
Row() {
Button($r('app.string.napi_unwrap'), { type: ButtonType.Capsule })
.backgroundColor(Color.Blue)
.width('80%')
.height(48)
.fontSize(16)
.fontWeight(500)
.fontColor(this.btnFontColor)
.margin({ left: 24 })
.id('napi_unwrap')
.onClick(() => {
let ret1 = testNapi.testNapiUnwrap(true);
console.log(`testNapi.testNapiUnwrap() is ${ret1}`);
this.testcont = this.testcont.replace('log(result)', 'log(## ' + ret1 + ' ##)');
})
}
.width('100%')
.height(48)
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.SpaceBetween)
}
.width('100%')
}
.height('100%')
.width('100%')
.backgroundColor($r('app.color.background_shallow_grey'))
}
}

View File

@ -0,0 +1,101 @@
/*
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import router from '@ohos.router';
import image from '@ohos.multimedia.image';
import Logger from '../../../util/Logger';
import testNapi, { testNapiValue } from 'libentry.so';
import { TitleBar } from '../../../common/TitleBar'
import hilog from '@ohos.hilog';
const TAG: string = 'napi_wrap';
@Entry
@Component
struct napiwrap {
private btnFontColor: Resource = $r('app.color.white');
private pixelMapFormat: image.PixelMapFormat = 3;
@State isSetInstance: Boolean = false;
@State imagePixelMap: PixelMap | undefined = undefined;
@State textcont: string = 'napi_wrap在 JavaScript 对象中封装原生实例。';
@State testcont: string = ' // 测试 N-API napi_wrap \n'
+ ' const result = testNapi.testNapiWrap(); \n'
+ ' console.log(result); \n'
controller: TextAreaController = new TextAreaController()
build() {
Column() {
// 标题
TitleBar({ title: $r('app.string.napi_wrap') })
Column() {
Column() {
TextArea({
text: this.textcont,
placeholder: '',
})
.placeholderFont({ size: 16, weight: 400 })
.width('90%')
.margin(10)
.fontSize(16)
.fontColor($r('app.color.sub_title_color'))
.backgroundColor($r('app.color.white'))
.enabled(false)
TextArea({
text: this.testcont,
placeholder: '',
})
.placeholderFont({ size: 16, weight: 400 })
.width('90%')
.margin(10)
.fontSize(16)
.fontColor($r('app.color.textarea_font_color'))
.backgroundColor($r('app.color.white'))
.enabled(false)
}
.width('100%')
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Start)
Row() {
Button($r('app.string.napi_wrap'), { type: ButtonType.Capsule })
.backgroundColor(Color.Blue)
.width('80%')
.height(48)
.fontSize(16)
.fontWeight(500)
.fontColor(this.btnFontColor)
.margin({ left: 24 })
.id('napi_wrap')
.onClick(() => {
console.log(`testNapi.testNapiWrap() is ${testNapi.testNapiWrap('tree')}`);
this.testcont = this.testcont.replace('log(result)', 'log(## ' +typeof (testNapi.testNapiWrap('tree')) + ' ##)');
})
}
.width('100%')
.height(48)
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.SpaceBetween)
}
.width('100%')
}
.height('100%')
.width('100%')
.backgroundColor($r('app.color.background_shallow_grey'))
}
}

View File

@ -98,6 +98,10 @@
"pages/javascript/jsabstractops/napistrictequals",
"pages/javascript/jsvalues/napicreateint32",
"pages/javascript/jsvalues/napicreateuint32",
"pages/javascript/jsvalues/napicreateint64"
"pages/javascript/jsvalues/napicreateint64",
"pages/javascript/jsfunctions/napicallfunction",
"pages/javascript/jsfunctions/napicreatefunction",
"pages/javascript/jsobjectwrap/napiwrap",
"pages/javascript/jsobjectwrap/napiunwrap"
]
}

View File

@ -0,0 +1,71 @@
/*
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import hilog from '@ohos.hilog';
import testNapi, { add } from 'libentry.so';
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
function AddTwo(num: number) {
return num + 2;
}
export default function abilityTestJsFunctions() {
describe('ActsAbilityTestJsFunctions', () => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(() => {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
})
beforeEach(() => {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
})
afterEach(() => {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
})
afterAll(() => {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
})
it('testNapiCallFunction', 0, () => {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
hilog.info(0x0000, 'testTag', '%{public}s', 'it testNapiCallFunction begin');
let result = testNapi.testNapiCallFunction(AddTwo, 7);
hilog.info(0x0000, 'testTag', `napi_call_function(AddTwo, 7) = ${result}`);
expect(result).assertEqual(9);
let result1 = testNapi.testNapiCallFunction(AddTwo, 888);
hilog.info(0x0000, 'testTag', `napi_call_function(AddTwo, 888) = ${result1}`);
expect(result1).assertEqual(890);
let result2 = testNapi.testNapiCallFunction(AddTwo, 77);
hilog.info(0x0000, 'testTag', `napi_call_function(AddTwo, 77) = ${result2}`);
expect(result2).assertEqual(79);
})
it('testNapiCreateFunction', 0, () => {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
hilog.info(0x0000, 'testTag', '%{public}s', 'it testNapiCreateFunction begin');
// let result = testNapi.testNapiCreateFunction();
hilog.info(0x0000, 'testTag', `type of napi_create_functon() is ${typeof(testNapi.testNapiCreateFunction())}`);
expect(typeof(testNapi.testNapiCreateFunction())).assertEqual('function');
})
})
}

View File

@ -0,0 +1,73 @@
/*
* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import hilog from '@ohos.hilog';
import testNapi from 'libentry.so';
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
export default function abilityTestJsObjectWrap() {
describe('ActsAbilityTestJsObjectWrap', () => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(() => {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
})
beforeEach(() => {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
})
afterEach(() => {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
})
afterAll(() => {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
})
it('testNapiWrap', 0, () => {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
hilog.info(0x0000, 'testTag', '%{public}s', 'it testNapiWrap begin');
hilog.info(0x0000, 'testTag', `type of napi_wrap("7") is = ${typeof (testNapi.testNapiWrap("7"))}`);
expect(typeof (testNapi.testNapiWrap("7"))).assertEqual('object');
hilog.info(0x0000, 'testTag', `type of napi_wrap("tree") is = ${typeof (testNapi.testNapiWrap("tree"))}`);
expect(typeof (testNapi.testNapiWrap("tree"))).assertEqual('object');
})
it('testNapiUnwrap', 0, () => {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
hilog.info(0x0000, 'testTag', '%{public}s', 'it testNapiUnwrap begin');
let ret = testNapi.testNapiUnwrap(7);
hilog.info(0x0000, 'testTag', `type of napi_unwrap(7) is = ${ret}`);
expect(ret).assertEqual('number');
let ret1 = testNapi.testNapiUnwrap('tree');
hilog.info(0x0000, 'testTag', `type of napi_unwrap('tree') is = ${ret1}`);
expect(ret1).assertEqual('string');
let ret2 = testNapi.testNapiUnwrap(false);
hilog.info(0x0000, 'testTag', `type of napi_unwrap(false) is = ${ret2}`);
expect(ret2).assertEqual('boolean');
let ret3 = testNapi.testNapiUnwrap(null);
hilog.info(0x0000, 'testTag', `type of napi_unwrap(null) is = ${ret3}`);
expect(ret3).assertEqual('null');
})
})
}

21
src/vscode_plugin/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,21 @@
// A launch configuration that compiles the extension and then opens it inside a new window
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
{
"version": "0.2.0",
"configurations": [{
"name": "Run Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/out/**/*.js"
],
"preLaunchTask": "npm: watch"
}
]
}

20
src/vscode_plugin/.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,20 @@
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "watch",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"presentation": {
"reveal": "never"
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

View File

@ -13,29 +13,16 @@
"Other"
],
"activationEvents": [
"onCommand:extension.h2sa3-2",
"onCommand:extension.h2sa4-1",
"onCommand:extension.h2hdf4-1",
"onCommand:extension.h2dts",
"onCommand:extension.h2dtscpp",
"onCommand:extension.dts2cpp",
"onCommand:extension.ohcrosscompile"
"onCommand:extension.ohcrosscompile",
"onCommand:extension.h2sa",
"onCommand:extension.h2hdf"
],
"main": "./out/extension.js",
"contributes": {
"commands": [
{
"command": "extension.h2sa3-2",
"title": "h2sa3-2"
},
{
"command": "extension.h2sa4-1",
"title": "h2sa4-1"
},
{
"command": "extension.h2hdf4-1",
"title": "h2hdf4-1"
},
{
"command": "extension.h2dts",
"title": "h2dts"
@ -51,33 +38,33 @@
{
"command": "extension.ohcrosscompile",
"title": "OH_CrossCompile"
},
{
"command": "extension.h2sa",
"title": "h2sa"
},
{
"command": "extension.h2hdf",
"title": "h2hdf"
}
],
"submenus": [
{
"id": "gen-menulist",
"label": "OHOS_Gen"
},
{
"id": "gen-h2sa",
"label": "gen_sa"
},
{
"id": "gen-h2hdf",
"label": "gen_hdf"
}
],
"menus": {
"gen-menulist": [
{
"submenu": "gen-h2sa",
"when": "resourceExtname == .h",
"group": "2_workspace"
"command": "extension.h2sa",
"when": "resourceExtname == .h",
"group": "2_workspace"
},
{
"submenu": "gen-h2hdf",
"when": "resourceExtname == .h",
"group": "2_workspace"
"command": "extension.h2hdf",
"when": "resourceExtname == .h",
"group": "2_workspace"
},
{
"command": "extension.h2dts",
@ -106,25 +93,6 @@
"when": "resourceScheme == 'file'",
"group": "2_workspace"
}
],
"gen-h2sa": [
{
"command": "extension.h2sa3-2",
"when": "resourceExtname == .h",
"group": "2_workspace"
},
{
"command": "extension.h2sa4-1",
"when": "resourceExtname == .h",
"group": "2_workspace"
}
],
"gen-h2hdf": [
{
"command": "extension.h2hdf4-1",
"when": "resourceExtname == .h",
"group": "2_workspace"
}
]
}
},

View File

@ -25,7 +25,6 @@ import { genServiceFile } from './gensa';
import { genDtsFile } from './gendts';
import { genHdfFile } from './genhdf';
import { genDtsCppFile } from './gendtscpp';
import fs = require('fs');
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
@ -53,124 +52,194 @@ export function activate(context: vscode.ExtensionContext) {
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
const h2sa3_2 = vscode.commands.registerCommand('extension.h2sa3-2', async (uri) => {
// The code you place here will be executed every time your command is executed
if (uri && uri.fsPath) {
// parse
let funDescList = await parseHeaderFile(uri.fsPath);
console.log('parse header file res: ', funDescList);
console.log('parse header file jsonstr: ', JSON.stringify(funDescList));
// generator
let out = path.dirname(uri.fsPath);
let serviceName = path.basename(uri.fsPath, '.h');
let rootInfo = {
serviceName: serviceName,
funcs: funDescList.funcs,
serviceId: '19000',
versionTag: '3.2'
};
genServiceFile(rootInfo, out);
}
// Display a message box to the user
vscode.window.showInformationMessage('h2sa3_2!');
});
context.subscriptions.push(h2sa3_2);
const h2sa4_1 = vscode.commands.registerCommand('extension.h2sa4-1', async (uri) => {
const h2sa = vscode.commands.registerCommand('extension.h2sa', async (uri) => {
// The code you place here will be executed every time your command is executed
if (uri && uri.fsPath) {
// parse
let funDescList = await parseHeaderFile(uri.fsPath);
console.log('parse header file res: ', funDescList);
console.log('parse header file jsonstr: ', JSON.stringify(funDescList));
// generator
let out = path.dirname(uri.fsPath);
let serviceName = path.basename(uri.fsPath, '.h');
let rootInfo = {
serviceName: serviceName,
funcs: funDescList.funcs,
serviceId: '19000',
versionTag: '4.1'
};
genServiceFile(rootInfo, out);
let versionTag = '3.2';
const quickPick = vscode.window.createQuickPick();
quickPick.title = "h2sa";
quickPick.items = [
{ label: 'h2sa3-2' },
{ label: 'h2sa4-1'}
];
quickPick.canSelectMany = false;
quickPick.onDidAccept(async () => {
const selectedItems = quickPick.selectedItems;
if (selectedItems.length > 0) {
const selectedItem = selectedItems[0].label;
if (selectedItem === 'h2sa3-2') {
versionTag = '3.2';
} else if (selectedItem === 'h2sa4-1') {
versionTag = '4.1';
}
}
vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: "Generating SA...",
cancellable: false
}, async (progress) => {
// progress.report({ increment: 0, message: "Starting..." });
// analyze
let funDescList = await parseHeaderFile(uri.fsPath);
console.log('parse header file res: ', funDescList);
console.log('parse header file jsonstr: ', JSON.stringify(funDescList));
progress.report({ increment: 50, message: "Analyze complete." });
// generator
let out = path.dirname(uri.fsPath);
let serviceName = path.basename(uri.fsPath, '.h');
let rootInfo = {
serviceName: serviceName,
funcs: funDescList.funcs,
serviceId: '19000',
versionTag: versionTag
};
genServiceFile(rootInfo, out);
progress.report({ increment: 100, message: "Generation complete." });
});
quickPick.hide();
})
quickPick.onDidHide(() => {
quickPick.dispose();
})
quickPick.show();
}
// Display a message box to the user
vscode.window.showInformationMessage('h2sa4_1!');
vscode.window.showInformationMessage('h2sa!');
});
context.subscriptions.push(h2sa4_1);
context.subscriptions.push(h2sa);
const h2hdf4_1 = vscode.commands.registerCommand('extension.h2hdf4-1', async (uri) => {
const h2hdf = vscode.commands.registerCommand('extension.h2hdf', async (uri) => {
// The code you place here will be executed every time your command is executed
if (uri && uri.fsPath) {
// analyze
let funDescList = await parseHeaderFile(uri.fsPath);
console.log('parse header file res: ', funDescList);
console.log('parse header file jsonstr: ', JSON.stringify(funDescList));
let versionTag = '4.1';
const quickPick = vscode.window.createQuickPick();
quickPick.title = "h2hdf";
quickPick.items = [
{ label: 'h2hdf4-1'}
];
quickPick.canSelectMany = false;
// generator
let out = path.dirname(uri.fsPath);
let driverName = path.basename(uri.fsPath, '.h').toLocaleLowerCase();
let rootInfo = {
driverName: driverName,
funcs: funDescList.funcs,
versionTag: '4.1'
};
genHdfFile(rootInfo, out);
quickPick.onDidAccept(async () => {
const selectedItems = quickPick.selectedItems;
if (selectedItems.length > 0) {
const selectedItem = selectedItems[0].label;
if (selectedItem === 'h2hdf4-1') {
versionTag = '4.1';
}
}
vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: "Generating DTS...",
cancellable: false
}, async (progress) => {
// progress.report({ increment: 0, message: "Starting..." });
// analyze
let funDescList = await parseHeaderFile(uri.fsPath);
console.log('parse header file res: ', funDescList);
console.log('parse header file jsonstr: ', JSON.stringify(funDescList));
progress.report({ increment: 50, message: "Analyze complete." });
// generator
let out = path.dirname(uri.fsPath);
let driverName = path.basename(uri.fsPath, '.h').toLocaleLowerCase();
let rootInfo = {
driverName: driverName,
funcs: funDescList.funcs,
versionTag: versionTag
};
genHdfFile(rootInfo, out);
progress.report({ increment: 100, message: "Generation complete." });
});
quickPick.hide();
})
quickPick.onDidHide(() => {
quickPick.dispose();
})
quickPick.show();
}
// Display a message box to the user
vscode.window.showInformationMessage('h2hdf4_1!');
vscode.window.showInformationMessage('h2hdf!');
});
context.subscriptions.push(h2hdf4_1);
context.subscriptions.push(h2hdf);
const h2dts = vscode.commands.registerCommand('extension.h2dts', async (uri) => {
// The code you place here will be executed every time your command is executed
if (uri && uri.fsPath) {
// parse
let parseRes = await parseHeaderFile(uri.fsPath);
console.log('parse header file res: ', parseRes);
let rootInfo: GenInfo = {
parseObj: parseRes,
rawFilePath: uri.fsPath, // e://xxx.h
fileName: path.basename(uri.fsPath, '.h') // xxx
};
// generator
let outPath = genDtsFile(rootInfo);
vscode.window.showInformationMessage(`h2dts: gen dts to ${outPath}`);
} else {
// Display a message box to the user
vscode.window.showErrorMessage(`h2dts: error uri ${JSON.stringify(uri)}!`);
}
// The code you place here will be executed every time your command is executed
if (uri && uri.fsPath) {
vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: "Generating .d.ts ...",
cancellable: false
}, async (progress) => {
// parse
let parseRes = await parseHeaderFile(uri.fsPath);
console.log('parse header file res: ', parseRes);
progress.report({ increment: 50, message: "Parse complete." });
let rootInfo: GenInfo = {
parseObj: parseRes,
rawFilePath: uri.fsPath, // e://xxx.h
fileName: path.basename(uri.fsPath, '.h') // xxx
};
// generator
let outPath = genDtsFile(rootInfo);
progress.report({ increment: 100, message: `Generation complete: ${outPath}.` });
});
}
});
context.subscriptions.push(h2dts);
const h2dtscpp = vscode.commands.registerCommand('extension.h2dtscpp', async (uri) => {
// The code you place here will be executed every time your command is executed
if (uri && uri.fsPath) {
// let rawContent = fs.readFileSync(uri.fsPath);
// parse
let funDescList = await parseHeaderFile(uri.fsPath);
let fileName = path.basename(uri.fsPath, '.h');
console.log('parse header file res: ', funDescList);
console.log('parse header file jsonstr: ', JSON.stringify(funDescList));
let rootInfo: DtscppRootInfo = {
funcs: funDescList.funcs,
rawFilePath: uri.fsPath, // e://xxx.h
fileName: fileName // xxx
};
// generator
let out = path.dirname(uri.fsPath);
genDtsCppFile(rootInfo, out);
vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: "Generating DTS...",
cancellable: false
}, async (progress) => {
// progress.report({ increment: 0, message: "Starting..." });
// parse
let funDescList = await parseHeaderFile(uri.fsPath);
let fileName = path.basename(uri.fsPath, '.h');
console.log('parse header file res: ', funDescList);
console.log('parse header file jsonstr: ', JSON.stringify(funDescList));
progress.report({ increment: 50, message: "Analyze complete." });
let rootInfo: DtscppRootInfo = {
funcs: funDescList.funcs,
rawFilePath: uri.fsPath, // e://xxx.h
fileName: fileName // xxx
};
// generator
let out = path.dirname(uri.fsPath);
genDtsCppFile(rootInfo, out);
progress.report({ increment: 100, message: "Generation complete." });
});
}
// Display a message box to the user
vscode.window.showInformationMessage('h2dtscpp!');
});
context.subscriptions.push(h2dtscpp);
const dts2cpp = vscode.commands.registerCommand('extension.dts2cpp', (uri) => {
@ -194,6 +263,5 @@ export function activate(context: vscode.ExtensionContext) {
// generator
}
});
context.subscriptions.push(dts2cpp);
}