From 999a5332c6a1e83688427ab39416fbfd53a9342a Mon Sep 17 00:00:00 2001 From: zhangmenghan Date: Thu, 24 Oct 2024 10:10:59 +0800 Subject: [PATCH 1/7] function && objectwrap Signed-off-by: zhangmenghan --- .../entry/src/main/cpp/CMakeLists.txt | 6 + .../src/main/cpp/include/javascriptapi.h | 9 ++ .../napitutorials/entry/src/main/cpp/init.cpp | 6 + .../jsfunctions/jsFunctionsInit.cpp | 26 +++++ .../jsfunctions/napicallfunction.cpp | 62 ++++++++++ .../jsfunctions/napicreatefunction.cpp | 46 ++++++++ .../jsobjectwrap/jsObjectWrapInit.cpp | 26 +++++ .../javascriptapi/jsobjectwrap/napiunwrap.cpp | 87 ++++++++++++++ .../javascriptapi/jsobjectwrap/napiwrap.cpp | 75 ++++++++++++ .../src/main/cpp/types/libentry/index.d.ts | 8 ++ .../ets/pages/javascript/JavascriptApi.ets | 8 +- .../jsfunctions/napicallfunction.ets | 109 ++++++++++++++++++ .../jsfunctions/napicreatefunction.ets | 103 +++++++++++++++++ .../javascript/jsobjectwrap/napiunwrap.ets | 102 ++++++++++++++++ .../javascript/jsobjectwrap/napiwrap.ets | 101 ++++++++++++++++ .../resources/base/profile/main_pages.json | 6 +- .../test/javascriptapi/jsfunctions.test.ets | 71 ++++++++++++ .../test/javascriptapi/jsobjectwrap.test.ets | 73 ++++++++++++ 18 files changed, 919 insertions(+), 5 deletions(-) create mode 100644 examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp create mode 100644 examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicallfunction.cpp create mode 100644 examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicreatefunction.cpp create mode 100644 examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp create mode 100644 examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiunwrap.cpp create mode 100644 examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp create mode 100644 examples/napitutorials/entry/src/main/ets/pages/javascript/jsfunctions/napicallfunction.ets create mode 100644 examples/napitutorials/entry/src/main/ets/pages/javascript/jsfunctions/napicreatefunction.ets create mode 100644 examples/napitutorials/entry/src/main/ets/pages/javascript/jsobjectwrap/napiunwrap.ets create mode 100644 examples/napitutorials/entry/src/main/ets/pages/javascript/jsobjectwrap/napiwrap.ets create mode 100644 examples/napitutorials/entry/src/ohosTest/ets/test/javascriptapi/jsfunctions.test.ets create mode 100644 examples/napitutorials/entry/src/ohosTest/ets/test/javascriptapi/jsobjectwrap.test.ets diff --git a/examples/napitutorials/entry/src/main/cpp/CMakeLists.txt b/examples/napitutorials/entry/src/main/cpp/CMakeLists.txt index 69351324..2a2662c5 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 b9558d20..e784305b 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 0b9dbed7..16649b4a 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 00000000..b3c60397 --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp @@ -0,0 +1,26 @@ +/* + * 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 00000000..325901be --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicallfunction.cpp @@ -0,0 +1,62 @@ +/* + * 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 00000000..3ed1eef3 --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicreatefunction.cpp @@ -0,0 +1,46 @@ +/* + * 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 00000000..edd52ac3 --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp @@ -0,0 +1,26 @@ +/* + * 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 00000000..8e5ccf5f --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiunwrap.cpp @@ -0,0 +1,87 @@ +/* + * 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 00000000..c96d5276 --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp @@ -0,0 +1,75 @@ +/* + * 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 371d004f..a200f48e 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 f3d33cbc..dd3c6ad2 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 00000000..5cbb1576 --- /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 00000000..490edea7 --- /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 00000000..be2fe11d --- /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 00000000..c4c7146d --- /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 22a86a69..c3443b5d 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 00000000..e355b155 --- /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 00000000..d88edb75 --- /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 From f83b832d516dbcf5f0572b038376c6b2f6d61393 Mon Sep 17 00:00:00 2001 From: zhangmenghan Date: Thu, 24 Oct 2024 10:47:38 +0800 Subject: [PATCH 2/7] codecheck Signed-off-by: zhangmenghan --- .../cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp | 3 ++- .../cpp/javascriptapi/jsfunctions/napicreatefunction.cpp | 6 ++++-- .../main/cpp/javascriptapi/jsobjectwrap/napiunwrap.cpp | 9 ++++++--- .../src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp | 6 ++++-- 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp index b3c60397..58caabf9 100644 --- a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp @@ -17,7 +17,8 @@ #include "javascriptapi.h" napi_value jsFunctionsInit(napi_env env, napi_value exports) { - napi_property_descriptor desc[] = { + napi_property_descriptor desc[] = + { {"testNapiCallFunction", nullptr, testNapiCallFunction, nullptr, nullptr, nullptr, napi_default, nullptr}, {"testNapiCreateFunction", nullptr, testNapiCreateFunction, nullptr, nullptr, nullptr, napi_default, nullptr}, }; diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicreatefunction.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicreatefunction.cpp index 3ed1eef3..b8abc22e 100644 --- a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicreatefunction.cpp +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicreatefunction.cpp @@ -18,12 +18,14 @@ static const char *TAG = "[javascriptapi_function]"; -napi_value SayHello(napi_env env, napi_callback_info info) { +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) { +napi_value testNapiCreateFunction(napi_env env, napi_callback_info info) +{ // pages/javascript/jsfunctions/napicreatefunction napi_value func; napi_status status; diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiunwrap.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiunwrap.cpp index 8e5ccf5f..4445da86 100644 --- a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiunwrap.cpp +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiunwrap.cpp @@ -24,7 +24,8 @@ public: napi_valuetype result; napi_value resultStr; const napi_extended_error_info *extended_error_info; - MyNode(napi_env env, napi_value val) { + MyNode(napi_env env, napi_value val) + { // Call napi_typeof(), any -> napi_valuetype status = napi_typeof(env, val, &result); if (status != napi_ok) { @@ -38,12 +39,14 @@ public: napi_throw_error(env, NULL, errMsg.c_str()); } } - napi_value GetResult(napi_env env) { + napi_value GetResult(napi_env env) + { return resultStr; } }; -napi_value testNapiUnwrap(napi_env env, napi_callback_info info) { +napi_value testNapiUnwrap(napi_env env, napi_callback_info info) +{ size_t argc = PARAM1; napi_value argv[PARAM1]; napi_value thisObj; diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp index c96d5276..61f1d6b5 100644 --- a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp @@ -20,7 +20,8 @@ static const char *TAG = "[javascriptapi_object_wrap]"; class Node { public: - Node(napi_env env, napi_value id) { + Node(napi_env env, napi_value id) + { // 将 JavaScript 字符串转换为 C++ 字符串 size_t idLength; napi_get_value_string_utf8(env, id, nullptr, 0, &idLength); @@ -36,7 +37,8 @@ private: std::string _id; // 成员变量,存储 id }; -napi_value testNapiWrap(napi_env env, napi_callback_info info) { +napi_value testNapiWrap(napi_env env, napi_callback_info info) +{ size_t argc = PARAM1; napi_value argv[PARAM1] = {0}; napi_value thisObj = nullptr; From d17acb23fd44739aa49560c1ace1c0448c3f51e4 Mon Sep 17 00:00:00 2001 From: zhangmenghan Date: Thu, 24 Oct 2024 10:49:21 +0800 Subject: [PATCH 3/7] codecheck Signed-off-by: zhangmenghan --- .../main/cpp/javascriptapi/jsfunctions/napicallfunction.cpp | 3 ++- .../main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicallfunction.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicallfunction.cpp index 325901be..96f750c6 100644 --- a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicallfunction.cpp +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/napicallfunction.cpp @@ -18,7 +18,8 @@ static const char *TAG = "[javascriptapi_function]"; -napi_value testNapiCallFunction(napi_env env, napi_callback_info info) { +napi_value testNapiCallFunction(napi_env env, napi_callback_info info) +{ // pages/javascript/jsfunctions/napicallfunction // 获取参数数量 size_t argc = PARAM2; diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp index edd52ac3..8cfdd9ae 100644 --- a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp @@ -17,7 +17,8 @@ #include "javascriptapi.h" napi_value jsObjectWrapInit(napi_env env, napi_value exports) { - napi_property_descriptor desc[] = { + napi_property_descriptor desc[] = + { {"testNapiWrap", nullptr, testNapiWrap, nullptr, nullptr, nullptr, napi_default, nullptr}, {"testNapiUnwrap", nullptr, testNapiUnwrap, nullptr, nullptr, nullptr, napi_default, nullptr}}; From 72bd9ec5d1bdae63a59b694f16129f78c5e06b99 Mon Sep 17 00:00:00 2001 From: zhangmenghan Date: Thu, 24 Oct 2024 10:57:41 +0800 Subject: [PATCH 4/7] codecheck Signed-off-by: zhangmenghan --- .../main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp | 6 +++--- .../cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp index 58caabf9..df16c482 100644 --- a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsfunctions/jsFunctionsInit.cpp @@ -16,9 +16,9 @@ #include "common.h" #include "javascriptapi.h" -napi_value jsFunctionsInit(napi_env env, napi_value exports) { - napi_property_descriptor desc[] = - { +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}, }; diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp index 8cfdd9ae..61e3a01f 100644 --- a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/jsObjectWrapInit.cpp @@ -16,9 +16,9 @@ #include "common.h" #include "javascriptapi.h" -napi_value jsObjectWrapInit(napi_env env, napi_value exports) { - napi_property_descriptor desc[] = - { +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}}; From 57aa01b02098c4fc4ba54674c14e0e68f9dd14f5 Mon Sep 17 00:00:00 2001 From: zhangmenghan Date: Thu, 24 Oct 2024 17:37:10 +0800 Subject: [PATCH 5/7] modified Signed-off-by: zhangmenghan --- .../javascriptapi/jsobjectwrap/napiwrap.cpp | 28 +++++++++---------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp index 61f1d6b5..74a5ee42 100644 --- a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp @@ -17,35 +17,32 @@ #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) - { + 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); + 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); - // 释放分配的内存 - delete[] buffer; } std::string GetId() { return _id; } + private: std::string _id; // 成员变量,存储 id }; -napi_value testNapiWrap(napi_env env, napi_callback_info info) -{ +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); @@ -61,17 +58,18 @@ napi_value testNapiWrap(napi_env env, napi_callback_info info) return NULL; } auto instance = new Node(env, argv[PARAM0]); - status = napi_wrap(env, thisObj, instance, + 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); + }, + NULL, NULL); if (status != napi_ok) { getErrMsg(status, env, extended_error_info, "wrap", TAG); return NULL; } return thisObj; } - From 766b2a05b9f3a4b37ff1b16a284e0d31f2a340ba Mon Sep 17 00:00:00 2001 From: zhangmenghan Date: Thu, 24 Oct 2024 17:41:29 +0800 Subject: [PATCH 6/7] codecheck Signed-off-by: zhangmenghan --- .../cpp/javascriptapi/jsobjectwrap/napiwrap.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp index 74a5ee42..fca853d2 100644 --- a/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp +++ b/examples/napitutorials/entry/src/main/cpp/javascriptapi/jsobjectwrap/napiwrap.cpp @@ -18,9 +18,11 @@ static const char *TAG = "[javascriptapi_object_wrap]"; static const int MAX_BUFFER_SIZE = 128; + class Node { public: - Node(napi_env env, napi_value id) { + Node(napi_env env, napi_value id) + { // 将 JavaScript 字符串转换为 C++ 字符串 size_t idLength = MAX_BUFFER_SIZE; char buf[MAX_BUFFER_SIZE]; @@ -30,19 +32,18 @@ public: _id = std::string(buffer); } std::string GetId() { return _id; } - private: std::string _id; // 成员变量,存储 id }; -napi_value testNapiWrap(napi_env env, napi_callback_info info) { +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); @@ -58,15 +59,13 @@ napi_value testNapiWrap(napi_env env, napi_callback_info info) { return NULL; } auto instance = new Node(env, argv[PARAM0]); - status = napi_wrap( - env, thisObj, instance, + 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); + }, NULL, NULL); if (status != napi_ok) { getErrMsg(status, env, extended_error_info, "wrap", TAG); return NULL; From c9eb0db16403ccc5956a12ff23f96f1c1bd96181 Mon Sep 17 00:00:00 2001 From: chen-zhongwei050 Date: Mon, 28 Oct 2024 14:39:58 +0800 Subject: [PATCH 7/7] =?UTF-8?q?=E6=8F=92=E4=BB=B6=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E9=80=89=E6=8B=A9=E5=BC=B9=E6=A1=86=EF=BC=88quickpicker?= =?UTF-8?q?=EF=BC=89=E5=92=8C=20=E8=BF=9B=E5=BA=A6=E7=AA=97=EF=BC=88withPr?= =?UTF-8?q?ogress=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: chen-zhongwei050 --- src/vscode_plugin/.vscode/launch.json | 21 +++ src/vscode_plugin/.vscode/tasks.json | 20 ++ src/vscode_plugin/package.json | 66 ++----- src/vscode_plugin/src/extension.ts | 257 +++++++++++++++++--------- 4 files changed, 225 insertions(+), 139 deletions(-) create mode 100644 src/vscode_plugin/.vscode/launch.json create mode 100644 src/vscode_plugin/.vscode/tasks.json diff --git a/src/vscode_plugin/.vscode/launch.json b/src/vscode_plugin/.vscode/launch.json new file mode 100644 index 00000000..a875cead --- /dev/null +++ b/src/vscode_plugin/.vscode/launch.json @@ -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" + } + ] +} diff --git a/src/vscode_plugin/.vscode/tasks.json b/src/vscode_plugin/.vscode/tasks.json new file mode 100644 index 00000000..241aa6d9 --- /dev/null +++ b/src/vscode_plugin/.vscode/tasks.json @@ -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 + } + } + ] +} \ No newline at end of file diff --git a/src/vscode_plugin/package.json b/src/vscode_plugin/package.json index c2c3d231..44440281 100644 --- a/src/vscode_plugin/package.json +++ b/src/vscode_plugin/package.json @@ -13,28 +13,15 @@ "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.dts2cpp", + "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" @@ -46,33 +33,33 @@ { "command": "extension.dts2cpp", "title": "dts2cpp" + }, + { + "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", @@ -96,25 +83,6 @@ "when": "resourceExtname == .h || resourceExtname == .ts", "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" - } ] } }, diff --git a/src/vscode_plugin/src/extension.ts b/src/vscode_plugin/src/extension.ts index 5c7a8f29..0dfd802a 100644 --- a/src/vscode_plugin/src/extension.ts +++ b/src/vscode_plugin/src/extension.ts @@ -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 @@ -37,125 +36,204 @@ 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 funDescList = await parseHeaderFile(uri.fsPath); - console.log('parse header file res: ', funDescList); - console.log('parse header file jsonstr: ', JSON.stringify(funDescList)); - let fileName = path.basename(uri.fsPath, '.h'); - let rootInfo: DtscppRootInfo = { - funcs: funDescList.funcs, - rawFilePath: uri.fsPath, // e://xxx.h - fileName: fileName // xxx - }; - // generator - let out = path.dirname(uri.fsPath); - genDtsFile(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); + console.log('parse header file res: ', funDescList); + console.log('parse header file jsonstr: ', JSON.stringify(funDescList)); + + progress.report({ increment: 50, message: "Analyze complete." }); + + let fileName = path.basename(uri.fsPath, '.h'); + let rootInfo = { + funcs: funDescList.funcs, + rawFilePath: uri.fsPath, + fileName: fileName + }; + // generator + let out = path.dirname(uri.fsPath); + genDtsFile(rootInfo, out); + + progress.report({ increment: 100, message: "Generation complete." }); + }); } // Display a message box to the user vscode.window.showInformationMessage('h2dts!'); }); - 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) => { @@ -179,6 +257,5 @@ export function activate(context: vscode.ExtensionContext) { // generator } }); - context.subscriptions.push(dts2cpp); }