From 50515b7fd8ddf5a4acc58bc8e5b118b4ebf4c540 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Fri, 18 Oct 2024 17:35:21 +0700 Subject: [PATCH 1/9] improv: preserve punctuation completions --- core/autocomplete/completionProvider.ts | 10 +++++++--- core/autocomplete/filter.ts | 6 +++--- manual-testing-sandbox/Button.tsx | 15 +++++++++++++++ 3 files changed, 25 insertions(+), 6 deletions(-) create mode 100644 manual-testing-sandbox/Button.tsx diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index d954c3f31..bc826f934 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -28,7 +28,7 @@ import { constructAutocompletePrompt, languageForFilepath, } from "./constructPrompt.js"; -import { isOnlyPunctuationAndWhitespace } from "./filter.js"; +import { isOnlyWhitespace } from "./filter.js"; import { AutocompleteLanguageInfo } from "./languages.js"; import { postprocessCompletion } from "./postprocessing.js"; import { AutocompleteSnippet } from "./ranking.js"; @@ -355,8 +355,12 @@ export class CompletionProvider { return undefined; } - // Filter out unwanted results - if (isOnlyPunctuationAndWhitespace(outcome.completion)) { + /** + * This check is most likely not needed because we do trim the LLM output + * elsewhere in the code. That said, I'm not yet confident enough to + * remove this. + */ + if (isOnlyWhitespace(outcome.completion)) { return undefined; } diff --git a/core/autocomplete/filter.ts b/core/autocomplete/filter.ts index 9fb9b7d0b..5b2b66df0 100644 --- a/core/autocomplete/filter.ts +++ b/core/autocomplete/filter.ts @@ -1,4 +1,4 @@ -export function isOnlyPunctuationAndWhitespace(completion: string): boolean { - const punctuationAndWhitespaceRegex = /^[^\w\d\}\)\]]+$/; - return punctuationAndWhitespaceRegex.test(completion); +export function isOnlyWhitespace(completion: string): boolean { + const whitespaceRegex = /^[\s]+$/; + return whitespaceRegex.test(completion); } diff --git a/manual-testing-sandbox/Button.tsx b/manual-testing-sandbox/Button.tsx new file mode 100644 index 000000000..4d6f8f91b --- /dev/null +++ b/manual-testing-sandbox/Button.tsx @@ -0,0 +1,15 @@ +import React from "react"; + +export const Button = ({ + onClick, + children, +}: { + children: React.ReactNode; + onClick: () => void; +}) => { + return ( + + ); +}; From f280eca8ae85558ecd995dc5b679a100ea5bd04f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 21 Oct 2024 22:20:02 +0200 Subject: [PATCH 2/9] remove stack overflow context provider --- core/commands/slash/index.ts | 2 - core/commands/slash/stackOverflow.ts | 126 --------------------- docs/docs/customize/slash-commands.md | 15 --- gui/src/redux/slices/serverStateReducer.ts | 1 - 4 files changed, 144 deletions(-) delete mode 100644 core/commands/slash/stackOverflow.ts diff --git a/core/commands/slash/index.ts b/core/commands/slash/index.ts index 0a6fc327d..f94c6ee05 100644 --- a/core/commands/slash/index.ts +++ b/core/commands/slash/index.ts @@ -6,13 +6,11 @@ import EditSlashCommand from "./edit"; import HttpSlashCommand from "./http"; import ReviewMessageCommand from "./review"; import ShareSlashCommand from "./share"; -import StackOverflowSlashCommand from "./stackOverflow"; import OnboardSlashCommand from "./onboard"; export default [ DraftIssueCommand, ShareSlashCommand, - StackOverflowSlashCommand, GenerateTerminalCommand, EditSlashCommand, CommentSlashCommand, diff --git a/core/commands/slash/stackOverflow.ts b/core/commands/slash/stackOverflow.ts deleted file mode 100644 index 3e967990d..000000000 --- a/core/commands/slash/stackOverflow.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { TRIAL_PROXY_URL } from "../../control-plane/client.js"; -import { ChatMessageRole, FetchFunction, SlashCommand } from "../../index.js"; -import { pruneStringFromBottom } from "../../llm/countTokens.js"; -import { stripImages } from "../../llm/images.js"; - -const PROMPT = ( - input: string, -) => `The above sources are excerpts from related StackOverflow questions. Use them to help answer the below question from our user. Provide links to the sources in markdown whenever possible: - -${input} -`; - -async function getResults(q: string, fetch: FetchFunction): Promise { - const payload = JSON.stringify({ - q: `${q} site:stackoverflow.com`, - }); - - const resp = await fetch(new URL("/search", TRIAL_PROXY_URL), { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: payload, - }); - return await resp.json(); -} - -async function fetchData( - url: string, - fetch: FetchFunction, -): Promise { - const response = await fetch(url, { - headers: { - Accept: "text/html", - }, - }); - const htmlString = await response.text(); - - const parser = new DOMParser(); - const doc = parser.parseFromString(htmlString, "text/html"); - - const h1 = doc.querySelector("h1.fs-headline1"); - const title = h1?.textContent?.trim() ?? "No Title"; - - const bodies = doc.querySelectorAll("div.js-post-body"); - if (bodies.length < 2) { - return undefined; - } - - const question = bodies[0].textContent ?? ""; - const answer = bodies[1].textContent ?? ""; - - return ` - # Question: [${title}](${url}) - -${question} - -# Best Answer - -${answer} - `; -} - -const StackOverflowSlashCommand: SlashCommand = { - name: "so", - description: "Search Stack Overflow", - run: async function* ({ llm, input, addContextItem, history, fetch }) { - const contextLength = llm.contextLength; - - const sources: string[] = []; - const results = await getResults(input, fetch); - const links = results.organic.map((result: any) => result.link); - let totalTokens = llm.countTokens(input) + 200; - - for (const link of links) { - const contents = await fetchData(link, fetch); - if (!contents) { - continue; - } - sources.push(contents); - const newTokens = llm.countTokens(contents); - totalTokens += newTokens; - - let shouldBreak = false; - if (totalTokens > contextLength) { - sources[sources.length - 1] = pruneStringFromBottom( - llm.model, - contextLength - (totalTokens - newTokens), - sources[sources.length - 1], - ); - shouldBreak = true; - } - - if (sources.length >= 3) { - shouldBreak = true; - } - - addContextItem({ - content: sources[sources.length - 1], - description: "StackOverflow Answer", - name: `StackOverflow ${sources.length}`, - id: { - providerTitle: "so", - itemId: links[sources.length - 1], - }, - }); - - if (shouldBreak) { - break; - } - } - - for await (const chunk of llm.streamChat([ - ...history, - ...sources.map((source) => ({ - role: "user" as ChatMessageRole, - content: source, - })), - { role: "user", content: PROMPT(input) }, - ])) { - yield stripImages(chunk.content); - } - }, -}; - -export default StackOverflowSlashCommand; diff --git a/docs/docs/customize/slash-commands.md b/docs/docs/customize/slash-commands.md index 702d00c7c..7c1d05ed9 100644 --- a/docs/docs/customize/slash-commands.md +++ b/docs/docs/customize/slash-commands.md @@ -122,21 +122,6 @@ Describe the issue you'd like to generate, and Continue will turn into a well-fo } ``` -### `/So` - -The StackOverflow slash command will automatically pull results from StackOverflow to answer your question, quoting links along with its answer. - -```json title="config.json" -{ - "slashCommands": [ - { - "name": "so", - "description": "Reference StackOverflow to answer the question" - } - ] -} -``` - ### `/Onboard` The Onboard slash command helps to familiarize yourself with a new project by analyzing the project structure, READMEs, and dependency files. It identifies key folders, explains their purpose, and highlights popular packages used. Additionally, it offers insights into the project's architecture. diff --git a/gui/src/redux/slices/serverStateReducer.ts b/gui/src/redux/slices/serverStateReducer.ts index b3e17a096..16b2c0d78 100644 --- a/gui/src/redux/slices/serverStateReducer.ts +++ b/gui/src/redux/slices/serverStateReducer.ts @@ -53,7 +53,6 @@ export const serverStateSlice = createSlice({ state.slashCommands = [ ...action.payload, { name: "codebase", description: "Retrieve codebase context" }, - { name: "so", description: "Search StackOverflow" }, ]; }, setContextProviders: ( From 2b87a1685dd85566e1be9c6fa5f2138611e98707 Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 21 Oct 2024 16:07:59 -0700 Subject: [PATCH 3/9] add additional run configs --- .vscode/settings.json | 2 - core/config/load.ts | 4 +- core/indexing/ignore.ts | 1 + .../intellij/.run}/Run_Continue.xml | 1 + extensions/intellij/.run/Tail_dev_logs.xml | 17 + extensions/intellij/CONTRIBUTING.md | 30 +- .../editor/InlineEditAction.kt | 986 +++++++++--------- gui/src/pages/More/MoreHelpRow.tsx | 10 +- 8 files changed, 556 insertions(+), 495 deletions(-) rename {.idea/runConfigurations => extensions/intellij/.run}/Run_Continue.xml (80%) create mode 100644 extensions/intellij/.run/Tail_dev_logs.xml diff --git a/.vscode/settings.json b/.vscode/settings.json index d07234a75..eaf1da238 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -14,8 +14,6 @@ } }, "search.exclude": { - "**/binary": true, - "binary/": false, "**/core/vendor/**": true, "**/gui/dist": true, "**/extensions/vscode/gui/**": true, diff --git a/core/config/load.ts b/core/config/load.ts index 4edb2da82..2064dd61d 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -674,7 +674,7 @@ function readConfigJs(): string | undefined { return fs.readFileSync(configJsPath, "utf8"); } -async function buildConfigTs(ide: IDE, ideType: IdeType) { +async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) { const configTsPath = getConfigTsPath(); if (!fs.existsSync(configTsPath)) { @@ -724,7 +724,7 @@ async function loadFullConfigNode( let intermediate = await serializedToIntermediateConfig(serialized, ide); // Apply config.ts to modify intermediate config - const configJsContents = await buildConfigTs(ide, ideType); + const configJsContents = await buildConfigTsandReadConfigJs(ide, ideType); if (configJsContents) { try { // Try config.ts first diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 93ad7b43d..0b2714f1d 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -70,6 +70,7 @@ export const DEFAULT_IGNORE_FILETYPES = [ "*.bin", "*.pag", "*.swp", + "*.jsonl", // "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt ]; diff --git a/.idea/runConfigurations/Run_Continue.xml b/extensions/intellij/.run/Run_Continue.xml similarity index 80% rename from .idea/runConfigurations/Run_Continue.xml rename to extensions/intellij/.run/Run_Continue.xml index 13c802366..59aa4a51a 100644 --- a/.idea/runConfigurations/Run_Continue.xml +++ b/extensions/intellij/.run/Run_Continue.xml @@ -2,6 +2,7 @@ + \ No newline at end of file diff --git a/extensions/intellij/.run/Tail_dev_logs.xml b/extensions/intellij/.run/Tail_dev_logs.xml new file mode 100644 index 000000000..9f738c563 --- /dev/null +++ b/extensions/intellij/.run/Tail_dev_logs.xml @@ -0,0 +1,17 @@ + + + + \ No newline at end of file diff --git a/extensions/intellij/CONTRIBUTING.md b/extensions/intellij/CONTRIBUTING.md index 5ea6929f2..544cb6323 100644 --- a/extensions/intellij/CONTRIBUTING.md +++ b/extensions/intellij/CONTRIBUTING.md @@ -1,7 +1,6 @@ # Contributing to Continue (JetBrains extension) -This file is for contribution guidelines specific to the JetBrains extension. See the root [ -`CONTRIBUTING.md`](../../CONTRIBUTING.md) for general contribution guidelines. +This file is for contribution guidelines specific to the JetBrains extension. See the root [`CONTRIBUTING.md`](../../CONTRIBUTING.md) for general contribution guidelines. ## Table of Contents @@ -18,6 +17,7 @@ This file is for contribution guidelines specific to the JetBrains extension. Se - [Setting breakpoints](#setting-breakpoints) - [Available Gradle tasks](#available-gradle-tasks) - [Packaging](#packaging) + - [Testing the packaged extension](#testing-the-packaged-extension) ## Architecture Overview @@ -57,22 +57,27 @@ This project requires Node.js version 20.11.0 (LTS) or higher. You have two opti ## Development Workflow -Because the `gui` and `core` are written in TypeScript, our development workflow is built around the assumption that you have VS Code installed. +Because the `gui` and `core` are written in TypeScript, our development workflow is built around the assumption that you +have VS Code installed. ### Running the extension - Open the project in VS Code and star the `Core binary` task - Switch back to Intellij and select the "Run Continue" configuration in the top-right corner of the IDE - Click the "Debug" button - - The first time running this will install the IDE version specified by the `platformVersion` property in [`./run/Run Extension.run.xml`](./.run/Run%20Extension.run.xml). This will take a moment as the installation size can be close to 1GB. + - The first time running this will install the IDE version specified by the `platformVersion` property in [ + `./run/Run Extension.run.xml`](./.run/Run%20Extension.run.xml). This will take a moment as the installation size + can be close to 1GB. ![run-extension-screenshot](../../media/run-intellij-extension.png)\ -This should open a new instance on IntelliJ with the extension installed and connected via TCP to the server started through the `Core binary` task. +This should open a new instance on IntelliJ with the extension installed and connected via TCP to the server started +through the `Core binary` task. ### Reloading changes -- `extensions/intellij`: Attempt to reload changed classes by selecting `Run | Debugging Actions | Reload Changed Classes` +- `extensions/intellij`: Attempt to reload changed classes by selecting + _Run | Debugging Actions | Reload Changed Classes`_ - This will often fail on new imports, schema changes etc. In that case, you need to stop and restart the extension - `gui`: Changes will be reloaded automatically - `core`: Run `npm run build` from the `binary` directory and restart the `Core binary` task in VS Code @@ -103,8 +108,13 @@ verifyPluginConfiguration - Checks if Java and Kotlin compilers configuration me ### Packaging -- Unix: `./gradlew build` -- Windows: `./gradlew.bat build` +- Unix: `./gradlew buildPlugin` +- Windows: `./gradlew.bat buildPlugin` -This will generate a .zip file in `./build/distributions` with the version defined in [ -`./gradle.properties`](./gradle.properties) +This will generate a .zip file in `./build/distributions` with the version defined in [`./gradle.properties`](./gradle.properties) + +#### Testing the packaged extension + +- Navigate to the Plugins settings page (_Settings | Plugins_) +- Click on the gear icon +- Click _Install from disk_ and select the ZIP file in `./build/distributions` diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index fbfb7c986..9beb8b0c8 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -16,31 +16,33 @@ import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project +import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.Ref import com.intellij.openapi.util.TextRange import com.intellij.ui.JBColor import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil -import net.miginfocom.swing.MigLayout -import org.jdesktop.swingx.JXPanel -import org.jdesktop.swingx.JXTextArea import java.awt.* import java.awt.event.* +import java.awt.geom.AffineTransform import java.awt.geom.Path2D +import java.awt.geom.RoundRectangle2D import javax.swing.* import javax.swing.border.EmptyBorder import javax.swing.event.DocumentEvent import javax.swing.event.DocumentListener +import javax.swing.event.ListDataListener import javax.swing.plaf.basic.BasicComboBoxUI import kotlin.math.max -import java.awt.geom.RoundRectangle2D -import java.awt.geom.AffineTransform -import javax.swing.event.ListDataListener +import net.miginfocom.swing.MigLayout +import org.jdesktop.swingx.JXPanel +import org.jdesktop.swingx.JXTextArea const val MAIN_FONT_SIZE = 13 fun makeTextArea(): JTextArea { - val textArea = CustomTextArea(1, 40).apply { + val textArea = + CustomTextArea(1, 40).apply { lineWrap = true wrapStyleWord = true isOpaque = false @@ -49,9 +51,9 @@ fun makeTextArea(): JTextArea { margin = JBUI.insets(6, 4, 6, 4) font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) preferredSize = Dimension(400, 75) - } - textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) - return textArea + } + textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) + return textArea } fun makePanel( @@ -67,249 +69,270 @@ fun makePanel( onAccept: () -> Unit, onReject: () -> Unit ): JPanel { - val topPanel = ShadowPanel(MigLayout("wrap 1, insets 2 ${leftInset} 2 2, gap 0!")).apply { + val topPanel = + ShadowPanel(MigLayout("wrap 1, insets 2 ${leftInset} 2 2, gap 0!")).apply { background = JBColor(0x20888888.toInt(), 0x20888888.toInt()) isOpaque = false - } + } - val panel = CustomPanel( - MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"), - project, - modelTitles, - comboBoxRef, - onEnter, - onCancel, - onAccept, - onReject, - textArea - ).apply { - val globalScheme = EditorColorsManager.getInstance().globalScheme - val defaultBackground = globalScheme.defaultBackground - background = defaultBackground - add(textArea, "grow, gap 0!, height 100%") + val panel = + CustomPanel( + MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"), + project, + modelTitles, + comboBoxRef, + onEnter, + onCancel, + onAccept, + onReject, + textArea) + .apply { + val globalScheme = EditorColorsManager.getInstance().globalScheme + val defaultBackground = globalScheme.defaultBackground + background = defaultBackground + add(textArea, "grow, gap 0!, height 100%") - putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) - preferredSize = textArea.preferredSize - setup() - } + putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true) + preferredSize = textArea.preferredSize + setup() + } - customPanelRef.set(panel) + customPanelRef.set(panel) - textArea.addComponentListener(object : ComponentAdapter() { + textArea.addComponentListener( + object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) { - panel.revalidate() - panel.repaint() + panel.revalidate() + panel.repaint() } - }) + }) - topPanel.add(panel, "grow, gap 0!") + topPanel.add(panel, "grow, gap 0!") - return topPanel + return topPanel } fun openInlineEdit(project: Project?, editor: Editor) { - if (project == null) return + if (project == null) return - // Don't open in terminal - if (EditorUtils().isTerminal(editor)) { - return - } + // Don't open in terminal + if (EditorUtils().isTerminal(editor)) { + return + } - val manager = EditorComponentInlaysManager.from(editor, true) + val manager = EditorComponentInlaysManager.from(editor, true) - // Get list of model titles - val continuePluginService = project.service() - val modelTitles = mutableListOf() - continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response -> - val config = response as Map - val models = (config["config"] as Map)["models"] as List> - modelTitles.addAll(models.map { it["title"] as String }) - } - val maxWaitTime = 200 - val startTime = System.currentTimeMillis() - while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) { - Thread.sleep(20) - } + // Get list of model titles + val continuePluginService = project.service() + val modelTitles = mutableListOf() + continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { + response -> + val config = response as Map + val models = (config["config"] as Map)["models"] as List> + modelTitles.addAll(models.map { it["title"] as String }) + } + val maxWaitTime = 200 + val startTime = System.currentTimeMillis() + while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) { + Thread.sleep(20) + } - // Get highlighted range - val selectionModel = editor.selectionModel - val startOffset = selectionModel.selectionStart - val endOffset = selectionModel.selectionEnd - val startLineNumber = editor.document.getLineNumber(startOffset) - var endLineNumber = editor.document.getLineNumber(endOffset) + // Get highlighted range + val selectionModel = editor.selectionModel + val startOffset = selectionModel.selectionStart + val endOffset = selectionModel.selectionEnd + val startLineNumber = editor.document.getLineNumber(startOffset) + var endLineNumber = editor.document.getLineNumber(endOffset) - // Doesn't seem to be any built-in methods to check for a line selection that contains trailing newlines. - // The only case this matters is when a user double-clicks to highlight a full line. Without this check. - // the highlighted range will continue to the following line. - val isSingleLineSelection = endLineNumber > startLineNumber && - endLineNumber < editor.document.lineCount && - editor.document.getLineStartOffset(endLineNumber) == endOffset + // Doesn't seem to be any built-in methods to check for a line selection that contains trailing + // newlines. + // The only case this matters is when a user double-clicks to highlight a full line. Without this + // check. + // the highlighted range will continue to the following line. + val isSingleLineSelection = + endLineNumber > startLineNumber && + endLineNumber < editor.document.lineCount && + editor.document.getLineStartOffset(endLineNumber) == endOffset + if (isSingleLineSelection) { + endLineNumber-- + } - if (isSingleLineSelection) { - endLineNumber-- - } + val prefix = editor.document.getText(TextRange(0, startOffset)) + val highlighted = editor.document.getText(TextRange(startOffset, endOffset)) + val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength)) + val lineNumber = max(0, startLineNumber - 1) - val prefix = editor.document.getText(TextRange(0, startOffset)) - val highlighted = editor.document.getText(TextRange(startOffset, endOffset)) - val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength)) - val lineNumber = max(0, startLineNumber - 1) + // Un-highlight the selected text + selectionModel.removeSelection() + // Get indentation width in pixels + val indentationLineNum = lineNumber + 1 + val lineStart = editor.document.getLineStartOffset(indentationLineNum) + val lineEnd = editor.document.getLineEndOffset(indentationLineNum) + val text = editor.document.getText(TextRange(lineStart, lineEnd)) + val indentation = text.takeWhile { it == ' ' }.length + val charWidth = + editor.contentComponent + .getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)) + .charWidth(' ') + val leftInset = indentation * charWidth * 2 / 3 - // Un-highlight the selected text - selectionModel.removeSelection() + val inlayRef = Ref() + val customPanelRef = Ref() - // Get indentation width in pixels - val indentationLineNum = lineNumber + 1 - val lineStart = editor.document.getLineStartOffset(indentationLineNum) - val lineEnd = editor.document.getLineEndOffset(indentationLineNum) - val text = editor.document.getText(TextRange(lineStart, lineEnd)) - val indentation = text.takeWhile { it == ' ' }.length - val charWidth = - editor.contentComponent.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)).charWidth(' ') - val leftInset = indentation * charWidth * 2 / 3 + // Create text area, attach key listener + val textArea = makeTextArea() - val inlayRef = Ref() - val customPanelRef = Ref() + // Create diff stream handler + val diffStreamHandler = + DiffStreamHandler( + project, + editor, + startLineNumber, + endLineNumber, + { inlayRef.get().dispose() }, + { + textArea.document.insertString(textArea.caretPosition, ", ", null) + textArea.requestFocus() + customPanelRef.get().finish() + }) - // Create text area, attach key listener - val textArea = makeTextArea() + val diffStreamService = project.service() + diffStreamService.register(diffStreamHandler, editor) - // Create diff stream handler - val diffStreamHandler = DiffStreamHandler(project, editor, startLineNumber, endLineNumber, { - inlayRef.get().dispose() - }, { - textArea.document.insertString(textArea.caretPosition, ", ", null) - textArea.requestFocus() - customPanelRef.get().finish() - }) + val comboBoxRef = Ref>() - val diffStreamService = project.service() - diffStreamService.register(diffStreamHandler, editor) + fun onEnter() { + val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(" ▾") + customPanelRef.get().enter() + diffStreamHandler.streamDiffLinesToEditor( + textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret) + } - val comboBoxRef = Ref>() - - fun onEnter() { - val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(" ▾") - customPanelRef.get().enter() - diffStreamHandler.streamDiffLinesToEditor( - textArea.text, - prefix, - highlighted, - suffix, - selectedModelStrippedOfCaret - ) - } - - val panel = - makePanel(project, customPanelRef, textArea, inlayRef, comboBoxRef, leftInset, modelTitles, { onEnter() }, { + val panel = + makePanel( + project, + customPanelRef, + textArea, + inlayRef, + comboBoxRef, + leftInset, + modelTitles, + { onEnter() }, + { diffStreamService.reject(editor) selectionModel.setSelection(startOffset, endOffset) - }, { + }, + { diffStreamService.accept(editor) inlayRef.get().dispose() - }, { + }, + { diffStreamService.reject(editor) inlayRef.get().dispose() - }) + }) - val inlay = manager.insert(startLineNumber, panel, true) + val inlay = manager.insert(startLineNumber, panel, true) - panel.revalidate() - inlayRef.set(inlay) - val viewport = (editor as? EditorImpl)?.scrollPane?.viewport - viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) + panel.revalidate() + inlayRef.set(inlay) + val viewport = (editor as? EditorImpl)?.scrollPane?.viewport + viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) - // Scroll to the top of the startLine plus the height of the panel - editor.scrollingModel.scrollVertically(editor.visualLineToY(startLineNumber) - panel.height) + // Scroll to the top of the startLine plus the height of the panel + editor.scrollingModel.scrollVertically(editor.visualLineToY(startLineNumber) - panel.height) - // Add key listener to text area - textArea.addKeyListener(object : KeyAdapter() { + // Add key listener to text area + textArea.addKeyListener( + object : KeyAdapter() { override fun keyTyped(e: KeyEvent) { - if (customPanelRef.get().isFinished) { - customPanelRef.get().setup() - } + if (customPanelRef.get().isFinished) { + customPanelRef.get().setup() + } } - override fun keyPressed(e: KeyEvent) { - when (e.keyCode) { - KeyEvent.VK_ESCAPE -> { - diffStreamService.reject(editor) - selectionModel.setSelection(startOffset, endOffset) - } - - KeyEvent.VK_ENTER -> { - when (e.modifiersEx) { - KeyEvent.SHIFT_DOWN_MASK -> { - textArea.document.insertString(textArea.caretPosition, "\n", null) - } - - 0 -> { - onEnter() - e.consume() - } - } - } + when (e.keyCode) { + KeyEvent.VK_ESCAPE -> { + diffStreamService.reject(editor) + selectionModel.setSelection(startOffset, endOffset) } + + KeyEvent.VK_ENTER -> { + when (e.modifiersEx) { + KeyEvent.SHIFT_DOWN_MASK -> { + textArea.document.insertString(textArea.caretPosition, "\n", null) + } + + 0 -> { + onEnter() + e.consume() + } + } + } + } } - // We need this because backspace/delete is not registering properly on keyPressed for an unknown reason + // We need this because backspace/delete is not registering properly on keyPressed for an + // unknown reason override fun keyReleased(e: KeyEvent) { - if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) { - if (customPanelRef.get().isFinished) { - customPanelRef.get().setup() - } + if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) { + if (customPanelRef.get().isFinished) { + customPanelRef.get().setup() } + } } - }) + }) - // Listen for changes to textarea line count - textArea.document.addDocumentListener(object : DocumentListener { + // Listen for changes to textarea line count + textArea.document.addDocumentListener( + object : DocumentListener { private var lastNumLines: Int = 0 + private fun updateSize() { - val numLines = textArea.text.lines().size - if (numLines != lastNumLines) { - lastNumLines = numLines - viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) - } + val numLines = textArea.text.lines().size + if (numLines != lastNumLines) { + lastNumLines = numLines + viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED)) + } } override fun insertUpdate(e: DocumentEvent?) { - updateSize() + updateSize() } override fun removeUpdate(e: DocumentEvent?) { - updateSize() + updateSize() } override fun changedUpdate(e: DocumentEvent?) { - updateSize() + updateSize() } - }) + }) - - textArea.requestFocus() + textArea.requestFocus() } /** - * Adapted from https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/InlineEditAction.kt + * Adapted from + * https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/InlineEditAction.kt */ class InlineEditAction : AnAction(), DumbAware { - override fun update(e: AnActionEvent) { - e.presentation.isEnabled = true - e.presentation.isVisible = true - } + override fun update(e: AnActionEvent) { + e.presentation.isEnabled = true + e.presentation.isVisible = true + } - override fun getActionUpdateThread(): ActionUpdateThread { - return ActionUpdateThread.EDT - } + override fun getActionUpdateThread(): ActionUpdateThread { + return ActionUpdateThread.EDT + } - override fun actionPerformed(e: AnActionEvent) { - val editor = e.getData(PlatformDataKeys.EDITOR) ?: return - val project = e.getData(PlatformDataKeys.PROJECT) ?: return - openInlineEdit(project, editor) - } + override fun actionPerformed(e: AnActionEvent) { + val editor = e.getData(PlatformDataKeys.EDITOR) ?: return + val project = e.getData(PlatformDataKeys.PROJECT) ?: return + openInlineEdit(project, editor) + } } class CustomPanel( @@ -323,93 +346,97 @@ class CustomPanel( private val onReject: () -> Unit, private val textArea: JTextArea ) : JPanel(layout) { - private val shadowSize = 5 - private val cornerRadius = 8 - private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow - private val borderColor = Color(128, 128, 128, 128) - private val borderThickness = 1 - private val triangleSize = 6 - private val rightMargin = 3.0 - private val closeButton: JComponent = createCloseButton() - private val originalTextColor: Color = textArea.foreground - private val greyTextColor: Color = Color(128, 128, 128, 200) - var isFinished = false + private val shadowSize = 5 + private val cornerRadius = 8 + private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow + private val borderColor = Color(128, 128, 128, 128) + private val borderThickness = 1 + private val triangleSize = 6 + private val rightMargin = 3.0 + private val closeButton: JComponent = createCloseButton() + private val originalTextColor: Color = textArea.foreground + private val greyTextColor: Color = Color(128, 128, 128, 200) + var isFinished = false - init { - isOpaque = false - add(closeButton, "pos 100%-20 0 -3 3, w 20!, h 20!") + init { + isOpaque = false + add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!") + } + + private fun createCloseButton(): JComponent { + val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass) + return JLabel(closeIcon).apply { + background = Color(0, 0, 0, 0) + border = EmptyBorder(2, 6, 2, 0) + toolTipText = "`esc` to cancel" + isOpaque = false + addMouseListener( + object : MouseAdapter() { + override fun mouseEntered(e: MouseEvent) { + cursor = Cursor(Cursor.HAND_CURSOR) + } + + override fun mouseExited(e: MouseEvent) { + cursor = Cursor.getDefaultCursor() + } + + override fun mouseClicked(e: MouseEvent) { + onCancel() + } + }) } + } - private fun createCloseButton(): JComponent { - return JLabel("X").apply { - foreground = Color(128, 128, 128, 128) - background = Color(0, 0, 0, 0) - font = UIUtil.getFontWithFallback("Arial", Font.BOLD, 10) - border = EmptyBorder(2, 6, 2, 0) - toolTipText = "`esc` to cancel" - isOpaque = false - - addMouseListener(object : MouseAdapter() { - override fun mouseEntered(e: MouseEvent) { - foreground = Color(128, 128, 128, 255) - cursor = Cursor(Cursor.HAND_CURSOR) - } - - override fun mouseExited(e: MouseEvent) { - foreground = Color(128, 128, 128, 128) - cursor = Cursor.getDefaultCursor() - } - - override fun mouseClicked(e: MouseEvent) { - onCancel() - } - }) - } - } - - private val subPanelA: JPanel = JPanel(MigLayout("insets 0, fillx")).apply { + private val subPanelA: JPanel = + JPanel(MigLayout("insets 0, fillx")).apply { val globalScheme = EditorColorsManager.getInstance().globalScheme val defaultBackground = globalScheme.defaultBackground val continueSettingsService = service() - val dropdown = JComboBox(modelTitles.toTypedArray()).apply { - setUI(TransparentArrowButtonUI()) - isEditable = true - background = defaultBackground - foreground = Color(128, 128, 128, 200) - font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) - border = EmptyBorder(2, 4, 2, 4) - isOpaque = false - isEditable = false - cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) - renderer = DefaultListCellRenderer().apply { - horizontalAlignment = SwingConstants.LEFT - } - selectedIndex = continueSettingsService.continueState.lastSelectedInlineEditModel?.let { - if (modelTitles.isEmpty()) -1 else { - val index = modelTitles.indexOf(it) - if (index != -1) index else 0 - } - } ?: 0 + val dropdown = + JComboBox(modelTitles.toTypedArray()).apply { + setUI(TransparentArrowButtonUI()) + isEditable = true + background = defaultBackground + foreground = Color(128, 128, 128, 200) + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) + border = EmptyBorder(2, 4, 2, 4) + isOpaque = false + isEditable = false + cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) + renderer = + DefaultListCellRenderer().apply { horizontalAlignment = SwingConstants.LEFT } + selectedIndex = + continueSettingsService.continueState.lastSelectedInlineEditModel?.let { + if (modelTitles.isEmpty()) -1 + else { + val index = modelTitles.indexOf(it) + if (index != -1) index else 0 + } + } ?: 0 - addActionListener { - continueSettingsService.continueState.lastSelectedInlineEditModel = selectedItem as String + addActionListener { + continueSettingsService.continueState.lastSelectedInlineEditModel = + selectedItem as String + } } - } comboBoxRef.set(dropdown) - val rightButton = CustomButton("⏎ Enter") { onEnter() }.apply { - background = JBColor(0x999998.toInt(), 0x999998.toInt()) - foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) - border = EmptyBorder(2, 6, 2, 6) - } + val rightButton = + CustomButton("⏎ Enter") { onEnter() } + .apply { + background = JBColor(0x999998.toInt(), 0x999998.toInt()) + foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) + border = EmptyBorder(2, 6, 2, 6) + } - val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply { - isOpaque = false - border = EmptyBorder(0, 0, 0, 0) - add(dropdown, "align right") - add(rightButton, "align right") - } + val rightPanel = + JPanel(MigLayout("insets 0, fillx")).apply { + isOpaque = false + border = EmptyBorder(0, 0, 0, 0) + add(dropdown, "align right") + add(rightButton, "align right") + } border = EmptyBorder(0, 0, 16, 12) @@ -418,285 +445,292 @@ class CustomPanel( isOpaque = false cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR) - } + } - private val subPanelB: JPanel = JPanel(BorderLayout()).apply { + private val subPanelB: JPanel = + JPanel(BorderLayout()).apply { isOpaque = false - val progressBar = JProgressBar().apply { - isIndeterminate = true - } + val progressBar = JProgressBar().apply { isIndeterminate = true } add(progressBar, BorderLayout.CENTER) border = BorderFactory.createEmptyBorder(0, 0, 16, 12) - } + } - private val subPanelC: JPanel = JPanel(MigLayout("insets 0, fillx")).apply { - val leftLabel = JLabel("Type to re-prompt").apply { - foreground = Color(156, 163, 175) // text-gray-400 - font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) - border = EmptyBorder(0, 4, 0, 0) - } + private val subPanelC: JPanel = + JPanel(MigLayout("insets 0, fillx")).apply { + val leftLabel = + JLabel("Type to re-prompt").apply { + foreground = Color(156, 163, 175) // text-gray-400 + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) + border = EmptyBorder(0, 4, 0, 0) + } - val leftButton = CustomButton("Reject All (${getMetaKeyLabel()}⇧⌫)") { onReject() }.apply { - background = JBColor(0x30FF0000.toInt(), 0x30FF0000.toInt()) - foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) - } + val leftButton = + CustomButton("Reject All (${getMetaKeyLabel()}⇧⌫)") { onReject() } + .apply { + background = JBColor(0x30FF0000.toInt(), 0x30FF0000.toInt()) + foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) + } - val rightButton = CustomButton("Accept All (${getMetaKeyLabel()}⇧⏎)") { onAccept() }.apply { - background = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt()) - foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) - } + val rightButton = + CustomButton("Accept All (${getMetaKeyLabel()}⇧⏎)") { onAccept() } + .apply { + background = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt()) + foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt()) + } - val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply { - isOpaque = false - add(leftButton, "align right") - add(rightButton, "align right") - border = EmptyBorder(0, 0, 0, 0) - } + val rightPanel = + JPanel(MigLayout("insets 0, fillx")).apply { + isOpaque = false + add(leftButton, "align right") + add(rightButton, "align right") + border = EmptyBorder(0, 0, 0, 0) + } add(leftLabel, "align left") add(rightPanel, "align right") border = BorderFactory.createEmptyBorder(0, 0, 16, 12) isOpaque = false - } + } - fun setup() { - remove(subPanelB) - remove(subPanelC) - add(subPanelA, "grow, gap 0!") - isFinished = false - revalidate() - repaint() - textArea.foreground = originalTextColor - } + fun setup() { + remove(subPanelB) + remove(subPanelC) + add(subPanelA, "grow, gap 0!") + isFinished = false + revalidate() + repaint() + textArea.foreground = originalTextColor + } - fun enter() { - remove(subPanelA) - remove(subPanelC) - add(subPanelB, "grow, gap 0!") - revalidate() - repaint() - } + fun enter() { + remove(subPanelA) + remove(subPanelC) + add(subPanelB, "grow, gap 0!") + revalidate() + repaint() + } - fun finish() { - remove(subPanelB) - add(subPanelC, "grow, gap 0!") - revalidate() - repaint() - isFinished = true - textArea.foreground = greyTextColor - } + fun finish() { + remove(subPanelB) + add(subPanelC, "grow, gap 0!") + revalidate() + repaint() + isFinished = true + textArea.foreground = greyTextColor + } - override fun paintComponent(g: Graphics) { - super.paintComponent(g) + override fun paintComponent(g: Graphics) { + super.paintComponent(g) - val g2 = g as Graphics2D - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + val g2 = g as Graphics2D + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) - val w = width - shadowSize - val h = height - shadowSize + val w = width - shadowSize + val h = height - shadowSize - // Create the shape for the tooltip/triangle - val shape = Path2D.Double() - shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble()) - shape.quadTo(borderThickness / 2.0, borderThickness / 2.0, cornerRadius.toDouble(), borderThickness / 2.0) - shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0) - shape.quadTo( - w - borderThickness / 2.0 - rightMargin, - borderThickness / 2.0, - w - borderThickness / 2.0 - rightMargin, - cornerRadius.toDouble() - ) - shape.lineTo(w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()) - shape.quadTo( - w - borderThickness / 2.0 - rightMargin, - h - triangleSize.toDouble(), - w - cornerRadius.toDouble() - rightMargin, - h - triangleSize.toDouble() - ) - shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble()) - shape.lineTo(borderThickness / 2.0, h.toDouble()) - shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble()) + // Create the shape for the tooltip/triangle + val shape = Path2D.Double() + shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble()) + shape.quadTo( + borderThickness / 2.0, + borderThickness / 2.0, + cornerRadius.toDouble(), + borderThickness / 2.0) + shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0) + shape.quadTo( + w - borderThickness / 2.0 - rightMargin, + borderThickness / 2.0, + w - borderThickness / 2.0 - rightMargin, + cornerRadius.toDouble()) + shape.lineTo( + w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()) + shape.quadTo( + w - borderThickness / 2.0 - rightMargin, + h - triangleSize.toDouble(), + w - cornerRadius.toDouble() - rightMargin, + h - triangleSize.toDouble()) + shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble()) + shape.lineTo(borderThickness / 2.0, h.toDouble()) + shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble()) - // Draw shadow - g2.color = shadowColor - g2.fill( - shape.createTransformedShape( - AffineTransform.getTranslateInstance( - shadowSize.toDouble(), - shadowSize.toDouble() - ) - ) - ) + // Draw shadow + g2.color = shadowColor + g2.fill( + shape.createTransformedShape( + AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble()))) - // Draw main shape - g2.color = background - g2.fill(shape) + // Draw main shape + g2.color = background + g2.fill(shape) - // Draw border - g2.color = borderColor - g2.stroke = BasicStroke(borderThickness.toFloat()) - g2.draw(shape) - } + // Draw border + g2.color = borderColor + g2.stroke = BasicStroke(borderThickness.toFloat()) + g2.draw(shape) + } } class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) { - private var isHovered = false + private var isHovered = false - init { - isOpaque = false - cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) - addMouseListener(object : MouseAdapter() { - override fun mouseEntered(e: MouseEvent?) { - isHovered = true - repaint() - } + init { + isOpaque = false + cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) + addMouseListener( + object : MouseAdapter() { + override fun mouseEntered(e: MouseEvent?) { + isHovered = true + repaint() + } - override fun mouseExited(e: MouseEvent?) { - isHovered = false - repaint() - } + override fun mouseExited(e: MouseEvent?) { + isHovered = false + repaint() + } - override fun mouseClicked(e: MouseEvent?) { - onClick() - } + override fun mouseClicked(e: MouseEvent?) { + onClick() + } }) - font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) - border = EmptyBorder(2, 6, 2, 6) - } + font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11) + border = EmptyBorder(2, 6, 2, 6) + } - override fun paintComponent(g: Graphics) { - val g2 = g as Graphics2D - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) + override fun paintComponent(g: Graphics) { + val g2 = g as Graphics2D + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) - val cornerRadius = 8 - val rect = Rectangle(0, 0, width, height) - val roundRect = RoundRectangle2D.Float( + val cornerRadius = 8 + val rect = Rectangle(0, 0, width, height) + val roundRect = + RoundRectangle2D.Float( rect.x.toFloat(), rect.y.toFloat(), rect.width.toFloat(), rect.height.toFloat(), cornerRadius.toFloat(), - cornerRadius.toFloat() - ) - if (isHovered) { - val brightenFactor = 1.1f - val brighterColor = Color( - (background.red * brightenFactor).coerceIn(0f, 255f).toInt(), - (background.green * brightenFactor).coerceIn(0f, 255f).toInt(), - (background.blue * brightenFactor).coerceIn(0f, 255f).toInt() - ) - g2.color = brighterColor - } else { - g2.color = background - } - g2.fill(roundRect) - g2.color = foreground - g2.drawString( - text, (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(), - (height / 2 + g.fontMetrics.ascent / 2).toFloat() - ) + cornerRadius.toFloat()) + if (isHovered) { + val brightenFactor = 1.1f + val brighterColor = + Color( + (background.red * brightenFactor).coerceIn(0f, 255f).toInt(), + (background.green * brightenFactor).coerceIn(0f, 255f).toInt(), + (background.blue * brightenFactor).coerceIn(0f, 255f).toInt()) + g2.color = brighterColor + } else { + g2.color = background } + g2.fill(roundRect) + g2.color = foreground + g2.drawString( + text, + (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(), + (height / 2 + g.fontMetrics.ascent / 2).toFloat()) + } } class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") { - init { - setRows(rows) - setColumns(columns) + init { + setRows(rows) + setColumns(columns) + } + + override fun paintComponent(g: Graphics) { + // Draw placeholder + if (text.isEmpty()) { + g.color = Color(128, 128, 128, 255) + g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) + g.drawString("Enter instructions...", 3, 20) } - override fun paintComponent(g: Graphics) { - // Draw placeholder - if (text.isEmpty()) { - g.color = Color(128, 128, 128, 255) - g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE) - g.drawString("Enter instructions...", 3, 20) - } - - super.paintComponent(g) - } + super.paintComponent(g) + } } class ShadowPanel(layout: LayoutManager) : JXPanel(layout) { - override fun getPreferredSize(): Dimension { - val prefSize = super.getPreferredSize() - val insets = getInsets() - prefSize.width += insets.left + insets.right - prefSize.height += insets.top + insets.bottom - return prefSize - } + override fun getPreferredSize(): Dimension { + val prefSize = super.getPreferredSize() + val insets = getInsets() + prefSize.width += insets.left + insets.right + prefSize.height += insets.top + insets.bottom + return prefSize + } - override fun paintComponent(g: Graphics) { - super.paintComponent(g) - } + override fun paintComponent(g: Graphics) { + super.paintComponent(g) + } } class TransparentArrowButtonUI : BasicComboBoxUI() { - override fun createArrowButton() = JButton().apply { + override fun createArrowButton() = + JButton().apply { isVisible = false preferredSize = Dimension(0, 0) - } + } - override fun getInsets(): Insets { - return JBUI.insets(0, 6, 0, 0) - } + override fun getInsets(): Insets { + return JBUI.insets(0, 6, 0, 0) + } - override fun installUI(c: JComponent?) { - super.installUI(c) - comboBox.isOpaque = false - val globalScheme = EditorColorsManager.getInstance().globalScheme - val defaultBackground = globalScheme.defaultBackground - comboBox.background = defaultBackground + override fun installUI(c: JComponent?) { + super.installUI(c) + comboBox.isOpaque = false + val globalScheme = EditorColorsManager.getInstance().globalScheme + val defaultBackground = globalScheme.defaultBackground + comboBox.background = defaultBackground - // Modify the ComboBoxModel to include the down symbol - val originalModel = comboBox.model - comboBox.model = object : ComboBoxModel { - override fun getSize(): Int = originalModel.size - override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index) - override fun setSelectedItem(anItem: Any?) { - originalModel.selectedItem = anItem - } + // Modify the ComboBoxModel to include the down symbol + val originalModel = comboBox.model + comboBox.model = + object : ComboBoxModel { + override fun getSize(): Int = originalModel.size - override fun getSelectedItem(): Any? { - val item = originalModel.selectedItem - return "$item ▾" - } + override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index) - override fun addListDataListener(l: ListDataListener?) { - originalModel.addListDataListener(l) - } + override fun setSelectedItem(anItem: Any?) { + originalModel.selectedItem = anItem + } - override fun removeListDataListener(l: ListDataListener?) { - originalModel.removeListDataListener(l) - } - } - } - - - override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { - // Do nothing to prevent painting the background - } - - - override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { - val renderer = comboBox.renderer - val item = comboBox.selectedItem - - if (item != null) { - val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false) - c.font = comboBox.font - c.foreground = Color(156, 163, 175) // text-gray-400 - c.background = comboBox.background - - if (c is JComponent) { - c.isOpaque = false - } - - val currentValuePane = currentValuePane - currentValuePane.paintComponent(g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true) + override fun getSelectedItem(): Any? { + val item = originalModel.selectedItem + return "$item ▾" + } + + override fun addListDataListener(l: ListDataListener?) { + originalModel.addListDataListener(l) + } + + override fun removeListDataListener(l: ListDataListener?) { + originalModel.removeListDataListener(l) + } } + } + + override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { + // Do nothing to prevent painting the background + } + + override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) { + val renderer = comboBox.renderer + val item = comboBox.selectedItem + + if (item != null) { + val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false) + c.font = comboBox.font + c.foreground = Color(156, 163, 175) // text-gray-400 + c.background = comboBox.background + + if (c is JComponent) { + c.isOpaque = false + } + + val currentValuePane = currentValuePane + currentValuePane.paintComponent( + g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true) } + } } - diff --git a/gui/src/pages/More/MoreHelpRow.tsx b/gui/src/pages/More/MoreHelpRow.tsx index 8a0412dab..0a55169cf 100644 --- a/gui/src/pages/More/MoreHelpRow.tsx +++ b/gui/src/pages/More/MoreHelpRow.tsx @@ -9,15 +9,15 @@ interface MoreHelpRowProps { function MoreHelpRow({ title, description, onClick, Icon }: MoreHelpRowProps) { return (
-
-

