├── .gitignore
├── LICENSE
├── README.md
├── README_EN.md
├── build.gradle.kts
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle.kts
└── src
└── main
├── java
└── com
│ └── codeshell
│ └── intellij
│ ├── actions
│ ├── assistants
│ │ ├── CleanCode.java
│ │ ├── ExplainCode.java
│ │ ├── GenerateComment.java
│ │ ├── GenerateUnitTests.java
│ │ ├── InsertCode.java
│ │ ├── OpenDevTools.java
│ │ ├── OptimizeCode.java
│ │ ├── PerformanceCheck.java
│ │ ├── SecurityCheck.java
│ │ └── StyleCheck.java
│ └── complete
│ │ ├── CodeGenEscAction.java
│ │ ├── CodeGenInsertAllAction.java
│ │ ├── CodeGenTabAction.java
│ │ └── CodeTriggerCompletionAction.java
│ ├── constant
│ ├── ConnectionParams.java
│ └── PrefixString.java
│ ├── enums
│ ├── ChatMaxToken.java
│ ├── CodeShellStatus.java
│ ├── CodeShellURI.java
│ ├── CompletionMaxToken.java
│ └── TabActionOption.java
│ ├── handlers
│ ├── ClosedConnection.java
│ ├── CustomResourceHandler.java
│ ├── CustomSchemeHandlerFactory.java
│ ├── OpenedConnection.java
│ └── ResourceHandlerState.java
│ ├── model
│ └── GenerateModel.java
│ ├── services
│ ├── CodeShellCompleteService.java
│ └── CodeShellSideWindowService.java
│ ├── settings
│ ├── CodeShellSettings.java
│ ├── CodeShellSettingsProvider.java
│ ├── SettingsPanel.form
│ └── SettingsPanel.java
│ ├── utils
│ ├── CodeGenHintRenderer.java
│ ├── CodeShellIcons.java
│ ├── CodeShellUtils.java
│ └── EditorUtils.java
│ ├── widget
│ ├── CodeShellWidget.java
│ └── CodeShellWidgetFactory.java
│ └── window
│ ├── CodeShellSideWindow.java
│ └── CodeShellSideWindowFactory.java
└── resources
├── META-INF
├── plugin.xml
└── pluginIcon.svg
├── assets
├── logo.png
├── logo.svg
└── readme
│ ├── docs_assistants.png
│ ├── docs_chat.png
│ ├── docs_completion.png
│ ├── docs_debug_plugin.png
│ ├── docs_install_plugin.png
│ └── docs_settings.png
├── icons
├── actionIcon.svg
├── actionIcon_dark.svg
├── widgetDisabled.svg
├── widgetDisabled_dark.svg
├── widgetEnabled.svg
├── widgetEnabled_dark.svg
├── widgetError.svg
└── widgetError_dark.svg
└── webview
├── css
├── app.85ac4201.css
└── chunk-vendors.b81b0806.css
├── favicon.ico
├── fonts
├── element-icons.f1a45d74.ttf
└── element-icons.ff18efd1.woff
├── index.html
└── js
├── app.1d492095.js
├── app.1d492095.js.map
├── chunk-vendors.c4a1abba.js
└── chunk-vendors.c4a1abba.js.map
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | build/
3 | !gradle/wrapper/gradle-wrapper.jar
4 | !**/src/main/**/build/
5 | !**/src/test/**/build/
6 |
7 | ### IntelliJ IDEA ###
8 | /.idea/
9 | *.iws
10 | *.iml
11 | *.ipr
12 | out/
13 | !**/src/main/**/out/
14 | !**/src/test/**/out/
15 |
16 | ### Eclipse ###
17 | .apt_generated
18 | .classpath
19 | .factorypath
20 | .project
21 | .settings
22 | .springBeans
23 | .sts4-cache
24 | bin/
25 | !**/src/main/**/bin/
26 | !**/src/test/**/bin/
27 |
28 | ### NetBeans ###
29 | /nbproject/private/
30 | /nbbuild/
31 | /dist/
32 | /nbdist/
33 | /.nb-gradle/
34 |
35 | ### VS Code ###
36 | .vscode/
37 |
38 | ### Mac OS ###
39 | .DS_Store
40 |
41 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CodeShell IntelliJ IDEA Extension
2 |
3 | [](README_EN.md)
4 |
5 | `codeshell-intellij`项目是基于[CodeShell大模型](https://github.com/WisdomShell/codeshell)开发的支持[IntelliJ IDEA、Pycharm、GoLand](https://www.jetbrains.com/zh-cn/products/)等多种IDE的智能编码助手插件,支持python、java、c++/c、javascript、go等多种编程语言,为开发者提供代码补全、代码解释、代码优化、注释生成、对话问答等功能,旨在通过智能化的方式帮助开发者提高编程效率。
6 |
7 | ## 环境要求
8 |
9 | - [CodeShell 模型服务](https://github.com/WisdomShell/llama_cpp_for_codeshell)已启动
10 | - IDE 版本要求在2022.2至2023.2之间
11 |
12 | ## 插件编译
13 |
14 | 如果要从源码进行打包,请先获取代码:
15 |
16 | ```bash
17 | git clone https://github.com/WisdomShell/codeshell-intellij.git
18 | ```
19 | - 项目使用Gradle管理依赖,点击`刷新`按钮自动重新加载依赖
20 | - 本地运行插件:`Gradle`-`CodeShell`-`Task`-`intellij`-`runIde`
21 | - 在`runIde`右键,可选择使用Debug模式启动
22 |
23 | 
24 |
25 | ### 打包插件
26 |
27 | - 本地生成插件安装包:`Gradle`-`CodeShell`-`Task`-`intellij`-`buildPlugin`
28 | - 打包任务执行完成后,插件安装包在项目根目录下的`build/distributions`目录中
29 |
30 | ### 安装插件
31 |
32 | - 安装入口:`Settings`-`Plugins`-`Install Plugin from Disk...`,在打开的资源选择窗口中选择插件安装包即可
33 |
34 | 
35 |
36 |
37 |
38 | ## 模型服务
39 |
40 | [`llama_cpp_for_codeshell`](https://github.com/WisdomShell/llama_cpp_for_codeshell)项目提供[CodeShell大模型](https://github.com/WisdomShell/codeshell) 4bits量化后的模型,模型名称为`codeshell-chat-q4_0.gguf`。以下为部署模型服务步骤:
41 |
42 | ### 编译代码
43 |
44 | + Linux / Mac(Apple Silicon设备)
45 |
46 | ```bash
47 | git clone https://github.com/WisdomShell/llama_cpp_for_codeshell.git
48 | cd llama_cpp_for_codeshell
49 | make
50 | ```
51 |
52 | 在 macOS 上,默认情况下启用了Metal,启用Metal可以将模型加载到 GPU 上运行,从而显著提升性能。
53 |
54 | + Mac(非Apple Silicon设备)
55 |
56 | ```bash
57 | git clone https://github.com/WisdomShell/llama_cpp_for_codeshell.git
58 | cd llama_cpp_for_codeshell
59 | LLAMA_NO_METAL=1 make
60 | ```
61 |
62 | 对于非 Apple Silicon 芯片的 Mac 用户,在编译时可以使用 `LLAMA_NO_METAL=1` 或 `LLAMA_METAL=OFF` 的 CMake 选项来禁用Metal构建,从而使模型正常运行。
63 |
64 | + Windows
65 |
66 | 您可以选择在[Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/about)中按照Linux的方法编译代码,也可以选择参考[llama.cpp仓库](https://github.com/ggerganov/llama.cpp#build)中的方法,配置好[w64devkit](https://github.com/skeeto/w64devkit/releases)后再按照Linux的方法编译。
67 |
68 | ### 下载模型
69 |
70 | 在[Hugging Face Hub](https://huggingface.co/WisdomShell)上,我们提供了三种不同的模型,分别是[CodeShell-7B](https://huggingface.co/WisdomShell/CodeShell-7B)、[CodeShell-7B-Chat](https://huggingface.co/WisdomShell/CodeShell-7B-Chat)和[CodeShell-7B-Chat-int4](https://huggingface.co/WisdomShell/CodeShell-7B-Chat-int4)。以下是下载模型的步骤。
71 |
72 | - 使用[CodeShell-7B-Chat-int4](https://huggingface.co/WisdomShell/CodeShell-7B-Chat-int4)模型推理,将模型下载到本地后并放置在以上代码中的 `llama_cpp_for_codeshell/models` 文件夹的路径
73 |
74 | ```
75 | git clone https://huggingface.co/WisdomShell/CodeShell-7B-Chat-int4/blob/main/codeshell-chat-q4_0.gguf
76 | ```
77 |
78 | - 使用[CodeShell-7B](https://huggingface.co/WisdomShell/CodeShell-7B)、[CodeShell-7B-Chat](https://huggingface.co/WisdomShell/CodeShell-7B-Chat)推理,将模型放置在本地文件夹后,使用[TGI](https://github.com/WisdomShell/text-generation-inference.git)加载本地模型,启动模型服务
79 |
80 | ### 加载模型
81 |
82 | - `CodeShell-7B-Chat-int4`模型使用`llama_cpp_for_codeshell`项目中的`server`命令即可提供API服务
83 |
84 | ```bash
85 | ./server -m ./models/codeshell-chat-q4_0.gguf --host 127.0.0.1 --port 8080
86 | ```
87 |
88 | 注意:对于编译时启用了 Metal 的情况下,若运行时出现异常,您也可以在命令行添加参数 `-ngl 0 `显式地禁用Metal GPU推理,从而使模型正常运行。
89 |
90 | - [CodeShell-7B](https://huggingface.co/WisdomShell/CodeShell-7B)和[CodeShell-7B-Chat](https://huggingface.co/WisdomShell/CodeShell-7B-Chat)模型,使用[TGI](https://github.com/WisdomShell/text-generation-inference.git)加载本地模型,启动模型服务
91 |
92 | ## 模型服务[NVIDIA GPU]
93 |
94 | 对于希望使用NVIDIA GPU进行推理的用户,可以使用[`text-generation-inference`](https://github.com/huggingface/text-generation-inference)项目部署[CodeShell大模型](https://github.com/WisdomShell/codeshell)。以下为部署模型服务步骤:
95 |
96 | ### 下载模型
97 |
98 | 在 [Hugging Face Hub](https://huggingface.co/WisdomShell/CodeShell-7B-Chat)将模型下载到本地后,将模型放置在 `$HOME/models` 文件夹的路径下,即可从本地加载模型。
99 |
100 | ```bash
101 | git clone https://huggingface.co/WisdomShell/CodeShell-7B-Chat
102 | ```
103 |
104 | ### 部署模型
105 |
106 | 使用以下命令即可用text-generation-inference进行GPU加速推理部署:
107 |
108 | ```bash
109 | docker run --gpus 'all' --shm-size 1g -p 9090:80 -v $HOME/models:/data \
110 | --env LOG_LEVEL="info,text_generation_router=debug" \
111 | ghcr.nju.edu.cn/huggingface/text-generation-inference:1.0.3 \
112 | --model-id /data/CodeShell-7B-Chat --num-shard 1 \
113 | --max-total-tokens 5000 --max-input-length 4096 \
114 | --max-stop-sequences 12 --trust-remote-code
115 | ```
116 |
117 | 更详细的参数说明请参考[text-generation-inference项目文档](https://github.com/huggingface/text-generation-inference)。
118 |
119 | ## 配置插件
120 |
121 | - 设置CodeShell大模型服务地址
122 | - 配置是否自动触发代码补全建议
123 | - 配置补全的最大tokens数量
124 | - 配置问答的最大tokens数量
125 | - 配置模型运行环境
126 |
127 | 注意:不同的模型运行环境可以在插件中进行配置。对于[CodeShell-7B-Chat-int4](https://huggingface.co/WisdomShell/CodeShell-7B-Chat-int4)模型,您可以在`Model Runtime Environment`选项中选择`Use CPU Mode(with llama.cpp)`选项。而对于[CodeShell-7B](https://huggingface.co/WisdomShell/CodeShell-7B)和[CodeShell-7B-Chat](https://huggingface.co/WisdomShell/CodeShell-7B-Chat)模型,应选择`Use GPU Model(with TGI framework)`选项。
128 |
129 | 
130 |
131 | ## 功能特性
132 |
133 | ### 1. 代码补全
134 |
135 | - 自动触发代码建议
136 |
137 | 在编码时,当您停止输入时,代码建议将自动触发。
138 |
139 | 当插件提供代码建议时,建议内容以灰色显示在编辑器光标位置,您可以按下Tab键来接受该建议,或者继续输入以忽略该建议。
140 |
141 | 
142 |
143 | ### 2. 代码辅助
144 |
145 | - 对一段代码进行解释/优化/清理
146 | - 为一段代码生成注释/单元测试
147 | - 检查一段代码是否存在性能/安全性问题
148 |
149 | 在IDE侧边栏中打开插件问答界面,在编辑器中选中一段代码,在鼠标右键CodeShell菜单中选择对应的功能项,插件将在问答界面中给出相应的答复。
150 |
151 | 
152 |
153 | ### 3. 智能问答
154 |
155 | - 可编辑问题,重新提问
156 | - 对任一问题,可重新获取回答
157 | - 在回答过程中,可以打断
158 |
159 | 
160 |
161 | 在问答界面的代码块中,可以点击复制按钮复制该代码块。
162 |
163 | ## 开源协议
164 |
165 | Apache 2.0
--------------------------------------------------------------------------------
/README_EN.md:
--------------------------------------------------------------------------------
1 | # CodeShell IntelliJ IDEA Extension
2 |
3 | [](README.md)
4 |
5 | The `codeshell-intellij`project is an open-source plugin developed based on the [CodeShell LLM](https://github.com/WisdomShell/codeshell) that support various IDEs, including [IntelliJ IDEA、Pycharm、GoLand](https://www.jetbrains.com/zh-cn/products/). It serves as an intelligent coding assistant, offering support for various programming languages such as Python, Java, C/C++, JavaScript, Go, and more. This plugin provides features like code completion, code interpretation, code optimization, comment generation, and conversational Q&A to help developers enhance their coding efficiency in an intelligent manner.
6 |
7 | ## Requirements
8 |
9 | - The [CodeShell](https://github.com/WisdomShell/llama_cpp_for_codeshell) service is running
10 | - The IDE version requirement is between 2022.2 and 2023.2
11 |
12 | ## Compile the Plugin
13 |
14 | If you want to package from source code, please obtain the code first:
15 |
16 | ```bash
17 | git clone https://github.com/WisdomShell/codeshell-intellij.git
18 | ```
19 |
20 | - The project uses Gradle to manage dependencies. Click the "Refresh" button to automatically reload dependencies.
21 | - To run the plugin locally, navigate to `Gradle` > `CodeShell` > `Task` > `intellij` > `runIde`.
22 | - Right-click on `runIde` and choose to start in Debug mode.
23 |
24 |
25 | 
26 |
27 | ### Package the Plugin
28 |
29 | - Generate a Local Plugin Installation Package: Navigate to `Gradle` > `CodeShell` > `Task` > `intellij` > `buildPlugin`.
30 | - Once the packaging task is completed, the plugin installation package can be found in the `build/distributions` directory at the project's root.
31 |
32 | ### Install the Plugin
33 |
34 | - Installation Process: Go to `Settings` > `Plugins` > `Install Plugin from Disk...`, and in the opened file selection window, choose the plugin installation package
35 |
36 | 
37 |
38 | ## Model Service
39 |
40 | The [`llama_cpp_for_codeshell`](https://github.com/WisdomShell/llama_cpp_for_codeshell) project provides the 4-bit quantized model service of the [CodeShell](https://github.com/WisdomShell/codeshell) LLM, named `codeshell-chat-q4_0.gguf`. Here are the steps to deploy the model service:
41 |
42 | ### Compile the code
43 |
44 | + Linux / Mac(Apple Silicon Devices)
45 |
46 | ```bash
47 | git clone https://github.com/WisdomShell/llama_cpp_for_codeshell.git
48 | cd llama_cpp_for_codeshell
49 | make
50 | ```
51 |
52 | On macOS, Metal is enabled by default, which allows loading the model onto the GPU for significant performance improvements.
53 |
54 | + Mac(Non Apple Silicon Devices)
55 |
56 | ```bash
57 | git clone https://github.com/WisdomShell/llama_cpp_for_codeshell.git
58 | cd llama_cpp_for_codeshell
59 | LLAMA_NO_METAL=1 make
60 | ```
61 |
62 | For Mac users with non-Apple Silicon chips, you can disable Metal builds during compilation using the CMake options `LLAMA_NO_METAL=1` or `LLAMA_METAL=OFF` to ensure the model runs properly.
63 |
64 | + Windows
65 |
66 | You have the option to compile the code using the Linux approach within the [Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/about) or you can follow the instructions provided in the [llama.cpp repository](https://github.com/ggerganov/llama.cpp#build). Another option is to configure [w64devkit](https://github.com/skeeto/w64devkit/releases) and then proceed with the Linux compilation method.
67 |
68 |
69 | ### Download the model
70 |
71 | On the [Hugging Face Hub](https://huggingface.co/WisdomShell), we provide three different models: [CodeShell-7B](https://huggingface.co/WisdomShell/CodeShell-7B), [CodeShell-7B-Chat](https://huggingface.co/WisdomShell/CodeShell-7B-Chat), and [CodeShell-7B-Chat-int4](https://huggingface.co/WisdomShell/CodeShell-7B-Chat-int4). Below are the steps to download these models.
72 |
73 | - To perform inference using the [CodeShell-7B-Chat-int4](https://huggingface.co/WisdomShell/CodeShell-7B-Chat-int4) model, download the model to your local machine and place it in the path of the `llama_cpp_for_codeshell/models` folder as indicated in the code above.
74 |
75 | ```
76 | git clone https://huggingface.co/WisdomShell/CodeShell-7B-Chat-int4/blob/main/codeshell-chat-q4_0.gguf
77 | ```
78 |
79 | - For performing inference using [CodeShell-7B](https://huggingface.co/WisdomShell/CodeShell-7B) and [CodeShell-7B-Chat](https://huggingface.co/WisdomShell/CodeShell-7B-Chat) models, after placing the models in a local folder, you can utilize [TGI (Text Generation Inference)](https://github.com/WisdomShell/text-generation-inference.git) to load these local models and initiate the model service.
80 |
81 | ### Load the model
82 |
83 | - The `CodeShell-7B-Chat-int4` model can be served as an API using the `server` command within the `llama_cpp_for_codeshell` project.
84 |
85 | ```bash
86 | ./server -m ./models/codeshell-chat-q4_0.gguf --host 127.0.0.1 --port 8080
87 | ```
88 |
89 | Note: In cases where Metal is enabled during compilation, if you encounter runtime exceptions, you can explicitly disable Metal GPU inference by adding the `-ngl 0` parameter in the command line to ensure the proper functioning of the model.
90 |
91 | - [CodeShell-7B](https://huggingface.co/WisdomShell/CodeShell-7B) and [CodeShell-7B-Chat](https://huggingface.co/WisdomShell/CodeShell-7B-Chat) models, loading local models with [TGI](https://github.com/WisdomShell/text-generation-inference.git) and starting the model service.
92 |
93 | ## Model Service [NVIDIA GPU]
94 |
95 | For users wishing to use NVIDIA GPUs for inference, the [`text-generation-inference`](https://github.com/huggingface/text-generation-inference) project can be used to deploy the [CodeShell Large Model](https://github.com/WisdomShell/codeshell). Below are the steps to deploy the model service:
96 |
97 | ### Download the Model
98 |
99 | After downloading the model from the [Hugging Face Hub](https://huggingface.co/WisdomShell/CodeShell-7B-Chat) to your local machine, place the model under the path of the `$HOME/models` folder, and you can load the model locally.
100 |
101 | ```bash
102 | git clone https://huggingface.co/WisdomShell/CodeShell-7B-Chat
103 | ```
104 |
105 | ### Deploy the Model
106 |
107 | The following command can be used for GPU-accelerated inference deployment with text-generation-inference:
108 |
109 | ```bash
110 | docker run --gpus 'all' --shm-size 1g -p 9090:80 -v $HOME/models:/data \
111 | --env LOG_LEVEL="info,text_generation_router=debug" \
112 | ghcr.nju.edu.cn/huggingface/text-generation-inference:1.0.3 \
113 | --model-id /data/CodeShell-7B-Chat --num-shard 1 \
114 | --max-total-tokens 5000 --max-input-length 4096 \
115 | --max-stop-sequences 12 --trust-remote-code
116 | ```
117 |
118 | For a more detailed explanation of the parameters, please refer to the [text-generation-inference project documentation](https://github.com/huggingface/text-generation-inference).
119 |
120 | ## Configure the Plugin
121 |
122 | - Set the address for the CodeShell service
123 | - Configure whether to enable automatic code completion suggestions
124 | - Specify the maximum number of tokens for code completion
125 | - Specify the maximum number of tokens for Q&A
126 | - Configure the model runtime environment
127 |
128 | Note: Different model runtime environments can be configured within the plugin. For the [CodeShell-7B-Chat-int4](https://huggingface.co/WisdomShell/CodeShell-7B-Chat-int4) model, you can choose the `Model Runtime Environment`option in the `Use CPU Mode(with llama.cpp)` menu. However, for the [CodeShell-7B](https://huggingface.co/WisdomShell/CodeShell-7B) and [CodeShell-7B-Chat](https://huggingface.co/WisdomShell/CodeShell-7B-Chat) models, you should select the `Use GPU Model(with TGI framework)` option.
129 |
130 | 
131 |
132 | ## Features
133 |
134 | ### 1. Code Completion
135 |
136 | - Automatic Code Suggestions
137 |
138 | During coding, when you stop typing, code suggestions will automatically trigger.
139 |
140 | When the plugin provides code suggestions, they are displayed in gray at the editor's cursor location. You can press the Tab key to accept the suggestion or continue typing to ignore it.
141 |
142 | 
143 |
144 | ### 2. Code Assistance
145 |
146 | - Explain/Optimize/Cleanse a Code Segment
147 | - Generate Comments/Unit Tests for Code
148 | - Check Code for Performance/Security Issues
149 |
150 | In the IDE sidebar, open the plugin's Q&A interface. Select a portion of code in the editor, right-click to access the CodeShell menu, and choose the corresponding function. The plugin will provide relevant responses in the Q&A interface.
151 |
152 | 
153 |
154 | ### 3. Code Q&A
155 |
156 | - Edit Questions and Rephrase Inquiries
157 | - Request Fresh Responses for Any Question
158 | - Interrupt During the Answering Process
159 |
160 | 
161 |
162 | Within the Q&A interface's code block, you can click the copy button to copy the code block or use the insert button to insert the code block's content at the editor's cursor location.
163 |
164 | ## License
165 |
166 | Apache 2.0
167 |
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("java")
3 | id("org.jetbrains.intellij") version "1.13.3"
4 | }
5 |
6 | group = "com.codeshell.intellij"
7 | version = "0.0.3"
8 |
9 | repositories {
10 | mavenCentral()
11 | }
12 |
13 | dependencies {
14 | implementation("cn.hutool:hutool-all:5.8.22")
15 | implementation("com.alibaba.fastjson2:fastjson2:2.0.41")
16 | }
17 |
18 | intellij {
19 | version.set("2022.2.5")
20 | type.set("IC")
21 | }
22 |
23 | tasks {
24 | withType {
25 | sourceCompatibility = "17"
26 | targetCompatibility = "17"
27 | options.encoding = "UTF-8"
28 | }
29 |
30 | patchPluginXml {
31 | sinceBuild.set("222")
32 | untilBuild.set("232.*")
33 | }
34 |
35 | signPlugin {
36 | certificateChain.set(System.getenv("CERTIFICATE_CHAIN"))
37 | privateKey.set(System.getenv("PRIVATE_KEY"))
38 | password.set(System.getenv("PRIVATE_KEY_PASSWORD"))
39 | }
40 |
41 | publishPlugin {
42 | token.set(System.getenv("PUBLISH_TOKEN"))
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.stdlib.default.dependency=false
2 | # TODO temporary workaround for Kotlin 1.8.20+ (https://jb.gg/intellij-platform-kotlin-oom)
3 | kotlin.incremental.useClasspathSnapshot=false
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WisdomShell/codeshell-intellij/62ffd71bea45989a973288d8f6c7fa98071758ee/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Use "xargs" to parse quoted args.
209 | #
210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
211 | #
212 | # In Bash we could simply go:
213 | #
214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
215 | # set -- "${ARGS[@]}" "$@"
216 | #
217 | # but POSIX shell has neither arrays nor command substitution, so instead we
218 | # post-process each arg (as a line of input to sed) to backslash-escape any
219 | # character that might be a shell metacharacter, then use eval to reverse
220 | # that process (while maintaining the separation between arguments), and wrap
221 | # the whole thing up as a single "set" statement.
222 | #
223 | # This will of course break if any of these variables contains a newline or
224 | # an unmatched quote.
225 | #
226 |
227 | eval "set -- $(
228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
229 | xargs -n1 |
230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
231 | tr '\n' ' '
232 | )" '"$@"'
233 |
234 | exec "$JAVACMD" "$@"
235 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | mavenCentral()
4 | gradlePluginPortal()
5 | }
6 | }
7 |
8 | rootProject.name = "CodeShell"
9 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/assistants/CleanCode.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.assistants;
2 |
3 | import com.codeshell.intellij.constant.PrefixString;
4 | import com.codeshell.intellij.services.CodeShellSideWindowService;
5 | import com.codeshell.intellij.utils.EditorUtils;
6 | import com.google.gson.JsonObject;
7 | import com.intellij.codeInsight.intention.IntentionAction;
8 | import com.intellij.codeInspection.util.IntentionFamilyName;
9 | import com.intellij.codeInspection.util.IntentionName;
10 | import com.intellij.openapi.actionSystem.AnActionEvent;
11 | import com.intellij.openapi.actionSystem.CommonDataKeys;
12 | import com.intellij.openapi.actionSystem.LangDataKeys;
13 | import com.intellij.openapi.application.ApplicationManager;
14 | import com.intellij.openapi.application.ModalityState;
15 | import com.intellij.openapi.diagnostic.Logger;
16 | import com.intellij.openapi.editor.Editor;
17 | import com.intellij.openapi.project.DumbAwareAction;
18 | import com.intellij.openapi.project.Project;
19 | import com.intellij.openapi.vfs.VirtualFile;
20 | import com.intellij.openapi.wm.ToolWindowManager;
21 | import com.intellij.psi.PsiFile;
22 | import com.intellij.util.IncorrectOperationException;
23 | import org.jetbrains.annotations.NotNull;
24 |
25 | import java.util.Objects;
26 |
27 | public class CleanCode extends DumbAwareAction implements IntentionAction {
28 |
29 | @SafeFieldForPreview
30 | private Logger logger = Logger.getInstance(this.getClass());
31 |
32 | @Override
33 | @IntentionName
34 | @NotNull
35 | public String getText() {
36 | return "Clean Code";
37 | }
38 |
39 | @Override
40 | @NotNull
41 | @IntentionFamilyName
42 | public String getFamilyName() {
43 | return "CodeShell";
44 | }
45 |
46 | @Override
47 | public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
48 | return false;
49 | }
50 |
51 | @Override
52 | public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
53 |
54 | }
55 |
56 | @Override
57 | public boolean startInWriteAction() {
58 | return true;
59 | }
60 |
61 | @Override
62 | public void actionPerformed(@NotNull AnActionEvent e) {
63 | Project project = e.getData(LangDataKeys.PROJECT);
64 | if (Objects.isNull(project)) {
65 | return;
66 | }
67 | ApplicationManager.getApplication().invokeLater(() -> {
68 | VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
69 | Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
70 | if (EditorUtils.isNoneTextSelected(editor)) {
71 | return;
72 | }
73 | PsiFile psiFile = e.getRequiredData(CommonDataKeys.PSI_FILE);
74 | JsonObject jsonObject = EditorUtils.getFileSelectionDetails(editor, psiFile, true, PrefixString.CLEAN_CODE);
75 | JsonObject result = new JsonObject();
76 | ToolWindowManager tool = ToolWindowManager.getInstance(project);
77 | Objects.requireNonNull(tool.getToolWindow("CodeShell")).activate(() -> {
78 | if(logger.isDebugEnabled()){
79 | logger.debug("******************* CleanCode Enabled CodeShell window *******************");
80 | }
81 | }, true, true);
82 | jsonObject.addProperty("fileName", vf.getName());
83 | jsonObject.addProperty("filePath", vf.getCanonicalPath());
84 | result.addProperty("data", jsonObject.toString());
85 | (project.getService(CodeShellSideWindowService.class)).notifyIdeAppInstance(result);
86 | }, ModalityState.NON_MODAL);
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/assistants/ExplainCode.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.assistants;
2 |
3 | import com.codeshell.intellij.constant.PrefixString;
4 | import com.codeshell.intellij.services.CodeShellSideWindowService;
5 | import com.codeshell.intellij.utils.EditorUtils;
6 | import com.google.gson.JsonObject;
7 | import com.intellij.codeInsight.intention.IntentionAction;
8 | import com.intellij.codeInspection.util.IntentionFamilyName;
9 | import com.intellij.codeInspection.util.IntentionName;
10 | import com.intellij.openapi.actionSystem.AnActionEvent;
11 | import com.intellij.openapi.actionSystem.CommonDataKeys;
12 | import com.intellij.openapi.actionSystem.LangDataKeys;
13 | import com.intellij.openapi.application.ApplicationManager;
14 | import com.intellij.openapi.application.ModalityState;
15 | import com.intellij.openapi.diagnostic.Logger;
16 | import com.intellij.openapi.editor.Editor;
17 | import com.intellij.openapi.project.DumbAwareAction;
18 | import com.intellij.openapi.project.Project;
19 | import com.intellij.openapi.vfs.VirtualFile;
20 | import com.intellij.openapi.wm.ToolWindowManager;
21 | import com.intellij.psi.PsiFile;
22 | import com.intellij.util.IncorrectOperationException;
23 | import org.jetbrains.annotations.NotNull;
24 |
25 | import java.util.Objects;
26 |
27 | public class ExplainCode extends DumbAwareAction implements IntentionAction {
28 |
29 | @SafeFieldForPreview
30 | private Logger logger = Logger.getInstance(this.getClass());
31 |
32 | @Override
33 | @IntentionName
34 | @NotNull
35 | public String getText() {
36 | return "Explain Code";
37 | }
38 |
39 | @Override
40 | @NotNull
41 | @IntentionFamilyName
42 | public String getFamilyName() {
43 | return "CodeShell";
44 | }
45 |
46 | @Override
47 | public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
48 | return false;
49 | }
50 |
51 | @Override
52 | public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
53 |
54 | }
55 |
56 | @Override
57 | public boolean startInWriteAction() {
58 | return true;
59 | }
60 |
61 | @Override
62 | public void actionPerformed(@NotNull AnActionEvent e) {
63 | Project project = e.getData(LangDataKeys.PROJECT);
64 | if (Objects.isNull(project)) {
65 | return;
66 | }
67 | ApplicationManager.getApplication().invokeLater(() -> {
68 | VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
69 | Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
70 | if (EditorUtils.isNoneTextSelected(editor)) {
71 | return;
72 | }
73 | PsiFile psiFile = e.getRequiredData(CommonDataKeys.PSI_FILE);
74 | JsonObject jsonObject = EditorUtils.getFileSelectionDetails(editor, psiFile, true, PrefixString.EXPLAIN_CODE);
75 | JsonObject result = new JsonObject();
76 | ToolWindowManager tool = ToolWindowManager.getInstance(project);
77 | Objects.requireNonNull(tool.getToolWindow("CodeShell")).activate(()-> {
78 | if (logger.isDebugEnabled()) {
79 | logger.debug("******************* ExplainCode Enabled CodeShell window *******************");
80 | }
81 | } , true, true);
82 | jsonObject.addProperty("fileName", vf.getName());
83 | jsonObject.addProperty("filePath", vf.getCanonicalPath());
84 | result.addProperty("data", jsonObject.toString());
85 | (project.getService(CodeShellSideWindowService.class)).notifyIdeAppInstance(result);
86 | }, ModalityState.NON_MODAL);
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/assistants/GenerateComment.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.assistants;
2 |
3 | import com.codeshell.intellij.constant.PrefixString;
4 | import com.codeshell.intellij.services.CodeShellSideWindowService;
5 | import com.codeshell.intellij.utils.EditorUtils;
6 | import com.google.gson.JsonObject;
7 | import com.intellij.codeInsight.intention.IntentionAction;
8 | import com.intellij.codeInspection.util.IntentionFamilyName;
9 | import com.intellij.codeInspection.util.IntentionName;
10 | import com.intellij.openapi.actionSystem.AnActionEvent;
11 | import com.intellij.openapi.actionSystem.CommonDataKeys;
12 | import com.intellij.openapi.actionSystem.LangDataKeys;
13 | import com.intellij.openapi.application.ApplicationManager;
14 | import com.intellij.openapi.application.ModalityState;
15 | import com.intellij.openapi.diagnostic.Logger;
16 | import com.intellij.openapi.editor.Editor;
17 | import com.intellij.openapi.project.DumbAwareAction;
18 | import com.intellij.openapi.project.Project;
19 | import com.intellij.openapi.vfs.VirtualFile;
20 | import com.intellij.openapi.wm.ToolWindowManager;
21 | import com.intellij.psi.PsiFile;
22 | import com.intellij.util.IncorrectOperationException;
23 | import org.jetbrains.annotations.NotNull;
24 |
25 | import java.util.Objects;
26 |
27 | public class GenerateComment extends DumbAwareAction implements IntentionAction {
28 |
29 | @SafeFieldForPreview
30 | private Logger logger = Logger.getInstance(this.getClass());
31 |
32 | @Override
33 | @IntentionName
34 | @NotNull
35 | public String getText() {
36 | return "Generate Comment";
37 | }
38 |
39 | @Override
40 | @NotNull
41 | @IntentionFamilyName
42 | public String getFamilyName() {
43 | return "CodeShell";
44 | }
45 |
46 | @Override
47 | public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
48 | return false;
49 | }
50 |
51 | @Override
52 | public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
53 |
54 | }
55 |
56 | @Override
57 | public boolean startInWriteAction() {
58 | return true;
59 | }
60 |
61 | @Override
62 | public void actionPerformed(@NotNull AnActionEvent e) {
63 | Project project = e.getData(LangDataKeys.PROJECT);
64 | if (Objects.isNull(project)) {
65 | return;
66 | }
67 | ApplicationManager.getApplication().invokeLater(() -> {
68 | VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
69 | Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
70 | if (EditorUtils.isNoneTextSelected(editor)) {
71 | return;
72 | }
73 | PsiFile psiFile = e.getRequiredData(CommonDataKeys.PSI_FILE);
74 | JsonObject jsonObject = EditorUtils.getFileSelectionDetails(editor, psiFile, true, PrefixString.COMMENT_CODE);
75 | JsonObject result = new JsonObject();
76 | ToolWindowManager tool = ToolWindowManager.getInstance(project);
77 | Objects.requireNonNull(tool.getToolWindow("CodeShell")).activate(() ->{
78 | if(logger.isDebugEnabled()){
79 | logger.debug("******************* GenerateComment Enabled CodeShell window *******************");
80 | }
81 | }, true, true);
82 | jsonObject.addProperty("fileName", vf.getName());
83 | jsonObject.addProperty("filePath", vf.getCanonicalPath());
84 | result.addProperty("data", jsonObject.toString());
85 | (project.getService(CodeShellSideWindowService.class)).notifyIdeAppInstance(result);
86 | }, ModalityState.NON_MODAL);
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/assistants/GenerateUnitTests.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.assistants;
2 |
3 | import com.codeshell.intellij.constant.PrefixString;
4 | import com.codeshell.intellij.services.CodeShellSideWindowService;
5 | import com.codeshell.intellij.utils.EditorUtils;
6 | import com.google.gson.JsonObject;
7 | import com.intellij.codeInsight.intention.IntentionAction;
8 | import com.intellij.codeInspection.util.IntentionFamilyName;
9 | import com.intellij.codeInspection.util.IntentionName;
10 | import com.intellij.openapi.actionSystem.AnActionEvent;
11 | import com.intellij.openapi.actionSystem.CommonDataKeys;
12 | import com.intellij.openapi.actionSystem.LangDataKeys;
13 | import com.intellij.openapi.application.ApplicationManager;
14 | import com.intellij.openapi.application.ModalityState;
15 | import com.intellij.openapi.diagnostic.Logger;
16 | import com.intellij.openapi.editor.Editor;
17 | import com.intellij.openapi.project.DumbAwareAction;
18 | import com.intellij.openapi.project.Project;
19 | import com.intellij.openapi.vfs.VirtualFile;
20 | import com.intellij.openapi.wm.ToolWindowManager;
21 | import com.intellij.psi.PsiFile;
22 | import com.intellij.util.IncorrectOperationException;
23 | import org.jetbrains.annotations.NotNull;
24 |
25 | import java.util.Objects;
26 |
27 | public class GenerateUnitTests extends DumbAwareAction implements IntentionAction {
28 |
29 | @SafeFieldForPreview
30 | private Logger logger = Logger.getInstance(this.getClass());
31 |
32 | @Override
33 | @IntentionName
34 | @NotNull
35 | public String getText() {
36 | return "Generate Unit Tests";
37 | }
38 |
39 | @Override
40 | @NotNull
41 | @IntentionFamilyName
42 | public String getFamilyName() {
43 | return "CodeShell";
44 | }
45 |
46 | @Override
47 | public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
48 | return false;
49 | }
50 |
51 | @Override
52 | public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
53 |
54 | }
55 |
56 | @Override
57 | public boolean startInWriteAction() {
58 | return true;
59 | }
60 |
61 | @Override
62 | public void actionPerformed(@NotNull AnActionEvent e) {
63 | Project project = e.getData(LangDataKeys.PROJECT);
64 | if (Objects.isNull(project)) {
65 | return;
66 | }
67 | ApplicationManager.getApplication().invokeLater(() -> {
68 | VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
69 | Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
70 | if (EditorUtils.isNoneTextSelected(editor)) {
71 | return;
72 | }
73 | PsiFile psiFile = e.getRequiredData(CommonDataKeys.PSI_FILE);
74 | JsonObject json = EditorUtils.getFileSelectionDetails(editor, psiFile, true, PrefixString.UNIT_TEST_CODE);
75 | JsonObject result = new JsonObject();
76 | ToolWindowManager tool = ToolWindowManager.getInstance(project);
77 | Objects.requireNonNull(tool.getToolWindow("CodeShell")).activate(() -> {
78 | if(logger.isDebugEnabled()){
79 | logger.debug("******************* UnitTestCode Enabled CodeShell window *******************");
80 | }
81 | }, true, true);
82 | json.addProperty("fileName", vf.getName());
83 | json.addProperty("filePath", vf.getCanonicalPath());
84 | result.addProperty("data", json.toString());
85 | (project.getService(CodeShellSideWindowService.class)).notifyIdeAppInstance(result);
86 | }, ModalityState.NON_MODAL);
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/assistants/InsertCode.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.assistants;
2 |
3 | import com.codeshell.intellij.constant.PrefixString;
4 | import com.codeshell.intellij.services.CodeShellSideWindowService;
5 | import com.codeshell.intellij.utils.EditorUtils;
6 | import com.google.gson.JsonObject;
7 | import com.intellij.codeInsight.intention.FileModifier;
8 | import com.intellij.openapi.actionSystem.AnAction;
9 | import com.intellij.openapi.actionSystem.AnActionEvent;
10 | import com.intellij.openapi.actionSystem.CommonDataKeys;
11 | import com.intellij.openapi.actionSystem.LangDataKeys;
12 | import com.intellij.openapi.application.ApplicationManager;
13 | import com.intellij.openapi.application.ModalityState;
14 | import com.intellij.openapi.diagnostic.Logger;
15 | import com.intellij.openapi.editor.Editor;
16 | import com.intellij.openapi.project.Project;
17 | import com.intellij.openapi.vfs.VirtualFile;
18 | import com.intellij.openapi.wm.ToolWindowManager;
19 | import com.intellij.psi.PsiFile;
20 | import org.jetbrains.annotations.NotNull;
21 |
22 | import java.util.Objects;
23 |
24 | public class InsertCode extends AnAction {
25 |
26 | @FileModifier.SafeFieldForPreview
27 | private Logger logger = Logger.getInstance(this.getClass());
28 |
29 | @Override
30 | public void actionPerformed(@NotNull AnActionEvent e) {
31 | Project project = e.getData(LangDataKeys.PROJECT);
32 | if (Objects.isNull(project)) {
33 | return;
34 | }
35 | ApplicationManager.getApplication().invokeLater(() -> {
36 | VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
37 | Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
38 | if (EditorUtils.isNoneTextSelected(editor)) {
39 | return;
40 | }
41 | PsiFile psiFile = e.getRequiredData(CommonDataKeys.PSI_FILE);
42 | JsonObject jsonObject = EditorUtils.getFileSelectionDetails(editor, psiFile, true, PrefixString.COMMENT_CODE);
43 | JsonObject result = new JsonObject();
44 | ToolWindowManager tool = ToolWindowManager.getInstance(project);
45 | Objects.requireNonNull(tool.getToolWindow("CodeShell")).activate(() -> {
46 | if(logger.isDebugEnabled()){
47 | logger.debug("******************* InsertCode Enabled CodeShell window *******************");
48 | }
49 | }, true, true);
50 | jsonObject.addProperty("fileName", vf.getName());
51 | jsonObject.addProperty("filePath", vf.getCanonicalPath());
52 | result.addProperty("data", jsonObject.toString());
53 | (project.getService(CodeShellSideWindowService.class)).notifyIdeAppInstance(result);
54 | }, ModalityState.NON_MODAL);
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/assistants/OpenDevTools.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.assistants;
2 |
3 |
4 | import com.codeshell.intellij.services.CodeShellSideWindowService;
5 | import com.codeshell.intellij.window.CodeShellSideWindow;
6 | import com.intellij.openapi.actionSystem.AnActionEvent;
7 | import com.intellij.openapi.diagnostic.Logger;
8 | import com.intellij.openapi.project.DumbAwareAction;
9 | import org.jetbrains.annotations.NotNull;
10 |
11 | import java.util.Objects;
12 |
13 | public class OpenDevTools extends DumbAwareAction {
14 | public OpenDevTools() {
15 | }
16 |
17 | @Override
18 | public void actionPerformed(@NotNull AnActionEvent e) {
19 | try {
20 | CodeShellSideWindow codeShellSideWindow = Objects.requireNonNull(e.getProject()).getService(CodeShellSideWindowService.class).getCodeShellSideWindow();
21 | codeShellSideWindow.jbCefBrowser().openDevtools();
22 | } catch (Exception exception) {
23 | Logger.getInstance(this.getClass()).error("openDevtools exception", exception);
24 | }
25 |
26 | }
27 | }
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/assistants/OptimizeCode.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.assistants;
2 |
3 | import com.codeshell.intellij.constant.PrefixString;
4 | import com.codeshell.intellij.services.CodeShellSideWindowService;
5 | import com.codeshell.intellij.utils.EditorUtils;
6 | import com.google.gson.JsonObject;
7 | import com.intellij.codeInsight.intention.IntentionAction;
8 | import com.intellij.codeInspection.util.IntentionFamilyName;
9 | import com.intellij.codeInspection.util.IntentionName;
10 | import com.intellij.openapi.actionSystem.AnActionEvent;
11 | import com.intellij.openapi.actionSystem.CommonDataKeys;
12 | import com.intellij.openapi.actionSystem.LangDataKeys;
13 | import com.intellij.openapi.application.ApplicationManager;
14 | import com.intellij.openapi.application.ModalityState;
15 | import com.intellij.openapi.diagnostic.Logger;
16 | import com.intellij.openapi.editor.Editor;
17 | import com.intellij.openapi.project.DumbAwareAction;
18 | import com.intellij.openapi.project.Project;
19 | import com.intellij.openapi.vfs.VirtualFile;
20 | import com.intellij.openapi.wm.ToolWindowManager;
21 | import com.intellij.psi.PsiFile;
22 | import com.intellij.util.IncorrectOperationException;
23 | import org.jetbrains.annotations.NotNull;
24 |
25 | import java.util.Objects;
26 |
27 | public class OptimizeCode extends DumbAwareAction implements IntentionAction {
28 |
29 | @SafeFieldForPreview
30 | private Logger logger = Logger.getInstance(this.getClass());
31 |
32 | @Override
33 | @IntentionName
34 | @NotNull
35 | public String getText() {
36 | return "Optimize Code";
37 | }
38 |
39 | @Override
40 | @NotNull
41 | @IntentionFamilyName
42 | public String getFamilyName() {
43 | return "CodeShell";
44 | }
45 |
46 | @Override
47 | public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
48 | return false;
49 | }
50 |
51 | @Override
52 | public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
53 |
54 | }
55 |
56 | @Override
57 | public boolean startInWriteAction() {
58 | return true;
59 | }
60 |
61 | @Override
62 | public void actionPerformed(@NotNull AnActionEvent e) {
63 | Project project = e.getData(LangDataKeys.PROJECT);
64 | if (Objects.isNull(project)) {
65 | return;
66 | }
67 | ApplicationManager.getApplication().invokeLater(() -> {
68 | VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
69 | Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
70 | if (EditorUtils.isNoneTextSelected(editor)) {
71 | return;
72 | }
73 | PsiFile psiFile = e.getRequiredData(CommonDataKeys.PSI_FILE);
74 | JsonObject jsonObject = EditorUtils.getFileSelectionDetails(editor, psiFile, true, PrefixString.OPTIMIZE_CODE);
75 | JsonObject result = new JsonObject();
76 | ToolWindowManager tool = ToolWindowManager.getInstance(project);
77 | Objects.requireNonNull(tool.getToolWindow("CodeShell")).activate(() -> {
78 | if(logger.isDebugEnabled()){
79 | logger.debug("******************* OptimizeCode Enabled CodeShell window *******************");
80 | }
81 | }, true, true);
82 | jsonObject.addProperty("fileName", vf.getName());
83 | jsonObject.addProperty("filePath", vf.getCanonicalPath());
84 | result.addProperty("data", jsonObject.toString());
85 | (project.getService(CodeShellSideWindowService.class)).notifyIdeAppInstance(result);
86 | }, ModalityState.NON_MODAL);
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/assistants/PerformanceCheck.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.assistants;
2 |
3 | import com.codeshell.intellij.constant.PrefixString;
4 | import com.codeshell.intellij.services.CodeShellSideWindowService;
5 | import com.codeshell.intellij.utils.EditorUtils;
6 | import com.google.gson.JsonObject;
7 | import com.intellij.codeInsight.intention.IntentionAction;
8 | import com.intellij.codeInspection.util.IntentionFamilyName;
9 | import com.intellij.codeInspection.util.IntentionName;
10 | import com.intellij.openapi.actionSystem.AnActionEvent;
11 | import com.intellij.openapi.actionSystem.CommonDataKeys;
12 | import com.intellij.openapi.actionSystem.LangDataKeys;
13 | import com.intellij.openapi.application.ApplicationManager;
14 | import com.intellij.openapi.application.ModalityState;
15 | import com.intellij.openapi.diagnostic.Logger;
16 | import com.intellij.openapi.editor.Editor;
17 | import com.intellij.openapi.project.DumbAwareAction;
18 | import com.intellij.openapi.project.Project;
19 | import com.intellij.openapi.vfs.VirtualFile;
20 | import com.intellij.openapi.wm.ToolWindowManager;
21 | import com.intellij.psi.PsiFile;
22 | import com.intellij.util.IncorrectOperationException;
23 | import org.jetbrains.annotations.NotNull;
24 |
25 | import java.util.Objects;
26 |
27 | public class PerformanceCheck extends DumbAwareAction implements IntentionAction {
28 |
29 | @SafeFieldForPreview
30 | private Logger logger = Logger.getInstance(this.getClass());
31 |
32 | @Override
33 | @IntentionName
34 | @NotNull
35 | public String getText() {
36 | return "Performance Check";
37 | }
38 |
39 | @Override
40 | @NotNull
41 | @IntentionFamilyName
42 | public String getFamilyName() {
43 | return "CodeShell";
44 | }
45 |
46 | @Override
47 | public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
48 | return false;
49 | }
50 |
51 | @Override
52 | public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
53 |
54 | }
55 |
56 | @Override
57 | public boolean startInWriteAction() {
58 | return true;
59 | }
60 |
61 | @Override
62 | public void actionPerformed(@NotNull AnActionEvent e) {
63 | Project project = e.getData(LangDataKeys.PROJECT);
64 | if (Objects.isNull(project)) {
65 | return;
66 | }
67 | ApplicationManager.getApplication().invokeLater(() -> {
68 | VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
69 | Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
70 | if (EditorUtils.isNoneTextSelected(editor)) {
71 | return;
72 | }
73 | PsiFile psiFile = e.getRequiredData(CommonDataKeys.PSI_FILE);
74 | JsonObject jsonObject = EditorUtils.getFileSelectionDetails(editor, psiFile, true, PrefixString.PERFORMANCE_CODE);
75 | JsonObject result = new JsonObject();
76 | ToolWindowManager tool = ToolWindowManager.getInstance(project);
77 | Objects.requireNonNull(tool.getToolWindow("CodeShell")).activate(() -> {
78 | if(logger.isDebugEnabled()){
79 | logger.debug("******************* PerformanceCode Enabled CodeShell window *******************");
80 | }
81 | }, true, true);
82 | jsonObject.addProperty("fileName", vf.getName());
83 | jsonObject.addProperty("filePath", vf.getCanonicalPath());
84 | result.addProperty("data", jsonObject.toString());
85 | (project.getService(CodeShellSideWindowService.class)).notifyIdeAppInstance(result);
86 | }, ModalityState.NON_MODAL);
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/assistants/SecurityCheck.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.assistants;
2 |
3 | import com.codeshell.intellij.constant.PrefixString;
4 | import com.codeshell.intellij.services.CodeShellSideWindowService;
5 | import com.codeshell.intellij.utils.EditorUtils;
6 | import com.google.gson.JsonObject;
7 | import com.intellij.codeInsight.intention.IntentionAction;
8 | import com.intellij.codeInspection.util.IntentionFamilyName;
9 | import com.intellij.codeInspection.util.IntentionName;
10 | import com.intellij.openapi.actionSystem.AnActionEvent;
11 | import com.intellij.openapi.actionSystem.CommonDataKeys;
12 | import com.intellij.openapi.actionSystem.LangDataKeys;
13 | import com.intellij.openapi.application.ApplicationManager;
14 | import com.intellij.openapi.application.ModalityState;
15 | import com.intellij.openapi.diagnostic.Logger;
16 | import com.intellij.openapi.editor.Editor;
17 | import com.intellij.openapi.project.DumbAwareAction;
18 | import com.intellij.openapi.project.Project;
19 | import com.intellij.openapi.vfs.VirtualFile;
20 | import com.intellij.openapi.wm.ToolWindowManager;
21 | import com.intellij.psi.PsiFile;
22 | import com.intellij.util.IncorrectOperationException;
23 | import org.jetbrains.annotations.NotNull;
24 |
25 | import java.util.Objects;
26 |
27 | public class SecurityCheck extends DumbAwareAction implements IntentionAction {
28 |
29 | @SafeFieldForPreview
30 | private Logger logger = Logger.getInstance(this.getClass());
31 |
32 | @Override
33 | @IntentionName
34 | @NotNull
35 | public String getText() {
36 | return "Security Check";
37 | }
38 |
39 | @Override
40 | @NotNull
41 | @IntentionFamilyName
42 | public String getFamilyName() {
43 | return "CodeShell";
44 | }
45 |
46 | @Override
47 | public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
48 | return false;
49 | }
50 |
51 | @Override
52 | public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
53 |
54 | }
55 |
56 | @Override
57 | public boolean startInWriteAction() {
58 | return true;
59 | }
60 |
61 | @Override
62 | public void actionPerformed(@NotNull AnActionEvent e) {
63 | Project project = e.getData(LangDataKeys.PROJECT);
64 | if (Objects.isNull(project)) {
65 | return;
66 | }
67 | ApplicationManager.getApplication().invokeLater(() -> {
68 | VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
69 | Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
70 | if (EditorUtils.isNoneTextSelected(editor)) {
71 | return;
72 | }
73 | PsiFile psiFile = e.getRequiredData(CommonDataKeys.PSI_FILE);
74 | JsonObject json = EditorUtils.getFileSelectionDetails(editor, psiFile, true, PrefixString.SECURITY_CODE);
75 | JsonObject result = new JsonObject();
76 | ToolWindowManager tool = ToolWindowManager.getInstance(project);
77 | Objects.requireNonNull(tool.getToolWindow("CodeShell")).activate(() -> {
78 | if(logger.isDebugEnabled()){
79 | logger.debug("******************* SecurityCode Enabled CodeShell window *******************");
80 | }
81 | }, true, true);
82 | json.addProperty("fileName", vf.getName());
83 | json.addProperty("filePath", vf.getCanonicalPath());
84 | result.addProperty("data", json.toString());
85 | (project.getService(CodeShellSideWindowService.class)).notifyIdeAppInstance(result);
86 | }, ModalityState.NON_MODAL);
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/assistants/StyleCheck.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.assistants;
2 |
3 | import com.codeshell.intellij.constant.PrefixString;
4 | import com.codeshell.intellij.services.CodeShellSideWindowService;
5 | import com.codeshell.intellij.utils.EditorUtils;
6 | import com.google.gson.JsonObject;
7 | import com.intellij.codeInsight.intention.IntentionAction;
8 | import com.intellij.codeInspection.util.IntentionFamilyName;
9 | import com.intellij.codeInspection.util.IntentionName;
10 | import com.intellij.openapi.actionSystem.AnActionEvent;
11 | import com.intellij.openapi.actionSystem.CommonDataKeys;
12 | import com.intellij.openapi.actionSystem.LangDataKeys;
13 | import com.intellij.openapi.application.ApplicationManager;
14 | import com.intellij.openapi.application.ModalityState;
15 | import com.intellij.openapi.diagnostic.Logger;
16 | import com.intellij.openapi.editor.Editor;
17 | import com.intellij.openapi.project.DumbAwareAction;
18 | import com.intellij.openapi.project.Project;
19 | import com.intellij.openapi.vfs.VirtualFile;
20 | import com.intellij.openapi.wm.ToolWindowManager;
21 | import com.intellij.psi.PsiFile;
22 | import com.intellij.util.IncorrectOperationException;
23 | import org.jetbrains.annotations.NotNull;
24 |
25 | import java.util.Objects;
26 |
27 | public class StyleCheck extends DumbAwareAction implements IntentionAction {
28 |
29 | @SafeFieldForPreview
30 | private Logger logger = Logger.getInstance(this.getClass());
31 |
32 | @Override
33 | @IntentionName
34 | @NotNull
35 | public String getText() {
36 | return "Style Check";
37 | }
38 |
39 | @Override
40 | @NotNull
41 | @IntentionFamilyName
42 | public String getFamilyName() {
43 | return "CodeShell";
44 | }
45 |
46 | @Override
47 | public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
48 | return false;
49 | }
50 |
51 | @Override
52 | public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
53 |
54 | }
55 |
56 | @Override
57 | public boolean startInWriteAction() {
58 | return true;
59 | }
60 |
61 | @Override
62 | public void actionPerformed(@NotNull AnActionEvent e) {
63 | Project project = e.getData(LangDataKeys.PROJECT);
64 | if (Objects.isNull(project)) {
65 | return;
66 | }
67 | ApplicationManager.getApplication().invokeLater(() -> {
68 | VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
69 | Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
70 | if (EditorUtils.isNoneTextSelected(editor)) {
71 | return;
72 | }
73 | PsiFile psiFile = e.getRequiredData(CommonDataKeys.PSI_FILE);
74 | JsonObject json = EditorUtils.getFileSelectionDetails(editor, psiFile, true, PrefixString.STYLE_CODE);
75 | JsonObject result = new JsonObject();
76 | ToolWindowManager tool = ToolWindowManager.getInstance(project);
77 | Objects.requireNonNull(tool.getToolWindow("CodeShell")).activate(() -> {
78 | if(logger.isDebugEnabled()){
79 | logger.debug("******************* StyleCode Enabled CodeShell window *******************");
80 | }
81 | }, true, true);
82 | json.addProperty("fileName", vf.getName());
83 | json.addProperty("filePath", vf.getCanonicalPath());
84 | result.addProperty("data", json.toString());
85 | (project.getService(CodeShellSideWindowService.class)).notifyIdeAppInstance(result);
86 | }, ModalityState.NON_MODAL);
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/complete/CodeGenEscAction.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.complete;
2 |
3 | import com.codeshell.intellij.utils.CodeGenHintRenderer;
4 | import com.codeshell.intellij.widget.CodeShellWidget;
5 | import com.intellij.openapi.actionSystem.CommonDataKeys;
6 | import com.intellij.openapi.actionSystem.DataContext;
7 | import com.intellij.openapi.editor.Caret;
8 | import com.intellij.openapi.editor.Editor;
9 | import com.intellij.openapi.editor.Inlay;
10 | import com.intellij.openapi.editor.InlayModel;
11 | import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
12 | import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler;
13 | import com.intellij.openapi.vfs.VirtualFile;
14 | import org.jetbrains.annotations.NotNull;
15 | import org.jetbrains.annotations.Nullable;
16 |
17 | import java.util.Objects;
18 |
19 | public class CodeGenEscAction extends EditorWriteActionHandler {
20 | protected final EditorActionHandler handler;
21 |
22 | public CodeGenEscAction(EditorActionHandler actionHandler) {
23 | handler = actionHandler;
24 | }
25 |
26 | @Override
27 | public void executeWriteAction(@NotNull Editor editor, @Nullable Caret caret, DataContext dataContext) {
28 | cancelCodeCompletion(editor, caret, dataContext);
29 | }
30 |
31 | private void cancelCodeCompletion(Editor editor, Caret caret, DataContext dataContext) {
32 | VirtualFile file = dataContext.getData(CommonDataKeys.VIRTUAL_FILE);
33 | if (Objects.isNull(file)) {
34 | return;
35 | }
36 | InlayModel inlayModel = editor.getInlayModel();
37 | inlayModel.getInlineElementsInRange(0, editor.getDocument().getTextLength()).forEach(this::disposeInlayHints);
38 | inlayModel.getBlockElementsInRange(0, editor.getDocument().getTextLength()).forEach(this::disposeInlayHints);
39 | CodeShellWidget.enableSuggestion = false;
40 | }
41 |
42 | private void disposeInlayHints(Inlay> inlay) {
43 | if (inlay.getRenderer() instanceof CodeGenHintRenderer) {
44 | inlay.dispose();
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/complete/CodeGenInsertAllAction.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.complete;
2 |
3 | import com.codeshell.intellij.widget.CodeShellWidget;
4 | import com.intellij.openapi.actionSystem.AnAction;
5 | import com.intellij.openapi.actionSystem.AnActionEvent;
6 | import com.intellij.openapi.actionSystem.CommonDataKeys;
7 | import com.intellij.openapi.command.WriteCommandAction;
8 | import com.intellij.openapi.editor.Caret;
9 | import com.intellij.openapi.editor.Editor;
10 | import com.intellij.openapi.vfs.VirtualFile;
11 | import org.jetbrains.annotations.NotNull;
12 |
13 | import java.util.Arrays;
14 | import java.util.Objects;
15 | import java.util.StringJoiner;
16 |
17 | public class CodeGenInsertAllAction extends AnAction {
18 |
19 | @Override
20 | public void actionPerformed(@NotNull AnActionEvent e) {
21 | Editor editor = e.getData(CommonDataKeys.EDITOR);
22 | Caret caret = e.getData(CommonDataKeys.CARET);
23 | VirtualFile file = e.getData(CommonDataKeys.VIRTUAL_FILE);
24 | if (!performAction(editor, caret, file)) {
25 | }
26 | }
27 |
28 | @Override
29 | public void update(@NotNull AnActionEvent e) {
30 | VirtualFile file = e.getData(CommonDataKeys.VIRTUAL_FILE);
31 | if (Objects.isNull(file)) {
32 | return;
33 | }
34 |
35 | String[] hints = file.getUserData(CodeShellWidget.SHELL_CODER_CODE_SUGGESTION);
36 | e.getPresentation().setEnabledAndVisible(Objects.nonNull(hints) && hints.length > 0);
37 | }
38 |
39 | public static boolean performAction(Editor editor, Caret caret, VirtualFile file) {
40 | if (Objects.isNull(file)) {
41 | return false;
42 | }
43 |
44 | String[] hints = file.getUserData(CodeShellWidget.SHELL_CODER_CODE_SUGGESTION);
45 | if (Objects.isNull(hints) || (hints.length == 0)) {
46 | return false;
47 | }
48 |
49 | Integer position = file.getUserData(CodeShellWidget.SHELL_CODER_POSITION);
50 | int lastPosition = Objects.isNull(position) ? 0 : position;
51 | if (Objects.isNull(caret) || (caret.getOffset() != lastPosition)) {
52 | return false;
53 | }
54 |
55 | StringJoiner insertTextJoiner = new StringJoiner("");
56 | Arrays.stream(hints).forEach(insertTextJoiner::add);
57 | file.putUserData(CodeShellWidget.SHELL_CODER_CODE_SUGGESTION, null);
58 |
59 | String insertText = insertTextJoiner.toString();
60 | WriteCommandAction.runWriteCommandAction(editor.getProject(), "CodeShell Insert", null, () -> {
61 | editor.getDocument().insertString(lastPosition, insertText);
62 | editor.getCaretModel().moveToOffset(lastPosition + insertText.length());
63 | });
64 | return true;
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/complete/CodeGenTabAction.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.complete;
2 |
3 | import com.intellij.openapi.actionSystem.CommonDataKeys;
4 | import com.intellij.openapi.actionSystem.DataContext;
5 | import com.intellij.openapi.editor.Caret;
6 | import com.intellij.openapi.editor.Editor;
7 | import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
8 | import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler;
9 | import com.intellij.openapi.vfs.VirtualFile;
10 | import org.jetbrains.annotations.NotNull;
11 | import org.jetbrains.annotations.Nullable;
12 |
13 | public class CodeGenTabAction extends EditorWriteActionHandler {
14 | protected final EditorActionHandler handler;
15 |
16 | public CodeGenTabAction(EditorActionHandler actionHandler) {
17 | handler = actionHandler;
18 | }
19 |
20 | @Override
21 | public void executeWriteAction(@NotNull Editor editor, @Nullable Caret caret, DataContext dataContext) {
22 | if (!insertCodeSuggestion(editor, caret, dataContext)) {
23 | handler.execute(editor, caret, dataContext);
24 | }
25 | }
26 |
27 | private boolean insertCodeSuggestion(Editor editor, Caret caret, DataContext dataContext) {
28 | VirtualFile file = dataContext.getData(CommonDataKeys.VIRTUAL_FILE);
29 | return CodeGenInsertAllAction.performAction(editor, caret, file);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/actions/complete/CodeTriggerCompletionAction.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.actions.complete;
2 |
3 | import com.codeshell.intellij.services.CodeShellCompleteService;
4 | import com.codeshell.intellij.utils.CodeShellUtils;
5 | import com.codeshell.intellij.utils.EditorUtils;
6 | import com.codeshell.intellij.widget.CodeShellWidget;
7 | import com.intellij.codeInsight.intention.IntentionAction;
8 | import com.intellij.codeInspection.util.IntentionFamilyName;
9 | import com.intellij.codeInspection.util.IntentionName;
10 | import com.intellij.openapi.actionSystem.AnActionEvent;
11 | import com.intellij.openapi.actionSystem.CommonDataKeys;
12 | import com.intellij.openapi.application.ApplicationManager;
13 | import com.intellij.openapi.diagnostic.Logger;
14 | import com.intellij.openapi.editor.Editor;
15 | import com.intellij.openapi.editor.InlayModel;
16 | import com.intellij.openapi.fileEditor.FileDocumentManager;
17 | import com.intellij.openapi.project.DumbAwareAction;
18 | import com.intellij.openapi.project.Project;
19 | import com.intellij.openapi.vfs.VirtualFile;
20 | import com.intellij.psi.PsiFile;
21 | import com.intellij.util.IncorrectOperationException;
22 | import org.jetbrains.annotations.NotNull;
23 |
24 | import java.util.Objects;
25 | import java.util.concurrent.CompletableFuture;
26 |
27 | public class CodeTriggerCompletionAction extends DumbAwareAction implements IntentionAction {
28 |
29 | @SafeFieldForPreview
30 | private Logger logger = Logger.getInstance(this.getClass());
31 |
32 | @Override
33 | @IntentionName
34 | @NotNull
35 | public String getText() {
36 | return "Trigger Completion";
37 | }
38 |
39 | @Override
40 | @NotNull
41 | @IntentionFamilyName
42 | public String getFamilyName() {
43 | return "CodeShell";
44 | }
45 |
46 | @Override
47 | public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
48 | return false;
49 | }
50 |
51 | @Override
52 | public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
53 |
54 | }
55 |
56 | @Override
57 | public boolean startInWriteAction() {
58 | return true;
59 | }
60 |
61 | @Override
62 | public void actionPerformed(@NotNull AnActionEvent e) {
63 | Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
64 | updateInlayHints(editor);
65 | // Project project = e.getData(LangDataKeys.PROJECT);
66 | // if (Objects.isNull(project)) {
67 | // return;
68 | // }
69 | // ApplicationManager.getApplication().invokeLater(() -> {
70 | // VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
71 | // Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
72 | // if (EditorUtils.isNoneTextSelected(editor)) {
73 | // return;
74 | // }
75 | // PsiFile psiFile = e.getRequiredData(CommonDataKeys.PSI_FILE);
76 | // JsonObject jsonObject = EditorUtils.getFileSelectionDetails(editor, psiFile, true, PrefixString.CLEAN_CODE);
77 | // JsonObject result = new JsonObject();
78 | // ToolWindowManager tool = ToolWindowManager.getInstance(project);
79 | // Objects.requireNonNull(tool.getToolWindow("CodeShell")).activate(() -> {
80 | // if(logger.isDebugEnabled()){
81 | // logger.debug("******************* CleanCode Enabled CodeShell window *******************");
82 | // }
83 | // }, true, true);
84 | // jsonObject.addProperty("fileName", vf.getName());
85 | // jsonObject.addProperty("filePath", vf.getCanonicalPath());
86 | // result.addProperty("data", jsonObject.toString());
87 | // (project.getService(CodeShellSideWindowService.class)).notifyIdeAppInstance(result);
88 | // }, ModalityState.NON_MODAL);
89 | }
90 |
91 | private void updateInlayHints(Editor focusedEditor) {
92 | if (Objects.isNull(focusedEditor) || !EditorUtils.isMainEditor(focusedEditor)) {
93 | return;
94 | }
95 | VirtualFile file = FileDocumentManager.getInstance().getFile(focusedEditor.getDocument());
96 | if (Objects.isNull(file)) {
97 | return;
98 | }
99 |
100 | String selection = focusedEditor.getCaretModel().getCurrentCaret().getSelectedText();
101 | if (Objects.nonNull(selection) && !selection.isEmpty()) {
102 | String[] existingHints = file.getUserData(CodeShellWidget.SHELL_CODER_CODE_SUGGESTION);
103 | if (Objects.nonNull(existingHints) && existingHints.length > 0) {
104 | file.putUserData(CodeShellWidget.SHELL_CODER_CODE_SUGGESTION, null);
105 | file.putUserData(CodeShellWidget.SHELL_CODER_POSITION, focusedEditor.getCaretModel().getOffset());
106 |
107 | InlayModel inlayModel = focusedEditor.getInlayModel();
108 | inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
109 | inlayModel.getBlockElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
110 | }
111 | return;
112 | }
113 |
114 | Integer codeShellPos = file.getUserData(CodeShellWidget.SHELL_CODER_POSITION);
115 | int currentPosition = focusedEditor.getCaretModel().getOffset();
116 |
117 | InlayModel inlayModel = focusedEditor.getInlayModel();
118 | inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
119 | inlayModel.getBlockElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
120 | file.putUserData(CodeShellWidget.SHELL_CODER_POSITION, currentPosition);
121 | CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);
122 | CharSequence editorContents = focusedEditor.getDocument().getCharsSequence();
123 | CompletableFuture future = CompletableFuture.supplyAsync(() -> codeShell.getCodeCompletionHints(editorContents, currentPosition));
124 | future.thenAccept(hintList -> CodeShellUtils.addCodeSuggestion(focusedEditor, file, currentPosition, hintList));
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/constant/ConnectionParams.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.constant;
2 |
3 | public interface ConnectionParams {
4 |
5 | int CONNECTION_TIMEOUT = 2000;
6 |
7 | int READ_TIMEOUT = 8000;
8 |
9 | int GET_CONNECTION_TIMEOUT = 1500;
10 | }
11 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/constant/PrefixString.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.constant;
2 |
3 | public interface PrefixString {
4 |
5 | String EXPLAIN_CODE = "请解释以下%s代码: %s";
6 |
7 | String OPTIMIZE_CODE = "请优化以下%s代码: %s";
8 |
9 | String CLEAN_CODE = "请清理以下%s代码: %s";
10 |
11 | String COMMENT_CODE = "请为以下%s代码的每一行生成注释: %s";
12 |
13 | String UNIT_TEST_CODE = "请为以下%s代码生成单元测试: %s";
14 |
15 | String PERFORMANCE_CODE = "检查以下%s代码,是否存在性能问题,请给出优化建议: %s";
16 |
17 | String STYLE_CODE = "检查以下%s代码的风格样式,请给出优化建议: %s";
18 |
19 | String SECURITY_CODE = "检查以下%s代码,是否存在安全性问题,请给出优化建议: %s";
20 |
21 | String MARKDOWN_CODE_FIX = "```";
22 |
23 | String REQUST_END_TAG = "||";
24 |
25 | String RESPONSE_END_TAG = "<|endoftext|>";
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/enums/ChatMaxToken.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.enums;
2 |
3 | public enum ChatMaxToken {
4 | LOW("1024"),
5 | MEDIUM("2048"),
6 | HIGH("4096"),
7 | ULTRA("8192");
8 |
9 | private final String description;
10 |
11 | ChatMaxToken(String description) {
12 | this.description = description;
13 | }
14 |
15 | public String getDescription() {
16 | return description;
17 | }
18 |
19 | @Override
20 | public String toString() {
21 | return description;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/enums/CodeShellStatus.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.enums;
2 |
3 | import java.util.stream.Stream;
4 |
5 | public enum CodeShellStatus {
6 | UNKNOWN(0, "Unknown"),
7 | OK(200, "OK"),
8 | BAD_REQUEST(400, "Bad request/token"),
9 | NOT_FOUND(404, "404 Not found"),
10 | TOO_MANY_REQUESTS(429, "Too many requests right now");
11 |
12 | private final int code;
13 | private final String displayValue;
14 |
15 | CodeShellStatus(int i, String s) {
16 | code = i;
17 | displayValue = s;
18 | }
19 |
20 | public int getCode() {
21 | return code;
22 | }
23 |
24 | public String getDisplayValue() {
25 | return displayValue;
26 | }
27 |
28 | public static CodeShellStatus getStatusByCode(int code) {
29 | return Stream.of(CodeShellStatus.values())
30 | .filter(s -> s.getCode() == code)
31 | .findFirst()
32 | .orElse(CodeShellStatus.UNKNOWN);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/enums/CodeShellURI.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.enums;
2 |
3 | public enum CodeShellURI {
4 |
5 | CPU_COMPLETE("/infill"),
6 | CPU_CHAT("/completion"),
7 | GPU_COMPLETE("/generate"),
8 | GPU_CHAT("/generate_stream");
9 |
10 | private final String uri;
11 |
12 | CodeShellURI(String uri) {
13 | this.uri = uri;
14 | }
15 |
16 | public String getUri() {
17 | return uri;
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/enums/CompletionMaxToken.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.enums;
2 |
3 | public enum CompletionMaxToken {
4 |
5 | LOW("32"),
6 | MEDIUM("64"),
7 | HIGH("128"),
8 | ULTRA("256");
9 |
10 | private final String description;
11 |
12 | CompletionMaxToken(String description) {
13 | this.description = description;
14 | }
15 |
16 | public String getDescription() {
17 | return description;
18 | }
19 |
20 | @Override
21 | public String toString() {
22 | return description;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/enums/TabActionOption.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.enums;
2 |
3 | public enum TabActionOption {
4 | ALL("All suggestions");
5 |
6 | private final String description;
7 |
8 | TabActionOption(String description) {
9 | this.description = description;
10 | }
11 |
12 | @Override
13 | public String toString() {
14 | return description;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/handlers/ClosedConnection.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.handlers;
2 |
3 | import org.cef.callback.CefCallback;
4 | import org.cef.misc.IntRef;
5 | import org.cef.misc.StringRef;
6 | import org.cef.network.CefResponse;
7 |
8 | import java.io.IOException;
9 |
10 | public class ClosedConnection implements ResourceHandlerState {
11 | @Override
12 | public void getResponseHeaders(CefResponse cefResponse, IntRef responseLength, StringRef redirectUrl) {
13 | cefResponse.setStatus(404);
14 | }
15 |
16 | @Override
17 | public Boolean readResponse(byte[] paramArrayOfByte, int designedBytesToRead, IntRef bytesRead, CefCallback callback) throws IOException {
18 | return Boolean.FALSE;
19 | }
20 |
21 | @Override
22 | public void close() throws IOException {
23 | }
24 | }
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/handlers/CustomResourceHandler.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.handlers;
2 |
3 | import com.intellij.openapi.diagnostic.Logger;
4 | import com.intellij.openapi.project.Project;
5 | import org.cef.callback.CefCallback;
6 | import org.cef.handler.CefResourceHandler;
7 | import org.cef.misc.IntRef;
8 | import org.cef.misc.StringRef;
9 | import org.cef.network.CefRequest;
10 | import org.cef.network.CefResponse;
11 | import org.jetbrains.annotations.NotNull;
12 |
13 | import java.io.IOException;
14 | import java.net.URL;
15 | import java.util.Objects;
16 | import java.util.regex.Pattern;
17 |
18 |
19 | public class CustomResourceHandler implements CefResourceHandler {
20 |
21 | private final Logger logger = Logger.getInstance(this.getClass());
22 |
23 | private final Project project;
24 |
25 | private ResourceHandlerState resourceHandlerState;
26 |
27 | public CustomResourceHandler(@NotNull Project project) {
28 | this.project = project;
29 | }
30 |
31 | private void setResourceHandlerState(ResourceHandlerState resourceHandlerState) {
32 | this.resourceHandlerState = resourceHandlerState;
33 | }
34 |
35 | private ResourceHandlerState getResourceHandlerState() {
36 | return this.resourceHandlerState;
37 | }
38 |
39 | @Override
40 | public boolean processRequest(CefRequest request, CefCallback callback) {
41 | boolean isRequestProcessed;
42 | try {
43 | URL destURL;
44 | String url = request.getURL();
45 | String[] resourcePath = url.replace("http://codeshell/", "webview/").split(Pattern.quote("?"));
46 | String pathToResource = (resourcePath.length > 0) ? resourcePath[0] : "webview/index.html";
47 | URL newUrl = getClass().getClassLoader().getResource(pathToResource);
48 | if (Objects.nonNull(newUrl)) {
49 | if (resourcePath.length > 1) {
50 | destURL = new URL(newUrl + "#/?" + resourcePath[1]);
51 | } else {
52 | destURL = newUrl;
53 | }
54 | } else {
55 | destURL = getClass().getClassLoader().getResource("webview/index.html");
56 | }
57 | OpenedConnection openedConnection = new OpenedConnection((Objects.requireNonNull(destURL)).openConnection());
58 | setResourceHandlerState(openedConnection);
59 | callback.Continue();
60 | isRequestProcessed = true;
61 | } catch (IOException e) {
62 | logger.error("JBCefBrowser# request failed:{}", e);
63 | isRequestProcessed = false;
64 | }
65 | return isRequestProcessed;
66 | }
67 |
68 | @Override
69 | public void getResponseHeaders(CefResponse response, IntRef responseLength, StringRef redirectUrl) {
70 | getResourceHandlerState().getResponseHeaders(response, responseLength, redirectUrl);
71 | }
72 |
73 | @Override
74 | public boolean readResponse(byte[] dataOut, int bytesToRead, IntRef bytesRead, CefCallback callback) {
75 | boolean isResponseRead;
76 | try {
77 | isResponseRead = getResourceHandlerState().readResponse(dataOut, bytesToRead, bytesRead, callback);
78 | } catch (IOException e) {
79 | logger.error("JBCefBrowser# readResponse failed:{}", e);
80 | isResponseRead = false;
81 | }
82 | return isResponseRead;
83 | }
84 |
85 | @Override
86 | public void cancel() {
87 | try {
88 | getResourceHandlerState().close();
89 | setResourceHandlerState(null);
90 | } catch (IOException e) {
91 | logger.error("JBCefBrowser# cancel failed:{}", e);
92 | }
93 |
94 | }
95 | }
96 |
97 |
98 |
99 |
100 |
101 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/handlers/CustomSchemeHandlerFactory.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.handlers;
2 |
3 | import com.intellij.openapi.project.Project;
4 | import org.cef.browser.CefBrowser;
5 | import org.cef.browser.CefFrame;
6 | import org.cef.callback.CefSchemeHandlerFactory;
7 | import org.cef.handler.CefResourceHandler;
8 | import org.cef.network.CefRequest;
9 | import org.jetbrains.annotations.NotNull;
10 |
11 | public class CustomSchemeHandlerFactory implements CefSchemeHandlerFactory {
12 | private final Project project;
13 |
14 | public CustomSchemeHandlerFactory(@NotNull Project project) {
15 | this.project = project;
16 | }
17 |
18 | @Override
19 | public CefResourceHandler create(CefBrowser browser, CefFrame frame, String schemeName, CefRequest request) {
20 | return new CustomResourceHandler(this.project);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/handlers/OpenedConnection.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.handlers;
2 |
3 | import com.intellij.openapi.diagnostic.Logger;
4 | import org.cef.callback.CefCallback;
5 | import org.cef.handler.CefLoadHandler;
6 | import org.cef.misc.IntRef;
7 | import org.cef.misc.StringRef;
8 | import org.cef.network.CefResponse;
9 |
10 | import java.io.IOException;
11 | import java.io.InputStream;
12 | import java.net.URLConnection;
13 |
14 | public class OpenedConnection implements ResourceHandlerState {
15 | private InputStream inputStream;
16 | private final URLConnection connection;
17 | private boolean isConnectionOpened;
18 |
19 | public URLConnection connection() {
20 | return this.connection;
21 | }
22 |
23 | private InputStream inputStreamLazyCompute() throws IOException {
24 | if (!this.isConnectionOpened) {
25 | this.inputStream = connection().getInputStream();
26 | this.isConnectionOpened = true;
27 | }
28 | return this.inputStream;
29 | }
30 |
31 | private InputStream inputStream() throws IOException {
32 | return !this.isConnectionOpened ? inputStreamLazyCompute() : this.inputStream;
33 | }
34 |
35 | @Override
36 | public void getResponseHeaders(CefResponse cefResponse, IntRef responseLength, StringRef redirectUrl) {
37 | try {
38 | String url = connection().getURL().toString();
39 | if (url.contains(".css")) {
40 | cefResponse.setMimeType("text/css");
41 | } else if (url.contains(".js")) {
42 | cefResponse.setMimeType("text/javascript");
43 | } else if (url.contains(".html")) {
44 | cefResponse.setMimeType("text/html");
45 | } else {
46 | cefResponse.setMimeType(connection().getContentType());
47 | }
48 | responseLength.set(inputStream().available());
49 | cefResponse.setStatus(200);
50 | } catch (IOException e) {
51 | Logger.getInstance(this.getClass()).error("getResponseHeaders error", e);
52 | cefResponse.setError(CefLoadHandler.ErrorCode.ERR_FILE_NOT_FOUND);
53 | cefResponse.setStatusText(e.getLocalizedMessage());
54 | cefResponse.setStatus(404);
55 | }
56 | }
57 |
58 | @Override
59 | public Boolean readResponse(byte[] paramArrayOfByte, int designedBytesToRead, IntRef bytesRead, CefCallback callback) throws IOException {
60 | boolean isResponseRead;
61 | int availableSize = inputStream().available();
62 | if (availableSize > 0) {
63 | int maxBytesToRead = Math.min(availableSize, designedBytesToRead);
64 | int realNumberOfReadBytes = inputStream().read(paramArrayOfByte, 0, maxBytesToRead);
65 | bytesRead.set(realNumberOfReadBytes);
66 | isResponseRead = true;
67 | } else {
68 | inputStream().close();
69 | isResponseRead = false;
70 | }
71 | return isResponseRead;
72 | }
73 |
74 | @Override
75 | public void close() throws IOException {
76 | inputStream().close();
77 | }
78 |
79 | public OpenedConnection(URLConnection connection) {
80 | this.connection = connection;
81 | }
82 | }
83 |
84 |
85 |
86 |
87 |
88 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/handlers/ResourceHandlerState.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.handlers;
2 |
3 | import org.cef.callback.CefCallback;
4 | import org.cef.misc.IntRef;
5 | import org.cef.misc.StringRef;
6 | import org.cef.network.CefResponse;
7 |
8 | import java.io.IOException;
9 |
10 | public interface ResourceHandlerState {
11 | void getResponseHeaders(CefResponse paramCefResponse, IntRef paramIntRef, StringRef paramStringRef);
12 |
13 | Boolean readResponse(byte[] paramArrayOfByte, int paramInt, IntRef paramIntRef, CefCallback paramCefCallback) throws IOException;
14 |
15 | void close() throws IOException;
16 | }
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/model/GenerateModel.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.model;
2 |
3 | public class GenerateModel {
4 |
5 | private String generated_text;
6 |
7 | public String getGenerated_text() {
8 | return generated_text;
9 | }
10 |
11 | public void setGenerated_text(String generated_text) {
12 | this.generated_text = generated_text;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/services/CodeShellCompleteService.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.services;
2 |
3 | import com.codeshell.intellij.constant.PrefixString;
4 | import com.codeshell.intellij.enums.CodeShellURI;
5 | import com.codeshell.intellij.settings.CodeShellSettings;
6 | import com.codeshell.intellij.utils.CodeShellUtils;
7 | import com.codeshell.intellij.widget.CodeShellWidget;
8 | import com.google.gson.JsonObject;
9 | import com.intellij.openapi.diagnostic.Logger;
10 | import com.intellij.openapi.project.Project;
11 | import com.intellij.openapi.project.ProjectManager;
12 | import com.intellij.openapi.wm.WindowManager;
13 | import org.apache.commons.lang3.StringUtils;
14 | import org.apache.http.HttpResponse;
15 | import org.apache.http.client.methods.HttpPost;
16 | import org.apache.http.entity.ContentType;
17 | import org.apache.http.entity.StringEntity;
18 | import org.apache.http.impl.client.CloseableHttpClient;
19 | import org.apache.http.impl.client.HttpClients;
20 | import org.apache.http.util.EntityUtils;
21 |
22 | import java.io.IOException;
23 | import java.util.regex.Pattern;
24 |
25 | public class CodeShellCompleteService {
26 | private final Logger logger = Logger.getInstance(this.getClass());
27 | private static final String PREFIX_TAG = "";
28 | private static final String SUFFIX_TAG = "";
29 | private static final String MIDDLE_TAG = "";
30 | private static final String REG_EXP = "data:\\s?(.*?)\n";
31 | private static final Pattern PATTERN = Pattern.compile(REG_EXP);
32 | private static long lastRequestTime = 0;
33 | private static boolean httpRequestFinFlag = true;
34 | private int statusCode = 200;
35 |
36 | public String[] getCodeCompletionHints(CharSequence editorContents, int cursorPosition) {
37 | CodeShellSettings settings = CodeShellSettings.getInstance();
38 | String contents = editorContents.toString();
39 | if (!httpRequestFinFlag || !settings.isSaytEnabled() || StringUtils.isBlank(contents)) {
40 | return null;
41 | }
42 | if (contents.contains(PREFIX_TAG) || contents.contains(SUFFIX_TAG) || contents.contains(MIDDLE_TAG) || contents.contains(PrefixString.RESPONSE_END_TAG)) {
43 | return null;
44 | }
45 | String prefix = contents.substring(CodeShellUtils.prefixHandle(0, cursorPosition), cursorPosition);
46 | String suffix = contents.substring(cursorPosition, CodeShellUtils.suffixHandle(cursorPosition, editorContents.length()));
47 | String generatedText = "";
48 | String codeShellPrompt = generateFIMPrompt(prefix, suffix);
49 | if(settings.isCPURadioButtonEnabled()){
50 | HttpPost httpPost = buildApiPostForCPU(settings, prefix, suffix);
51 | generatedText = getApiResponseForCPU(settings, httpPost, codeShellPrompt);
52 | }else{
53 | HttpPost httpPost = buildApiPostForGPU(settings, codeShellPrompt);
54 | generatedText = getApiResponseForGPU(settings, httpPost, codeShellPrompt);
55 | }
56 | String[] suggestionList = null;
57 | if (generatedText.contains(MIDDLE_TAG)) {
58 | String[] parts = generatedText.split(MIDDLE_TAG);
59 | if (parts.length > 0) {
60 | suggestionList = StringUtils.splitPreserveAllTokens(parts[1], "\n");
61 | if (suggestionList.length == 1 && suggestionList[0].trim().isEmpty()) {
62 | return null;
63 | }
64 | if (suggestionList.length > 1) {
65 | for (int i = 0; i < suggestionList.length; i++) {
66 | StringBuilder sb = new StringBuilder(suggestionList[i]);
67 | sb.append("\n");
68 | suggestionList[i] = sb.toString();
69 | }
70 | }
71 | }
72 | }
73 | return suggestionList;
74 | }
75 |
76 | private String generateFIMPrompt(String prefix, String suffix) {
77 | return PREFIX_TAG + prefix + SUFFIX_TAG + suffix + MIDDLE_TAG;
78 | }
79 |
80 | private HttpPost buildApiPostForCPU(CodeShellSettings settings, String prefix,String suffix) {
81 | String apiURL = settings.getServerAddressURL() + CodeShellURI.CPU_COMPLETE.getUri();
82 | HttpPost httpPost = new HttpPost(apiURL);
83 | JsonObject httpBody = CodeShellUtils.pakgHttpRequestBodyForCPU(settings, prefix, suffix);
84 | StringEntity requestEntity = new StringEntity(httpBody.toString(), ContentType.APPLICATION_JSON);
85 | httpPost.setEntity(requestEntity);
86 | return httpPost;
87 | }
88 |
89 | private HttpPost buildApiPostForGPU(CodeShellSettings settings, String codeShellPrompt) {
90 | String apiURL = settings.getServerAddressURL() + CodeShellURI.GPU_COMPLETE.getUri();
91 | HttpPost httpPost = new HttpPost(apiURL);
92 | JsonObject httpBody = CodeShellUtils.pakgHttpRequestBodyForGPU(settings, codeShellPrompt);
93 | StringEntity requestEntity = new StringEntity(httpBody.toString(), ContentType.APPLICATION_JSON);
94 | httpPost.setEntity(requestEntity);
95 | return httpPost;
96 | }
97 |
98 | private String getApiResponseForCPU(CodeShellSettings settings, HttpPost httpPost, String codeShellPrompt) {
99 | String responseText = "";
100 | httpRequestFinFlag = false;
101 | try {
102 | CloseableHttpClient httpClient = HttpClients.createDefault();
103 | HttpResponse response = httpClient.execute(httpPost);
104 | int oldStatusCode = statusCode;
105 | statusCode = response.getStatusLine().getStatusCode();
106 | if (statusCode != oldStatusCode) {
107 | for (Project openProject : ProjectManager.getInstance().getOpenProjects()) {
108 | WindowManager.getInstance().getStatusBar(openProject).updateWidget(CodeShellWidget.ID);
109 | }
110 | }
111 | if (statusCode != 200) {
112 | return responseText;
113 | }
114 | String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
115 | responseText = CodeShellUtils.parseHttpResponseContentForCPU(settings, responseBody, PATTERN);
116 | httpClient.close();
117 | } catch (IOException e) {
118 | logger.error("getApiResponseForCPU error", e);
119 | } finally {
120 | httpRequestFinFlag = true;
121 | }
122 | return codeShellPrompt + responseText;
123 | }
124 |
125 | private String getApiResponseForGPU(CodeShellSettings settings, HttpPost httpPost, String codeShellPrompt) {
126 | String responseText = "";
127 | httpRequestFinFlag = false;
128 | try {
129 | CloseableHttpClient httpClient = HttpClients.createDefault();
130 | HttpResponse response = httpClient.execute(httpPost);
131 | int oldStatusCode = statusCode;
132 | statusCode = response.getStatusLine().getStatusCode();
133 | if (statusCode != oldStatusCode) {
134 | for (Project openProject : ProjectManager.getInstance().getOpenProjects()) {
135 | WindowManager.getInstance().getStatusBar(openProject).updateWidget(CodeShellWidget.ID);
136 | }
137 | }
138 | if (statusCode != 200) {
139 | return responseText;
140 | }
141 | String responseBody = EntityUtils.toString(response.getEntity());
142 | responseText = CodeShellUtils.parseHttpResponseContentForGPU(settings, responseBody);
143 | httpClient.close();
144 | } catch (IOException e) {
145 | logger.error("getApiResponseForGPU error", e);
146 | } finally {
147 | httpRequestFinFlag = true;
148 | }
149 |
150 | return codeShellPrompt + responseText;
151 | }
152 |
153 | public int getStatus() {
154 | return statusCode;
155 | }
156 |
157 |
158 | }
159 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/services/CodeShellSideWindowService.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.services;
2 |
3 | import com.codeshell.intellij.window.CodeShellSideWindow;
4 | import com.google.gson.JsonObject;
5 | import com.intellij.openapi.components.Service;
6 | import com.intellij.openapi.project.Project;
7 | import org.cef.browser.CefBrowser;
8 | import org.jetbrains.annotations.NotNull;
9 |
10 | @Service
11 | public final class CodeShellSideWindowService {
12 |
13 | private final Project project;
14 | private final CodeShellSideWindow codeShellSideWindow;
15 |
16 | public Project getProject() {
17 | return this.project;
18 | }
19 |
20 | public CodeShellSideWindow getCodeShellSideWindow() {
21 | return this.codeShellSideWindow;
22 | }
23 |
24 | public CodeShellSideWindowService(Project project) {
25 | this.project = project;
26 | this.codeShellSideWindow = new CodeShellSideWindow(project);
27 | }
28 |
29 |
30 | public void notifyIdeAppInstance(@NotNull JsonObject result) {
31 | CefBrowser browser = this.getCodeShellSideWindow().jbCefBrowser().getCefBrowser();
32 | browser.executeJavaScript("window.postMessage(" + result + ",'*');", browser.getURL(), 0);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/settings/CodeShellSettings.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.settings;
2 |
3 | import com.codeshell.intellij.enums.ChatMaxToken;
4 | import com.codeshell.intellij.enums.CompletionMaxToken;
5 | import com.codeshell.intellij.enums.TabActionOption;
6 | import com.intellij.openapi.application.ApplicationManager;
7 | import com.intellij.openapi.components.PersistentStateComponent;
8 | import com.intellij.openapi.components.State;
9 | import com.intellij.openapi.components.Storage;
10 | import org.jdom.Element;
11 | import org.jetbrains.annotations.NotNull;
12 | import org.jetbrains.annotations.Nullable;
13 |
14 | import java.util.Objects;
15 |
16 | @State(name = "CodeShellSettings", storages = @Storage("codeshell_settings.xml"))
17 | public class CodeShellSettings implements PersistentStateComponent {
18 | public static final String SETTINGS_TAG = "CodeShellSettings";
19 | private static final String SERVER_ADDRESS_TAG = "SERVER_ADDRESS_URL";
20 | private static final String SAYT_TAG = "SAYT_ENABLED";
21 | private static final String CPU_RADIO_BUTTON_TAG = "CPU_RADIO_BUTTON_ENABLED";
22 | private static final String GPU_RADIO_BUTTON_TAG = "GPU_RADIO_BUTTON_ENABLED";
23 | private static final String TAB_ACTION_TAG = "TAB_ACTION";
24 | private static final String COMPLETION_MAX_TOKENS_TAG = "COMPLETION_MAX_TOKENS";
25 | private static final String CHAT_MAX_TOKENS_TAG = "CHAT_MAX_TOKENS";
26 | private boolean saytEnabled = true;
27 | private boolean cpuRadioButtonEnabled = true;
28 | private boolean gpuRadioButtonEnabled = false;
29 | private String serverAddressURL = "http://127.0.0.1:8080";
30 | private TabActionOption tabActionOption = TabActionOption.ALL;
31 | private CompletionMaxToken completionMaxToken = CompletionMaxToken.MEDIUM;
32 | private ChatMaxToken chatMaxToken = ChatMaxToken.MEDIUM;
33 |
34 | private static final CodeShellSettings SHELL_CODER_SETTINGS_INSTANCE = new CodeShellSettings();
35 |
36 | @Override
37 | public @Nullable Element getState() {
38 | Element state = new Element(SETTINGS_TAG);
39 | state.setAttribute(CPU_RADIO_BUTTON_TAG, Boolean.toString(isCPURadioButtonEnabled()));
40 | state.setAttribute(GPU_RADIO_BUTTON_TAG, Boolean.toString(isGPURadioButtonEnabled()));
41 | state.setAttribute(SERVER_ADDRESS_TAG, getServerAddressURL());
42 | state.setAttribute(SAYT_TAG, Boolean.toString(isSaytEnabled()));
43 | state.setAttribute(TAB_ACTION_TAG, getTabActionOption().name());
44 | state.setAttribute(COMPLETION_MAX_TOKENS_TAG, getCompletionMaxToken().name());
45 | state.setAttribute(CHAT_MAX_TOKENS_TAG, getChatMaxToken().name());
46 | return state;
47 | }
48 |
49 | @Override
50 | public void loadState(@NotNull Element state) {
51 | if (Objects.nonNull(state.getAttributeValue(CPU_RADIO_BUTTON_TAG))) {
52 | setCPURadioButtonEnabled(Boolean.parseBoolean(state.getAttributeValue(CPU_RADIO_BUTTON_TAG)));
53 | }
54 | if (Objects.nonNull(state.getAttributeValue(GPU_RADIO_BUTTON_TAG))) {
55 | setGPURadioButtonEnabled(Boolean.parseBoolean(state.getAttributeValue(GPU_RADIO_BUTTON_TAG)));
56 | }
57 | if (Objects.nonNull(state.getAttributeValue(SERVER_ADDRESS_TAG))) {
58 | setServerAddressURL(state.getAttributeValue(SERVER_ADDRESS_TAG));
59 | }
60 | if (Objects.nonNull(state.getAttributeValue(SAYT_TAG))) {
61 | setSaytEnabled(Boolean.parseBoolean(state.getAttributeValue(SAYT_TAG)));
62 | }
63 | if (Objects.nonNull(state.getAttributeValue(TAB_ACTION_TAG))) {
64 | setTabActionOption(TabActionOption.valueOf(state.getAttributeValue(TAB_ACTION_TAG)));
65 | }
66 | if (Objects.nonNull(state.getAttributeValue(COMPLETION_MAX_TOKENS_TAG))) {
67 | setCompletionMaxToken(CompletionMaxToken.valueOf(state.getAttributeValue(COMPLETION_MAX_TOKENS_TAG)));
68 | }
69 | if (Objects.nonNull(state.getAttributeValue(CHAT_MAX_TOKENS_TAG))) {
70 | setChatMaxToken(ChatMaxToken.valueOf(state.getAttributeValue(CHAT_MAX_TOKENS_TAG)));
71 | }
72 | }
73 |
74 | public static CodeShellSettings getInstance() {
75 | if (Objects.isNull(ApplicationManager.getApplication())) {
76 | return SHELL_CODER_SETTINGS_INSTANCE;
77 | }
78 |
79 | CodeShellSettings service = ApplicationManager.getApplication().getService(CodeShellSettings.class);
80 | if (Objects.isNull(service)) {
81 | return SHELL_CODER_SETTINGS_INSTANCE;
82 | }
83 | return service;
84 | }
85 |
86 | public boolean isSaytEnabled() {
87 | return saytEnabled;
88 | }
89 |
90 | public void setSaytEnabled(boolean saytEnabled) {
91 | this.saytEnabled = saytEnabled;
92 | }
93 |
94 | public void toggleSaytEnabled() {
95 | this.saytEnabled = !this.saytEnabled;
96 | }
97 |
98 | public boolean isCPURadioButtonEnabled() {
99 | return cpuRadioButtonEnabled;
100 | }
101 |
102 | public void setCPURadioButtonEnabled(boolean cpuRadioButtonEnabled) {
103 | this.cpuRadioButtonEnabled = cpuRadioButtonEnabled;
104 | }
105 |
106 | public boolean isGPURadioButtonEnabled() {
107 | return gpuRadioButtonEnabled;
108 | }
109 |
110 | public void setGPURadioButtonEnabled(boolean gpuRadioButtonEnabled) {
111 | this.gpuRadioButtonEnabled = gpuRadioButtonEnabled;
112 | }
113 |
114 | public String getServerAddressURL() {
115 | return serverAddressURL;
116 | }
117 |
118 | public void setServerAddressURL(String serverAddressURL) {
119 | this.serverAddressURL = serverAddressURL;
120 | }
121 |
122 | public CompletionMaxToken getCompletionMaxToken() {
123 | return completionMaxToken;
124 | }
125 |
126 | public void setCompletionMaxToken(CompletionMaxToken completionMaxToken) {
127 | this.completionMaxToken = completionMaxToken;
128 | }
129 |
130 | public ChatMaxToken getChatMaxToken() {
131 | return chatMaxToken;
132 | }
133 |
134 | public void setChatMaxToken(ChatMaxToken chatMaxToken) {
135 | this.chatMaxToken = chatMaxToken;
136 | }
137 |
138 | public TabActionOption getTabActionOption() {
139 | return tabActionOption;
140 | }
141 |
142 | public void setTabActionOption(TabActionOption tabActionOption) {
143 | this.tabActionOption = tabActionOption;
144 | }
145 |
146 | }
147 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/settings/CodeShellSettingsProvider.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.settings;
2 |
3 | import com.codeshell.intellij.enums.CodeShellURI;
4 | import com.codeshell.intellij.services.CodeShellSideWindowService;
5 | import com.codeshell.intellij.widget.CodeShellWidget;
6 | import com.google.gson.JsonObject;
7 | import com.intellij.application.options.editor.EditorOptionsProvider;
8 | import com.intellij.ide.DataManager;
9 | import com.intellij.openapi.actionSystem.CommonDataKeys;
10 | import com.intellij.openapi.project.Project;
11 | import com.intellij.openapi.project.ProjectManager;
12 | import com.intellij.openapi.util.NlsContexts;
13 | import com.intellij.openapi.wm.WindowManager;
14 | import org.jetbrains.annotations.NonNls;
15 | import org.jetbrains.annotations.NotNull;
16 | import org.jetbrains.annotations.Nullable;
17 |
18 | import javax.swing.*;
19 | import java.util.Objects;
20 |
21 | public class CodeShellSettingsProvider implements EditorOptionsProvider {
22 | private SettingsPanel settingsPanel;
23 |
24 | @Override
25 | public @NotNull @NonNls String getId() {
26 | return "CodeShell.Settings";
27 | }
28 |
29 | @Override
30 | public @NlsContexts.ConfigurableName String getDisplayName() {
31 | return "CodeShell";
32 | }
33 |
34 | @Override
35 | public @Nullable JComponent createComponent() {
36 | if (Objects.isNull(settingsPanel)) {
37 | settingsPanel = new SettingsPanel();
38 | }
39 | return settingsPanel.getPanel();
40 | }
41 |
42 | @Override
43 | public boolean isModified() {
44 | CodeShellSettings savedSettings = CodeShellSettings.getInstance();
45 | return !savedSettings.getServerAddressURL().equals(settingsPanel.getServerAddressUrl())
46 | || savedSettings.getTabActionOption() != settingsPanel.getTabActionOption()
47 | || savedSettings.isSaytEnabled() != settingsPanel.getEnableSAYTCheckBox()
48 | || savedSettings.isCPURadioButtonEnabled() != settingsPanel.getCPUModelRadioButton()
49 | || savedSettings.isGPURadioButtonEnabled() != settingsPanel.getGPUModelRadioButton()
50 | || savedSettings.getCompletionMaxToken() != settingsPanel.getCompletionMaxTokens()
51 | || savedSettings.getChatMaxToken() != settingsPanel.getChatMaxTokens();
52 | }
53 |
54 | @Override
55 | public void apply() {
56 | CodeShellSettings savedSettings = CodeShellSettings.getInstance();
57 | savedSettings.setServerAddressURL(settingsPanel.getServerAddressUrl());
58 | savedSettings.setSaytEnabled(settingsPanel.getEnableSAYTCheckBox());
59 | savedSettings.setCPURadioButtonEnabled(settingsPanel.getCPUModelRadioButton());
60 | savedSettings.setGPURadioButtonEnabled(settingsPanel.getGPUModelRadioButton());
61 | savedSettings.setTabActionOption(settingsPanel.getTabActionOption());
62 | savedSettings.setCompletionMaxToken(settingsPanel.getCompletionMaxTokens());
63 | savedSettings.setChatMaxToken(settingsPanel.getChatMaxTokens());
64 |
65 | for (Project openProject : ProjectManager.getInstance().getOpenProjects()) {
66 | WindowManager.getInstance().getStatusBar(openProject).updateWidget(CodeShellWidget.ID);
67 | }
68 |
69 | JsonObject jsonObject = new JsonObject();
70 | if(CodeShellSettings.getInstance().isCPURadioButtonEnabled()){
71 | jsonObject.addProperty("sendUrl", CodeShellSettings.getInstance().getServerAddressURL() + CodeShellURI.CPU_CHAT.getUri());
72 | jsonObject.addProperty("modelType", "CPU");
73 | }else{
74 | jsonObject.addProperty("sendUrl", CodeShellSettings.getInstance().getServerAddressURL() + CodeShellURI.GPU_CHAT.getUri());
75 | jsonObject.addProperty("modelType", "GPU");
76 | }
77 | jsonObject.addProperty("maxToken", CodeShellSettings.getInstance().getChatMaxToken().getDescription());
78 | JsonObject result = new JsonObject();
79 | result.addProperty("data", jsonObject.toString());
80 | Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContextFromFocus().getResultSync());
81 | (project.getService(CodeShellSideWindowService.class)).notifyIdeAppInstance(result);
82 | }
83 |
84 | @Override
85 | public void reset() {
86 | CodeShellSettings savedSettings = CodeShellSettings.getInstance();
87 | settingsPanel.setServerAddressUrl(savedSettings.getServerAddressURL());
88 | settingsPanel.setEnableSAYTCheckBox(savedSettings.isSaytEnabled());
89 | settingsPanel.setTabActionOption(savedSettings.getTabActionOption());
90 | settingsPanel.setCPUModelRadioButton(savedSettings.isCPURadioButtonEnabled());
91 | settingsPanel.setGPUModelRadioButton(savedSettings.isGPURadioButtonEnabled());
92 | settingsPanel.setCompletionMaxTokens(savedSettings.getCompletionMaxToken());
93 | settingsPanel.setChatMaxTokens(savedSettings.getChatMaxToken());
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/settings/SettingsPanel.form:
--------------------------------------------------------------------------------
1 |
2 |
239 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/settings/SettingsPanel.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.settings;
2 |
3 | import com.codeshell.intellij.enums.ChatMaxToken;
4 | import com.codeshell.intellij.enums.CompletionMaxToken;
5 | import com.codeshell.intellij.enums.TabActionOption;
6 | import com.intellij.ui.EnumComboBoxModel;
7 |
8 | import javax.swing.*;
9 |
10 | public class SettingsPanel {
11 |
12 | private JPanel panel;
13 | private JTextField serverAddressTextField;
14 |
15 | private JPanel modelRuntime;
16 | private JPanel Parameters;
17 | private JCheckBox enableSAYTCheckBox;
18 | private JPanel Settings;
19 | private JPanel ParamOuter;
20 | private JPanel TabActionPanel;
21 | private JComboBox tabActionComboBox;
22 | private JLabel tabActionLabel;
23 | private JComboBox completionMaxTokensComboBox;
24 | private JComboBox chatMaxTokensComboBox;
25 | private JRadioButton useGPUModelRadioButton;
26 | private JRadioButton useCPUModelRadioButton;
27 |
28 | public SettingsPanel() {
29 |
30 | ButtonGroup buttonGroup = new ButtonGroup();
31 | buttonGroup.add(useGPUModelRadioButton);
32 | buttonGroup.add(useCPUModelRadioButton);
33 |
34 | tabActionComboBox.setModel(new EnumComboBoxModel<>(TabActionOption.class));
35 | enableSAYTCheckBox.addActionListener(e -> {
36 | tabActionLabel.setEnabled(enableSAYTCheckBox.isSelected());
37 | tabActionComboBox.setEnabled(enableSAYTCheckBox.isSelected());
38 | });
39 |
40 | completionMaxTokensComboBox.setModel(new EnumComboBoxModel<>(CompletionMaxToken.class));
41 | chatMaxTokensComboBox.setModel(new EnumComboBoxModel<>(ChatMaxToken.class));
42 |
43 | }
44 |
45 | public JComponent getPanel() {
46 | return panel;
47 | }
48 |
49 | public boolean getCPUModelRadioButton() {
50 | return useCPUModelRadioButton.isSelected();
51 | }
52 |
53 | public void setCPUModelRadioButton(boolean enabledCPURadioButton) {
54 | useCPUModelRadioButton.setSelected(enabledCPURadioButton);
55 | }
56 |
57 | public boolean getGPUModelRadioButton() {
58 | return useGPUModelRadioButton.isSelected();
59 | }
60 |
61 | public void setGPUModelRadioButton(boolean enabledGPURadioButton) {
62 | useGPUModelRadioButton.setSelected(enabledGPURadioButton);
63 | }
64 |
65 | public String getServerAddressUrl() {
66 | return serverAddressTextField.getText();
67 | }
68 |
69 | public void setServerAddressUrl(String serverAddress) {
70 | serverAddressTextField.setText(serverAddress);
71 | }
72 |
73 | public boolean getEnableSAYTCheckBox() {
74 | return enableSAYTCheckBox.isSelected();
75 | }
76 |
77 | public void setEnableSAYTCheckBox(boolean enableSAYT) {
78 | enableSAYTCheckBox.setSelected(enableSAYT);
79 | }
80 |
81 | public TabActionOption getTabActionOption() {
82 | return (TabActionOption) tabActionComboBox.getModel().getSelectedItem();
83 | }
84 |
85 | public void setTabActionOption(TabActionOption option) {
86 | tabActionComboBox.getModel().setSelectedItem(option);
87 | }
88 |
89 | public CompletionMaxToken getCompletionMaxTokens() {
90 | return (CompletionMaxToken) completionMaxTokensComboBox.getModel().getSelectedItem();
91 | }
92 |
93 | public void setCompletionMaxTokens(CompletionMaxToken option) {
94 | completionMaxTokensComboBox.getModel().setSelectedItem(option);
95 | }
96 | public ChatMaxToken getChatMaxTokens() {
97 | return (ChatMaxToken) chatMaxTokensComboBox.getModel().getSelectedItem();
98 | }
99 |
100 | public void setChatMaxTokens(ChatMaxToken option) {
101 | chatMaxTokensComboBox.getModel().setSelectedItem(option);
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/utils/CodeGenHintRenderer.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.utils;
2 |
3 | import com.intellij.openapi.editor.Editor;
4 | import com.intellij.openapi.editor.EditorCustomElementRenderer;
5 | import com.intellij.openapi.editor.Inlay;
6 | import com.intellij.openapi.editor.colors.EditorFontType;
7 | import com.intellij.openapi.editor.markup.TextAttributes;
8 | import com.intellij.ui.JBColor;
9 | import org.jetbrains.annotations.NotNull;
10 |
11 | import java.awt.*;
12 |
13 | public class CodeGenHintRenderer implements EditorCustomElementRenderer {
14 | private final String myText;
15 | private Font myFont;
16 |
17 | public CodeGenHintRenderer(String text, Font font) {
18 | myText = text;
19 | myFont = font;
20 | }
21 |
22 | public CodeGenHintRenderer(String text) {
23 | myText = text;
24 | }
25 |
26 | @Override
27 | public int calcWidthInPixels(@NotNull Inlay inlay) {
28 | Editor editor = inlay.getEditor();
29 | Font font = editor.getColorsScheme().getFont(EditorFontType.PLAIN);
30 | myFont = new Font(font.getName(), Font.ITALIC, font.getSize());
31 | return editor.getContentComponent().getFontMetrics(font).stringWidth(myText);
32 | }
33 |
34 | @Override
35 | public void paint(@NotNull Inlay inlay, @NotNull Graphics g, @NotNull Rectangle targetRegion, @NotNull TextAttributes textAttributes) {
36 | g.setColor(JBColor.GRAY);
37 | g.setFont(myFont);
38 | g.drawString(myText, targetRegion.x, targetRegion.y + targetRegion.height - (int) Math.ceil((double) g.getFontMetrics().getFont().getSize() / 2) + 1);
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/utils/CodeShellIcons.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.utils;
2 |
3 | import com.intellij.openapi.util.IconLoader;
4 |
5 | import javax.swing.*;
6 |
7 | public interface CodeShellIcons {
8 | Icon Action = IconLoader.getIcon("/icons/actionIcon.svg", CodeShellIcons.class);
9 | Icon ActionDark = IconLoader.getIcon("/icons/actionIcon_dark.svg", CodeShellIcons.class);
10 | Icon WidgetEnabled = IconLoader.getIcon("/icons/widgetEnabled.svg", CodeShellIcons.class);
11 | Icon WidgetEnabledDark = IconLoader.getIcon("/icons/widgetEnabled_dark.svg", CodeShellIcons.class);
12 | Icon WidgetDisabled = IconLoader.getIcon("/icons/widgetDisabled.svg", CodeShellIcons.class);
13 | Icon WidgetDisabledDark = IconLoader.getIcon("/icons/widgetDisabled_dark.svg", CodeShellIcons.class);
14 | Icon WidgetError = IconLoader.getIcon("/icons/widgetError.svg", CodeShellIcons.class);
15 | Icon WidgetErrorDark = IconLoader.getIcon("/icons/widgetError_dark.svg", CodeShellIcons.class);
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/utils/CodeShellUtils.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.utils;
2 |
3 | import com.alibaba.fastjson2.JSONObject;
4 | import com.codeshell.intellij.constant.PrefixString;
5 | import com.codeshell.intellij.model.GenerateModel;
6 | import com.codeshell.intellij.settings.CodeShellSettings;
7 | import com.codeshell.intellij.widget.CodeShellWidget;
8 | import com.google.gson.Gson;
9 | import com.google.gson.JsonObject;
10 | import com.intellij.openapi.application.ApplicationInfo;
11 | import com.intellij.openapi.command.WriteCommandAction;
12 | import com.intellij.openapi.diagnostic.Logger;
13 | import com.intellij.openapi.editor.Editor;
14 | import com.intellij.openapi.editor.Inlay;
15 | import com.intellij.openapi.editor.InlayModel;
16 | import com.intellij.openapi.vfs.VirtualFile;
17 | import org.apache.commons.lang3.StringUtils;
18 |
19 | import java.util.Objects;
20 | import java.util.regex.Matcher;
21 | import java.util.regex.Pattern;
22 |
23 | public class CodeShellUtils {
24 | public static String includePreText(String preText, String language, String text) {
25 | String sufText = "\n```" + language + "\n" + text + "\n```\n";
26 | return String.format(preText, language, sufText);
27 | }
28 | public static int prefixHandle(int begin, int end) {
29 | if (end - begin > 3000) {
30 | return end - 3000;
31 | } else {
32 | return begin;
33 | }
34 | }
35 | public static int suffixHandle(int begin, int end) {
36 | if (end - begin > 256) {
37 | return begin + 256;
38 | } else {
39 | return end;
40 | }
41 | }
42 |
43 | public static JsonObject pakgHttpRequestBodyForCPU(CodeShellSettings settings, String prefix, String suffix){
44 | JsonObject httpBody = new JsonObject();
45 | httpBody.addProperty("input_prefix", prefix);
46 | httpBody.addProperty("input_suffix", suffix);
47 | httpBody.addProperty("n_predict", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));
48 | httpBody.addProperty("temperature", 0.2);
49 | httpBody.addProperty("repetition_penalty", 1.0);
50 | httpBody.addProperty("top_k", 10);
51 | httpBody.addProperty("top_p", 0.95);
52 | // httpBody.addProperty("prompt", PrefixString.REQUST_END_TAG + codeShellPrompt);
53 | // httpBody.addProperty("frequency_penalty", 1.2);
54 | // httpBody.addProperty("n_predict", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));
55 | // httpBody.addProperty("stream", false);
56 | // JsonArray stopArray = new JsonArray();
57 | // stopArray.add("||");
58 | // httpBody.add("stop", stopArray);
59 | return httpBody;
60 | }
61 |
62 | public static JsonObject pakgHttpRequestBodyForGPU(CodeShellSettings settings, String codeShellPrompt){
63 | JsonObject httpBody = new JsonObject();
64 | httpBody.addProperty("inputs", codeShellPrompt);
65 | JsonObject parameters = new JsonObject();
66 | parameters.addProperty("max_new_tokens", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));
67 | httpBody.add("parameters", parameters);
68 | return httpBody;
69 | }
70 |
71 | public static String parseHttpResponseContentForCPU(CodeShellSettings settings, String responseBody, Pattern pattern){
72 | String generatedText = "";
73 | Matcher matcher = pattern.matcher(responseBody);
74 | StringBuilder contentBuilder = new StringBuilder();
75 | while (matcher.find()) {
76 | String jsonString = matcher.group(1);
77 | JSONObject json = JSONObject.parseObject(jsonString);
78 | String content = json.getString("content");
79 | if(StringUtils.equalsAny(content, "<|endoftext|>", "")){
80 | continue;
81 | }
82 | contentBuilder.append(content);
83 | }
84 | return contentBuilder.toString().replace(PrefixString.RESPONSE_END_TAG, "");
85 | }
86 |
87 | public static String parseHttpResponseContentForGPU(CodeShellSettings settings, String responseBody){
88 | String generatedText = "";
89 | Gson gson = new Gson();
90 | GenerateModel generateModel = gson.fromJson(responseBody, GenerateModel.class);
91 | if (StringUtils.isNotBlank(generateModel.getGenerated_text())) {
92 | generatedText = generateModel.getGenerated_text();
93 | }
94 | return generatedText.replace(PrefixString.RESPONSE_END_TAG, "");
95 | }
96 |
97 | public static String getIDEVersion(String whichVersion) {
98 | ApplicationInfo applicationInfo = ApplicationInfo.getInstance();
99 | String version = "";
100 | try {
101 | if (whichVersion.equalsIgnoreCase("major")) {
102 | version = applicationInfo.getMajorVersion();
103 | } else {
104 | version = applicationInfo.getFullVersion();
105 | }
106 | } catch (Exception e) {
107 | Logger.getInstance(CodeShellUtils.class).error("get IDE full version error", e);
108 | }
109 | return version;
110 | }
111 |
112 | public static void addCodeSuggestion(Editor focusedEditor, VirtualFile file, int suggestionPosition, String[] hintList) {
113 | WriteCommandAction.runWriteCommandAction(focusedEditor.getProject(), () -> {
114 | if (suggestionPosition != focusedEditor.getCaretModel().getOffset()) {
115 | return;
116 | }
117 | if (Objects.nonNull(focusedEditor.getSelectionModel().getSelectedText())) {
118 | return;
119 | }
120 |
121 | file.putUserData(CodeShellWidget.SHELL_CODER_CODE_SUGGESTION, hintList);
122 | file.putUserData(CodeShellWidget.SHELL_CODER_POSITION, suggestionPosition);
123 |
124 | InlayModel inlayModel = focusedEditor.getInlayModel();
125 | inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
126 | inlayModel.getBlockElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
127 | if (Objects.nonNull(hintList) && hintList.length > 0) {
128 | if (!hintList[0].trim().isEmpty()) {
129 | inlayModel.addInlineElement(suggestionPosition, true, new CodeGenHintRenderer(hintList[0]));
130 | }
131 | for (int i = 1; i < hintList.length; i++) {
132 | inlayModel.addBlockElement(suggestionPosition, false, false, 0, new CodeGenHintRenderer(hintList[i]));
133 | }
134 | }
135 | });
136 | }
137 |
138 | public static void disposeInlayHints(Inlay> inlay) {
139 | if (inlay.getRenderer() instanceof CodeGenHintRenderer) {
140 | inlay.dispose();
141 | }
142 | }
143 |
144 | }
145 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/utils/EditorUtils.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.utils;
2 |
3 | import com.codeshell.intellij.enums.CodeShellURI;
4 | import com.codeshell.intellij.settings.CodeShellSettings;
5 | import com.google.gson.JsonObject;
6 | import com.intellij.openapi.application.ApplicationManager;
7 | import com.intellij.openapi.editor.Document;
8 | import com.intellij.openapi.editor.Editor;
9 | import com.intellij.openapi.editor.EditorKind;
10 | import com.intellij.openapi.editor.LogicalPosition;
11 | import com.intellij.openapi.util.TextRange;
12 | import com.intellij.psi.PsiFile;
13 | import org.apache.commons.lang3.StringUtils;
14 | import org.jetbrains.annotations.NotNull;
15 |
16 | import java.util.Objects;
17 |
18 | public class EditorUtils {
19 |
20 | public static JsonObject getFileSelectionDetails(Editor editor, @NotNull PsiFile psiFile, String preText) {
21 | return getFileSelectionDetails(editor, psiFile, false, preText);
22 | }
23 |
24 | public static boolean isNoneTextSelected(Editor editor) {
25 | return Objects.isNull(editor) || StringUtils.isEmpty(editor.getCaretModel().getCurrentCaret().getSelectedText());
26 | }
27 |
28 | public static JsonObject getFileSelectionDetails(Editor editor, @NotNull PsiFile psiFile, boolean isCodeNote, String preText) {
29 | if (Objects.isNull(editor)) {
30 | return getEmptyRange();
31 | } else {
32 | Document document = editor.getDocument();
33 | int startOffset;
34 | int endOffset;
35 | String editorText;
36 |
37 | if (editor.getSelectionModel().hasSelection()) {
38 | startOffset = editor.getSelectionModel().getSelectionStart();
39 | endOffset = editor.getSelectionModel().getSelectionEnd();
40 | editorText = editor.getSelectionModel().getSelectedText();
41 | } else {
42 | LogicalPosition logicalPos = editor.getCaretModel().getCurrentCaret().getLogicalPosition();
43 | int line = logicalPos.line;
44 | startOffset = editor.logicalPositionToOffset(new LogicalPosition(line, 0));
45 | endOffset = editor.logicalPositionToOffset(new LogicalPosition(line, Integer.MAX_VALUE));
46 | editorText = lspPosition(document, endOffset).get("text").toString();
47 | if (isCodeNote) {
48 | editor.getDocument();
49 | for (int linenumber = 0; linenumber < editor.getDocument().getLineCount(); ++linenumber) {
50 | startOffset = editor.logicalPositionToOffset(new LogicalPosition(linenumber, 0));
51 | endOffset = editor.logicalPositionToOffset(new LogicalPosition(linenumber, Integer.MAX_VALUE));
52 | String tempText = lspPosition(document, endOffset).get("text").toString();
53 | if (Objects.nonNull(tempText) && !"\"\"".equals(tempText.trim()) && !tempText.trim().isEmpty()) {
54 | editorText = tempText;
55 | break;
56 | }
57 | }
58 | }
59 | }
60 | JsonObject range = new JsonObject();
61 | range.add("start", lspPosition(document, startOffset));
62 | range.add("end", lspPosition(document, endOffset));
63 | range.addProperty("selectedText", includePreText(preText, psiFile.getLanguage().getID(), editorText));
64 | JsonObject sendText = new JsonObject();
65 | sendText.addProperty("inputs", includePreText(preText, psiFile.getLanguage().getID(), editorText));
66 | JsonObject parameters = new JsonObject();
67 | parameters.addProperty("max_new_tokens", CodeShellSettings.getInstance().getChatMaxToken().getDescription());
68 | sendText.add("parameters", parameters);
69 |
70 | JsonObject returnObj = new JsonObject();
71 | returnObj.add("range", range);
72 | if(CodeShellSettings.getInstance().isCPURadioButtonEnabled()){
73 | returnObj.addProperty("sendUrl", CodeShellSettings.getInstance().getServerAddressURL() + CodeShellURI.CPU_CHAT.getUri());
74 | returnObj.addProperty("modelType", "CPU");
75 | }else{
76 | returnObj.addProperty("sendUrl", CodeShellSettings.getInstance().getServerAddressURL() + CodeShellURI.GPU_CHAT.getUri());
77 | returnObj.addProperty("modelType", "GPU");
78 | }
79 | returnObj.addProperty("maxToken", CodeShellSettings.getInstance().getChatMaxToken().getDescription());
80 | returnObj.add("sendText", sendText);
81 | return returnObj;
82 | }
83 | }
84 |
85 | public static JsonObject lspPosition(Document document, int offset) {
86 | int line = document.getLineNumber(offset);
87 | int lineStart = document.getLineStartOffset(line);
88 | String lineTextBeforeOffset = document.getText(TextRange.create(lineStart, offset));
89 | int column = lineTextBeforeOffset.length();
90 | JsonObject jsonObject = new JsonObject();
91 | jsonObject.addProperty("line", line);
92 | jsonObject.addProperty("column", column);
93 | jsonObject.addProperty("text", lineTextBeforeOffset);
94 | return jsonObject;
95 | }
96 |
97 | public static JsonObject getEmptyRange() {
98 | JsonObject jsonObject = new JsonObject();
99 | JsonObject range = new JsonObject();
100 | JsonObject lineCol = new JsonObject();
101 | lineCol.addProperty("line", "0");
102 | lineCol.addProperty("column", "0");
103 | lineCol.addProperty("text", "0");
104 | range.add("start", lineCol);
105 | range.add("end", lineCol);
106 | jsonObject.add("range", range);
107 | jsonObject.addProperty("selectedText", "");
108 | return jsonObject;
109 | }
110 |
111 | private static String includePreText(String preText, String language, String text) {
112 | String sufText = "\n```" + language + "\n" + text + "\n```\n";
113 | return String.format(preText, language, sufText);
114 | }
115 |
116 | public static boolean isMainEditor(Editor editor) {
117 | return editor.getEditorKind() == EditorKind.MAIN_EDITOR || ApplicationManager.getApplication().isUnitTestMode();
118 | }
119 |
120 | }
121 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/widget/CodeShellWidget.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.widget;
2 |
3 | import com.codeshell.intellij.enums.CodeShellStatus;
4 | import com.codeshell.intellij.services.CodeShellCompleteService;
5 | import com.codeshell.intellij.settings.CodeShellSettings;
6 | import com.codeshell.intellij.utils.CodeGenHintRenderer;
7 | import com.codeshell.intellij.utils.CodeShellIcons;
8 | import com.codeshell.intellij.utils.CodeShellUtils;
9 | import com.codeshell.intellij.utils.EditorUtils;
10 | import com.intellij.openapi.application.ApplicationManager;
11 | import com.intellij.openapi.editor.*;
12 | import com.intellij.openapi.editor.event.*;
13 | import com.intellij.openapi.editor.impl.EditorComponentImpl;
14 | import com.intellij.openapi.fileEditor.FileDocumentManager;
15 | import com.intellij.openapi.project.Project;
16 | import com.intellij.openapi.util.Disposer;
17 | import com.intellij.openapi.util.Key;
18 | import com.intellij.openapi.util.NlsContexts;
19 | import com.intellij.openapi.vfs.VirtualFile;
20 | import com.intellij.openapi.wm.IdeFocusManager;
21 | import com.intellij.openapi.wm.StatusBar;
22 | import com.intellij.openapi.wm.StatusBarWidget;
23 | import com.intellij.openapi.wm.impl.status.EditorBasedWidget;
24 | import com.intellij.util.Consumer;
25 | import org.jetbrains.annotations.NonNls;
26 | import org.jetbrains.annotations.NotNull;
27 | import org.jetbrains.annotations.Nullable;
28 |
29 | import javax.swing.*;
30 | import java.awt.*;
31 | import java.awt.event.MouseEvent;
32 | import java.beans.PropertyChangeEvent;
33 | import java.beans.PropertyChangeListener;
34 | import java.util.Arrays;
35 | import java.util.Objects;
36 | import java.util.concurrent.CompletableFuture;
37 |
38 | public class CodeShellWidget extends EditorBasedWidget
39 | implements StatusBarWidget.Multiframe, StatusBarWidget.IconPresentation,
40 | CaretListener, SelectionListener, BulkAwareDocumentListener.Simple, PropertyChangeListener {
41 | public static final String ID = "CodeShellWidget";
42 |
43 | public static final Key SHELL_CODER_CODE_SUGGESTION = new Key<>("CodeShell Code Suggestion");
44 | public static final Key SHELL_CODER_POSITION = new Key<>("CodeShell Position");
45 | public static boolean enableSuggestion = false;
46 | protected CodeShellWidget(@NotNull Project project) {
47 | super(project);
48 | }
49 |
50 | @Override
51 | public @NonNls @NotNull String ID() {
52 | return ID;
53 | }
54 |
55 | @Override
56 | public StatusBarWidget copy() {
57 | return new CodeShellWidget(getProject());
58 | }
59 |
60 | @Override
61 | public @Nullable Icon getIcon() {
62 | CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);
63 | CodeShellStatus status = CodeShellStatus.getStatusByCode(codeShell.getStatus());
64 | if (status == CodeShellStatus.OK) {
65 | return CodeShellSettings.getInstance().isSaytEnabled() ? CodeShellIcons.WidgetEnabled : CodeShellIcons.WidgetDisabled;
66 | } else {
67 | return CodeShellIcons.WidgetError;
68 | }
69 | }
70 |
71 | @Override
72 | public WidgetPresentation getPresentation() {
73 | return this;
74 | }
75 |
76 | @Override
77 | public @Nullable @NlsContexts.Tooltip String getTooltipText() {
78 | StringBuilder toolTipText = new StringBuilder("CodeShell");
79 | if (CodeShellSettings.getInstance().isSaytEnabled()) {
80 | toolTipText.append(" enabled");
81 | } else {
82 | toolTipText.append(" disabled");
83 | }
84 |
85 | CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);
86 | int statusCode = codeShell.getStatus();
87 | CodeShellStatus status = CodeShellStatus.getStatusByCode(statusCode);
88 | switch (status) {
89 | case OK:
90 | if (CodeShellSettings.getInstance().isSaytEnabled()) {
91 | toolTipText.append(" (Click to disable)");
92 | } else {
93 | toolTipText.append(" (Click to enable)");
94 | }
95 | break;
96 | case UNKNOWN:
97 | toolTipText.append(" (http error ");
98 | toolTipText.append(statusCode);
99 | toolTipText.append(")");
100 | break;
101 | default:
102 | toolTipText.append(" (");
103 | toolTipText.append(status.getDisplayValue());
104 | toolTipText.append(")");
105 | }
106 |
107 | return toolTipText.toString();
108 | }
109 |
110 | @Override
111 | public @Nullable Consumer getClickConsumer() {
112 | return mouseEvent -> {
113 | CodeShellSettings.getInstance().toggleSaytEnabled();
114 | if (Objects.nonNull(myStatusBar)) {
115 | myStatusBar.updateWidget(ID);
116 | }
117 | };
118 | }
119 |
120 | @Override
121 | public void install(@NotNull StatusBar statusBar) {
122 | super.install(statusBar);
123 | EditorEventMulticaster multicaster = EditorFactory.getInstance().getEventMulticaster();
124 | multicaster.addCaretListener(this, this);
125 | multicaster.addSelectionListener(this, this);
126 | multicaster.addDocumentListener(this, this);
127 | KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", this);
128 | Disposer.register(this,
129 | () -> KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("focusOwner",
130 | this)
131 | );
132 | }
133 |
134 | private Editor getFocusOwnerEditor() {
135 | Component component = getFocusOwnerComponent();
136 | Editor editor = component instanceof EditorComponentImpl ? ((EditorComponentImpl) component).getEditor() : getEditor();
137 | return Objects.nonNull(editor) && !editor.isDisposed() && EditorUtils.isMainEditor(editor) ? editor : null;
138 | }
139 |
140 | private Component getFocusOwnerComponent() {
141 | Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
142 | if (Objects.isNull(focusOwner)) {
143 | IdeFocusManager focusManager = IdeFocusManager.getInstance(getProject());
144 | Window frame = focusManager.getLastFocusedIdeWindow();
145 | if (Objects.nonNull(frame)) {
146 | focusOwner = focusManager.getLastFocusedFor(frame);
147 | }
148 | }
149 | return focusOwner;
150 | }
151 |
152 | private boolean isFocusedEditor(Editor editor) {
153 | Component focusOwner = getFocusOwnerComponent();
154 | return focusOwner == editor.getContentComponent();
155 | }
156 |
157 | @Override
158 | public void propertyChange(PropertyChangeEvent evt) {
159 | updateInlayHints(getFocusOwnerEditor());
160 | }
161 |
162 | @Override
163 | public void selectionChanged(SelectionEvent event) {
164 | updateInlayHints(event.getEditor());
165 | }
166 |
167 | @Override
168 | public void caretPositionChanged(@NotNull CaretEvent event) {
169 | updateInlayHints(event.getEditor());
170 | }
171 |
172 | @Override
173 | public void caretAdded(@NotNull CaretEvent event) {
174 | updateInlayHints(event.getEditor());
175 | }
176 |
177 | @Override
178 | public void caretRemoved(@NotNull CaretEvent event) {
179 | updateInlayHints(event.getEditor());
180 | }
181 |
182 | @Override
183 | public void afterDocumentChange(@NotNull Document document) {
184 | enableSuggestion = true;
185 | if (ApplicationManager.getApplication().isDispatchThread()) {
186 | EditorFactory.getInstance().editors(document)
187 | .filter(this::isFocusedEditor)
188 | .findFirst()
189 | .ifPresent(this::updateInlayHints);
190 | }
191 | }
192 |
193 | private void updateInlayHints(Editor focusedEditor) {
194 | if (Objects.isNull(focusedEditor) || !EditorUtils.isMainEditor(focusedEditor)) {
195 | return;
196 | }
197 | VirtualFile file = FileDocumentManager.getInstance().getFile(focusedEditor.getDocument());
198 | if (Objects.isNull(file)) {
199 | return;
200 | }
201 |
202 | String selection = focusedEditor.getCaretModel().getCurrentCaret().getSelectedText();
203 | if (Objects.nonNull(selection) && !selection.isEmpty()) {
204 | String[] existingHints = file.getUserData(SHELL_CODER_CODE_SUGGESTION);
205 | if (Objects.nonNull(existingHints) && existingHints.length > 0) {
206 | file.putUserData(SHELL_CODER_CODE_SUGGESTION, null);
207 | file.putUserData(SHELL_CODER_POSITION, focusedEditor.getCaretModel().getOffset());
208 |
209 | InlayModel inlayModel = focusedEditor.getInlayModel();
210 | inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
211 | inlayModel.getBlockElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
212 | }
213 | return;
214 | }
215 |
216 | Integer codeShellPos = file.getUserData(SHELL_CODER_POSITION);
217 | int lastPosition = (Objects.isNull(codeShellPos)) ? 0 : codeShellPos;
218 | int currentPosition = focusedEditor.getCaretModel().getOffset();
219 |
220 | if (lastPosition == currentPosition) return;
221 |
222 | InlayModel inlayModel = focusedEditor.getInlayModel();
223 | if (currentPosition > lastPosition) {
224 | String[] existingHints = file.getUserData(SHELL_CODER_CODE_SUGGESTION);
225 | if (Objects.nonNull(existingHints) && existingHints.length > 0) {
226 | String inlineHint = existingHints[0];
227 | String modifiedText = focusedEditor.getDocument().getCharsSequence().subSequence(lastPosition, currentPosition).toString();
228 | if (modifiedText.startsWith("\n")) {
229 | modifiedText = modifiedText.replace(" ", "");
230 | }
231 | if (inlineHint.startsWith(modifiedText)) {
232 | inlineHint = inlineHint.substring(modifiedText.length());
233 | enableSuggestion = false;
234 | if (inlineHint.length() > 0) {
235 | inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
236 | inlayModel.addInlineElement(currentPosition, true, new CodeGenHintRenderer(inlineHint));
237 | existingHints[0] = inlineHint;
238 |
239 | file.putUserData(SHELL_CODER_CODE_SUGGESTION, existingHints);
240 | file.putUserData(SHELL_CODER_POSITION, currentPosition);
241 | return;
242 | } else if (existingHints.length > 1) {
243 | existingHints = Arrays.copyOfRange(existingHints, 1, existingHints.length);
244 | CodeShellUtils.addCodeSuggestion(focusedEditor, file, currentPosition, existingHints);
245 | return;
246 | } else {
247 | file.putUserData(SHELL_CODER_CODE_SUGGESTION, null);
248 | }
249 | }
250 | }
251 | }
252 |
253 | inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
254 | inlayModel.getBlockElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
255 |
256 | file.putUserData(SHELL_CODER_POSITION, currentPosition);
257 | if(!enableSuggestion || currentPosition < lastPosition){
258 | enableSuggestion = false;
259 | return;
260 | }
261 | CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class);
262 | CharSequence editorContents = focusedEditor.getDocument().getCharsSequence();
263 | CompletableFuture future = CompletableFuture.supplyAsync(() -> codeShell.getCodeCompletionHints(editorContents, currentPosition));
264 | future.thenAccept(hintList -> CodeShellUtils.addCodeSuggestion(focusedEditor, file, currentPosition, hintList));
265 | }
266 |
267 | }
268 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/widget/CodeShellWidgetFactory.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.widget;
2 |
3 | import com.intellij.openapi.project.Project;
4 | import com.intellij.openapi.util.Disposer;
5 | import com.intellij.openapi.wm.StatusBarWidget;
6 | import com.intellij.openapi.wm.impl.status.widget.StatusBarEditorBasedWidgetFactory;
7 | import org.jetbrains.annotations.Nls;
8 | import org.jetbrains.annotations.NonNls;
9 | import org.jetbrains.annotations.NotNull;
10 |
11 | public class CodeShellWidgetFactory extends StatusBarEditorBasedWidgetFactory {
12 | @Override
13 | public @NonNls @NotNull String getId() {
14 | return CodeShellWidget.ID;
15 | }
16 |
17 | @Override
18 | public @Nls @NotNull String getDisplayName() {
19 | return "CodeShell";
20 | }
21 |
22 | @Override
23 | public @NotNull StatusBarWidget createWidget(@NotNull Project project) {
24 | return new CodeShellWidget(project);
25 | }
26 |
27 | @Override
28 | public void disposeWidget(@NotNull StatusBarWidget widget) {
29 | Disposer.dispose(widget);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/window/CodeShellSideWindow.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.window;
2 |
3 | import com.codeshell.intellij.enums.CodeShellURI;
4 | import com.codeshell.intellij.handlers.CustomSchemeHandlerFactory;
5 | import com.codeshell.intellij.services.CodeShellSideWindowService;
6 | import com.codeshell.intellij.settings.CodeShellSettings;
7 | import com.codeshell.intellij.utils.CodeShellUtils;
8 | import com.google.gson.JsonObject;
9 | import com.intellij.openapi.diagnostic.Logger;
10 | import com.intellij.openapi.project.Project;
11 | import com.intellij.openapi.util.Disposer;
12 | import com.intellij.openapi.util.SystemInfo;
13 | import com.intellij.ui.jcef.JBCefBrowser;
14 | import com.intellij.ui.jcef.JBCefBrowserBase;
15 | import com.intellij.ui.jcef.JBCefJSQuery;
16 | import org.cef.CefApp;
17 | import org.cef.browser.CefBrowser;
18 | import org.cef.browser.CefFrame;
19 | import org.cef.handler.CefLifeSpanHandlerAdapter;
20 | import org.cef.handler.CefLoadHandler;
21 | import org.cef.network.CefRequest;
22 |
23 | import javax.swing.*;
24 | import java.util.Objects;
25 |
26 | public class CodeShellSideWindow {
27 |
28 | private final Logger logger = Logger.getInstance(this.getClass());
29 | private JBCefBrowser jbCefBrowser;
30 | private final Project project;
31 | private boolean webLoaded;
32 |
33 | public CodeShellSideWindow(Project project) {
34 | super();
35 | this.webLoaded = false;
36 | this.project = project;
37 | }
38 |
39 | public synchronized JBCefBrowser jbCefBrowser() {
40 | return !this.webLoaded ? lazyLoad() : this.jbCefBrowser;
41 | }
42 |
43 | private JBCefBrowser lazyLoad() {
44 | try {
45 | String ideaVersion = CodeShellUtils.getIDEVersion("major");
46 | if (!this.webLoaded) {
47 | boolean isOffScreenRendering = true;
48 | if (SystemInfo.isMac) {
49 | isOffScreenRendering = false;
50 | } else if (SystemInfo.isLinux || SystemInfo.isUnix) {
51 | int version = Integer.parseInt(ideaVersion);
52 | if (version >= 2023) {
53 | isOffScreenRendering = true;
54 | } else if (version < 2023) {
55 | isOffScreenRendering = false;
56 | }
57 | } else if (SystemInfo.isWindows) {
58 | isOffScreenRendering = false;
59 | }
60 | JBCefBrowser browser;
61 | try {
62 | browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOffScreenRendering).build();
63 | } catch (Exception e) {
64 | logger.error("JBCefBrowser# build Browser not supported", e);
65 | browser = new JBCefBrowser();
66 | }
67 |
68 | registerLifeSpanHandler(browser);
69 | registerJsCallJavaHandler(browser);
70 | browser.loadURL("http://codeshell/index.html?");
71 | this.jbCefBrowser = browser;
72 | this.webLoaded = true;
73 | }
74 | } catch (Exception e) {
75 | logger.error("JBCefBrowser lazyLoad error", e);
76 | }
77 | return this.jbCefBrowser;
78 | }
79 |
80 | private void registerJsCallJavaHandler(JBCefBrowser browser) {
81 | JBCefJSQuery query = JBCefJSQuery.create((JBCefBrowserBase) browser);
82 | query.addHandler((String arg) -> {
83 | try {
84 | return new JBCefJSQuery.Response("123");
85 | } catch (Exception e) {
86 | logger.warn("JBCefJSQuery error", e);
87 | return new JBCefJSQuery.Response(null, 0, "errorMsg");
88 | }
89 | });
90 | browser.getJBCefClient().addLoadHandler(new CefLoadHandler() {
91 | @Override
92 | public void onLoadingStateChange(CefBrowser browser, boolean isLoading, boolean canGoBack, boolean canGoForward) {
93 |
94 | }
95 |
96 | @Override
97 | public void onLoadStart(CefBrowser browser, CefFrame frame, CefRequest.TransitionType transitionType) {
98 |
99 | }
100 |
101 | @Override
102 | public void onLoadEnd(CefBrowser browser, CefFrame frame, int httpStatusCode) {
103 |
104 | JsonObject jsonObject = new JsonObject();
105 | if(CodeShellSettings.getInstance().isCPURadioButtonEnabled()){
106 | jsonObject.addProperty("sendUrl", CodeShellSettings.getInstance().getServerAddressURL() + CodeShellURI.CPU_CHAT.getUri());
107 | jsonObject.addProperty("modelType", "CPU");
108 | }else{
109 | jsonObject.addProperty("sendUrl", CodeShellSettings.getInstance().getServerAddressURL() + CodeShellURI.GPU_CHAT.getUri());
110 | jsonObject.addProperty("modelType", "GPU");
111 | }
112 | jsonObject.addProperty("maxToken", CodeShellSettings.getInstance().getChatMaxToken().getDescription());
113 | JsonObject result = new JsonObject();
114 | result.addProperty("data", jsonObject.toString());
115 | (project.getService(CodeShellSideWindowService.class)).notifyIdeAppInstance(result);
116 |
117 | browser.executeJavaScript(
118 | "window.callJava = function(arg) {" +
119 | query.inject(
120 | "arg",
121 | "response => console.log(response)",
122 | "(error_code, error_message) => console.log('callJava 失败', error_code, error_message)"
123 | ) +
124 | "};",
125 | null, 0);
126 | }
127 |
128 | @Override
129 | public void onLoadError(CefBrowser browser, CefFrame frame, ErrorCode errorCode, String errorText, String failedUrl) {
130 | logger.error("JBCefBrowser# onLoadError, failedUrl:{}, errorText:{}", failedUrl, errorText);
131 | }
132 | }, browser.getCefBrowser());
133 | }
134 |
135 | private void registerLifeSpanHandler(JBCefBrowser browser) {
136 | final CefLifeSpanHandlerAdapter lifeSpanHandlerAdapter = new CefLifeSpanHandlerAdapter() {
137 | @Override
138 | public void onAfterCreated(CefBrowser browse) {
139 | CefApp.getInstance().registerSchemeHandlerFactory("http", "codeshell", new CustomSchemeHandlerFactory(CodeShellSideWindow.this.project));
140 | }
141 | };
142 | browser.getJBCefClient().addLifeSpanHandler(lifeSpanHandlerAdapter, browser.getCefBrowser());
143 | final JBCefBrowser tempBrowser = browser;
144 | Disposer.register(this.project, () -> tempBrowser.getJBCefClient().removeLifeSpanHandler(lifeSpanHandlerAdapter, tempBrowser.getCefBrowser()));
145 | }
146 |
147 | public JComponent getComponent() {
148 | if (Objects.nonNull(jbCefBrowser())) {
149 | return jbCefBrowser().getComponent();
150 | }
151 | return null;
152 | }
153 |
154 |
155 | }
156 |
157 |
158 |
159 |
160 |
161 |
--------------------------------------------------------------------------------
/src/main/java/com/codeshell/intellij/window/CodeShellSideWindowFactory.java:
--------------------------------------------------------------------------------
1 | package com.codeshell.intellij.window;
2 |
3 | import com.codeshell.intellij.services.CodeShellSideWindowService;
4 | import com.intellij.openapi.project.Project;
5 | import com.intellij.openapi.wm.ToolWindow;
6 | import com.intellij.openapi.wm.ToolWindowFactory;
7 | import com.intellij.ui.content.Content;
8 | import com.intellij.ui.content.ContentManager;
9 | import com.intellij.ui.jcef.JBCefApp;
10 | import org.jetbrains.annotations.NotNull;
11 |
12 | import javax.swing.*;
13 | import java.awt.*;
14 | import java.util.Objects;
15 |
16 | public class CodeShellSideWindowFactory implements ToolWindowFactory {
17 |
18 | @Override
19 | public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
20 | ContentManager contentManager = toolWindow.getContentManager();
21 | JPanel webPanel = new JPanel(new BorderLayout());
22 | CodeShellSideWindowService service = project.getService(CodeShellSideWindowService.class);
23 | if (Objects.nonNull(service.getCodeShellSideWindow()) && Objects.nonNull(service.getCodeShellSideWindow().getComponent())) {
24 | webPanel.add(service.getCodeShellSideWindow().getComponent());
25 | Content labelContent = contentManager.getFactory().createContent(webPanel, "", false);
26 | contentManager.addContent(labelContent);
27 | }
28 | }
29 |
30 | static {
31 | JBCefApp.getInstance();
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/resources/META-INF/plugin.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | codeshell
5 |
6 |
8 | CodeShell
9 |
10 |
11 | WisdomShell
12 |
13 |
16 |
21 | Features:
22 |
23 | - Explain/Optimize/Cleanse a Code Segment
24 | - Generate Comments/Unit Tests for Code
25 | - Check Code for Performance/Security Issues
26 | - Support for Multi-turn Conversations
27 | - Edit Questions and Rephrase Inquiries
28 | - Request Fresh Responses for Any Question
29 | - Interrupt During the Answering Process
30 |
31 |
32 |
33 |
34 | The plugin relies on a locally running CodeShell model. For more information, please refer to CodeShell repository
35 | ]]>
36 |
37 |
39 | com.intellij.modules.platform
40 |
41 |
43 |
44 |
45 |
46 |
48 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
--------------------------------------------------------------------------------
/src/main/resources/assets/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WisdomShell/codeshell-intellij/62ffd71bea45989a973288d8f6c7fa98071758ee/src/main/resources/assets/logo.png
--------------------------------------------------------------------------------
/src/main/resources/assets/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/src/main/resources/assets/readme/docs_assistants.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WisdomShell/codeshell-intellij/62ffd71bea45989a973288d8f6c7fa98071758ee/src/main/resources/assets/readme/docs_assistants.png
--------------------------------------------------------------------------------
/src/main/resources/assets/readme/docs_chat.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WisdomShell/codeshell-intellij/62ffd71bea45989a973288d8f6c7fa98071758ee/src/main/resources/assets/readme/docs_chat.png
--------------------------------------------------------------------------------
/src/main/resources/assets/readme/docs_completion.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WisdomShell/codeshell-intellij/62ffd71bea45989a973288d8f6c7fa98071758ee/src/main/resources/assets/readme/docs_completion.png
--------------------------------------------------------------------------------
/src/main/resources/assets/readme/docs_debug_plugin.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WisdomShell/codeshell-intellij/62ffd71bea45989a973288d8f6c7fa98071758ee/src/main/resources/assets/readme/docs_debug_plugin.png
--------------------------------------------------------------------------------
/src/main/resources/assets/readme/docs_install_plugin.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WisdomShell/codeshell-intellij/62ffd71bea45989a973288d8f6c7fa98071758ee/src/main/resources/assets/readme/docs_install_plugin.png
--------------------------------------------------------------------------------
/src/main/resources/assets/readme/docs_settings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WisdomShell/codeshell-intellij/62ffd71bea45989a973288d8f6c7fa98071758ee/src/main/resources/assets/readme/docs_settings.png
--------------------------------------------------------------------------------
/src/main/resources/webview/css/app.85ac4201.css:
--------------------------------------------------------------------------------
1 | [data-v-0784d80e] .markdown-body p{margin:0}.markdown-body[data-v-0784d80e]{border-radius:8px;padding:8px}.aaa[data-v-d3949b08]:hover{background-color:hsla(0,1%,39%,.58);transition:.3s}.addHistory[data-v-145bd453]{font-weight:bolder;border-radius:4px;text-align:center;line-height:26px;font-size:18px;border:1px solid #409eff;background-color:#409eff;color:#fff;cursor:pointer;margin:0 20px;width:26px;height:26px}.stopStyle[data-v-145bd453]{padding-top:2px;width:130px;background-color:hsla(0,0%,100%,0);color:#fff;outline:none;border:1px solid #868484;border-radius:5px 5px 0 0;cursor:pointer}.loadingIcon[data-v-145bd453],.sendIcon[data-v-145bd453]{width:34px;display:flex;justify-content:center;align-items:center;margin-left:16px;cursor:pointer;color:#fff}.sendIcon[data-v-145bd453]{background-color:#409eff;border-radius:3px}[data-v-145bd453] .markdown-body{background-color:#303943}[data-v-145bd453] .markdown-body p{padding:0 12px;color:#fff}[data-v-145bd453] .el-icon-loading{color:#fff}[data-v-145bd453] .el-loading-mask{border-radius:8px;justify-content:center;display:flex;align-items:center}[data-v-145bd453] .el-loading-spinner{border-radius:8px;font-size:22px;top:26px}.container[data-v-145bd453]{background-color:#3d3d3f;width:100%}.container .container-head[data-v-145bd453]{height:50px;display:flex;justify-content:flex-end;align-items:center;border-bottom:1px solid #817b7b;width:98%;margin:0 auto}.container .main-box[data-v-145bd453]{cursor:pointer;display:flex;border-radius:4px;margin:14px 0 4px 20px;background-color:#409eff;width:28px;color:#fff;justify-content:center;align-items:center}.container .main-title[data-v-145bd453]{justify-content:space-between;padding:6px 12px;color:#fff}.container .container-main[data-v-145bd453]{width:100%;overflow-y:scroll;height:calc(100vh - 234px)}.container .container-foot[data-v-145bd453]{width:100%}[data-v-145bd453]::-webkit-scrollbar{width:5px}[data-v-145bd453]::-webkit-scrollbar-thumb{background-color:#817b7b}[data-v-145bd453] .el-textarea__inner{height:120px;display:block;resize:vertical;padding:10px 15px;box-sizing:border-box;width:96%;color:#000;background-color:#fff;background-image:none;border:none;border-radius:4px;transition:border-color .2s cubic-bezier(.645,.045,.355,1);font-family:Helvetica Neue,Helvetica,PingFang SC,Hiragino Sans GB,Microsoft YaHei,微软雅黑,Arial,sans-serif}[data-v-145bd453] .el-divider--horizontal{background-color:#6e6d6d;width:98%;margin:0 auto}[data-v-145bd453] .markdown-body p{margin:0}[data-v-145bd453] .el-radio{color:#fff;margin-right:16px}#app{color:#2c3e50;font-size:14px;font-family:Microsoft YaHei,微软雅黑}body{margin:0}
--------------------------------------------------------------------------------
/src/main/resources/webview/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WisdomShell/codeshell-intellij/62ffd71bea45989a973288d8f6c7fa98071758ee/src/main/resources/webview/favicon.ico
--------------------------------------------------------------------------------
/src/main/resources/webview/fonts/element-icons.f1a45d74.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WisdomShell/codeshell-intellij/62ffd71bea45989a973288d8f6c7fa98071758ee/src/main/resources/webview/fonts/element-icons.f1a45d74.ttf
--------------------------------------------------------------------------------
/src/main/resources/webview/fonts/element-icons.ff18efd1.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/WisdomShell/codeshell-intellij/62ffd71bea45989a973288d8f6c7fa98071758ee/src/main/resources/webview/fonts/element-icons.ff18efd1.woff
--------------------------------------------------------------------------------
/src/main/resources/webview/index.html:
--------------------------------------------------------------------------------
1 | CodeShell
--------------------------------------------------------------------------------
/src/main/resources/webview/js/app.1d492095.js:
--------------------------------------------------------------------------------
1 | (function(){"use strict";var e={74032:function(e,t,n){var s=n(20144),i=function(){var e=this,t=e._self._c;return t("div",{attrs:{id:"app"}},[t("MainPage")],1)},a=[],o=function(){var e=this,t=e._self._c;return t("div",{staticClass:"container",staticStyle:{height:"100vh"}},[t("div",{staticClass:"container-head"},[t("el-popover",{attrs:{placement:"left",trigger:"hover"}},[t("span",[e._v("添加新会话")]),t("span",{staticClass:"el-icon-plus addHistory",attrs:{slot:"reference"},on:{click:e.addChart},slot:"reference"})])],1),t("div",{ref:"mainRef",staticClass:"container-main"},[e.dataList?.length&&e.dataList?.length>0?t("div",e._l(e.dataList,(function(n,s){return t("div",{key:s},[t("div",{staticClass:"main-title"},[t("QuestionComponent",{attrs:{question:n.question}})],1),t("div",{staticClass:"main-title"},[t("div",{staticStyle:{display:"flex","justify-content":"space-between","padding-left":"8px","margin-bottom":"5px"}},[t("div",{staticStyle:{"font-weight":"bold","font-size":"14px"}},[e._v("Answer:")]),t("div",[n.refresh?t("span",{staticClass:"el-icon-refresh-right",staticStyle:{"margin-right":"8px",cursor:"pointer","font-size":"16px"},on:{click:function(t){return e.onRefresh(n.question)}}}):e._e(),n.success?t("span",{directives:[{name:"clipboard",rawName:"v-clipboard:copy",value:n.answer,expression:"item.answer",arg:"copy"},{name:"clipboard",rawName:"v-clipboard:success",value:e.onCopy,expression:"onCopy",arg:"success"},{name:"clipboard",rawName:"v-clipboard:error",value:e.onCopyError,expression:"onCopyError",arg:"error"}],staticClass:"el-icon-document-copy",staticStyle:{cursor:"pointer","font-size":"16px"}}):e._e()])]),t("div",{directives:[{name:"loading",rawName:"v-loading",value:s===e.dataList?.length-1&&e.loading,expression:"index === dataList?.length - 1 && loading"}],staticStyle:{"background-color":"#303943","border-radius":"8px",padding:"8px"},attrs:{"element-loading-background":"rgb(255 255 255 / 28%)","element-loading-spinner":"el-icon-loading"}},[t("div",{staticClass:"markdown-body",staticStyle:{"min-height":"24px","font-size":"14px"}},[t("vue-markdown",{directives:[{name:"highlight",rawName:"v-highlight"}],attrs:{source:n.answer}})],1)])]),s!==e.dataList?.length-1?t("el-divider"):e._e()],1)})),0):e._e(),e.dataList?.length&&0!==e.dataList?.length?e._e():t("div",{staticStyle:{margin:"auto",width:"80%","text-align":"center","padding-top":"100px"}},[t("QuickSearch",{on:{quickSend:e.quickSend}})],1)]),t("div",{staticClass:"container-foot"},[t("div",{staticStyle:{"margin-bottom":"10px"}},[t("div",{staticStyle:{display:"flex","justify-content":"center",height:"20px"}},[e.stopVisible?t("button",{staticClass:"stopStyle",on:{click:e.stop}},[e._v("stop generating")]):e._e()]),t("el-input",{staticStyle:{width:"100%",display:"flex","justify-content":"center"},attrs:{placeholder:"请输入内容",type:"textarea",resize:"none",id:"textArea",contenteditable:"true"},model:{value:e.sendMessage,callback:function(t){e.sendMessage=t},expression:"sendMessage"}})],1),t("div",{staticStyle:{display:"flex","justify-content":"end",color:"#777777",width:"97%",height:"20px"},attrs:{id:"sendContainer"}},[t("div",[e._v("Enter 发送")]),e.loading?e._e():t("div",{staticClass:"sendIcon",on:{click:e.send}},[t("div",{staticClass:"el-icon-position",staticStyle:{rotate:"45deg","font-size":"16px"}})]),e.loading?t("div",{staticClass:"loadingIcon"},[t("div",{staticClass:"el-icon-loading",staticStyle:{"font-size":"16px"}})]):e._e()])])])},r=[],l=(n(57658),n(89296)),d=n.n(l),c=function(){var e=this,t=e._self._c;return t("div",[t("div",{staticStyle:{"text-indent":"8px","margin-bottom":"5px","font-weight":"bold","font-size":"14px"}},[e._v("Question:")]),t("div",{staticClass:"markdown-body",staticStyle:{"font-size":"14px"}},[t("vue-markdown",{directives:[{name:"highlight",rawName:"v-highlight"}],attrs:{source:e.question}})],1)])},u=[],p={components:{VueMarkdown:d()},props:["question"],name:"questionComponent"},h=p,g=n(1001),f=(0,g.Z)(h,c,u,!1,null,"0784d80e",null),m=f.exports,v=function(){var e=this,t=e._self._c;return t("div",e._l(e.list,(function(n,s){return t("div",{key:s,staticStyle:{color:"white"}},[t("div",{staticClass:"aaa",staticStyle:{border:"1px solid rgba(147,146,146,0.8)","margin-bottom":"8px","border-radius":"16px",padding:"8px 0",cursor:"pointer"},on:{click:function(t){return e.quickSend(n)}}},[e._v(" "+e._s(n)+" ")])])})),0)},y=[],b={name:"quickSearch",data(){return{list:["Generate code in Java to convert a number from one base to another","Generate code to implement a simple REST API in go","How to set global variables in git","Create an encrypted s3 bucket using the AWS CLI","Explain B+ trees, give an example with code"]}},methods:{quickSend(e){this.$emit("quickSend",e)}}},x=b,w=(0,g.Z)(x,v,y,!1,null,"d3949b08",null),S=w.exports,C=n(96486),k=n.n(C),_=n(20637),L=n(1375);const T=(e,t)=>({inputs:`##human:${e}||##assistant:`,parameters:{max_new_tokens:t??1024,temperature:.2,top_p:.95,do_sample:!0,repetition_penalty:1,stop:["||","","<|endoftext|>","## human","|end|","|end>|","({frequency_penalty:1.2,n_predict:t??1024,prompt:`||## human:${e}||## assistant:`,temperature:.2,stream:!0,stop:["||"]});var O={name:"MainPage",components:{"vue-markdown":d(),QuestionComponent:m,QuickSearch:S},data(){return{loading:!1,inputs:"",sendMessage:"",dataList:[],res:"",range:null,inputHeight:"",messageType:"",answer:"",delay:50,stopStatus:!1,stopVisible:!1,ideaSelect:null,sendUrl:null,maxToken:null,controller:new AbortController,modelType:"CPU"}},methods:{addChart(){this.$confirm("确定要清空所有对话记录?","提示",{confirmButtonText:"确定",cancelButtonText:"取消",type:"warning",center:!0}).then((()=>{this.dataList=[]})).catch((e=>{console.debug(e)}))},send(){if(k().isEmpty(k().trim(this.sendMessage)))return void this.$message({message:"message is empty",type:"warning"});this.loading=!0,this.dataList.push({question:this.ideaSelect??this.sendMessage,answer:""});const e=this.sendMessage;this.sendMessage="",this.stopStatus=!1,this.$refs.mainRef.scrollTop=this.$refs.mainRef.scrollHeight;const t=this;t.stopVisible=!0,(0,L.L)(this.sendUrl??"http://127.0.0.1:8080/completion",{method:"POST",signal:t.controller.signal,headers:{"Content-Type":"application/json"},body:JSON.stringify("GPU"===this.modelType?T(e,this.maxToken):M(e,this.maxToken)),onerror(){t.$message.error("返回错误!"),t.ideaSelect=null,t.loading=!1,t.ideaSelect=null,t.stopVisible=!1,t.controller.abort("onerror"),t.controller=new AbortController,this.onclose()},onmessage({data:e}){const n=/[|<]+end[>|]+|<\|endoftext\|>|## human/g;if(e){t.stopVisible=!0,t.loading=!1;const{content:s,stop:i,generated_text:a,token:o}=JSON.parse(e)??{},{text:r}={...o};if(i)return t.dataList=k().map(t.dataList,((e,s)=>k().size(t.dataList)-1===s?{...e,answer:k().replace(e.answer,n,"")}:e)),t.ideaSelect=null,t.stopVisible=!1,t.controller.abort(),void(t.controller=new AbortController);if(s)t.dataList=k().map(t.dataList,((e,n)=>k().size(t.dataList)-1===n?{...e,refresh:!0,success:!0,answer:e.answer+s}:e));else if(r&&(t.dataList=k().map(t.dataList,((e,n)=>k().size(t.dataList)-1===n?{...e,refresh:!0,success:!0,answer:e.answer+r}:e)),a)){const e=k().replace(a,n,"");t.dataList=k().map(t.dataList,((n,s)=>k().size(t.dataList)-1===s?{...n,refresh:!0,success:!0,answer:e}:n)),t.ideaSelect=null,t.stopVisible=!1,t.controller.abort(),t.controller=new AbortController}t.$refs.mainRef.scrollTop=t.$refs.mainRef.scrollHeight}},onclose(){}})},async stop(){await this.controller.abort(),this.controller=new AbortController,this.loading=!1,this.stopStatus=!0,this.stopVisible=!1},quickSend(e){this.sendMessage=e},onCopy(){this.$message.success("已复制到剪贴板")},onCopyError(){this.$message.warning("复制失败")},onRefresh(e){this.sendMessage=e,this.send()}},mounted(){window.addEventListener("message",(e=>{const{data:t}=e?.data;if(k().isString(t)){const n=JSON.parse(t)??{},{range:s,sendText:i,sendUrl:a,maxToken:o,modelType:r}={...n};this.modelType=r,this.sendUrl=a,console.debug("IDEA JSON","-------\x3e",e),console.debug("IDEA MESSAGE",n,"-------\x3e",s,i,a);const{inputs:l}={...i},{selectedText:d,end:c,start:u}={...s};console.debug("range ----\x3e",u,c,"selectedText -----\x3e",d),this.ideaSelect=d,this.sendMessage=l,this.maxToken=o?k().toNumber(o):1024,!r&&this.$message.warning("请选择模型运行环境!"),i&&this.send()}})),document.getElementById("textArea").addEventListener("keydown",(e=>{13!==e.keyCode||e.shiftKey||(e.preventDefault(),this.send())}))},updated(){this.$el.querySelectorAll("pre").forEach((e=>{_.Z.highlightBlock(e)}))}},q=O,E=(0,g.Z)(q,o,r,!1,null,"145bd453",null),$=E.exports,A={name:"App",components:{MainPage:$},data(){return{test:""}}},j=A,z=(0,g.Z)(j,i,a,!1,null,null,null),N=z.exports,P=n(64720),V=n.n(P),R=n(6154),Z=n(72268),I=n.n(Z);n(34457);s["default"].prototype.$axios=R.Z,s["default"].prototype.$hljs=_.Z,s["default"].directive("highlight",(e=>{let t=e.querySelectorAll("pre code");t.forEach((e=>{_.Z.highlightBlock(e)}))})),s["default"].config.productionTip=!1,s["default"].use(V()),s["default"].use(I()),new s["default"]({render:e=>e(N)}).$mount("#app")}},t={};function n(s){var i=t[s];if(void 0!==i)return i.exports;var a=t[s]={id:s,loaded:!1,exports:{}};return e[s].call(a.exports,a,a.exports,n),a.loaded=!0,a.exports}n.m=e,function(){n.amdO={}}(),function(){var e=[];n.O=function(t,s,i,a){if(!s){var o=1/0;for(c=0;c=a)&&Object.keys(n.O).every((function(e){return n.O[e](s[l])}))?s.splice(l--,1):(r=!1,a0&&e[c-1][2]>a;c--)e[c]=e[c-1];e[c]=[s,i,a]}}(),function(){n.n=function(e){var t=e&&e.__esModule?function(){return e["default"]}:function(){return e};return n.d(t,{a:t}),t}}(),function(){n.d=function(e,t){for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})}}(),function(){n.g=function(){if("object"===typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"===typeof window)return window}}()}(),function(){n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}}(),function(){n.r=function(e){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}}(),function(){n.nmd=function(e){return e.paths=[],e.children||(e.children=[]),e}}(),function(){var e={143:0};n.O.j=function(t){return 0===e[t]};var t=function(t,s){var i,a,o=s[0],r=s[1],l=s[2],d=0;if(o.some((function(t){return 0!==e[t]}))){for(i in r)n.o(r,i)&&(n.m[i]=r[i]);if(l)var c=l(n)}for(t&&t(s);d