diff --git a/napi_IntelliJ_plugin/README_zh.md b/napi_IntelliJ_plugin/README_zh.md deleted file mode 100644 index f66295c81e3d492bba31c48317515e201db5344e..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/README_zh.md +++ /dev/null @@ -1,119 +0,0 @@ -# NAPI框架生成工具IntelliJ插件说明 - -## 简介 - -NAPI框架代码生成工具,它可以根据用户指定路径下的ts(typescript)接口文件一键生成NAPI框架代码、业务代码框架、GN文件等。目前工具支持可执行文件、VS Code插件、DevEco Studio上使用的IntelliJ插件三种入口,本文主要介绍IntelliJ插件使用说明。 - -## 目录 - - ├── napi_generator # NAPI框架代码生成工具 - │ ├── ... # 其他文件 - │ ├── napi_IntelliJ_plugin # IntelliJ插件代码 - │ │ ├── docs # IntelliJ插件说明 - │ │ ├── resources # IntelliJ插件说明 - │ │ ├── src # IntelliJ插件源码 - │ │ └── README_zh # IntelliJ插件说明 - -## 约束 - -系统:建议Windows 10 - -依赖版本:JDK 11 - -开发工具:DevEco stdio、IDEA Community 2021.3.3 - -## 使用方法 - -### 使用对象 - -系统开发者 - -### 使用场景 - -1) 系统框架层新增子系统,需对应用层提供接口。 -2) 系统框架层子系统能力增强后,需对应用层提供新接口。 - -### 工具使用 - -插件下载路径如下,选择新版本下载。 - -[DevEco Studio上使用的IntelliJ插件下载链接](https://plugins.jetbrains.com/plugin/19593-napi-generator/versions) - -![](../figures/picGoogle-napi_jar_download.png) - -具体的工具使用步骤,可以左键单击以下链接了解: - -[工具使用说明](https://gitee.com/openharmony/napi_generator/tree/master/napi_IntelliJ_plugin/docs/napi/INSTRUCTION_ZH.md) - -### 工具输出 - -根据使用者指定的typescript文件,工具会输出NAPI框架代码、业务代码框架、GN脚本等文件。 - -为了方便使用者快速上手工具,可供测试的typescript文件存放在DevEco Studio中以下路径: - -``` -entry/src -``` - -在window环境下的,根据输入文件@ohos.napitest.d.ts和basic.d.ts生成的输出文件,如下所示: - -![](../figures/pic-d-ts-dev_transition.png) - - - -其中CMakeLists.txt为编译构建需要的文件,cfg.json为生成的业务代码配置文件,若用户不进行业务代码配置,则不会生成该文件;生成的"napitest.h"文件,定义了框架代码的接口,生成的部分接口如下所示: - -``` -... -class NodeISayHello { -public: - bool addSayHelloListener(NodeISayHelloListener& listener); - static NodeISayHelloListener listener_; - bool removeSayHelloListener(NodeISayHelloListener& listener); - bool registerCallbackfunc(); - // 供业务调用的回调接口 - void CallbackfuncCallback(NUMBER_TYPE_2& wid); - - bool unRegisterCallbackfunc(); - bool sayHello(std::string& from, std::string& to, NUMBER_TYPE_9& sayType); - bool sayHi(std::string& from, std::string& to, NUMBER_TYPE_10& sayType); - bool sayHelloWithResponse(std::string& from, std::string& to, NUMBER_TYPE_11& sayType, uint32_t& outErrCode, AUTO_INTERFACE_5& out); - static AUTO_INTERFACE_5 auto_interface_5OutRes; - void auto_interface_5SetCbValue(NUMBER_TYPE_6 result, std::string errMsg, std::string response); -}; -... -``` - -## 开发说明 - -### 对象 - -工具的开发者 - -### 开发场景 - -若当前工具的功能已经不能满足开发者的全部需求,则开发者可以基于已有的源码对工具进行二次开发,来增强工具的能力,编译打包生成自定义的可执行文件和插件。 - -### 开发步骤 - -开发者可以根据如下的步骤来完成对DevEco Studio上使用的工具IntelliJ插件的开发: - - [工具开发说明](https://gitee.com/openharmony/napi_generator/tree/master/napi_IntelliJ_plugin/docs/napi/DEVELOP_ZH.md) - -## 版本说明 - -当前版本已支持的特性和待开发的特性,如下所示: - - [已支持特性](https://gitee.com/openharmony/napi_generator/blob/master/release-notes) - - [待支持特性](https://gitee.com/openharmony/napi_generator/blob/master/docs/guide/ROADMAP_ZH.md) - -## FAQ - -对于常见问题解决方法指导如下: - - [FAQ](https://gitee.com/openharmony/napi_generator/blob/master/FAQ.md) - -## 相关仓 - -暂无 \ No newline at end of file diff --git a/napi_IntelliJ_plugin/docs/napi/DEVELOP_ZH.md b/napi_IntelliJ_plugin/docs/napi/DEVELOP_ZH.md deleted file mode 100755 index 0665666708a205133939ac9d31338120a9c9a660..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/docs/napi/DEVELOP_ZH.md +++ /dev/null @@ -1,100 +0,0 @@ -# NAPI框架生成工具IntelliJ插件开发说明 - -若当前工具功能不满足开发者需求,开发者需增强工具能力,则可基于已有源码进行工具二次开发,编译打包生成自定义的DevEco Studio上使用的IntelliJ插件。 - -## DevEco Studio上使用的IntelliJ插件打包说明 - -### 环境说明 - -系统:建议Windows 10 - -### 开发步骤 - -#### 环境准备 - -1.下载napi工具可执行程序,并放置在napi_generator/napi_IntelliJ_plugin/resources/cmds目录下对应系统的文件夹下,可执行文件下载路径如下(由于网络原因,可能会导致有的下载链接失效,因此提供了以下三个下载链接): - -[可执行文件下载链接1](http://ftpkaihongdigi.i234.me:5000/sharing/yaRiKSjBI) - -[可执行文件下载链接2](http://ftp.kaihong.com:5000/fsdownload/yaRiKSjBI/) - -[可执行文件下载链接3](http://ftp.kaihongdigi.com:5000/fsdownload/yaRiKSjBI/) - -访问密码:kaihong - -压缩包解压密码:kaihong20231121 - -2.下载并安装IDEA Community、JDK11配置好环境。IDEA Community版本可以左键单击以下链接下载。 - -[下载链接](https://www.jetbrains.com/idea/download/) - -3.打开IDEA Community应用程序 -依次点击项目File>Open 选择napi_generator/napi_IntelliJ_plugin项目文件夹。 -![](../../../figures/IntelliJ_env_config_open_proj.png) - -4.配置Project -项目打开完成,点击File>Project Structure,在出现的界面中点击Project,下图的SDK选择JDK 11,选择或者新建complier output目录为项目文件下的out目录。 -![](../../../figures/IntelliJ_env_proj_structure.png) - -5.配置Modules -Project Settings > Modules 新建Modules。点击上方“-”删除原有的Modules,然后点击“+”选择 New Module。 -![](../../../figures/IntelliJ_env_Proj_Module.png) - -6.配置Module SDK -在New Module对话框中,选择IntelliJ Platform Plugin。若Module SDK中无可选SDK,请在Module SDK 下拉框中点击 Add IntelliJ Platform Plugin SDK 选择IDEA Community安装目录,点击OK,在Select Internal Java Platform 选择 JAVA SDK 11(213版本只支持 11),点击New Module对话框中Next。 -![](../../../figures/IntelliJ_env_Proj_Module_New.png) - -7.配置Content root -Content root选择~/napi_generator/napi_IntelliJ_plugin文件夹,module name填写napi_generator。点击Finish,若出现提示已存在是否覆盖的提示,请点“Yes”完成配置。 - -![](../../../figures/IntelliJ_env_module_root.png) - -8.Modules配置完成后,若在SDKs中无相应JDK和Plugin SDK,请点击+号分别添加 Add Java JDK和Add Intellij PlantForm Plugin SDK,Java JDK为java11的安装目录,Plugin SDK为 IDEA Community 2021.3.3的安装目录。 -![](../../../figures/IntelliJ_env_config_SDKs.png) - -9.配置Libraries - -由于IntellIj插件市场兼容性问题,原使用的json库与新版本的IDE不兼容,因此使用新的json库解决兼容性问题,新的json库需要从Maven仓库下载并将依赖配置到工程中(napi 1.0.3版本以及之后版本才需要配置依赖,之前的版本跳过此步骤 )。 - -步骤:点击"+",选择"From Maven...";在搜索框搜索依赖的jar包:com.alibaba.fastjson2:fastjson2:2.0.42,勾选"Download to"并点击OK,将依赖下载至工程目录下的lib文件夹;点击"Choose Modules"中的OK。 - -![](../../../figures/IntelliJ_env_config_libs.png) - -![](../../../figures/IntelliJ_env_config_libs_download.png) - -![](../../../figures/IntelliJ_env_config_libs_choose_module.png) - -![](../../../figures/IntelliJ_env_config_libs_check.png) - -10.若完成以上步骤配置,点击OK完成配置。Rebuild项目,若IDEA不能点击右上角的运行,点击Plugin后下三角选择Edit Configurations...选项,Run/Debug Configurations框中Use classpath of moudle选择napi_generator,点击ok,等待安装完成。 - -![](../../../figures/IntelliJ_env_configurations.png) - -![](../../../figures/IntelliJ_env_run_debug.png) - -10.点击Intellij IDEA工具右上角Built Project按钮,等待工程built完成。 - -![](../../../figures/IntelliJ_env_built_pro.png) - -11.在IDEA Community中依次点击Build>Prepare All Plugin Modules for development",然后在Select Modules框中点击ok,jar/zip包生成完成后在工具右下角提示jar/zip包生成成功,且包含jar/zip包存放位置。 - -![](../../../figures/IntelliJ_env_built_jar.png) - -![](../../../figures/IntelliJ_env_select_moudles.png) - -1.0.3之前版本,版本格式.jar,由于1.0.3及之后新增了lib依赖(com.alibaba.fastjson2:fastjson2:2.0.42),版本格式为.zip。 - -![](../../../figures/IntelliJ_env_built_jar_success.png) - -![](../../../figures/IntelliJ_env_built_zip_success.png) - - - -## 工具测试 - -进行工具二次开发后,本地可进行单元测试、story特性测试确保工具的可用性。左键单击以下链接了解详情: - -[单元测试](https://gitee.com/openharmony/napi_generator/blob/master/test/unittest/README_ZH.md) - -[story测试](https://gitee.com/openharmony/napi_generator/blob/master/test/storytest/README_ZH.md) - diff --git a/napi_IntelliJ_plugin/docs/napi/ENSEMBLE_ZH.md b/napi_IntelliJ_plugin/docs/napi/ENSEMBLE_ZH.md deleted file mode 100644 index e2e7a5bf9ddc4bfc20770e0a911016babc1cc98c..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/docs/napi/ENSEMBLE_ZH.md +++ /dev/null @@ -1,280 +0,0 @@ -# 集成应用Native工程说明 - -## 简介 - 本文主要介绍使用Intellij插件将ts接口文件名格式如下ohos.A.B.C.d.ts文件转换后如何集成到应用Native工程中并编译打包,再对接口进行测试。 - -## 准备 - -### 接口测试相关的应用 - -在DevEco Studio中增加调用napi方法的测试用例。其中修改index.js文件内容如下: - -[Index.ets](https://gitee.com/openharmony/napi_generator/blob/master/examples/pluginCase/Index.ets) - -1.定义回调: - -1.1 定义object回调 - -``` -class NodeISayHelloListenerImpl { - onSayHelloStart(info: object) { - console.log('napiTestDemo ----onSayHelloStart', info); - AppStorage.SetOrCreate("textInfoStart", JSON.stringify(info)) - } - onSayHelloEnd(info: object) { - console.log('napiTestDemo ----onSayHelloEnd.', info); - AppStorage.SetOrCreate("textInfoEnd", JSON.stringify(info)) - } -} -let listener: NodeISayHelloListenerImpl = new NodeISayHelloListenerImpl() -``` - -1.2 定义register注册的回调 - -``` -function onCallbackfunnm(wid: number) { - AppStorage.SetOrCreate("callBackNum", JSON.stringify(wid)) - console.info("wid = " + wid) - return "ocCallbackfuncnm"; -} -``` - -2.注册回调: - -2.1 addXXX注册object回调 - -``` -ns.addSayHelloListener(listener); -``` - -2.2 registerXXX注册回调 - -``` -ns.registerCallbackfunc(onCallbackfunnm); -``` - -3.调用回调: - -3.1 调用sayHello普通函数,该函数业务实现会调用注册的object回调 - -``` -ns.sayHello("js1", "native1", napitest.SayType.kInitiative); -``` - -调用成功后,DevEco中HiLog打印传入的参数 - -``` -A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHello from=js1 -A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHello to=native1 -A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHello sayType=0 -``` - -js层打印回调数据 - -``` -A03d00/JSAPP: napiTestDemo ----onSayHelloStart {"from":"js1","fromId":992,"to":"native1","toId":1014,"content":"hello1","saidTime":"123456789","isEnd":false} -... -A03d00/JSAPP: napiTestDemo ----onSayHelloEnd. {"from":"native","fromId":101,"to":"js","toId":99,"content":"hello","saidTime":"987654321","isEnd":true} -``` - -3.2 调用sayHi普通函数,该函数业务实现会调用register注册的object回调 - -``` -ns.sayHi("js3", "native3", napitest.SayType.kResponse); -``` - -调用成功后,DevEco中HiLog打印传入的参数 - -``` -A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHi from=js3 -A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHi to=native3 -A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHi sayType=1 -``` - -js层打印回到数据 - -``` -I A03d00/JSAPP: napiTestDemo ----onCallbackfunnm wid = 50 -``` - -4.注销回调: - -4.1 removeXXX注销object回调 - -``` -ns.removeSayHelloListener(listener); -``` - -注销回调后再次调用sayHello方法,js层将无法再打印出回调数据 - -``` -ns.sayHello("js2", "native2", napitest.SayType.kInitiative); -``` - -4.2 unRegisterXXX注销回调 - -``` -ns.unRegisterCallbackfunc(onCallbackfunnm); -``` - -注销回调后再次调用sayHi方法,js层将无法再打印出回调数据 - -``` -ns.sayHi("js4", "native4", napitest.SayType.kResponse); -``` - -5.调用Promise回调 - -``` - await ns.sayHelloWithResponse("response from", "response to", napitest.SayType.kResponse).then((ret: object) => { - this.promiseRes = JSON.stringify(ret); - console.info("napiTestDemo ----sayHelloWithResponse ret = " + JSON.stringify(ret)); - }); -``` - -调用成功后,DevEco中HiLog打印传入的参数 - -``` -A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHelloWithResponse from=response from -A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHelloWithResponse to=response to -A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHelloWithResponse sayType=1 -``` - -js层打印promise回调数据 - -``` -I A03d00/JSAPP: napiTestDemo ----sayHelloWithResponse ret = {"result":0,"errMsg":"","response":""} -``` - -6.调用普通方法funcTest - -``` -this.returnVal = napitest.funcTest(false); -console.info("napiTestDemo ----funcTest returnVal = " + this.returnVal) -``` - -调用成功后,在js层打印返回值 - -``` -I A03d00/JSAPP: napiTestDemo ----funcTest returnVal = "ret is false" -``` - -7.工具生成代码集成到应用Native工程之后,该应用Native工程中已有模块的接口不影响使用,如:entry模块的方法add - -``` -this.addResult = testEntry.add(2, 3).toString(); -console.info("napiTestDemo ----add addResult = " + this.addResult) -``` - -调用成功后,在js层打印返回值 - -``` -I A03d00/JSAPP: napiTestDemo ----add addResult = 5 -``` - -8.Text打印数据说明 - - -``` -// 调用工具模块napitest中的sayHelloWithResponse后保存promise回调数据 -Text('promise回调: promiseResult = ' + this.promiseRes).margin({ top: 10 }) -// 调用工具模块napitest中的sayHello方法后保留addXXX注册的回调方法数据 -Text('sayHelloStart回调: info = ' + this.textInfoStart).margin({ top: 10 }) -Text('sayHelloEnd回调: info = ' + this.textInfoEnd).margin({ top: 10 }) -// 调用工具模块napitest中的sayHi方法后保留registerXXX注册的回调方法数据 -Text('register注册的回调: wid = ' + this.callBackNum).margin({ top: 10 }) -// 调用工具模块napitest中的fucnTest方法后保存返回值 -Text('普通方法funcTest返回值: returnVal = ' + this.returnVal).margin({ top: 10 }) -// 调用其它模块entry中的add方法后保存返回值 -Text('libentry模块: 2 + 3 = ' + this.addResult).margin({ top: 10 }) -``` - -## 集成说明 - -1. 在File->Project Structure->Project->Signing Configs自动签名,点击OK即可。 - - ![](../../../figures/DevEco_build_SignConfigs.png) - -2. 连接设备,并点击右上角三角符号编译打包。 - - 1.0.3版本的build-profile.json5文件去掉了"externalNativeOptions"中的abiFilters"字段,该字段含义是指定编译的版本;默认打包可能会编译x86,arm64,arm32三个版本的.so文件,都在hap包里会比较大,指定这个就只打arm64和arm32,若用户想过滤版本,可自行增加该字段 - - ``` - "abiFilters": ["armeabi-v7a", "arm64-v8a"] - ``` - - ![](../../../figures/DevEco_build.png) - -3. 执行成功后,设备中会出现安装的APP并进入APP测试页面 - - 3.1 注册object回调后SayHello调用回调 - - 点击"注册object回调后SayHello调用回调"按钮,APP页面中sayHelloStart回调info和sayHelloEnd回调info会显示出C++传到js层的回调数据;DevEco Studio控制台中Log->HiLog中会出现以下结果: - - ``` - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHello from=js1 - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHello to=native1 - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHello sayType=0 - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI NodeISayHelloListener_onSayHelloStartCallback begin - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI NodeISayHelloListener_onSayHelloStartCallback end - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI NodeISayHelloListener_onSayHelloEndCallback begin -A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI NodeISayHelloListener_onSayHelloEndCallback end - ``` - - 3.2 注销object回调后SayHello调用回调 - - 点击“注销object回调后SayHello调用回调”按钮,sayHelloStart回调info和sayHelloEnd回调info会显示出数据为空,即该回调已注销,C++无法调用回调,显示的为应用赋的空值;DevEco Studio控制台中Log->HiLog中会出现以下结果: - - ``` - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHello from=js2 - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHello to=native2 - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHello sayType=0 - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI NodeISayHelloListener_onSayHelloStartCallback begin -A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI NodeISayHelloListener_onSayHelloStartCallback end - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI NodeISayHelloListener_onSayHelloEndCallback begin -A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI NodeISayHelloListener_onSayHelloEndCallback end - ``` - - 3.3 Promise 回调 - - 点击“Promise 回调”按钮,Promise回调的errMsg, result, response会出现C++传到js层的回调数据;DevEco Studio控制台中Log->HiLog中会出现以下结果: - - ``` -A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHelloWithResponse from=response from - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHelloWithResponse to=response to - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHelloWithResponse sayType=1 - ``` - - 3.4 register回调后SayHi调用回调 - - 点击“register回调后SayHi调用回调”按钮,register注册的回调会显示出wid = 50, wid值为C++传到js的回调数据;DevEco Studio控制台中Log->HiLog中会出现以下结果: - - ``` - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHi from=js3 - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHi to=native3 - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHi sayType=1 - ``` - - 3.5 unRegister回调后SayHi调用回调 - - 点击“unRegister回调后SayHi调用回调”按钮,register注册的回调会显示出wid 为空,即该回调已注销,C++无法调用回调,显示的为应用赋的空值;DevEco Studio控制台中Log->HiLog中会出现以下结果: - - ``` - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHi from=js4 - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHi to=native4 - A03200/MY_TAG com.example.napitestdemo I NAPITEST_LOGI sayHi sayType=1 - ``` - - 3.6 调用funcTest方法 - - 点击”调用funcTest方法“按钮,普通方法funcTest返回值显示出 returnVal = ret is false。 - - 3.7 调用entry模块的方法 - - 点击“调用entry模块的方法”按钮,libentry模块:2 + 3 = 5。 - - ![](../../../figures/DevEco_run_result.png) - -## 相关仓 - -暂无 diff --git a/napi_IntelliJ_plugin/docs/napi/INSTRUCTION_ZH.md b/napi_IntelliJ_plugin/docs/napi/INSTRUCTION_ZH.md deleted file mode 100755 index c88d2d38b95a5193aa58aec549a40a9395aaafa6..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/docs/napi/INSTRUCTION_ZH.md +++ /dev/null @@ -1,75 +0,0 @@ -# NAPI框架生成工具IntelliJ插件使用说明 - -## 简介 - -NAPI框架生成工具目前支持三种入口,分别是可执行程序、DevEco Studio上使用的IntelliJ插件、VS Code插件,本文主要介绍DevEco Studio上使用的IntelliJ插件使用说明。DevEco Studio上使用的IntelliJ插件下载路径如下,选择新版本下载。 - -[DevEco Studio上使用的IntelliJ插件下载链接](https://plugins.jetbrains.com/plugin/19593-napi-generator/versions) - -![](../../../figures/picGoogle-napi_jar_download.png) - -## DevEco Studio上使用的IntelliJ插件使用方法 - -### 依赖 - -系统:建议Windows 10 - -开发工具:DevEco Studio - -### 使用指导 - -1.新建或打开项目工程,以下以新建项目工程为例。 - -File->New->Create Project。 - -![](../../../figures/DevEco_step_newFile.png) - -Ability Template选择Native C++,单击Next。 - -![](../../../figures/DevEco_step_firstNext.png) - -填写Project name、Save location,其它选项可不修改,单击Finish,新的工程就创建好了。 - -![](../../../figures/DevEco_step_finish.png) - -2.安装插件,File->Settings->Plugins->Installed->Install Plugin from Disk...,选择下载的napi_generator包,安装成功之后重启IDE。 - -![](../../../figures/DevEco_step_pluginsOk.png) - -v1.0.3之前版本,安装jar包 - -![](../../../figures/DevEco_step_applyPlugins.png) - -v1.0.3及之后版本,安装zip包 - -![](../../../figures/DevEco_step_applyPlugins_zip.png) - - - -3.使用工具的准备工作:使用工具之前,需要做以下准备工作,链接如下: - -[PREPERATION_ZH](https://gitee.com/openharmony/napi_generator/blob/master/napi_IntelliJ_plugin/docs/napi/PREPERATION_ZH.md) - -新建项目的src目录,把待转换的.d.ts文件放在DevEco Studio新建项目的src目录下;新建生成框架路径generatorCode;将业务代码放在./src/main/cpp目录下。若.d.ts文件中声明了basic.d.ts文件,将basic.d.ts文件放置在待转换.d.ts文件同一级目录;若除此之外还声明其它.d.ts文件,将此类文件放置在待转换.d.ts文件同级目录。 - -![](../../../figures/DevEco_step_napi.png) - -4.配置工具参数:选择.d.ts文件,点击右键选择 "Generate Napi Frame",工具弹出"Generate Napi Frame"弹窗。接口文件文本框填写.d.ts文件路径;"生成框架路径"填写生成框架存放路径;"编译脚本路径"填写生成CMakeList.txt文件输出路径;"number目的类型"此处选择uint32_t;因待转换.d.ts文件未引用其它文件,"启用import功能"不选择;"配置业务代码"按钮用于配置接口的业务代码,框架根据配置自动粘合工具代码与业务代码;若用户想手动配置业务代码,则不点击配置按钮配置。点击ok。 - -![](../../../figures/DevEco_step_napiGenerate.png) - -![](../../../figures/DevEco_step_napi_ok.png) - -![](../../../figures/DevEco_step_config_info.png) - -![](../../../figures/DevEco_step_show_configInfo.png) - -5.执行结束后会在对应生成框架路径目录下生成napi框架代码文件,会修改编译脚本路径下的CMakeLists.txt,且在此路径下会生成业务代码配置的cfg.json文件,其中cfg.json文件内容如下所示: - -[cfg.json](https://gitee.com/openharmony/napi_generator/blob/master/examples/pluginCase/cfg.json) - -## 集成应用Native工程说明 -NAPI框架代码生成后,系统框架开发者进行二次开发后,可在DevEco Studio将生成代码集成到应用Native工程中,并进行编译打包生成对应的库文件,供应用开发者调用接口。集成应用Native工程说明的具体操作步骤可以左键单击以下链接了解: - -[集成应用Native工程说明](https://gitee.com/openharmony/napi_generator/blob/master/napi_IntelliJ_plugin/docs/napi/ENSEMBLE_ZH.md) - diff --git a/napi_IntelliJ_plugin/docs/napi/PREPERATION_ZH.md b/napi_IntelliJ_plugin/docs/napi/PREPERATION_ZH.md deleted file mode 100644 index a9e7b786c9e120fb962d289722879c640c5a0f4d..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/docs/napi/PREPERATION_ZH.md +++ /dev/null @@ -1,25 +0,0 @@ -# 使用工具之前的准备 - -## 简介 - -本文主要介绍用户使用Napi生成工具之前需要做的准备工作。 - -## 准备 - -### 待转换的ts文件 - -待转换的@ohos.napitest.d.ts文件如下: - -[@ohos.napitest.d.ts](https://gitee.com/openharmony/napi_generator/blob/master/examples/ts/@ohos.napitest.d.ts) - -### 业务代码 - -业务代码用例如下: - -serviceCode/NodeISayHello.h - -[NodeISayHello.h](https://gitee.com/openharmony/napi_generator/blob/master/examples/pluginCase/serviceCode/NodeISayHello.h) - -serviceCode/NodeISayHello.cpp - -[NodeISayHello.cpp](https://gitee.com/openharmony/napi_generator/blob/master/examples/pluginCase/serviceCode/NodeISayHello.cpp) \ No newline at end of file diff --git a/napi_IntelliJ_plugin/resources/META-INF/plugin.xml b/napi_IntelliJ_plugin/resources/META-INF/plugin.xml deleted file mode 100644 index 5b6db82dce031de1a11d1128858eedf32aa2d7ce..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/resources/META-INF/plugin.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - com.sk.ng - Napi Generator - 1.0.1 - 深圳开鸿数字产业发展有限公司 - - Introduction -

    One-click generation of NAPI framework code, business code framework, GN file, etc. according to the ts (typescript) interface file in the user-specified path.