{title}

- {description} +
+

{title}

+ {description}
-
+
From dd61c4dff678c100cbacc848ef3d1c439c4a860f Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 21 Oct 2024 17:00:50 -0700 Subject: [PATCH 4/9] bugfix: remove esbuild permission setting --- .github/workflows/jetbrains-release.yaml | 1 - .../intellij/.run/Tail Dev Logs.run.xml | 17 +++ extensions/intellij/gradle.properties | 2 +- .../continue/CoreMessenger.kt | 6 +- .../continue/CoreMessengerManager.kt | 112 +++++++++--------- 5 files changed, 74 insertions(+), 64 deletions(-) create mode 100644 extensions/intellij/.run/Tail Dev Logs.run.xml diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index cf3cc4ae1..9fc410b38 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -320,7 +320,6 @@ jobs: chmod +x continue-binary chmod +x build/Release/node_sqlite3.node chmod +x index.node - chmod +x esbuild if: ${{ matrix.platform }} != 'win32' # Run tests for binary diff --git a/extensions/intellij/.run/Tail Dev Logs.run.xml b/extensions/intellij/.run/Tail Dev Logs.run.xml new file mode 100644 index 000000000..3348d6c51 --- /dev/null +++ b/extensions/intellij/.run/Tail Dev Logs.run.xml @@ -0,0 +1,17 @@ + + + + \ No newline at end of file diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index edd10ba34..5e79c0f95 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginName=continue-intellij-extension pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion=0.0.76 +pluginVersion=0.0.77 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=223 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index 3934029b1..aaa6ce28d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -17,7 +17,6 @@ import kotlinx.coroutines.* class CoreMessenger( private val project: Project, - esbuildPath: String, continueCorePath: String, private val ideProtocolClient: IdeProtocolClient, coroutineScope: CoroutineScope @@ -162,10 +161,7 @@ class CoreMessenger( } } else { // Set proper permissions - coroutineScope.launch(Dispatchers.IO) { - setPermissions(continueCorePath) - setPermissions(esbuildPath) - } + coroutineScope.launch(Dispatchers.IO) { setPermissions(continueCorePath) } // Start the subprocess val processBuilder = diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt index 88842a0d9..c8159f521 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessengerManager.kt @@ -7,8 +7,8 @@ import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.project.Project -import kotlinx.coroutines.* import java.nio.file.Paths +import kotlinx.coroutines.* class CoreMessengerManager( private val project: Project, @@ -16,69 +16,67 @@ class CoreMessengerManager( private val coroutineScope: CoroutineScope ) { - var coreMessenger: CoreMessenger? = null - var lastBackoffInterval = 0.5 + var coreMessenger: CoreMessenger? = null + var lastBackoffInterval = 0.5 - init { - coroutineScope.launch { - val continuePluginService = ServiceManager.getService( - project, - ContinuePluginService::class.java - ) + init { + coroutineScope.launch { + val continuePluginService = + ServiceManager.getService(project, ContinuePluginService::class.java) - val myPluginId = "com.github.continuedev.continueintellijextension" - val pluginDescriptor = - PluginManager.getPlugin(PluginId.getId(myPluginId)) ?: throw Exception("Plugin not found") + val myPluginId = "com.github.continuedev.continueintellijextension" + val pluginDescriptor = + PluginManager.getPlugin(PluginId.getId(myPluginId)) ?: throw Exception("Plugin not found") - val pluginPath = pluginDescriptor.pluginPath - val osName = System.getProperty("os.name").toLowerCase() - val os = when { - osName.contains("mac") || osName.contains("darwin") -> "darwin" - osName.contains("win") -> "win32" - osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux" - else -> "linux" - } - val osArch = System.getProperty("os.arch").toLowerCase() - val arch = when { - osArch.contains("aarch64") || (osArch.contains("arm") && osArch.contains("64")) -> "arm64" - osArch.contains("amd64") || osArch.contains("x86_64") -> "x64" - else -> "x64" - } - val target = "$os-$arch" + val pluginPath = pluginDescriptor.pluginPath + val osName = System.getProperty("os.name").toLowerCase() + val os = + when { + osName.contains("mac") || osName.contains("darwin") -> "darwin" + osName.contains("win") -> "win32" + osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux" + else -> "linux" + } + val osArch = System.getProperty("os.arch").toLowerCase() + val arch = + when { + osArch.contains("aarch64") || (osArch.contains("arm") && osArch.contains("64")) -> + "arm64" + osArch.contains("amd64") || osArch.contains("x86_64") -> "x64" + else -> "x64" + } + val target = "$os-$arch" - println("Identified OS: $os, Arch: $arch") + println("Identified OS: $os, Arch: $arch") - val corePath = Paths.get(pluginPath.toString(), "core").toString() - val targetPath = Paths.get(corePath, target).toString() - val continueCorePath = - Paths.get(targetPath, "continue-binary" + (if (os == "win32") ".exe" else "")).toString() + val corePath = Paths.get(pluginPath.toString(), "core").toString() + val targetPath = Paths.get(corePath, target).toString() + val continueCorePath = + Paths.get(targetPath, "continue-binary" + (if (os == "win32") ".exe" else "")).toString() - // esbuild needs permissions - val esbuildPath = Paths.get(targetPath, "esbuild" + (if (os == "win32") ".exe" else "")).toString() + setupCoreMessenger(continueCorePath) + } + } - setupCoreMessenger(esbuildPath, continueCorePath) - } + private fun setupCoreMessenger(continueCorePath: String): Unit { + coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope) + + coreMessenger?.request("config/getSerializedProfileInfo", null, null) { resp -> + val data = resp as? Map + val profileInfo = data?.get("config") as? Map + val allowAnonymousTelemetry = profileInfo?.get("allowAnonymousTelemetry") as? Boolean + val telemetryService = service() + if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) { + telemetryService.setup(getMachineUniqueID()) + } } - private fun setupCoreMessenger(esbuildPath: String, continueCorePath: String): Unit { - coreMessenger = CoreMessenger(project, esbuildPath, continueCorePath, ideProtocolClient, coroutineScope) - - coreMessenger?.request("config/getSerializedProfileInfo", null, null) { resp -> - val data = resp as? Map - val profileInfo = data?.get("config") as? Map - val allowAnonymousTelemetry = profileInfo?.get("allowAnonymousTelemetry") as? Boolean - val telemetryService = service() - if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) { - telemetryService.setup(getMachineUniqueID()) - } - } - - // On exit, use exponential backoff to create another CoreMessenger - coreMessenger?.onDidExit { - lastBackoffInterval *= 2 - println("CoreMessenger exited, retrying in $lastBackoffInterval seconds") - Thread.sleep((lastBackoffInterval * 1000).toLong()) - setupCoreMessenger(esbuildPath, continueCorePath) - } + // On exit, use exponential backoff to create another CoreMessenger + coreMessenger?.onDidExit { + lastBackoffInterval *= 2 + println("CoreMessenger exited, retrying in $lastBackoffInterval seconds") + Thread.sleep((lastBackoffInterval * 1000).toLong()) + setupCoreMessenger(continueCorePath) } -} \ No newline at end of file + } +} From 29230b735ce465eb1392af79a120d5973255b36a Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 21 Oct 2024 17:02:21 -0700 Subject: [PATCH 5/9] Delete extensions/intellij/.run/Tail_dev_logs.xml --- extensions/intellij/.run/Tail_dev_logs.xml | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 extensions/intellij/.run/Tail_dev_logs.xml diff --git a/extensions/intellij/.run/Tail_dev_logs.xml b/extensions/intellij/.run/Tail_dev_logs.xml deleted file mode 100644 index 9f738c563..000000000 --- a/extensions/intellij/.run/Tail_dev_logs.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - \ No newline at end of file From ba25172676978615cc42b682c1780c6b20a165e9 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 21 Oct 2024 17:03:01 -0700 Subject: [PATCH 6/9] Update Run_Continue.xml --- extensions/intellij/.run/Run_Continue.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/intellij/.run/Run_Continue.xml b/extensions/intellij/.run/Run_Continue.xml index 59aa4a51a..44b2610c4 100644 --- a/extensions/intellij/.run/Run_Continue.xml +++ b/extensions/intellij/.run/Run_Continue.xml @@ -2,7 +2,7 @@ - + - \ No newline at end of file + From 85040e3e480b7287609f90a3b8ecc4f22af2b739 Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 21 Oct 2024 17:29:31 -0700 Subject: [PATCH 7/9] update code styles --- .idea/codeStyles/Project.xml | 6 + .idea/ktfmt.xml | 2 +- extensions/intellij/.run/Run_Continue.xml | 2 +- .../intellij/.run/Tail Dev Logs.run.xml | 2 +- .../editor/InlineEditAction.kt | 1147 +++++++++-------- 5 files changed, 588 insertions(+), 571 deletions(-) diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml index 49630cce2..a98e3ae47 100644 --- a/.idea/codeStyles/Project.xml +++ b/.idea/codeStyles/Project.xml @@ -11,6 +11,9 @@