diff --git a/examples/napitutorials/entry/src/main/cpp/CMakeLists.txt b/examples/napitutorials/entry/src/main/cpp/CMakeLists.txt index 693513247012ca39ba27b3b42a2806686f28eef5..2a2662c576a9981cec2071ac39ca0f20b06c2ffd 100644 --- a/examples/napitutorials/entry/src/main/cpp/CMakeLists.txt +++ b/examples/napitutorials/entry/src/main/cpp/CMakeLists.txt @@ -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 diff --git a/examples/napitutorials/entry/src/main/cpp/include/javascriptapi.h b/examples/napitutorials/entry/src/main/cpp/include/javascriptapi.h index b9558d207d850c91af3c21747a0756c62a781c3c..e784305bb4d455ffa5c0c2b4d8d7128f0bca2a4f 100644 --- a/examples/napitutorials/entry/src/main/cpp/include/javascriptapi.h +++ b/examples/napitutorials/entry/src/main/cpp/include/javascriptapi.h @@ -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 diff --git a/examples/napitutorials/entry/src/main/cpp/init.cpp b/examples/napitutorials/entry/src/main/cpp/init.cpp index 0b9dbed7fd3e65cb55c72a4658987b5557e21cf2..16649b4a52aaa71a2bb5b904e993c0cbeea570b2 100644 --- a/examples/napitutorials/entry/src/main/cpp/init.cpp +++ b/examples/napitutorials/entry/src/main/cpp/init.cpp @@ -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}, diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df16c482a0b8d2a7cdb6284b0ee6566e7f3b6bd2 --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp @@ -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; +} diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicallfunction.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicallfunction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..96f750c6e9441cc3ae4a891a22b8b5bd41e47337 --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicallfunction.cpp @@ -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; +} + diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicreatefunction.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicreatefunction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b8abc22e24c5b127ea4d89512e56f8dd6cc6c44d --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicreatefunction.cpp @@ -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; +} diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61e3a01ff158e3abe76df5b629fc1b02050ae982 --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp @@ -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; +} diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiunwrap.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiunwrap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4445da86435a5602248dd89ee42c6ce7d79aa035 --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiunwrap.cpp @@ -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(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(&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; +} diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61f1d6b5b7a3ed59e8a5aad835c0735b5214d5ec --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp @@ -0,0 +1,77 @@ +/* + * 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]"; + +class Node { +public: + Node(napi_env env, napi_value id) + { + // 将 JavaScript 字符串转换为 C++ 字符串 + size_t idLength; + napi_get_value_string_utf8(env, id, nullptr, 0, &idLength); + char *buffer = new char[idLength + 1]; + napi_get_value_string_utf8(env, id, buffer, idLength + 1, nullptr); + // 将 C++ 字符串转换为 std::string + _id = std::string(buffer); + // 释放分配的内存 + delete[] 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(data); + if (objInfo != nullptr) { + delete objInfo; + } + }, NULL, NULL); + if (status != napi_ok) { + getErrMsg(status, env, extended_error_info, "wrap", TAG); + return NULL; + } + return thisObj; +} + diff --git a/examples/napitutorials/entry/src/main/cpp/types/libentry/index.d.ts b/examples/napitutorials/entry/src/main/cpp/types/libentry/index.d.ts index 371d004f4cee66ef8854f3cc4f10faeb3c29ba25..a200f48e0176505583e6173adae5c54a813823bd 100644 --- a/examples/napitutorials/entry/src/main/cpp/types/libentry/index.d.ts +++ b/examples/napitutorials/entry/src/main/cpp/types/libentry/index.d.ts @@ -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; \ No newline at end of file diff --git a/examples/napitutorials/entry/src/main/ets/pages/javascript/JavascriptApi.ets b/examples/napitutorials/entry/src/main/ets/pages/javascript/JavascriptApi.ets index f3d33cbc962d5cc51d38938214860440f84fa7f4..dd3c6ad251069e0256e1114f500b795c19bf8079 100644 --- a/examples/napitutorials/entry/src/main/ets/pages/javascript/JavascriptApi.ets +++ b/examples/napitutorials/entry/src/main/ets/pages/javascript/JavascriptApi.ets @@ -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'), diff --git a/examples/napitutorials/entry/src/main/ets/pages/javascript/jsfunctions/napicallfunction.ets b/examples/napitutorials/entry/src/main/ets/pages/javascript/jsfunctions/napicallfunction.ets new file mode 100644 index 0000000000000000000000000000000000000000..5cbb1576a611591b988ee5468a2748ed50eb8226 --- /dev/null +++ b/examples/napitutorials/entry/src/main/ets/pages/javascript/jsfunctions/napicallfunction.ets @@ -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')) + } +} \ No newline at end of file diff --git a/examples/napitutorials/entry/src/main/ets/pages/javascript/jsfunctions/napicreatefunction.ets b/examples/napitutorials/entry/src/main/ets/pages/javascript/jsfunctions/napicreatefunction.ets new file mode 100644 index 0000000000000000000000000000000000000000..490edea79d36535f0d61a955cc4b7eca92544340 --- /dev/null +++ b/examples/napitutorials/entry/src/main/ets/pages/javascript/jsfunctions/napicreatefunction.ets @@ -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')) + } +} \ No newline at end of file diff --git a/examples/napitutorials/entry/src/main/ets/pages/javascript/jsobjectwrap/napiunwrap.ets b/examples/napitutorials/entry/src/main/ets/pages/javascript/jsobjectwrap/napiunwrap.ets new file mode 100644 index 0000000000000000000000000000000000000000..be2fe11d2b51fdcfe44be987a21ff3ab53cdec2d --- /dev/null +++ b/examples/napitutorials/entry/src/main/ets/pages/javascript/jsobjectwrap/napiunwrap.ets @@ -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')) + } +} \ No newline at end of file diff --git a/examples/napitutorials/entry/src/main/ets/pages/javascript/jsobjectwrap/napiwrap.ets b/examples/napitutorials/entry/src/main/ets/pages/javascript/jsobjectwrap/napiwrap.ets new file mode 100644 index 0000000000000000000000000000000000000000..c4c7146d83a2a3d675c86c2faa947b5a3151876d --- /dev/null +++ b/examples/napitutorials/entry/src/main/ets/pages/javascript/jsobjectwrap/napiwrap.ets @@ -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')) + } +} \ No newline at end of file diff --git a/examples/napitutorials/entry/src/main/resources/base/profile/main_pages.json b/examples/napitutorials/entry/src/main/resources/base/profile/main_pages.json index 22a86a698391029befc3820a574901c9e957b590..c3443b5da5ecb0dd3b8aff0f5ab782953c84b7d3 100644 --- a/examples/napitutorials/entry/src/main/resources/base/profile/main_pages.json +++ b/examples/napitutorials/entry/src/main/resources/base/profile/main_pages.json @@ -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" ] } diff --git a/examples/napitutorials/entry/src/ohosTest/ets/test/javascriptapi/jsfunctions.test.ets b/examples/napitutorials/entry/src/ohosTest/ets/test/javascriptapi/jsfunctions.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..e355b1551a6a56d47c2f863f71ce6b0ab05fdd80 --- /dev/null +++ b/examples/napitutorials/entry/src/ohosTest/ets/test/javascriptapi/jsfunctions.test.ets @@ -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'); + }) + + }) +} \ No newline at end of file diff --git a/examples/napitutorials/entry/src/ohosTest/ets/test/javascriptapi/jsobjectwrap.test.ets b/examples/napitutorials/entry/src/ohosTest/ets/test/javascriptapi/jsobjectwrap.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..d88edb750c1a75a8423ddda06ef9c9095f326302 --- /dev/null +++ b/examples/napitutorials/entry/src/ohosTest/ets/test/javascriptapi/jsobjectwrap.test.ets @@ -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'); + }) + + }) +} \ No newline at end of file