-

    When developing the interface between JS applications and NAPI, the developers of the underlying framework do not need to pay attention to the upper-level application conversion logic such as Nodejs syntax, data type conversion between C++ and JS, and only focus on the underlying business logic. Professional people do professional things. Thus, the development efficiency can be greatly improved

-

Sources on Gitee

- ]]> -
- - Features - ]]> - - - - - com.intellij.modules.platform - - - - - - - - - - - - - - - - - - - - - - - - - -
\ No newline at end of file diff --git a/napi_IntelliJ_plugin/resources/cmds/linux/INTELLIJ_README_LINUX_zh.md b/napi_IntelliJ_plugin/resources/cmds/linux/INTELLIJ_README_LINUX_zh.md deleted file mode 100644 index d0893365de6d626394ae4428b4f42c5f224c3530..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/resources/cmds/linux/INTELLIJ_README_LINUX_zh.md +++ /dev/null @@ -1,4 +0,0 @@ -# 目录说明 - 此目录用于存放napi_generator-linux可执行文件 - -[可执行文件下载](http://ftpkaihongdigi.i234.me:5000/fsdownload/PPVcNMgVv/2022-06-13) \ No newline at end of file diff --git a/napi_IntelliJ_plugin/resources/cmds/mac/INTELLIJ_README_MAC_zh.md b/napi_IntelliJ_plugin/resources/cmds/mac/INTELLIJ_README_MAC_zh.md deleted file mode 100644 index 2b79c41e144f94743618a7ba57c625ac67e24a78..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/resources/cmds/mac/INTELLIJ_README_MAC_zh.md +++ /dev/null @@ -1,4 +0,0 @@ -# 目录说明 - 此目录用于存放napi_generator-macos可执行文件 - -[可执行文件下载](http://ftpkaihongdigi.i234.me:5000/fsdownload/PPVcNMgVv/2022-06-13) \ No newline at end of file diff --git a/napi_IntelliJ_plugin/resources/cmds/win/INTELLIJ_README_WIN_zh.md b/napi_IntelliJ_plugin/resources/cmds/win/INTELLIJ_README_WIN_zh.md deleted file mode 100644 index 95286c4fe3e5f61535020d5365a6af63851ed558..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/resources/cmds/win/INTELLIJ_README_WIN_zh.md +++ /dev/null @@ -1,4 +0,0 @@ -# 目录说明 - 此目录用于存放napi_generator-win.exe可执行文件 - -[可执行文件下载](http://ftpkaihongdigi.i234.me:5000/fsdownload/PPVcNMgVv/2022-06-13) \ No newline at end of file diff --git a/napi_IntelliJ_plugin/resources/images/openDisk.png b/napi_IntelliJ_plugin/resources/images/openDisk.png deleted file mode 100644 index 5956a0e538a400c7deaf41167ae5ea70348b8584..0000000000000000000000000000000000000000 Binary files a/napi_IntelliJ_plugin/resources/images/openDisk.png and /dev/null differ diff --git a/napi_IntelliJ_plugin/resources/images/text.png b/napi_IntelliJ_plugin/resources/images/text.png deleted file mode 100644 index f42534169aa41dd830a7cb09792fe1428c2f34f7..0000000000000000000000000000000000000000 Binary files a/napi_IntelliJ_plugin/resources/images/text.png and /dev/null differ diff --git a/napi_IntelliJ_plugin/src/com/sk/action/BrowseAction.java b/napi_IntelliJ_plugin/src/com/sk/action/BrowseAction.java deleted file mode 100644 index d32bb01a2fe66bb9ea249c5d944cfe28f34656fa..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/action/BrowseAction.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ -package com.sk.action; - -import com.intellij.notification.NotificationType; -import com.intellij.openapi.project.Project; -import com.sk.utils.FileUtil; -import com.sk.utils.GenNotification; -import org.apache.http.util.TextUtils; - -import javax.swing.JButton; -import javax.swing.JTextField; -import javax.swing.JFileChooser; -import javax.swing.filechooser.FileNameExtensionFilter; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.util.prefs.Preferences; - -/** - * 接口文件选择框。 - * - * @author: xudong - * @see: select file - * @version: v1.0.0 - * @since 2022-02-21 - */ -public class BrowseAction implements ActionListener { - private final JButton button; - private final JTextField interField; - private final JTextField genField; - private final JTextField scriptField; - private final Project project; - - - public BrowseAction(Project project, JButton button, JTextField interField, - JTextField geField, JTextField scriptField) { - this.project = project; - this.button = button; - this.interField = interField; - this.genField = geField; - this.scriptField = scriptField; - } - - @Override - public void actionPerformed(ActionEvent actionEvent) { - if (actionEvent.getSource().equals(button)) { - Preferences preferences = Preferences.userRoot(); - // 弹窗默认路径为上次选中的文件/目录路径 - String tsFilePath = interField.getText().split(",")[0]; - if (tsFilePath.isBlank()) { - // 如果上次选中路径为空,则取历史记录中上次打开的路径 - tsFilePath = preferences.get("interPathRecord", ""); - } - JFileChooser fcDlg = new JFileChooser(tsFilePath); - fcDlg.setDialogTitle("请选择接口文件..."); - fcDlg.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); - FileNameExtensionFilter filter = new FileNameExtensionFilter("文本文件(*.ts)", "ts"); - fcDlg.setMultiSelectionEnabled(true); - fcDlg.setFileFilter(filter); - int returnVal = fcDlg.showOpenDialog(null); - if (returnVal == JFileChooser.APPROVE_OPTION) { - String upPath = fcDlg.getSelectedFile().getParent(); - File[] files = fcDlg.getSelectedFiles(); - String interFile = setSelectFile(files); - if (TextUtils.isBlank(interFile)) { - return; - } - - // 设置默认打开路径; - - preferences.put("interPathRecord", upPath); - interField.setText(interFile.substring(0, interFile.length() - 1)); - genField.setText(upPath); - scriptField.setText(upPath); - } - } - } - - private String setSelectFile(File[] files) { - StringBuilder interFile = new StringBuilder(); - boolean existFile = false; - boolean existDir = false; - for (File file : files) { - if (file.isDirectory()) { - if (!existDir) { - existDir = true; - interFile.append(file.getPath()).append(","); - } else { - GenNotification.notifyMessage(project, - "目前只支持单个文件夹转换", - "选择不符合要求", - NotificationType.WARNING); - interField.setText(""); - return ""; - } - } else { - if (!FileUtil.patternFileName(file.getName())) { - GenNotification.notifyMessage(project, - file.getPath(), - file.getName() + "文件名不符合", - NotificationType.WARNING); - return ""; - } - existFile = true; - interFile.append(file.getPath()).append(","); - } - } - if (existDir && existFile) { - GenNotification.notifyMessage(project, - "不能同时转换文件和文件夹", - "选择不符合要求", - NotificationType.WARNING); - interField.setText(""); - return ""; - } - return interFile.toString(); - } -} diff --git a/napi_IntelliJ_plugin/src/com/sk/action/GenAction.java b/napi_IntelliJ_plugin/src/com/sk/action/GenAction.java deleted file mode 100644 index 5865428bca835fb3105ba8c4714d30b766b64dd5..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/action/GenAction.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ -package com.sk.action; - -import javax.swing.JButton; -import javax.swing.JFileChooser; -import javax.swing.JTextField; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -/** - * 编译文件夹选择框 - * - * @author: xudong - * @see: select generator file path - * @version: v1.0.0 - * @since 2022-02-21 - */ -public class GenAction implements ActionListener { - private final JButton button; - private final JTextField textField; - - public GenAction(JButton button, JTextField textField) { - this.button = button; - this.textField = textField; - } - - @Override - public void actionPerformed(ActionEvent actionEvent) { - if (actionEvent.getSource().equals(button)) { - JFileChooser fcDlg = new JFileChooser(textField.getText()); - fcDlg.setDialogTitle("请选择生成框架路径..."); - fcDlg.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - int returnVal = fcDlg.showOpenDialog(null); - if (returnVal == JFileChooser.APPROVE_OPTION) { - String filepath = fcDlg.getSelectedFile().getPath(); - textField.setText(filepath); - } - } - } -} diff --git a/napi_IntelliJ_plugin/src/com/sk/action/ScriptAction.java b/napi_IntelliJ_plugin/src/com/sk/action/ScriptAction.java deleted file mode 100644 index f549b1528b679477b3a745228a0eecb91f9baada..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/action/ScriptAction.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ -package com.sk.action; - -import javax.swing.JButton; -import javax.swing.JFileChooser; -import javax.swing.JTextField; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -/** - * 脚本选择对话框 - * - * @author: xudong - * @see: select compile script - * @version: v1.0.0 - * @since 2022-02-21 - */ -public class ScriptAction implements ActionListener { - private final JButton button; - private final JTextField textField; - - public ScriptAction(JButton button, JTextField textField) { - this.button = button; - this.textField = textField; - } - - @Override - public void actionPerformed(ActionEvent actionEvent) { - if (actionEvent.getSource().equals(button)) { - JFileChooser fcDlg = new JFileChooser(textField.getText()); - fcDlg.setDialogTitle("请选择编译脚本路径..."); - fcDlg.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - int returnVal = fcDlg.showOpenDialog(null); - if (returnVal == JFileChooser.APPROVE_OPTION) { - String filepath = fcDlg.getSelectedFile().getPath(); - textField.setText(filepath); - } - } - } -} \ No newline at end of file diff --git a/napi_IntelliJ_plugin/src/com/sk/action/SelectCppAction.java b/napi_IntelliJ_plugin/src/com/sk/action/SelectCppAction.java deleted file mode 100644 index e1b713cd66b6880d9f853f17589ff12041e1621b..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/action/SelectCppAction.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ -package com.sk.action; - -import javax.swing.JButton; -import javax.swing.JFileChooser; -import javax.swing.JTextField; -import javax.swing.filechooser.FileNameExtensionFilter; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.prefs.Preferences; -import com.sk.utils.FileUtil; - -/** - * 脚本选择对话框 - * - * @author: goujingjing - * @see: select cpp filepath - * @version: v1.0.3 - * @since 2023-12-20 - */ -public class SelectCppAction implements ActionListener { - private final JButton button; - private final JTextField textField; - private String genPath; - - /** - * 构造函数 - * @param button .cpp文件选择按钮 - * @param textField .cpp文件文本选择框 - * @param genPath 生成框架路径 - * @throws log 输出异常 - */ - public SelectCppAction(JButton button, JTextField textField, String genPath) { - this.button = button; - this.textField = textField; - this.genPath = genPath; - } - - /** - * 按钮监听函数 - * @param actionEvent .cpp文件选择事件 - * @throws log 输出异常 - */ - @Override - public void actionPerformed(ActionEvent actionEvent) { - if (actionEvent.getSource().equals(button)) { - Preferences preferences = Preferences.userRoot(); - // 弹窗默认路径为上次选中的文件/目录路径 - String cppFilePath = textField.getText(); - if (cppFilePath.isBlank()) { - // 如果上次选中路径为空,则取历史记录中上次打开的路径 - cppFilePath = preferences.get("cppPathRecord", ""); - } - JFileChooser fcDlg = new JFileChooser(cppFilePath); - fcDlg.setDialogTitle("请选择cppName路径..."); - fcDlg.setFileSelectionMode(JFileChooser.FILES_ONLY); - FileNameExtensionFilter filter = new FileNameExtensionFilter("cpp文件(*.cpp, *.cc, *.C, *.cxx, *.c++)", - "cpp", "cc", "C", "cxx", "c++"); - fcDlg.setMultiSelectionEnabled(false); - fcDlg.setFileFilter(filter); - int returnVal = fcDlg.showOpenDialog(null); - if (returnVal == JFileChooser.APPROVE_OPTION) { - String filepath = fcDlg.getSelectedFile().getPath(); - preferences.put("cppPathRecord", filepath); - FileUtil fileUtil = new FileUtil(); - String relativeCppName = fileUtil.getRelativePath(filepath, genPath); - relativeCppName = relativeCppName.substring(0, relativeCppName.length() - 1); - textField.setText(relativeCppName); - } - } - } -} \ No newline at end of file diff --git a/napi_IntelliJ_plugin/src/com/sk/action/SelectHAction.java b/napi_IntelliJ_plugin/src/com/sk/action/SelectHAction.java deleted file mode 100644 index 3e8063b9a89b902e21a221450f68dcf4669b976f..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/action/SelectHAction.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ -package com.sk.action; - -import com.sk.utils.FileUtil; -import javax.swing.JButton; -import javax.swing.JFileChooser; -import javax.swing.JTextField; -import javax.swing.filechooser.FileNameExtensionFilter; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.prefs.Preferences; - -/** - * 脚本选择对话框 - * - * @author: goujingjing - * @see: select h filepath - * @version: v1.0.3 - * @since 2023-12-20 - */ -public class SelectHAction implements ActionListener { - private final JButton button; - private final JTextField textField; - private String genPath; - - /** - * 构造函数 - * @param button .h文件选择按钮 - * @param textField .h文件文本选择框 - * @param genPath 生成框架路径 - * @throws log 输出异常 - */ - public SelectHAction(JButton button, JTextField textField, String genPath) { - this.button = button; - this.textField = textField; - this.genPath = genPath; - } - - /** - * 按钮监听函数 - * @param actionEvent .h文件选择事件 - * @throws log 输出异常 - */ - @Override - public void actionPerformed(ActionEvent actionEvent) { - if (actionEvent.getSource().equals(button)) { - Preferences preferences = Preferences.userRoot(); - // 弹窗默认路径为上次选中的文件/目录路径 - String hFilePath = textField.getText(); - if (hFilePath.isBlank()) { - // 如果上次选中路径为空,则取历史记录中上次打开的路径 - hFilePath = preferences.get("hPathRecord", ""); - } - JFileChooser fcDlg = new JFileChooser(hFilePath); - fcDlg.setDialogTitle("请选择includeName路径..."); - fcDlg.setFileSelectionMode(JFileChooser.FILES_ONLY); - FileNameExtensionFilter filter = new FileNameExtensionFilter("h文件(*.h, *.hpp, *.hxx)", "h", "hpp", "hxx"); - fcDlg.setMultiSelectionEnabled(false); - fcDlg.setFileFilter(filter); - int returnVal = fcDlg.showOpenDialog(null); - if (returnVal == JFileChooser.APPROVE_OPTION) { - String filepath = fcDlg.getSelectedFile().getPath(); - preferences.put("hPathRecord", filepath); - FileUtil fileUtil = new FileUtil(); - String relativeIncludeName = fileUtil.getRelativePath(filepath, genPath); - relativeIncludeName = relativeIncludeName.substring(0, relativeIncludeName.length() - 1); - textField.setText(relativeIncludeName); - } - } - } -} \ No newline at end of file diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/ConfigDialog.java b/napi_IntelliJ_plugin/src/com/sk/dialog/ConfigDialog.java deleted file mode 100644 index 20a5f951c1f18d24732cec2d5397d9c8507cbd15..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/ConfigDialog.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2023 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. - */ -package com.sk.dialog; - -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.ui.DialogWrapper; -import com.intellij.openapi.ui.ValidationInfo; -import com.sk.utils.Data; -import com.sk.utils.DataList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import javax.swing.Action; -import javax.swing.JComponent; -import java.awt.Desktop; -import java.awt.event.ActionEvent; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -/** - * 配置config文件对话框Wrapper - * - * @author: goujingjing - * @see: tool conversion plug-in - * @version: v1.0.3 - * @since 2023-12-14 - */ -public class ConfigDialog extends DialogWrapper { - private static final Logger LOG = Logger.getInstance(GenerateDialog.class); - private static final String FRAME_TITLE = "Config"; - private static final String CODE_URL = - "https://gitee.com/openharmony/napi_generator/blob/master/docs/INSTRUCTION_ZH.md"; - - private DataList list = null; - private final ConfigDialogPane genDiag; - private boolean isAddFlag; - private String genPath; - - /** - * 构造函数 - * @param list 配置文件数据列表 - * @param index 用户选择的列表行索引 - * @param data 用户选择的列表行数据 - * @param isAddFlag 增加数据或者修改数据的标志位 - * @param genPath 生成框架路径 - * @throws log 输出异常 - */ - public ConfigDialog(DataList list, int index, Data data, boolean isAddFlag, String genPath) { - super(true); - this.setResizable(false); - this.list = list; - this.isAddFlag = isAddFlag; - this.genPath = genPath; - setTitle(FRAME_TITLE); - setModal(true); - genDiag = new ConfigDialogPane(list, index, data, genPath); - init(); - } - - /** - * 创建视图 - * @param void 空 - * @return 组件内容 - * @throws log 输出异常 - */ - @Nullable - @Override - protected JComponent createCenterPanel() { - return genDiag.getContentPanel(); - } - - - /** - * 校验数据 - * @param void 空 - * @return 错误信息 检测用户是否填入配置信息。 - * @throws log 输出异常 - */ - @Nullable - @Override - protected ValidationInfo doValidate() { - return genDiag.validationInfo(); - } - - /** - * ok/cancel按钮 - * @param void 空 - * @return Action[] buttons list - * @throws log 输出异常 - */ - @NotNull - @Override - protected Action[] createActions() { - DialogWrapperExitAction exitAction = new DialogWrapperExitAction("Cancel", CANCEL_EXIT_CODE); - CustomOkAction okAction = new CustomOkAction(); - - // 设置默认的焦点按钮 - okAction.putValue(DialogWrapper.DEFAULT_ACTION, true); - return new Action[]{exitAction, okAction}; - } - - /** - * help 按钮 - * @param void 空 - * @return Action[] button helpAction - * @throws log 输出异常 - */ - @NotNull - @Override - protected Action[] createLeftSideActions() { - CustomHelpAction helpAction = new CustomHelpAction(); - return new Action[]{helpAction}; - } - - /** - * 自定义 ok Action - */ - protected class CustomOkAction extends DialogWrapperAction { - - protected CustomOkAction() { - super("OK"); - } - - @Override - protected void doAction(ActionEvent actionEvent) { - ValidationInfo validationInfo = doValidate(); - if (validationInfo != null) { - LOG.info(validationInfo.message); - } else { - if (isAddFlag) { - // 增加数据 - genDiag.setDataInfo(); - close(CANCEL_EXIT_CODE); - ShowCfgInfoDialog showCfgInfoDialog = new ShowCfgInfoDialog(list, genPath); - showCfgInfoDialog.showAndGet(); - } else { - // 修改数据 - genDiag.modifyDataInfo(); - close(CANCEL_EXIT_CODE); - ShowCfgInfoDialog showCfgInfoDialog = new ShowCfgInfoDialog(list, genPath); - showCfgInfoDialog.showAndGet(); - } - - } - } - } - - /** - * 自定义 help Action - */ - protected class CustomHelpAction extends DialogWrapperAction { - - protected CustomHelpAction() { - super("Help"); - } - - @Override - protected void doAction(ActionEvent actionEvent) { - try { - Desktop.getDesktop().browse(new URI(CODE_URL)); - } catch (URISyntaxException | IOException e) { - LOG.error("Open help error:" + e); - } - } - } -} diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/ConfigDialogPane.form b/napi_IntelliJ_plugin/src/com/sk/dialog/ConfigDialogPane.form deleted file mode 100644 index cf4d23bda44a981d59eaf67723d7e41b2f21237a..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/ConfigDialogPane.form +++ /dev/null @@ -1,250 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/ConfigDialogPane.java b/napi_IntelliJ_plugin/src/com/sk/dialog/ConfigDialogPane.java deleted file mode 100644 index bdad19d410f85ad1d418b2206df796767e12edbd..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/ConfigDialogPane.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (c) 2023 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. - */ -package com.sk.dialog; - -import com.intellij.notification.NotificationType; -import com.intellij.openapi.ui.ValidationInfo; -import com.sk.action.SelectCppAction; -import com.sk.action.SelectHAction; -import com.sk.utils.Data; -import com.sk.utils.DataList; -import com.sk.utils.GenNotification; -import org.apache.http.util.TextUtils; -import org.jetbrains.annotations.Nullable; - -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.JComponent; -import javax.swing.KeyStroke; -import javax.swing.JButton; -import java.awt.event.KeyEvent; -import java.util.ArrayList; - -/** - * ConfigDialog 配置文件对话框 - * - * @author: goujingjing - * @see: generator config dialog - * @version: v1.0.3 - * @since 2023-12-14 - */ -public class ConfigDialogPane extends JDialog { - private JPanel contentPane; - private JTextField textFieldIncludeName; - private JTextField textFieldCppName; - private JTextField textFieldInterName; - private JTextField textFieldServiceCode; - private JButton buttonIncludeName; - private JButton buttonCppName; - private JTextField textFieldRootPath; - private DataList list = new DataList(new ArrayList<>()); - private int index; - private String genPath; - - /** - * 构造函数 - * @param list 配置文件数据列表 - * @param index 用户选择的列表行索引 - * @param data 用户选择的列表行数据 - * @param genPath 生成框架路径 - * @throws log 输出异常 - */ - public ConfigDialogPane(DataList list, int index, Data data, String genPath) { - this.list = list; - this.index = index; - this.genPath = genPath; - textFieldRootPath.setText(genPath); - textFieldRootPath.setEditable(false); - if (data != null) { - textFieldIncludeName.setText(data.getIncludeName()); - textFieldCppName.setText(data.getCppName()); - textFieldInterName.setText(data.getCppName()); - textFieldServiceCode.setText(data.getServiceCode()); - } else { - textFieldIncludeName.setText(""); - textFieldCppName.setText(""); - textFieldInterName.setText(""); - textFieldServiceCode.setText(""); - } - buttonIncludeName.addActionListener(new SelectHAction(buttonIncludeName, textFieldIncludeName, - genPath)); - buttonCppName.addActionListener(new SelectCppAction(buttonCppName, textFieldCppName, - genPath)); - - setContentPane(contentPane); - setModal(true); - contentPane.registerKeyboardAction(actionEvent -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), - JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); - } - - /** - * 修改dataList数据,将用户输入的文本选择框数据存入dataList列表 - * - */ - public void modifyDataInfo() { - String includeNameText = textFieldIncludeName.getText(); - String cppNameText = textFieldCppName.getText(); - String interNameText = textFieldInterName.getText(); - String serviceCodeText = textFieldServiceCode.getText(); - Data data = new Data(genPath, includeNameText, cppNameText, interNameText, serviceCodeText); - list.modifyDataListInfo(index, data); - } - - /** - * 将用户输入的文本选择框数据存入dataList列表 - * @param void 空 - * @throws log 输出异常 - */ - public void setDataInfo() { - String includeNameText = textFieldIncludeName.getText(); - String cppNameText = textFieldCppName.getText(); - String interNameText = textFieldInterName.getText(); - String serviceCodeText = textFieldServiceCode.getText(); - Data data = new Data(genPath, includeNameText, cppNameText, interNameText, serviceCodeText); - list.addDataListInfo(data); - } - - /** - * 验证文本选择框是否空。是否替换已存在的内容 - * @param void 空 - * @return ValidationInfo 返回不符要求的信息。 - * @throws log 输出异常 - */ - @Nullable - public ValidationInfo validationInfo() { - ValidationInfo validationInfo = null; - String includeNameText = textFieldIncludeName.getText(); - String cppNameText = textFieldCppName.getText(); - String interNameText = textFieldInterName.getText(); - String serviceCodeText = textFieldServiceCode.getText(); - boolean isEmptyFile = - TextUtils.isEmpty(includeNameText) || TextUtils.isEmpty(cppNameText) || TextUtils.isEmpty(interNameText) - || TextUtils.isEmpty(serviceCodeText); - if (isEmptyFile) { - String warnMsg = "业务代码配置不能为空"; - warningMessage(warnMsg); - validationInfo = new ValidationInfo(warnMsg); - return validationInfo; - } - return validationInfo; - } - - private void onCancel() { - dispose(); - } - - private void warningMessage(String title) { - String notifyContent = "请配置业务代码"; - GenNotification.notifyMessage(null, notifyContent, title, NotificationType.WARNING); - } - - JPanel getContentPanel() { - return contentPane; - } -} \ No newline at end of file diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/ConfirmDiagPane.form b/napi_IntelliJ_plugin/src/com/sk/dialog/ConfirmDiagPane.form deleted file mode 100644 index 78b5332e8e279f9b033965b02b2c230015f8fef2..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/ConfirmDiagPane.form +++ /dev/null @@ -1,75 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/ConfirmDiagPane.java b/napi_IntelliJ_plugin/src/com/sk/dialog/ConfirmDiagPane.java deleted file mode 100644 index 62cc25feca56d0fd733efc19c436fdce7ca665e2..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/ConfirmDiagPane.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ -package com.sk.dialog; - -import javax.swing.JPanel; -import javax.swing.JLabel; -import javax.swing.JDialog; -import javax.swing.ImageIcon; - -/** - * ConfirmDiagPane自定义确认对话框 - * 解决ShowConfirmDiag 在Deveco里面会出现界面错位问题。 - * - * @author: xudong - * @see: generator error dialog - * @version: v1.0.0 - * @since 2022-02-21 - */ -public class ConfirmDiagPane extends JDialog { - private JPanel contentPane; - private JLabel msgLabel; - private JLabel iconLabel; - - /** - * 构造函数 - * - * @param sErrorMessage 错误信息 - */ - public ConfirmDiagPane(String sErrorMessage) { - msgLabel.setText(sErrorMessage); - iconLabel.setIcon(new ImageIcon("")); - } - - - JPanel getContentPanel() { - return contentPane; - } -} diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/ConfirmDialog.java b/napi_IntelliJ_plugin/src/com/sk/dialog/ConfirmDialog.java deleted file mode 100644 index d2baf22ffcc23f77f05fa20f8db296dab76fc311..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/ConfirmDialog.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2022 Guangzhou Digitalchina Information Technology Co., Ltd. - * All rights reserved. - * 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. - */ -package com.sk.dialog; - -import com.intellij.openapi.ui.DialogWrapper; -import org.jetbrains.annotations.Nullable; -import javax.swing.JComponent; - -/** - * 自定义确认对话框Wrapper - * - * @author: xudong - * @see: tool conversion plug-in - * @version: v1.0.0 - * @since 2022-02-21 - */ -public class ConfirmDialog extends DialogWrapper { - private final ConfirmDiagPane confirmDiagPane; - - /** - * 构造函数 - * @param message 弹出框信息内容 - * @throws log 输出异常 - */ - public ConfirmDialog(String message) { - super(true); - confirmDiagPane = new ConfirmDiagPane(message); - setOKButtonText("Yes"); - setCancelButtonText("No"); - setUndecorated(true); - setResizable(false); - init(); - } - - /** - * 创建视图 - * @param void 空 - * @return 组件内容 - * @throws log 输出异常 - */ - @Override - @Nullable - protected JComponent createCenterPanel() { - return confirmDiagPane.getContentPanel(); - } - -} diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/ErrorDialog.form b/napi_IntelliJ_plugin/src/com/sk/dialog/ErrorDialog.form deleted file mode 100644 index dd73a6f048ed8f10200d41c6efe828d53a934b0f..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/ErrorDialog.form +++ /dev/null @@ -1,86 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/ErrorDialog.java b/napi_IntelliJ_plugin/src/com/sk/dialog/ErrorDialog.java deleted file mode 100644 index 263cc10fd50cde3a547fd85b773c00e93a5fc2d5..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/ErrorDialog.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ -package com.sk.dialog; - -import com.intellij.openapi.diagnostic.Logger; - -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.JTextArea; -import javax.swing.KeyStroke; -import java.awt.event.KeyEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.IOException; - -/** - * ErrorDialog错误对话框 - * - * @author: xudong - * @see: generator error dialog - * @version: v1.0.0 - * @since 2022-02-21 - */ -public class ErrorDialog extends JDialog { - private static final Logger LOG = Logger.getInstance(ErrorDialog.class); - private static final String URL = - "rundll32 url.dll,FileProtocolHandler" + " https://gitee" + ".com/openharmony" + "-sig/napi_generator"; - - private JPanel contentPane; - private JButton buttonOK; - private JButton buttonHelp; - private JTextArea textAreaError; - private String errorMessage; - - public ErrorDialog(String sErrorMessage) { - errorMessage = sErrorMessage; - } - - /** - * 初始化 - */ - public void initDialog() { - setContentPane(contentPane); - setModal(true); - getRootPane().setDefaultButton(buttonOK); - setTitle("执行失败"); - textAreaError.setText(errorMessage); - buttonOK.addActionListener(actionEvent -> onOK()); - - buttonHelp.addActionListener(actionEvent -> onCancel()); - - // call onCancel() when cross is clicked - setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); - addWindowListener(new WindowAdapter() { - /** - * close dialog - * @param windowEvent WindowEvent - */ - @Override - public void windowClosing(WindowEvent windowEvent) { - onCancel(); - } - }); - - // call onCancel() on ESCAPE - contentPane.registerKeyboardAction(actionEvent -> onCancel(), - KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), - JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); - } - - private void onOK() { - dispose(); - } - - private void onCancel() { - try { - Runtime.getRuntime().exec(URL); - } catch (IOException ioException) { - LOG.error("exec command help error" + ioException); - } - dispose(); - } -} \ No newline at end of file diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/GenResultDialog.form b/napi_IntelliJ_plugin/src/com/sk/dialog/GenResultDialog.form deleted file mode 100644 index ccafe900fabcb8956801f012a7d5484041b15d31..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/GenResultDialog.form +++ /dev/null @@ -1,78 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/GenResultDialog.java b/napi_IntelliJ_plugin/src/com/sk/dialog/GenResultDialog.java deleted file mode 100644 index bb0b1617ea67edf10d48b86a65acb41e864885be..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/GenResultDialog.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ -package com.sk.dialog; - -import com.intellij.openapi.diagnostic.Logger; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JList; -import javax.swing.JPanel; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * GenResultDialog结果生成框 - * - * @author: xudong - * @see: generate success dialog - * @version: v1.0.0 - * @since 2022-02-21 - */ -public class GenResultDialog extends JDialog { - private static final Logger LOG = Logger.getInstance(GenResultDialog.class); - - private JPanel contentPane; - private JButton buttonOK; - private JList resultList; - private String path; - - public GenResultDialog(String directoryPath) { - path = directoryPath; - } - - /** - * 初始化 - */ - public void initResultDialog() { - setContentPane(contentPane); - setModal(true); - getRootPane().setDefaultButton(buttonOK); - setTitle("执行成功"); - buttonOK.addActionListener(actionEvent -> onOK()); - List fileList = getDirFileName(path); - resultList.setListData(fileList.toArray(new String[fileList.size()])); - } - - private void onOK() { - dispose(); - } - - private List getDirFileName(String path) { - List files = new ArrayList<>(); - File file = new File(path); - if (!file.exists()) { - LOG.info("getDirFileName f not exist"); - return files; - } - File[] fileArray = file.listFiles(); - for (int i = 0; i < fileArray.length; i++) { - File fs = fileArray[i]; - if (!fs.isDirectory()) { - files.add(fs.getPath()); - } else { - LOG.info("getDirFileName this file is dir"); - } - } - return files; - } -} diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/GenerateDialog.java b/napi_IntelliJ_plugin/src/com/sk/dialog/GenerateDialog.java deleted file mode 100644 index 652d93889e8a29c105ed38e46a19562fd348c690..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/GenerateDialog.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (c) 2022 Guangzhou Digitalchina Information Technology Co., Ltd. - * All rights reserved. - * 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. - */ -package com.sk.dialog; - -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.ui.DialogWrapper; -import com.intellij.openapi.ui.ValidationInfo; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import javax.swing.Action; -import javax.swing.JComponent; -import java.awt.Desktop; -import java.awt.event.ActionEvent; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -/** - * 主界面对话框Wrapper - * - * @author: xudong - * @see: tool conversion plug-in - * @version: v1.0.0 - * @since 2022-05-27 - */ -public class GenerateDialog extends DialogWrapper { - private static final Logger LOG = Logger.getInstance(GenerateDialog.class); - private static final String FRAME_TITLE = "Generate Napi Frame"; - private static final String CODE_URL = "https://gitee.com/openharmony/napi_generator"; - - private final GenerateDialogPane genDiag; - - /** - * 构造函数 - * - * @param project projectId - * @param destPath 目录文件 - * @param directoryPath 文件夹目录 - * @param fileName 文件名 - * @throws log 输出异常 - */ - public GenerateDialog(Project project, String destPath, String directoryPath, String fileName) { - super(true); - this.setResizable(false); - setTitle(FRAME_TITLE); - setModal(true); - genDiag = new GenerateDialogPane(project, destPath, directoryPath, fileName); - init(); - } - - /** - * 创建视图 - * @param void 空 - * @return 组件内容 - * @throws log 输出异常 - */ - @Nullable - @Override - protected JComponent createCenterPanel() { - return genDiag.getContentPanel(); - } - - - /** - * 校验数据 - * @param void 空 - * @return 检测文本框架是否有目录。 - * @throws log 输出异常 - */ - @Nullable - @Override - protected ValidationInfo doValidate() { - return genDiag.validationInfo(); - } - - /** - * ok/cancel按钮 - * @param void 空 - * @return Action[] buttons list - * @throws log 输出异常 - */ - @NotNull - @Override - protected Action[] createActions() { - DialogWrapperExitAction exitAction = new DialogWrapperExitAction("Cancel", CANCEL_EXIT_CODE); - CustomOKAction okAction = new CustomOKAction(); - - // 设置默认的焦点按钮 - okAction.putValue(DialogWrapper.DEFAULT_ACTION, true); - return new Action[]{exitAction, okAction}; - } - - /** - * help 按钮 - * @param void 空 - * @return Action[] button helpAction - * @throws log 输出异常 - */ - @NotNull - @Override - protected Action[] createLeftSideActions() { - CustomHelpAction helpAction = new CustomHelpAction(); - return new Action[]{helpAction}; - } - - /** - * 自定义 ok Action - */ - protected class CustomOKAction extends DialogWrapperAction { - - protected CustomOKAction() { - super("OK"); - } - - @Override - protected void doAction(ActionEvent actionEvent) { - ValidationInfo validationInfo = doValidate(); - if (validationInfo != null) { - LOG.info(validationInfo.message); - } else { - if (genDiag.runFun()) { - close(CANCEL_EXIT_CODE); - } - } - } - } - - /** - * 自定义 help Action - */ - protected class CustomHelpAction extends DialogWrapperAction { - - protected CustomHelpAction() { - super("Help"); - } - - @Override - protected void doAction(ActionEvent actionEvent) { - try { - Desktop.getDesktop().browse(new URI(CODE_URL)); - } catch (URISyntaxException | IOException e) { - LOG.error("Open help error:" + e); - } - } - } -} diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/GenerateDialogPane.form b/napi_IntelliJ_plugin/src/com/sk/dialog/GenerateDialogPane.form deleted file mode 100644 index 0dcba2483adf0aca749b3aef9c06dd44eef9b2e4..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/GenerateDialogPane.form +++ /dev/null @@ -1,292 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/GenerateDialogPane.java b/napi_IntelliJ_plugin/src/com/sk/dialog/GenerateDialogPane.java deleted file mode 100644 index d3c781bfbe71cf77cf7593739bf3e54033c17327..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/GenerateDialogPane.java +++ /dev/null @@ -1,696 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ -package com.sk.dialog; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.intellij.notification.NotificationType; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.ui.ValidationInfo; -import com.sk.action.BrowseAction; -import com.sk.action.GenAction; -import com.sk.action.ScriptAction; -import com.sk.utils.FileInfo; -import com.sk.utils.FileUtil; -import com.sk.utils.GenNotification; -import com.sk.utils.Data; -import com.sk.utils.DataList; -import org.apache.http.util.TextUtils; -import org.jetbrains.annotations.Nullable; - - -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.JRadioButton; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.KeyStroke; -import java.awt.event.KeyEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * 配置对话框 - * - * @author: xudong - * @see: generator dialog - * @version: v1.0.0 - * @since 2022-02-21 - */ -public class GenerateDialogPane extends JDialog { - private static final Logger LOG = Logger.getInstance(GenerateDialogPane.class); - private static final String FILE_NAME_REGEX = "(\\@ohos\\.)(.*?)(\\.d\\.ts)"; - private static final Pattern FILE_NAME_PATTERN = Pattern.compile(FILE_NAME_REGEX, Pattern.CASE_INSENSITIVE); - private static final String NAMESPACE_REGEX = "declare namespace ([a-zA-Z_0-9]+) *(\\{)"; - private static final Pattern NAMESPACE_PATTERN = Pattern.compile(NAMESPACE_REGEX, Pattern.CASE_INSENSITIVE); - private static final String CMAKE_SETCXX_TEMPLATE = "cmake_minimum_required(VERSION 3.4.1)" - + FileUtil.getNewline() + "project(napi_lib)" + FileUtil.getNewline() + "set(CMAKE_CXX_STANDARD 17)" - + FileUtil.getNewline() + FileUtil.getNewline(); - private static final String CMAKE_SETCXX_HASCMAKEFILE_TEMPLATE = FileUtil.getNewline() - + "set(CMAKE_CXX_STANDARD 17)" + FileUtil.getNewline() + FileUtil.getNewline(); - private static final String CMAKE_ADD_LIB_TEMPLATE = - "add_library(LIBNAME SHARED PATH/tool_utility.cpp PATH/FILE_PREFIX.cpp PATH/FILE_PREFIX_middle.cpp" - + " SERVICECODE)"; - private static final String CMAKE_LINK_TEMPLATE = - "target_link_libraries(LIBNAME PUBLIC libace_napi.z.so libuv.so libhilog_ndk.z.so)"; - - private final Project project; - private List tsFileList = new ArrayList<>(); - private List dataList = new ArrayList<>(); - private JPanel contentPane; - - private JTextField textFieldInterPath; - private JTextField textFieldGenPath; - private JTextField textFieldScriptPath; - private JRadioButton radioButton; - private JButton buttonSelectInter; - private JButton buttonSelectGenPath; - private JButton buttonSelectScriptPath; - private JComboBox comboBox; - private JButton buttonCfg; - private String interFileOrDir; - private String genOutDir; - private String scriptOutDir; - private String numberType; - private boolean generateSuccess = true; - private String sErrorMessage = ""; - private boolean isExistCmakeFile = false; - private DataList list = new DataList(dataList); - - /** - * 构造函数 - * - * @param project projectid - * @param interFilePath 接口文件路径 - * @param genDir 生成框架文件路径 - * @param scriptDir 脚本目录 - */ - public GenerateDialogPane(Project project, String interFilePath, String genDir, String scriptDir) { - setContentPane(contentPane); - setModal(true); - this.project = project; - this.interFileOrDir = interFilePath; - this.genOutDir = genDir; - this.scriptOutDir = scriptDir; - - textFieldInterPath.setText(interFileOrDir); - textFieldGenPath.setText(genOutDir); - textFieldScriptPath.setText(genOutDir); - - // call onCancel() on ESCAPE - contentPane.registerKeyboardAction(actionEvent -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), - JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); - - BrowseAction browseAction = new BrowseAction(project, buttonSelectInter, textFieldInterPath, - textFieldGenPath, textFieldScriptPath); - buttonSelectInter.addActionListener(browseAction); - buttonSelectGenPath.addActionListener(new GenAction(buttonSelectGenPath, textFieldGenPath)); - buttonSelectScriptPath.addActionListener(new ScriptAction(buttonSelectScriptPath, textFieldScriptPath)); - - buttonCfg.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String genPath = textFieldGenPath.getText().trim(); - if (genPath.isEmpty()) { - // 提醒用户填写生成框架路径 - GenNotification.notifyMessage(project, "请填写生成框架路径...", "生成框架路径不能为空", - NotificationType.WARNING); - } else { - ShowCfgInfoDialog showCfgInfoDialog = new ShowCfgInfoDialog(list, genPath); - showCfgInfoDialog.showAndGet(); - } - } - }); - } - - @Override - public synchronized void addWindowListener(WindowListener windowListener) { - super.addWindowListener(windowListener); - new WindowAdapter() { - /** - * close dialog - * - * @param windowEvent WindowEvent - */ - @Override - public void windowClosing(WindowEvent windowEvent) { - onCancel(); - } - }; - } - - /** - * 验证文本选择框是否空。是否替换已存在的内容 - * - * @return ValidationInfo 返回不符要求的信息。 - */ - @Nullable - public ValidationInfo validationInfo() { - ValidationInfo validationInfo = null; - String fileInter = textFieldInterPath.getText(); - String scriptDir = textFieldScriptPath.getText(); - String filegypDir = textFieldGenPath.getText(); - boolean isEmptyFile = - TextUtils.isEmpty(fileInter) || TextUtils.isEmpty(scriptDir) || TextUtils.isEmpty(filegypDir); - if (isEmptyFile) { - String warnMsg = "接口文件、框架、编译脚本路径不能为空"; - warningMessage(warnMsg); - validationInfo = new ValidationInfo(warnMsg); - return validationInfo; - } - File file = new File(filegypDir + "/binding.gyp"); - if (file.exists()) { - ConfirmDialog confirmDialog = new ConfirmDialog("是否替换已存在的编译脚本?"); - if (!confirmDialog.showAndGet()) { - validationInfo = new ValidationInfo(String.format("不替换现有编译脚本:%s", file)); - return validationInfo; - } - } - return validationInfo; - } - - private void onCancel() { - dispose(); - } - - private void warningMessage(String title) { - String notifyContent = "请选择接口文件或文件夹,生成框架路径,编译脚本路径"; - GenNotification.notifyMessage(this.project, notifyContent, title, NotificationType.WARNING); - } - - /** - * 执行主程序入口 - * - * @return 执行状态 - */ - public boolean runFun() { - // 获取dataList数据 - dataList = list.getDataList(); - // 写入cfg.json文件 - if (dataList.size() > 0) { - writeJsonFile(dataList); - } - GenNotification.notifyMessage(this.project, "", "Generating Napi", NotificationType.INFORMATION); - interFileOrDir = textFieldInterPath.getText(); - genOutDir = textFieldGenPath.getText(); - scriptOutDir = textFieldScriptPath.getText(); - numberType = comboBox.getSelectedItem().toString(); - String command; - command = genCommand(); - - File outPath = new File(textFieldGenPath.getText()); - List oldFileList = getFileInfoList(outPath); - try { - if (!TextUtils.isEmpty(command) && callExtProcess(command)) { - List newFileList = getFileInfoList(outPath); - newFileList.removeAll(oldFileList); - - GenNotification.notifyGenResult(project, newFileList, "Generate Napi Successfully", - NotificationType.INFORMATION); - return true; - } - } catch (IOException | InterruptedException ex) { - GenNotification.notifyMessage(project, textFieldGenPath.getText(), "Command exec error", - NotificationType.ERROR); - LOG.error(ex); - } - return false; - } - - /** - * 生成命令行指令 - * - * @return 返回命令行执行内容 - */ - private String genCommand() { - String sysName = System.getProperties().getProperty("os.name").toUpperCase(); - String tmpDirFile = System.getProperty("java.io.tmpdir"); - if (sysName.contains("WIN")) { - copyFileToLocalPath("napi_generator-win"); - tmpDirFile += "napi_generator-win.exe"; - } else if (sysName.contains("LINUX")) { - copyFileToLocalPath("napi_generator-linux"); - tmpDirFile += "napi_generator-linux"; - } else { - copyFileToLocalPath("napi_generator-macos"); - tmpDirFile += "napi_generator-macos"; - } - File file = new File(tmpDirFile); - String command = file.toString(); - String inArgs = genInArgs(interFileOrDir); - command += inArgs + " -o " + genOutDir + " -i " + radioButton.isSelected() + " -n " + genNumbertypeArgs(); - // 用户未配置业务代码则不加 -s 参数 - String cfgFilePath = textFieldScriptPath.getText().trim() + "/cfg.json"; - File fileExist = new File(cfgFilePath); - if (fileExist.exists()) { - command += " -s " + cfgFilePath; - } - return command; - } - - /** - * 生成 -n 输入参数。 - * - * @return 生成后的值-n的值 - */ - private String genNumbertypeArgs() { - String type = "uint32_t"; - if (numberType != "") { - type = numberType; - } - return type; - } - - /** - * 拷贝文件到本地临时目录 - * - * @param fileName 文件名 - */ - private void copyFileToLocalPath(String fileName) { - String sysName = System.getProperties().getProperty("os.name").toUpperCase(); - String tmpDirFile = System.getProperty("java.io.tmpdir"); - String execFn; - if (sysName.contains("WIN")) { - execFn = "cmds/win/" + fileName + ".exe"; - tmpDirFile += fileName + ".exe"; - } else if (sysName.contains("LINUX")) { - execFn = "cmds/linux/" + fileName; - tmpDirFile += fileName; - } else { - execFn = "cmds/mac/" + fileName; - tmpDirFile += fileName; - } - try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(execFn)) { - if (inputStream == null) { - throw new IOException("exec File InputStream is Null"); - } - byte[] bs = inputStream.readAllBytes(); - writeTmpFile(tmpDirFile, bs); - if (sysName.contains("LINUX") || sysName.contains("MAC OS")) { - executable(tmpDirFile); - } - } catch (IOException | InterruptedException e) { - GenNotification.notifyMessage(this.project, e.getMessage(), "Can not Find File:" + execFn, - NotificationType.ERROR); - LOG.error(e); - } - } - - /** - * 生成 -f -d 输入参数。 - * - * @param fileOrDir 选中的文件或文件夹路径 - * @return 生成后的 -f -d的值 - */ - private String genInArgs(String fileOrDir) { - tsFileList.clear(); - String[] interArr = fileOrDir.split(","); - StringBuilder tsParam = new StringBuilder(" -f "); - StringBuilder dirParam = new StringBuilder(" -d "); - String inputCommand = ""; - if (interArr.length > 0) { - for (String interStr : interArr) { - File interFile = new File(interStr); - if (interFile.isDirectory()) { - dirParam.append(interStr).append(" "); - for (File tsFile : interFile.listFiles()) { - tsFileList.add(tsFile.getPath()); - } - } else { - tsParam.append(interStr).append(","); - tsFileList.add(interStr); - } - } - if (!TextUtils.isBlank(tsParam.toString().replaceAll("-f", ""))) { - inputCommand += tsParam.substring(0, tsParam.length() - 1); - } - if (!TextUtils.isBlank(dirParam.toString().replace("-d", ""))) { - inputCommand += dirParam.substring(0, dirParam.length() - 1); - } - } - return inputCommand; - } - - private boolean callExtProcess(String command) throws IOException, InterruptedException { - - if (TextUtils.isEmpty(command)) { - GenNotification.notifyMessage(this.project, "执行命令文件为空", "空命令行提示", NotificationType.ERROR); - return false; - } - Process process = Runtime.getRuntime().exec(command); - genResultLog(process); - StreamConsumer errConsumer = new StreamConsumer(process.getErrorStream()); - StreamConsumer outputConsumer = new StreamConsumer(process.getInputStream()); - errConsumer.start(); - outputConsumer.start(); - - if (generateSuccess) { - writeCompileCfg(); - } else { - GenNotification.notifyMessage(project, sErrorMessage, "提示", NotificationType.ERROR); - return false; - } - - errConsumer.join(); - outputConsumer.join(); - return true; - } - - /** - * 获取NAPI工具生成的cpp文件前缀 - * - * @param tsFilePath ts接口文件名 - * @return cpp文件前缀 - */ - private String getCppNamePrefix(String tsFilePath) { - File tsFile = new File(tsFilePath); - - // NAPI工具中cpp前缀名取的是ts文件中声明的首个namespace的名称,插件这里按同样方法获取。 - try (InputStreamReader read = new InputStreamReader(new FileInputStream(tsFile), StandardCharsets.UTF_8); - BufferedReader bufferedReader = new BufferedReader(read)) { - String line = ""; - while ((line = bufferedReader.readLine()) != null) { - // 找到 "declare namespace" 这一行并将 namespace名称作为cpp文件前缀名返回。 - Matcher tsNamespaceMatcher = NAMESPACE_PATTERN.matcher(line); - if (tsNamespaceMatcher.find()) { - return tsNamespaceMatcher.group(1); - } - } - } catch (FileNotFoundException foundException) { - LOG.error("The ts file " + tsFilePath + " does not exist."); - } catch (IOException ioException) { - LOG.error("Failed to read file, error: " + ioException); - } - return ""; - } - - /** - * 使用 ts文件@ohos.xxx.d.ts中的xxx作为编译c++lib库的名字 - * - * @param tsFileName ts文件名 - * @return 解析出的lib库名称 - */ - private String getLibNameFromTsFile(String tsFileName) { - Matcher tsFileNameMatcher = FILE_NAME_PATTERN.matcher(tsFileName); - if (!tsFileNameMatcher.find()) { - LOG.warn("Invalid ts file name format, should be @ohos.xxx.d.ts."); - return tsFileName; - } - return tsFileNameMatcher.group(2); - } - - /** - * 创建路径,将业务配置数据dataList写入Json文件,Json文件路径与Cmake路径一致 - * @param dataList 用户配置的数据 - * @throws IOException e - */ - private void writeJsonFile(List dataList) { - FileUtil fileUtil = new FileUtil(); - String cfgFilePath = fileUtil.makeFile(textFieldScriptPath.getText().trim() + "/cfg.json"); - - if (TextUtils.isEmpty(cfgFilePath)) { - LOG.info("cfgFile is fail"); - return; - } - try { - // 创建 ObjectMapper 对象 - ObjectMapper mapper = new ObjectMapper(); - mapper.enable(SerializationFeature.INDENT_OUTPUT); - - // 将数据转换为 JSON 字符串 - String json = mapper.writeValueAsString(dataList); - StringBuilder cfgJson = new StringBuilder(json); - // 将 JSON 字符串写入文件 - String content = cfgJson.toString().replaceAll("\\\\n", "\\n"); - fileUtil.writeContentToFile(cfgFilePath, content, false); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * 生成编译文件 - */ - private void writeCompileCfg() { - FileUtil fileUtil = new FileUtil(); - String cmakePath = scriptOutDir + "/CMakeLists.txt"; - File fileTmp = new File(cmakePath); - if (fileTmp.exists()) { - isExistCmakeFile = true; - } - // 若没有,则创建CMakeLists.txt文件 - String cmakeFilePath = fileUtil.makeFile(scriptOutDir + "/CMakeLists.txt"); - if (TextUtils.isEmpty(cmakeFilePath)) { - LOG.info("makeFile is fail"); - return; - } - - try { - // 生成 CMakeList.txt文件内容 - StringBuilder cmakeBuilder = new StringBuilder(CMAKE_SETCXX_TEMPLATE); - // 若工程目录存在CMakeLists.txt文件 - if (isExistCmakeFile) { - cmakeBuilder = new StringBuilder(CMAKE_SETCXX_HASCMAKEFILE_TEMPLATE); - } - // 获取工具代码cpp文件相对于CMakeList.txt文件的路径 - String cppRelativePath = fileUtil.getRelativePath(new File(genOutDir).getPath(), - new File(scriptOutDir).getPath()); - String serviceCodeCfg = getCmakeLib(); - for (String tsFilePath : tsFileList) { - String cppNamePrefix = getCppNamePrefix(tsFilePath); - String libName = getLibNameFromTsFile(new File(tsFilePath).getName()); - String libStr = CMAKE_ADD_LIB_TEMPLATE.replaceAll("LIBNAME", libName) - .replaceAll("PATH/", cppRelativePath).replaceAll("FILE_PREFIX", cppNamePrefix) - .replaceAll("SERVICECODE", serviceCodeCfg); - cmakeBuilder.append(libStr).append(FileUtil.getNewline()); - - cmakeBuilder.append(CMAKE_LINK_TEMPLATE.replaceAll("LIBNAME", libName)) - .append(FileUtil.getNewline()); - } - fileUtil.writeContentToFile(cmakeFilePath, cmakeBuilder.toString(), true); - - // 需要在main文件夹下创建cpp目录, 如果没有此目录,DevEco 3.0版本编译时不会编译任何目录中的c++代码。 - Path path = Paths.get(project.getBasePath() + "/entry/src/main/cpp"); - Files.createDirectories(path); - - // 在{ProjectRoot}/entry/build-profile.json5 中增加 externalNativeOptions 配置 - String buildJsonFilePath = project.getBasePath() + "/entry/build-profile.json5"; - - // 获取CMakeLists.txt相对于build-profile.json5构建文件的相对路径 - String cmakeRelativePath = fileUtil.getRelativePath(new File(cmakeFilePath).getParent(), - new File(buildJsonFilePath).getParent()); - - fileUtil.writeBuildJsonFile(buildJsonFilePath, cmakeRelativePath + "CMakeLists.txt"); - } catch (IOException ioException) { - LOG.error("writeCommand io error" + ioException); - } - } - - /** - * 获取业务代码相对于CMakeLists.txt的相对路径。 - * - * @return 业务代码相对于CMakeLists.txt的相对路径 - */ - private String getCmakeLib() { - FileUtil fileUtil = new FileUtil(); - String serviceCodeCfg = ""; - // 获取用户配置的业务cpp相对路径 - for (Data data : dataList) { - String cppNamePath = data.getCppName(); - // 获取cppNamePath的绝对路径 - Path absGenPath = Paths.get(new File(scriptOutDir).getPath()); - Path relativePath = Paths.get(cppNamePath); - Path resolvedPath = absGenPath.resolveSibling(relativePath).normalize(); - String absCppNamePath = resolvedPath.toAbsolutePath().toString(); - // 获取业务代码cpp文件相对于CMakeLists.txt的路径 - String codeRelativePath = fileUtil.getRelativePath(new File(absCppNamePath).getPath(), - new File(scriptOutDir).getPath()); - // 去掉最后的斜杠"/" - codeRelativePath = codeRelativePath.substring(0, codeRelativePath.length() - 1); - if (serviceCodeCfg.indexOf(codeRelativePath) < 0) { - serviceCodeCfg += codeRelativePath + " "; - } - } - return serviceCodeCfg; - } - - /** - * 赋值可执行文件权限。 - * - * @param execFn 可执行命令 - * @throws IOException 打开文件异常 - * @throws InterruptedException 中断异常 - */ - private void executable(String execFn) throws IOException, InterruptedException { - callExtProcess("chmod a+x " + execFn); - } - - /** - * 拷贝可执行文件到临时文件夹 - * - * @param path 目标文件路径 - * @param bs 字节内容 - * @throws IOException exception - */ - private void writeTmpFile(String path, byte[] bs) throws IOException { - File file = new File(path); - if (!file.exists()) { - boolean isNewFile = file.createNewFile(); - if (!isNewFile) { - LOG.info("writeTmpFile createNewFile error"); - } - } - FileOutputStream fw = new FileOutputStream(file); - fw.write(bs, 0, bs.length); - fw.close(); - } - - /** - * 获取生成成功结果文件。 - * - * @param process 进程ID - */ - private void genResultLog(Process process) { - BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); - BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream())); - String sErr; - String sOut; - sErr = getErrorResult(stdError); - if (TextUtils.isEmpty(sErr)) { - sOut = genInputLog(stdInput); - if (!generateIsSuccess(sOut)) { - sErrorMessage = sOut; - } - return; - } - generateSuccess = false; - sErrorMessage = sErr; - } - - /** - * 获取生成失败结果文件。 - * - * @param stdError error buff - * @return ErrorResult - */ - private String getErrorResult(BufferedReader stdError) { - StringBuilder sErr = new StringBuilder(); - while (true) { - String sTmp; - try { - if ((sTmp = stdError.readLine()) == null) { - break; - } - sErr.append(sTmp).append(FileUtil.getNewline()); - } catch (IOException ioException) { - LOG.error(" genResultLog stdInput error" + ioException); - } - } - return sErr.toString(); - } - - private boolean generateIsSuccess(String sOut) { - generateSuccess = sOut.contains("success") || TextUtils.isEmpty(sOut); - return generateSuccess; - } - - /** - * 获取生成文本内容。 - * - * @param stdInput input buff - * @return 返回当前输入框内容 - */ - private String genInputLog(BufferedReader stdInput) { - StringBuilder sOut = new StringBuilder(); - while (true) { - String sTmp; - try { - if ((sTmp = stdInput.readLine()) == null) { - break; - } - sOut.append(sTmp).append(FileUtil.getNewline()); - } catch (IOException ioException) { - LOG.error(" genResultLog stdInput error" + ioException); - } - } - return sOut.toString(); - } - - static class StreamConsumer extends Thread { - InputStream is; - - StreamConsumer(InputStream is) { - super.setName("StreamConsumer"); - this.is = is; - } - - @Override - public void run() { - try { - InputStreamReader isr = new InputStreamReader(is); - BufferedReader br = new BufferedReader(isr); - String line; - while ((line = br.readLine()) != null) { - LOG.error("StreamConsumer" + line); - } - } catch (IOException ioException) { - LOG.error("StreamConsumer io error" + ioException); - } - } - } - - /** - * 获取指定输出目录下的文件列表 - * - * @param outPath 输出目录 - * @return 文件信息列表 - */ - public List getFileInfoList(File outPath) { - List fileInfoList = new ArrayList<>(); - File[] files = outPath.listFiles(); - for (File file : files) { - fileInfoList.add(new FileInfo(file)); - } - return fileInfoList; - } - - - JPanel getContentPanel() { - return contentPane; - } - -} diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/ShowCfgInfoDialog.java b/napi_IntelliJ_plugin/src/com/sk/dialog/ShowCfgInfoDialog.java deleted file mode 100644 index fff95d98030d9798372a9d20c8dbc23692279586..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/ShowCfgInfoDialog.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright (c) 2023 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. - */ -package com.sk.dialog; - -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.ui.DialogWrapper; -import com.sk.utils.Data; -import com.sk.utils.DataList; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import javax.swing.Action; -import javax.swing.JComponent; -import java.awt.Desktop; -import java.awt.event.ActionEvent; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -/** - * 配置config文件对话框Wrapper - * - * @author: goujingjing - * @see: tool conversion plug-in - * @version: v1.0.3 - * @since 2023-12-14 - */ -public class ShowCfgInfoDialog extends DialogWrapper { - private static final Logger LOG = Logger.getInstance(GenerateDialog.class); - private static final String FRAME_TITLE = "Config"; - private static final String CODE_URL = - "https://gitee.com/openharmony/napi_generator/blob/master/docs/INSTRUCTION_ZH.md"; - - private final ShowCfgInfoDialogPane genDiag; - private DataList list = null; - private String genPath; - - /** - * 构造函数 - * @param list 配置文件数据列表 - * @param genPath 生成框架文件路径 - * @throws log 输出异常 - */ - public ShowCfgInfoDialog(DataList list, String genPath) { - super(true); - this.setResizable(false); - this.list = list; - this.genPath = genPath; - setTitle(FRAME_TITLE); - setModal(true); - genDiag = new ShowCfgInfoDialogPane(list, genPath); - init(); - } - - /** - * 创建视图 - * @param void 空 - * @return 组件内容 - * @throws log 输出异常 - */ - @Nullable - @Override - protected JComponent createCenterPanel() { - return genDiag.getContentPanel(); - } - - /** - * ok/cancel按钮 - * @param void 空 - * @return Action[] buttons list - * @throws log 输出异常 - */ - @NotNull - @Override - protected Action[] createActions() { - DialogWrapperExitAction exitAction = new DialogWrapperExitAction("Cancel", CANCEL_EXIT_CODE); - CustomOkAction okAction = new CustomOkAction(); - CustomDelAction delAction = new CustomDelAction(); - CustomUpdateAction updateAction = new CustomUpdateAction(); - - return new Action[]{exitAction, okAction, delAction, updateAction}; - } - - /** - * help 按钮 - * @param void 空 - * @return Action[] button helpAction - * @throws log 输出异常 - */ - @NotNull - @Override - protected Action[] createLeftSideActions() { - CustomHelpAction helpAction = new CustomHelpAction(); - return new Action[]{helpAction}; - } - - /** - * 自定义 ok Action 增加配置数据 - */ - protected class CustomOkAction extends DialogWrapperAction { - - protected CustomOkAction() { - super("Add"); - } - - @Override - protected void doAction(ActionEvent actionEvent) { - close(CANCEL_EXIT_CODE); - ConfigDialog cfgDialog = new ConfigDialog(list, 0, null, true, genPath); - cfgDialog.showAndGet(); - } - } - - /** - * 自定义 Delete Action 增加配置数据 - */ - protected class CustomDelAction extends DialogWrapperAction { - - protected CustomDelAction() { - super("Delete"); - } - - @Override - protected void doAction(ActionEvent actionEvent) { - close(CANCEL_EXIT_CODE); - int index = genDiag.getSelectedIndex(); - list.deleteDataListInfo(index); - ShowCfgInfoDialog showCfgInfoDialog = new ShowCfgInfoDialog(list, genPath); - showCfgInfoDialog.showAndGet(); - } - } - - /** - * 自定义 Update Action 增加配置数据 - */ - protected class CustomUpdateAction extends DialogWrapperAction { - - protected CustomUpdateAction() { - super("Update"); - } - - @Override - protected void doAction(ActionEvent actionEvent) { - close(CANCEL_EXIT_CODE); - int index = genDiag.getSelectedIndex(); - Data data = genDiag.getSelectedData(); - ConfigDialog cfgDialog = new ConfigDialog(list, index, data, false, genPath); - cfgDialog.showAndGet(); - } - } - - /** - * 自定义 help Action - */ - protected class CustomHelpAction extends DialogWrapperAction { - - protected CustomHelpAction() { - super("Help"); - } - - @Override - protected void doAction(ActionEvent actionEvent) { - try { - Desktop.getDesktop().browse(new URI(CODE_URL)); - } catch (URISyntaxException | IOException e) { - LOG.error("Open help error:" + e); - } - } - } -} diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/ShowCfgInfoDialogPane.form b/napi_IntelliJ_plugin/src/com/sk/dialog/ShowCfgInfoDialogPane.form deleted file mode 100644 index 4bf40d3ce7933eaa762cd4a0e7be9ca8f8858b0c..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/ShowCfgInfoDialogPane.form +++ /dev/null @@ -1,87 +0,0 @@ - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/napi_IntelliJ_plugin/src/com/sk/dialog/ShowCfgInfoDialogPane.java b/napi_IntelliJ_plugin/src/com/sk/dialog/ShowCfgInfoDialogPane.java deleted file mode 100644 index 760bd45b17dd9cabd58fa7251997b566323b5e3e..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/dialog/ShowCfgInfoDialogPane.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2023 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. - */ -package com.sk.dialog; - -import com.intellij.openapi.diagnostic.Logger; -import com.sk.utils.Data; -import com.sk.utils.DataList; - -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.JTable; -import javax.swing.JScrollPane; -import javax.swing.JComponent; -import javax.swing.KeyStroke; -import javax.swing.table.DefaultTableModel; -import java.awt.event.KeyEvent; -import java.util.List; -import java.util.Vector; -import javax.swing.ListSelectionModel; - -/** - * ShowCfgInfoDialogPane 显示用户配置的信息 - * - * @author: goujingjing - * @see: generator showConfig dialog - * @version: v1.0.3 - * @since 2023-12-19 - */ -public class ShowCfgInfoDialogPane extends JDialog { - private static final Logger LOG = Logger.getInstance(GenerateDialog.class); - - private JPanel contentPane; - private JTable table; - private JScrollPane scrollPane; - private DefaultTableModel tableModel; - private String genPath; - - /** - * 构造函数 - * @param list 配置文件数据列表 - * @param genPath 生成框架路径 - * @throws log 输出异常 - */ - public ShowCfgInfoDialogPane(DataList list, String genPath) { - String[] tableColNames = new String[] {"includeName", "cppName", "interfaceName", "serviceCode"}; - // 初始化table: 获取List中的数据并展示在表格中 - List dataList = list.getDataList(); - this.genPath = genPath; - tableModel = new DefaultTableModel(tableColNames, 0) { - @Override - public boolean isCellEditable(int row, int column) { - return false; - } - }; - for (Data data : dataList) { - Vector rowData = new Vector<>(); - rowData.add(data.getIncludeName()); - rowData.add(data.getCppName()); - rowData.add(data.getInterfaceName()); - rowData.add(data.getServiceCode()); - tableModel.addRow(rowData); - } - table = new JTable(); - table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - table.setModel(tableModel); - table.setVisible(true); - scrollPane.setViewportView(table); - - contentPane.registerKeyboardAction(actionEvent -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), - JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); - } - - /** - * 获得选中行的数据 - * @param void 空 - * @return 选中行的用户已配置数据(Data) - * @throws log 输出异常 - */ - public Data getSelectedData() { - int index = table.getSelectedRow(); - Data data = null; - if (index != -1) { - // 获取原数据 - Object valueIncludeName = table.getValueAt(index, 0); - String oldIncludeName = valueIncludeName.toString(); - Object valueCppName = table.getValueAt(index, 1); - String oldCppName = valueCppName.toString(); - Object valueInterfaceName = table.getValueAt(index, 2); - String oldInterfaceName = valueInterfaceName.toString(); - Object valueServiceCode = table.getValueAt(index, 3); - String oldServiceCode = valueServiceCode.toString(); - data = new Data(genPath, oldIncludeName, oldCppName, oldInterfaceName, oldServiceCode); - } else { - LOG.error("Please select a row of data that you want to modify!"); - } - return data; - } - - /** - * 获得选中行的index - * @param void 空 - * @return 选中行的index(int) - * @throws log 输出异常 - */ - public int getSelectedIndex() { - return table.getSelectedRow(); - } - - private void onCancel() { - dispose(); - } - - JPanel getContentPanel() { - return contentPane; - } -} diff --git a/napi_IntelliJ_plugin/src/com/sk/ng/GenDTS.java b/napi_IntelliJ_plugin/src/com/sk/ng/GenDTS.java deleted file mode 100644 index ac8f52ae36fa0057d9a29c157612b9c062ad94cd..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/ng/GenDTS.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ -package com.sk.ng; - -import com.intellij.notification.NotificationType; -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.VirtualFile; -import com.sk.dialog.GenerateDialog; -import com.sk.utils.FileUtil; -import com.sk.utils.GenNotification; - -/** - * 项目文件入口 - * - * @author: xudong - * @see: tool conversion plug-in - * @version: v1.0.0 - * @since 2022-02-21 - */ -public class GenDTS extends AnAction { - - @Override - public void actionPerformed(AnActionEvent anActionEvent) { - Project project = anActionEvent.getProject(); - // 获取需要处理的.d.ts文件绝对路径 - VirtualFile file = anActionEvent.getData(PlatformDataKeys.VIRTUAL_FILE); - if (file == null) { - GenNotification.notifyMessage(project, "", "file is not exist", NotificationType.ERROR); - return; - } - if (project == null) { - return; - } - String destPath = file.getPath(); - String directoryPath = file.getParent().getPath(); - String fileName = file.getName(); - GenerateDialog wrapper = new GenerateDialog(project, destPath, directoryPath, fileName); - wrapper.showAndGet(); - } - - - @Override - public void update(AnActionEvent event) { - // 根据所选文件名,判断是否显示生成菜单项 - VirtualFile file = event.getData(PlatformDataKeys.VIRTUAL_FILE); - if (file == null) { - event.getPresentation().setEnabledAndVisible(false); - } else { - event.getPresentation().setEnabledAndVisible(FileUtil.patternFileName(file.getName())); - } - } -} diff --git a/napi_IntelliJ_plugin/src/com/sk/ng/GenMenuDTS.java b/napi_IntelliJ_plugin/src/com/sk/ng/GenMenuDTS.java deleted file mode 100644 index b3bbe227dc1dc3530bacb0accfc34ddaf31e8ea0..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/ng/GenMenuDTS.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2022 Guangzhou Digitalchina Information Technology 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. - */ -package com.sk.ng; - -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.project.Project; -import com.sk.dialog.GenerateDialog; -import org.jetbrains.annotations.NotNull; - -/** - * 工具菜单入口 - * - * @author: liulongc digitalchina.com - * @see: tool conversion plug-in - * @version: v1.0.0 - * @since 2022-05-27 - */ -public class GenMenuDTS extends AnAction { - - @Override - public void actionPerformed(@NotNull AnActionEvent anActionEvent) { - Project project = anActionEvent.getProject(); - - if (project == null) { - return; - } - GenerateDialog wrapper = new GenerateDialog(project, "", "", ""); - wrapper.showAndGet(); - } - -} diff --git a/napi_IntelliJ_plugin/src/com/sk/utils/Data.java b/napi_IntelliJ_plugin/src/com/sk/utils/Data.java deleted file mode 100644 index c668031c00758f224bcf11b0a9d21e316d055dcf..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/utils/Data.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2023 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. - */ -package com.sk.utils; - -/** - * 配置信息类,提供自定义的配置信息类 - * - * @author: goujingjing - * @see: generator dialog - * @version: v1.0.3 - * @since 2023-12-14 - */ -public class Data { - private String genPath; - private String includeName; - private String cppName; - private String interfaceName; - private String serviceCode; - - /** - * 构造函数 - * - * @param genPath 用户配置的生成框架路径 - * @param includeName 用户配置的业务代码头文件相对路径 - * @param cppName 用户配置的业务代码cpp文件相对路径 - * @param interfaceName 用户配置的业务代码接口名 - * @param serviceCode 用户配置的调用业务代码的代码 - * @throws log 输出异常 - */ - public Data(String genPath, String includeName, String cppName, String interfaceName, - String serviceCode) { - this.genPath = genPath; - this.includeName = includeName; - this.cppName = cppName; - this.interfaceName = interfaceName; - this.serviceCode = serviceCode; - } - - /** - * get函数 - * @param void 空 - * @return 用户配置的业务代码根路径 - * @throws log 输出异常 - */ - public String getGenPath() { - return genPath; - } - - /** - * set函数 - * - * @param genPath 用户配置的业务代码根路径 - * @throws log 输出异常 - */ - public void setGenPath(String genPath) { - this.genPath = genPath; - } - - /** - * get函数 - * @param void 空 - * @return 用户配置的业务代码头文件相对路径 - * @throws log 输出异常 - */ - public String getIncludeName() { - return includeName; - } - - /** - * set函数 - * @param includeName 用户配置的业务代码头文件相对路径 - * @throws log 输出异常 - */ - public void setIncludeName(String includeName) { - this.includeName = includeName; - } - - /** - * get函数 - * @param void 空 - * @return 用户配置的业务代码cpp文件相对路径 - * @throws log 输出异常 - */ - public String getCppName() { - return cppName; - } - - /** - * set函数 - * @param cppName 用户配置的业务代码cpp文件相对路径 - * @throws log 输出异常 - */ - public void setCppName(String cppName) { - this.cppName = cppName; - } - - /** - * get函数 - * @param void 空 - * @return 用户配置的业务代码接口名 - * @throws log 输出异常 - */ - public String getInterfaceName() { - return interfaceName; - } - - /** - * set函数 - * @param interfaceName 用户配置的业务代码接口名 - * @throws log 输出异常 - */ - public void setInterfaceName(String interfaceName) { - this.interfaceName = interfaceName; - } - - /** - * get函数 - * @param void 空 - * @return 用户配置的调用业务代码的代码 - * @throws log 输出异常 - */ - public String getServiceCode() { - return serviceCode; - } - - /** - * set函数 - * @param serviceCode 用户配置的调用业务代码的代码 - * @throws log 输出异常 - */ - public void setServiceCode(String serviceCode) { - this.serviceCode = serviceCode; - } -} diff --git a/napi_IntelliJ_plugin/src/com/sk/utils/DataList.java b/napi_IntelliJ_plugin/src/com/sk/utils/DataList.java deleted file mode 100644 index 0f9c42c54cd3fd34fba5e687cd695da64f693c7f..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/utils/DataList.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2023 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. - */ -package com.sk.utils; - -import com.intellij.notification.NotificationType; - -import java.util.List; - -/** - * 配置信息列表类,将每一组配置信息放入List中保存 - * - * @author: goujingjing - * @see: generator dialog - * @version: v1.0.3 - * @since 2023-12-14 - */ -public class DataList { - private List dataList; - - /** - * 构造函数 - * @param dataList 用户的配置文件信息 - * @throws log 输出异常 - */ - public DataList(List dataList) { - this.dataList = dataList; - } - - /** - * 返回用户输入的所有配置业务代码的数据 - * @param void 空 - * @return 保存的dataList数据。 - * @throws log 输出异常 - */ - public List getDataList() { - return this.dataList; - } - - /** - * 将用户输入的Data数据加入List中保存 - * @param data 用户输入的配置业务代码相关数据 - * @throws log 输出异常 - */ - public void addDataListInfo(Data data) { - this.dataList.add(data); - GenNotification.notifyMessage(null, "", "添加成功", NotificationType.INFORMATION); - } - - /** - * 修改数据,将用户输入的Data数据加入List中保存 - * @param index 用户要修改的那一项数据 - * @param data 用户输入的配置业务代码相关数据 - * @throws log 输出异常 - */ - public void modifyDataListInfo(int index, Data data) { - this.dataList.set(index, data); - GenNotification.notifyMessage(null, "", "修改成功", NotificationType.INFORMATION); - } - - /** - * 删除数据,删除一项配置数据 - * @param index 用户要删除的那一项数据的索引 - * @throws log 输出异常 - */ - public void deleteDataListInfo(int index) { - if (index >= 0 && index < this.dataList.size()) { - this.dataList.remove(index); - GenNotification.notifyMessage(null, "", "删除成功", NotificationType.INFORMATION); - } else { - GenNotification.notifyMessage(null, "", "删除失败", NotificationType.INFORMATION); - } - } - -} diff --git a/napi_IntelliJ_plugin/src/com/sk/utils/FileInfo.java b/napi_IntelliJ_plugin/src/com/sk/utils/FileInfo.java deleted file mode 100644 index 4b67fd384c51d1c06441607331204de3e479aa7f..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/utils/FileInfo.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ -package com.sk.utils; - -import java.io.File; -import java.util.Objects; - -/** - * 文件信息类,提供自定义的文件对象比较方法 - * - * @author: zhangzhicheng - * @see: generator dialog - * @version: v1.0.0 - * @since 2023-01-18 - */ -public class FileInfo { - private String name; - private String path; - private long lastModifiedTime; - - public FileInfo(File file) { - name = file.getName(); - path = file.getPath(); - lastModifiedTime = file.lastModified(); - } - - /** - * 获取文件路径 - * - * @return 文件路径 - */ - public String getPath() { - return path; - } - - /** - * 重写比较方法,文件名和最后修改时间都相同才认为相等(被修改覆盖过的文件也认为是新文件) - * - * @param obj 待比较的文件对象 - * @return 是否为相同文件 - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - FileInfo fileInfo = (FileInfo) obj; - return lastModifiedTime == fileInfo.lastModifiedTime && Objects.equals(name, fileInfo.name) - && Objects.equals(path, fileInfo.path); - } - - @Override - public int hashCode() { - return Objects.hash(name, path, lastModifiedTime); - } -} diff --git a/napi_IntelliJ_plugin/src/com/sk/utils/FileUtil.java b/napi_IntelliJ_plugin/src/com/sk/utils/FileUtil.java deleted file mode 100644 index 2bbf6eef0a0abd6e506f3495859e45d5160fbfaf..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/utils/FileUtil.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ -package com.sk.utils; - -import com.alibaba.fastjson2.JSON; -import com.alibaba.fastjson2.JSONObject; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.intellij.notification.NotificationType; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.project.Project; -import org.apache.http.util.TextUtils; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Properties; -import java.util.regex.Pattern; - -/** - * 文本文件工具 - * - * @author: xudong - * @see: file utils - * @version: v1.0.0 - * @since 2022-02-21 - */ -public class FileUtil { - private static final Logger LOG = Logger.getInstance(FileUtil.class); - - private static final int COMPILE_SDK_VERSION = 5; - - private static final String LF = getNewline(); // 换行符 - - private static final String BUILD_OPTION = "{" + LF - + " \"externalNativeOptions\": {" + LF - + " \"path\": \"\"," + LF - + " \"arguments\": \"\"," + LF - + " \"cppFlags\": \"\"," + LF - + " }" + LF - + " }"; - - /** - * 改写build-profile.json5文件 - * - * @param buildJsonFilePath build-profile.json5 文件路径 - * @param cmakeFilePath CMakeList.txt 文件路径 - */ - public void writeBuildJsonFile(String buildJsonFilePath, String cmakeFilePath) { - try { - String buildStr = readWholeFile(buildJsonFilePath); - JSONObject buildObj = (JSONObject) JSON.parse(buildStr); - JSONObject buildOptionObj = (JSONObject) JSON.parse(BUILD_OPTION); - ((JSONObject) buildOptionObj.get("externalNativeOptions")).put("path", cmakeFilePath); - buildObj.put("buildOption", buildOptionObj); - ObjectMapper mapper = new ObjectMapper(); - buildStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(buildObj); - - writeContentToFile(buildJsonFilePath, buildStr, false); - } catch (IOException ioException) { - LOG.error("Failed to write file [" + buildJsonFilePath + "], error: " + ioException); - } - } - - /** - * 将数据写入到指定文件中 - * - * @param path 文件路径 - * @param content 数据内容 - * @param isAppend 文件是否追加写入 - */ - public void writeContentToFile(String path, String content, boolean isAppend) { - File file = new File(path); - try (FileWriter fw = new FileWriter(file, isAppend)) { - fw.write(FileUtil.getNewline() + content + FileUtil.getNewline()); - } catch (IOException ioException) { - LOG.error("Failed to write file [" + path + "], error: " + ioException); - } - } - - /** - * 创建文件 - * - * @param path 文件路径 - * @return 文件路径 - */ - public String makeFile(String path) { - File file = new File(path); - if (!file.exists()) { - try { - boolean isCreateFile = file.createNewFile(); - if (isCreateFile) { - LOG.info(String.format("makeFile %s success", path)); - } - } catch (IOException ioException) { - LOG.error(String.format("makeFile %s error:%s", path, ioException)); - return ""; - } - } - return file.getPath(); - } - - /** - * 获得 pathA 相对于 pathB的相对路径 - * - * @param pathA 路径A,如 D:\xx\yy\zz\a1\a2 - * @param pathB 路径B, 如 D:\xx\yy\zz\b1\b2\b3 - * @return pathA 相对于 pathB的相对路径: ../../../a1/a2/ - */ - public String getRelativePath(String pathA, String pathB) { - String separatorStr = File.separator.equals("\\") ? "\\\\" : File.separator; - String[] pathAList = pathA.split(separatorStr); - String[] pathBList = pathB.split(separatorStr); - - int pos = 0; - for (; pos < pathAList.length && pos < pathBList.length; ++pos) { - if (!pathAList[pos].equals(pathBList[pos])) { - // 找到两个path路径存在差异的位置 - break; - } - } - // 截取pathA和pathB路径字符串的差异部分 - String[] diffPathAList = Arrays.copyOfRange(pathAList, pos, pathAList.length); - String[] diffPathBList = Arrays.copyOfRange(pathBList, pos, pathBList.length); - - // pathA的差异字符串作为相对路径的结尾部分 - String pathAStr = String.join("/", diffPathAList); - pathAStr = pathAStr.isBlank() ? "" : pathAStr + "/"; - - // 根据pathB的差异目录层级生成向上跳转字符串 - String rollbackPath = ""; - for (int i = 0; i < diffPathBList.length; ++i) { - rollbackPath += "../"; - } - rollbackPath = rollbackPath.isEmpty() ? "./" : rollbackPath; - - // 相对路径 = 向上跳转部分 + pathA的差异部分 - return rollbackPath + pathAStr; - } - - /** - * 将错误信息输入到txt中 - * - * @param path 路径 - * @param content 内容 - */ - public void writeErrorToTxt(String path, String content) { - File file = new File(path); - try (FileWriter fw = new FileWriter(file, true)) { - fw.write(content + FileUtil.getNewline()); - } catch (IOException ioException) { - LOG.error("writeErrorToTxt io error" + ioException); - } - } - - /** - * 判断文件是否包含指定字符串 - * - * @param path 文件路径 - * @param content 指定内容 - * @return 是否包含指定字符串 - * @throws IOException 异常信息 - */ - public boolean findStringInFile(String path, String content) throws IOException { - File file = new File(path); - String[] command = content.split(FileUtil.getNewline()); - - try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8); - BufferedReader bufferedReader = new BufferedReader(read)) { - return isContainString(bufferedReader, command[1]); - } catch (FileNotFoundException foundException) { - LOG.error("file not found" + foundException); - return false; - } - } - - private boolean isContainString(BufferedReader bufferedReader, String command) { - String line = null; - while (true) { - try { - if ((line = bufferedReader.readLine()) == null) { - return false; - } - } catch (IOException ioException) { - LOG.error("findStringInFile IOException" + ioException); - } - - if (line.contains(command)) { - return true; - } - } - } - - /** - * 获取换行符 - * - * @return 换行符 - */ - public static String getNewline() { - return System.getProperty("line.separator"); - } - - /** - * 正则匹配所选文件名是否符合规范 - * - * @param fileName 文件名 - * @return boolean 是否匹配 - */ - public static boolean patternFileName(String fileName) { - String pattern = "((@ohos\\.)*([.a-z_A-Z0-9]+).d.ts)"; - return Pattern.matches(pattern, fileName); - } - - /** - * check project SDK - * - * @param project projectid - * @param baseFile project root file - * @return boolean - */ - public static boolean checkProjectSDK(Project project, String baseFile) { - - String gradlePath = ""; - File baseDir = new File(baseFile); - if (baseDir.isDirectory()) { - File[] childFile = baseDir.listFiles(); - assert childFile != null; - for (File file : childFile) { - if (file.getName().equals("build.gradle") || file.getName().equals("build-profile.json5")) { - gradlePath = file.getPath(); - } - } - } - - Properties properties = new Properties(); - if (TextUtils.isBlank(gradlePath)) { - GenNotification.notifyMessage(project, "项目结构中没有grandle配置文件。", - "当前项目结构不支持", - NotificationType.WARNING); - return true; - } - try { - properties.load(new FileInputStream(gradlePath)); - } catch (IOException e) { - GenNotification.notifyMessage(project, e.getMessage(), "提示", NotificationType.ERROR); - LOG.error(String.format("Can not load file :%s . %s", gradlePath, e)); - return true; - } - String ohosSDK = properties.getProperty("compileSdkVersion"); - - if (ohosSDK != null && Integer.parseInt(ohosSDK) < COMPILE_SDK_VERSION) { - GenNotification.notifyMessage(project, "SKD版本过低,NAPI仅支持5.0及以上版本", - "提示", - NotificationType.WARNING); - return true; - } - return false; - } - - private String readWholeFile(String fileName) { - File file = new File(fileName); - byte[] rdBuf = new byte[(int) file.length()]; - try(FileInputStream in = new FileInputStream(file)) { - in.read(rdBuf); - return new String(rdBuf, "UTF-8"); - } catch (FileNotFoundException foundException) { - LOG.error(String.format("File %s does not exist.", fileName)); - } catch (IOException ioException) { - LOG.error(String.format("Failed to read file %s. Error: %s", fileName, ioException)); - } - return ""; - } -} diff --git a/napi_IntelliJ_plugin/src/com/sk/utils/GenNotification.java b/napi_IntelliJ_plugin/src/com/sk/utils/GenNotification.java deleted file mode 100644 index 3aee54d4e082a326ed841df912aaa13074272091..0000000000000000000000000000000000000000 --- a/napi_IntelliJ_plugin/src/com/sk/utils/GenNotification.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2022 Guangzhou Digitalchina Information Technology 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. - */ -package com.sk.utils; - -import com.intellij.ide.actions.OpenFileAction; -import com.intellij.notification.NotificationType; -import com.intellij.notification.Notification; -import com.intellij.notification.NotificationGroupManager; -import com.intellij.notification.NotificationGroup; -import com.intellij.notification.NotificationAction; -import com.intellij.notification.Notifications; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.project.Project; -import org.jetbrains.annotations.NotNull; - -import java.util.List; - -/** - * 通知框 - * - * @author: liulongc digitalchina.com - * @see: tool conversion plug-in - * @version: v1.0.0 - * @since 2022-05-27 - */ -public class GenNotification { - - private static final Logger LOG = Logger.getInstance(FileUtil.class); - - private GenNotification() { - } - - /** - * 消息通知 - * - * @param project projectid - * @param content 提示内容 - * @param title 提示栏内容 - * @param type 提示类型 Error,Waring,info - */ - public static void notifyMessage(@javax.annotation.Nullable Project project, - String content, - String title, - NotificationType type) { - - NotificationGroupManager manager = NotificationGroupManager.getInstance(); - NotificationGroup notificationGroup = manager.getNotificationGroup("Generate.Result.Group"); - Notification notification = notificationGroup.createNotification(content, type); - notification.setTitle(title); - notification.setContent(content); - - if (NotificationType.ERROR.equals(type)) { - LOG.error(content); - } else if (NotificationType.WARNING.equals(type)) { - LOG.warn(content); - } else { - LOG.info(content); - } - Notifications.Bus.notify(notification, project); - - } - - /** - * 消息通知 - * - * @param project projectid - * @param newFileList 新增文件列表 - * @param title 提示栏内容 - * @param type 提示类型 Error,Waring,info - */ - public static void notifyGenResult(@javax.annotation.Nullable Project project, List newFileList, - String title, NotificationType type) { - NotificationGroupManager manager = NotificationGroupManager.getInstance(); - NotificationGroup notificationGroup = manager.getNotificationGroup("Generate.Result.Group"); - Notification notification = notificationGroup.createNotification("", type); - notification.setTitle(title); - notification.setContent(null); - addAction(project, newFileList, notification); - Notifications.Bus.notify(notification, project); - } - - private static void addAction(Project project, List newFileList, Notification notification) { - LOG.info("generated file list log:"); - for (FileInfo fs : newFileList) { - String filePath = fs.getPath(); - NotificationAction action = new NotificationAction(filePath) { - @Override - public void actionPerformed(@NotNull AnActionEvent anActionEvent, - @NotNull Notification notification) { - OpenFileAction.openFile(filePath, project); - } - }; - notification.addAction(action); - - } - } -} diff --git a/src/tsGen/header_parser.py b/src/tsGen/header_parser.py deleted file mode 100644 index 4cd66f6a11140f1b585bb76b785678a6b8492d93..0000000000000000000000000000000000000000 --- a/src/tsGen/header_parser.py +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# -# Copyright (c) 2022 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 json -import sys -import CppHeaderParser - -if __name__ == "__main__": - fileName = sys.argv[1]; - try: - hjson = json.loads(CppHeaderParser.CppHeader(fileName).toJSON()) - print(json.dumps({ - "result": hjson - })) - except CppHeaderParser.CppParseError: - print(CppHeaderParser.CppParseError) - finally: - pass \ No newline at end of file diff --git a/src/tsGen/tsMain.js b/src/tsGen/tsMain.js deleted file mode 100644 index 99875f59a9f06cd02bcdc9fc47d2b915f67cc9eb..0000000000000000000000000000000000000000 --- a/src/tsGen/tsMain.js +++ /dev/null @@ -1,359 +0,0 @@ -/* -* Copyright (c) 2022 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. -*/ -const { NapiLog } = require("../gen/tools/NapiLog"); -const { writeFile } = require("../gen/tools/FileRW"); -const path = require('path') -const re = require("../gen/tools/re"); -const fs = require("fs"); -const os = require("os"); - -function parseFileAll(hFilePath) { - let execSync = require("child_process").execSync - let cmd = "" - if(fs.existsSync("./src/tsGen/header_parser.py")) { - // call python file (for debug test) - cmd = "python ./src/tsGen/header_parser.py " + hFilePath - } else { - // call exe file (for real runtime) - let sysInfo = os.platform() - let execPath = path.dirname(process.execPath) - let exeFile = sysInfo === 'win32' ? path.join(execPath, "header_parser.exe") : - path.join(execPath, "header_parser") - cmd = exeFile + " " + hFilePath - } - - let parseResult = null - let stdout = execSync(cmd) - parseResult = JSON.parse(stdout.toString()).result - return parseResult -} - -function createNameSpaceInfo(parseNameSpaceInfo) { - let nameSpaceInfo = { - "name": "", - "classes": [], - "functions": [] - } - nameSpaceInfo.name = parseNameSpaceInfo - return nameSpaceInfo -} - -function analyzeNameSpace(rootInfo, parseResult) { - let parseNameSpaces = parseResult.namespaces - for(var i = 0; i < parseNameSpaces.length; ++i) { - let nameSpaceInfo = createNameSpaceInfo(parseNameSpaces[i]) - rootInfo.namespaces.push(nameSpaceInfo) - } -} - -function isStringType(cType) { - switch(cType) { - case 'string': - case 'std::string': - case 'char': - case 'wchar_t': - case 'char16_t': - case 'char32_t': - return true - default: - return false - } -} - -function isBoolType(cType) { - if (cType == 'bool') { - return true - } - return false -} - -function isNumberType(cType) { - switch(cType) { - case 'short': - case 'int': - case 'uint32_t': - case 'size_t': - case 'long': - case 'long long': - case 'float': - case 'double': - case 'long double': - case 'int16_t': - case 'uint16_t': - case 'int32_t': - case 'int64_t': - case 'uint64_t': - case 'double_t': - case 'float_t': - return true - default: - return false - } -} - -function basicC2js(cType) { - let jsType = "" - if (isStringType(cType)) { - jsType = 'string' - } else if (isBoolType(cType)) { - jsType = 'boolean' - } else if (isNumberType(cType)) { - jsType = 'number' - } else { - jsType = cType - } - return jsType -} - -function getJsTypeFromC(cType, typeInfo) { - let basicCtype = cType - let matchs = re.match("(std::)?vector<([\x21-\x7e ]+)>", basicCtype); - if (matchs) { - basicCtype = re.getReg(basicCtype, matchs.regs[2]).trim() - typeInfo.array = 1 - } - - let unsignedIdx = basicCtype.indexOf('unsigned') - if ( unsignedIdx >= 0) { - // cut off the keywords 'unsigned' - basicCtype = basicCtype.substring(unsignedIdx + 8, basicCtype.length).trim() - } - let jsType = basicC2js(basicCtype) - if (typeInfo.array) { - jsType = "Array<%s>".format(jsType) - } - return jsType -} - -function createParam(parseParamInfo) { - let param = { - "name": "", - "type": "" - } - param.name = parseParamInfo.name - let rawType = getJsTypeFromC(parseParamInfo.raw_type, parseParamInfo) - param.type = rawType - - return param -} - -function createFuncInfo(parseFuncInfo, isClassFunc) { - let funcInfo = { - "name": "", - "params": [], - "namespace": "", - "retType": "", - "static":"" - } - funcInfo.name = parseFuncInfo.name - funcInfo.namespace = parseFuncInfo.namespace - let tokenIndex = funcInfo.namespace.indexOf('::') - if (tokenIndex >= 0) { - // delete '::' in namespace, get the pure space name. - funcInfo.namespace = funcInfo.namespace.substring(0, tokenIndex) - } - - let parseParams = parseFuncInfo.parameters - for(var i = 0; i < parseParams.length; ++i) { - let param = createParam(parseParams[i]) - funcInfo.params.push(param) - } - - funcInfo.isClassFunc = isClassFunc - - if (parseFuncInfo.static && isClassFunc) { - funcInfo.static = "static " - } - let retType = parseFuncInfo.returns === '' ? parseFuncInfo.rtnType : parseFuncInfo.returns - funcInfo.retType = getJsTypeFromC(retType, parseFuncInfo) - return funcInfo -} - -function putFuncIntoNamespace(funcInfo, namespaces) { - for (var i = 0; i < namespaces.length; ++i) { - if (namespaces[i].name === funcInfo.namespace) { - namespaces[i].functions.push(funcInfo) - return - } - } - NapiLog.logError('The namespace [%s] of function %s is not found.'.format(funcInfo.namespace, funcInfo.name)); -} - -function analyzeRootFunction(rootInfo, parseResult) { - let parseFunctions = parseResult.functions - for(var i = 0; i < parseFunctions.length; ++i) { - let funcInfo = createFuncInfo(parseFunctions[i], false) - if (parseFunctions[i].namespace != '') { - // function in namespace - putFuncIntoNamespace(funcInfo, rootInfo.namespaces) - } else { - // function without namespace, put on root - rootInfo.functions.push(funcInfo) - } - } -} - -function createProperties(parseProperties) { - let propertyList = [] - for (var i = 0; i < parseProperties.length; ++i) { - let property = {} - property.name = parseProperties[i].name - property.type = getJsTypeFromC(parseProperties[i].raw_type, parseProperties[i]) - propertyList.push(property) - } - return propertyList -} - -function createClassFunctions(parseFuncs) { - let funcList = [] - for(var i = 0; i < parseFuncs.length; ++i) { - let funcInfo = createFuncInfo(parseFuncs[i], true) - funcList.push(funcInfo) - } - return funcList -} - -function createClassInfo(parseClassInfo) { - let classInfo = { - "name": "", - "namespace": "", - "properties": [], - "functions": [], - "extends":[] - } - classInfo.name = parseClassInfo.name - classInfo.namespace = parseClassInfo.namespace - classInfo.properties = createProperties(parseClassInfo.properties.public) - classInfo.functions = createClassFunctions(parseClassInfo.methods.public) - - return classInfo -} - -function putClassIntoNamespace(classInfo, namespaces) { - for (var i = 0; i < namespaces.length; ++i) { - if (namespaces[i].name === classInfo.namespace) { - namespaces[i].classes.push(classInfo) - return - } - } - NapiLog.logError('The namespace [%s] of class %s is not found.'.format(classInfo.namespace, classInfo.name)); -} - -function analyzeClasses(rootInfo, parseResult) { - let parseClasses = parseResult.classes; - - for(var className in parseClasses) { - let classInfo = createClassInfo(parseClasses[className]) - if (classInfo.namespace != '') { - // class in namespace - putClassIntoNamespace(classInfo, rootInfo.namespaces) - } else { - // class without namespace, put on root - rootInfo.classes.push(classInfo) - } - } -} - -function getTab(tabLv) { - let tab = "" - for(var i = 0; i < tabLv; ++i) { - tab += " " - } - return tab -} - -function genFunction(func, tabLv, needDeclare = false) { - let tab = getTab(tabLv) - let funcPrefix = func.isClassFunc ? "" : "function " - let funcParams = "" - for (var i = 0; i < func.params.length; ++i) { - funcParams += i > 0 ? ", " : "" - funcParams += func.params[i].name + ": " + func.params[i].type - } - let declareStr = needDeclare ? "declare " : "" - return "%s%s%s%s%s(%s): %s;\n".format(tab, declareStr, funcPrefix, func.static, func.name, funcParams, func.retType) -} - -function genClass(classInfo, tabLv, needDeclare = false) { - let tab = getTab(tabLv) - let declareStr = needDeclare ? "declare " : "" - let tsClass = tab + declareStr + "class " + classInfo.name + " {\n" - let tab1 = getTab(tabLv+1) - for (var i = 0; i < classInfo.properties.length; ++i) { - tsClass += "%s%s: %s;\n".format(tab1, classInfo.properties[i].name, classInfo.properties[i].type) - } - for (var i = 0; i < classInfo.functions.length; ++i) { - tsClass += genFunction(classInfo.functions[i], tabLv+1) - } - tsClass += tab + "}\n" - return tsClass -} - -function genNamespace(namespace, tabLv) { - let tab = getTab(tabLv) - let tsNamespace = tab + "declare namespace %s {\n".format(namespace.name) - for(var i = 0; i < namespace.functions.length; ++i) { - tsNamespace += genFunction(namespace.functions[i], tabLv+1) - } - for(var i = 0; i < namespace.classes.length; ++i) { - tsNamespace += genClass(namespace.classes[i], tabLv+1) - } - tsNamespace += tab + "}\n" - return tsNamespace -} - -function genTsContent(rootInfo) { - let tsContent = rootInfo.needCallback ? "import { AsyncCallback, Callback } from './../basic';\n\n" : "" - - for(var i = 0; i < rootInfo.classes.length; ++i) { - tsContent += genClass(rootInfo.classes[i], 0, true) - } - - for(var i = 0; i < rootInfo.namespaces.length; ++i) { - tsContent += genNamespace(rootInfo.namespaces[i], 0) - } - - for(var i = 0; i < rootInfo.functions.length; ++i) { - tsContent += genFunction(rootInfo.functions[i], 0, true) - } - - if (rootInfo.namespaces.length > 0) { - // export the first namespace as default - tsContent += "\nexport default %s;".format(rootInfo.namespaces[0].name) - } - - return tsContent -} - -function doGenerate(hFilePath, destDir) { - let parseResult = parseFileAll(hFilePath) - let rootInfo = { - "namespaces": [], - "classes": [], - "functions": [], - "needCallback": false - } - analyzeNameSpace(rootInfo, parseResult) - analyzeRootFunction(rootInfo, parseResult) - analyzeClasses(rootInfo, parseResult) - let hfileName = path.basename(hFilePath, ".h") - let tsFilePath = re.pathJoin(destDir, "%s.d.ts".format(hfileName)) - let tsContent = genTsContent(rootInfo) - writeFile(tsFilePath,tsContent) -} - -module.exports = { - doGenerate -}