diff --git a/extensions/intellij/CONTRIBUTING.md b/extensions/intellij/CONTRIBUTING.md index c8b040424..5ea6929f2 100644 --- a/extensions/intellij/CONTRIBUTING.md +++ b/extensions/intellij/CONTRIBUTING.md @@ -1,6 +1,7 @@ # 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 @@ -13,11 +14,10 @@ This file is for contribution guidelines specific to the JetBrains extension. Se - [Misc](#misc) - [Development Workflow](#development-workflow) - [Running the extension](#running-the-extension) - - [Available Gradle tasks](#available-gradle-tasks) -- [Debugging](#debugging) - [Reloading changes](#reloading-changes) - [Setting breakpoints](#setting-breakpoints) -- [Packaging](#packaging) + - [Available Gradle tasks](#available-gradle-tasks) + - [Packaging](#packaging) ## Architecture Overview @@ -57,13 +57,31 @@ 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. + ### Running the extension -- Select the "Run Continue" Gradle configuration in the top-right corner of the IDE -- Click the "Run" or "Debug" button - - The first time running this will install the IDE version specified by the `platformVersion` property in [`./run/Run Continue.run.xml`](./.run/Run%20Continue.run.xml). This will take a moment as the installation size can be close to 1GB. +- 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. -![run-extension-screenshot](../../media/run-intellij-extension.png) +![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. + +### Reloading changes + +- `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 + +### Setting breakpoints + +- `extensions/intellij`: Breakpoints can be set in Intellij +- `gui`: You'll need to set explicit `debugger` statements in the source code, or through the browser dev tools +- `core`: Breakpoints can be set in VS Code ### Available Gradle tasks @@ -83,30 +101,10 @@ runIde - Runs the IDE instance with the developed plugin installed. verifyPluginConfiguration - Checks if Java and Kotlin compilers configuration meet IntelliJ SDK requirements ``` -## Debugging - -### Reloading changes - -- `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`: Run `npm run build` from the `gui` directory -- `core`: Run `npm run build` from the `binary` directory - -### Setting breakpoints - -- `extensions/intellij`: Run the extension in debug mode -- `gui`: You'll need to set explicit `debugger` statements in the source code, or through the browser dev tools -- `core`: To set breakpoints in `core`, we need to start `binary` in a debug configuration - - Select the "Run Continue (TCP)" task in the top right corner - - Open the project in a VS Code window (we recommend this for a preconfigured Typescript debugging experience) - - Select the "Core Binary" task from the Run and Debug panel - - You can now set breakpoints in `core`. Note that if you make changes, you'll need to restart the "Core Binary" - task and reload changes classes in Intellij. - -## Packaging +### Packaging - Unix: `./gradlew build` - Windows: `./gradlew.bat build` -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) 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 b47818158..3934029b1 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 @@ -1,19 +1,19 @@ package com.github.continuedev.continueintellijextension.`continue` +import com.github.continuedev.continueintellijextension.constants.MessageTypes import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.services.TelemetryService -import com.github.continuedev.continueintellijextension.constants.MessageTypes import com.google.gson.Gson import com.intellij.openapi.components.service import com.intellij.openapi.project.Project -import kotlinx.coroutines.* import java.io.* import java.net.Socket import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Paths import java.nio.file.attribute.PosixFilePermission +import kotlinx.coroutines.* class CoreMessenger( private val project: Project, @@ -22,235 +22,218 @@ class CoreMessenger( private val ideProtocolClient: IdeProtocolClient, coroutineScope: CoroutineScope ) { - private var writer: Writer? = null - private var reader: BufferedReader? = null - private var process: Process? = null - private val gson = Gson() - private val responseListeners = mutableMapOf Unit>() - private val useTcp: Boolean = System.getenv("USE_TCP")?.toBoolean() ?: false + private var writer: Writer? = null + private var reader: BufferedReader? = null + private var process: Process? = null + private val gson = Gson() + private val responseListeners = mutableMapOf Unit>() + private val useTcp: Boolean = System.getenv("USE_TCP")?.toBoolean() ?: false - private fun write(message: String) { - try { - writer?.write(message + "\r\n") - writer?.flush() - } catch (e: Exception) { - println("Error writing to Continue core: $e") - } + private fun write(message: String) { + try { + writer?.write(message + "\r\n") + writer?.flush() + } catch (e: Exception) { + println("Error writing to Continue core: $e") } + } - fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) { - val id = messageId ?: uuid() - val message = gson.toJson( - mapOf( - "messageId" to id, - "messageType" to messageType, - "data" to data - ) - ) - responseListeners[id] = onResponse + fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) { + val id = messageId ?: uuid() + val message = + gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data)) + responseListeners[id] = onResponse + write(message) + } + + private fun handleMessage(json: String) { + val responseMap = gson.fromJson(json, Map::class.java) + val messageId = responseMap["messageId"].toString() + val messageType = responseMap["messageType"].toString() + val data = responseMap["data"] + + // IDE listeners + if (MessageTypes.ideMessageTypes.contains(messageType)) { + ideProtocolClient.handleMessage(json) { data -> + val message = + gson.toJson( + mapOf("messageId" to messageId, "messageType" to messageType, "data" to data)) write(message) + } } - private fun handleMessage(json: String) { - val responseMap = gson.fromJson(json, Map::class.java) - val messageId = responseMap["messageId"].toString() - val messageType = responseMap["messageType"].toString() - val data = responseMap["data"] - - // IDE listeners - if (MessageTypes.ideMessageTypes.contains(messageType)) { - ideProtocolClient.handleMessage(json) { data -> - val message = gson.toJson( - mapOf( - "messageId" to messageId, - "messageType" to messageType, - "data" to data - ) - ) - write(message) - }; - } - - // Forward to webview - if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) { - // TODO: Currently we aren't set up to receive a response back from the webview - // Can circumvent for getDefaultsModelTitle here for now - if (messageType == "getDefaultModelTitle") { - val continueSettingsService = service() - val defaultModelTitle = continueSettingsService.continueState.lastSelectedInlineEditModel; - val message = gson.toJson( - mapOf( - "messageId" to messageId, - "messageType" to messageType, - "data" to defaultModelTitle - ) - ) - write(message) - } - val continuePluginService = project.service() - continuePluginService.sendToWebview(messageType, responseMap["data"], messageType) - } - - // Responses for messageId - responseListeners[messageId]?.let { listener -> - listener(data) - if (MessageTypes.generatorTypes.contains(messageType)) { - val done = (data as Map)["done"] - if (done == true) { - responseListeners.remove(messageId) - } else { - } - } else { - responseListeners.remove(messageId) - } - - } + // Forward to webview + if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) { + // TODO: Currently we aren't set up to receive a response back from the webview + // Can circumvent for getDefaultsModelTitle here for now + if (messageType == "getDefaultModelTitle") { + val continueSettingsService = service() + val defaultModelTitle = continueSettingsService.continueState.lastSelectedInlineEditModel + val message = + gson.toJson( + mapOf( + "messageId" to messageId, + "messageType" to messageType, + "data" to defaultModelTitle)) + write(message) + } + val continuePluginService = project.service() + continuePluginService.sendToWebview(messageType, responseMap["data"], messageType) } - private fun setPermissions(destination: String) { - val osName = System.getProperty("os.name").toLowerCase() - if (osName.contains("mac") || osName.contains("darwin")) { - ProcessBuilder( - "xattr", - "-dr", - "com.apple.quarantine", - destination - ).start() - setFilePermissions(destination, "rwxr-xr-x") - } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) { - setFilePermissions(destination, "rwxr-xr-x") - } + // Responses for messageId + responseListeners[messageId]?.let { listener -> + listener(data) + if (MessageTypes.generatorTypes.contains(messageType)) { + val done = (data as Map)["done"] + if (done == true) { + responseListeners.remove(messageId) + } else {} + } else { + responseListeners.remove(messageId) + } } + } - private fun setFilePermissions(path: String, posixPermissions: String) { - val perms = HashSet() - if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ) - if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE) - if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE) - Files.setPosixFilePermissions(Paths.get(path), perms) + private fun setPermissions(destination: String) { + val osName = System.getProperty("os.name").toLowerCase() + if (osName.contains("mac") || osName.contains("darwin")) { + ProcessBuilder("xattr", "-dr", "com.apple.quarantine", destination).start() + setFilePermissions(destination, "rwxr-xr-x") + } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) { + setFilePermissions(destination, "rwxr-xr-x") } + } - private val exitCallbacks: MutableList<() -> Unit> = mutableListOf() - fun onDidExit(callback: () -> Unit) { - exitCallbacks.add(callback) - } + private fun setFilePermissions(path: String, posixPermissions: String) { + val perms = HashSet() + if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ) + if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE) + if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE) + Files.setPosixFilePermissions(Paths.get(path), perms) + } - init { - if (useTcp) { - try { - val socket = Socket("127.0.0.1", 3000) - val writer = PrintWriter(socket.getOutputStream(), true) - this.writer = writer - val reader = BufferedReader(InputStreamReader(socket.getInputStream())) - this.reader = reader + private val exitCallbacks: MutableList<() -> Unit> = mutableListOf() - Thread { + fun onDidExit(callback: () -> Unit) { + exitCallbacks.add(callback) + } + + init { + if (useTcp) { + try { + val socket = Socket("127.0.0.1", 3000) + val writer = PrintWriter(socket.getOutputStream(), true) + this.writer = writer + val reader = BufferedReader(InputStreamReader(socket.getInputStream())) + this.reader = reader + + Thread { + try { + while (true) { + val line = reader.readLine() + if (line != null && line.isNotEmpty()) { try { - while (true) { - val line = reader.readLine() - if (line != null && line.isNotEmpty()) { - try { - handleMessage(line) - } catch (e: Exception) { - println("Error handling message: $line") - println(e) - } - } else { - Thread.sleep(100) - } - } - } catch (e: IOException) { - e.printStackTrace() - } finally { - try { - reader.close() - writer.close() - } catch (e: IOException) { - e.printStackTrace() - } - } - }.start() - } catch (e: Exception) { - println("An error occurred: ${e.message}") - } - } else { - // Set proper permissions - coroutineScope.launch(Dispatchers.IO) { - setPermissions(continueCorePath) - setPermissions(esbuildPath) - } - - // Start the subprocess - val processBuilder = ProcessBuilder(continueCorePath) - .directory(File(continueCorePath).parentFile) - process = processBuilder.start() - - val outputStream = process!!.outputStream - val inputStream = process!!.inputStream - - writer = OutputStreamWriter(outputStream, StandardCharsets.UTF_8) - reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8)) - - process!!.onExit().thenRun { - exitCallbacks.forEach { it() } - var err = process?.errorStream?.bufferedReader()?.readText()?.trim() - if (err != null) { - // There are often "⚡️Done in Xms" messages, and we want everything after the last one - val delimiter = "⚡ Done in" - val doneIndex = err.lastIndexOf(delimiter) - if (doneIndex != -1) { - err = err.substring(doneIndex + delimiter.length) + handleMessage(line) + } catch (e: Exception) { + println("Error handling message: $line") + println(e) } + } else { + Thread.sleep(100) + } } - - println("Core process exited with output: $err") - CoroutineScope(Dispatchers.Main).launch { - ideProtocolClient.showToast("error", "Core process exited with output: $err") - } - - // Log the cause of the failure - val telemetryService = service() - telemetryService.capture( - "jetbrains_core_exit", mapOf( - "error" to err - ) - ) - - // Clean up all resources - writer?.close() - reader?.close() - process?.destroy() - } - - coroutineScope.launch(Dispatchers.IO) { + } catch (e: IOException) { + e.printStackTrace() + } finally { try { - while (true) { - val line = reader?.readLine() - if (line != null && line.isNotEmpty()) { - try { - handleMessage(line) - } catch (e: Exception) { - println("Error handling message: $line") - println(e) - } - } else { - delay(100) - } - } + reader.close() + writer.close() } catch (e: IOException) { - e.printStackTrace() - } finally { - try { - reader?.close() - writer?.close() - outputStream.close() - inputStream.close() - process?.destroy() - } catch (e: IOException) { - e.printStackTrace() - } + e.printStackTrace() } + } } + .start() + } catch (e: Exception) { + println("TCP Connection Error: Unable to connect to 127.0.0.1:3000") + println("Reason: ${e.message}") + e.printStackTrace() + } + } else { + // Set proper permissions + coroutineScope.launch(Dispatchers.IO) { + setPermissions(continueCorePath) + setPermissions(esbuildPath) + } + + // Start the subprocess + val processBuilder = + ProcessBuilder(continueCorePath).directory(File(continueCorePath).parentFile) + process = processBuilder.start() + + val outputStream = process!!.outputStream + val inputStream = process!!.inputStream + + writer = OutputStreamWriter(outputStream, StandardCharsets.UTF_8) + reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8)) + + process!!.onExit().thenRun { + exitCallbacks.forEach { it() } + var err = process?.errorStream?.bufferedReader()?.readText()?.trim() + if (err != null) { + // There are often "⚡️Done in Xms" messages, and we want everything after the last one + val delimiter = "⚡ Done in" + val doneIndex = err.lastIndexOf(delimiter) + if (doneIndex != -1) { + err = err.substring(doneIndex + delimiter.length) + } } + + println("Core process exited with output: $err") + CoroutineScope(Dispatchers.Main).launch { + ideProtocolClient.showToast("error", "Core process exited with output: $err") + } + + // Log the cause of the failure + val telemetryService = service() + telemetryService.capture("jetbrains_core_exit", mapOf("error" to err)) + + // Clean up all resources + writer?.close() + reader?.close() + process?.destroy() + } + + coroutineScope.launch(Dispatchers.IO) { + try { + while (true) { + val line = reader?.readLine() + if (line != null && line.isNotEmpty()) { + try { + handleMessage(line) + } catch (e: Exception) { + println("Error handling message: $line") + println(e) + } + } else { + delay(100) + } + } + } catch (e: IOException) { + e.printStackTrace() + } finally { + try { + reader?.close() + writer?.close() + outputStream.close() + inputStream.close() + process?.destroy() + } catch (e: IOException) { + e.printStackTrace() + } + } + } } + } } diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index f7ab438b3..916003d86 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.219", + "version": "0.9.220", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.219", + "version": "0.9.220", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -116,6 +116,7 @@ "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", "follow-redirects": "^1.15.5", + "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 174c5dfdc..28a70181a 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.219", + "version": "0.9.220", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 13afd84c0..deddde65e 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -49,7 +49,10 @@ const HoverItem = styled.span<{ isActive?: boolean }>` padding-top: 2px; padding-bottom: 2px; cursor: pointer; - transition: color 200ms, background-color 200ms, box-shadow 200ms; + transition: + color 200ms, + background-color 200ms, + box-shadow 200ms; `; const EnterButton = styled.button` @@ -99,9 +102,9 @@ function InputToolbar(props: InputToolbarProps) { id="input-toolbar" className="flex" > -
+
-
+
{supportsImages && ( <>
-
-
+
+
{props.activeKey === "Alt" ? ( {`${getAltKeyLabel()}⏎ @@ -169,7 +172,7 @@ function InputToolbar(props: InputToolbarProps) { { props.onEnter({ - useCodebase: isMetaEquivalentKeyPressed(e), + useCodebase: isMetaEquivalentKeyPressed(e as any), noContext: useActiveFile ? e.altKey : !e.altKey, }); }} diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index d98bfef63..c12ade5b7 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -1,3 +1,4 @@ +import { KeyboardEvent } from "react"; import Document from "@tiptap/extension-document"; import History from "@tiptap/extension-history"; import Image from "@tiptap/extension-image"; @@ -44,6 +45,7 @@ import { import { RootState } from "../../redux/store"; import { getFontSize, + getPlatform, isJetBrains, isMetaEquivalentKeyPressed, isWebEnvironment, @@ -58,6 +60,7 @@ import { getSlashCommandDropdownOptions, } from "./getSuggestion"; import { ComboBoxItem } from "./types"; +import { handleMetaKeyPressJetBrains } from "../../util/handleMetaKeyPressJetBrains"; const InputBoxDiv = styled.div` resize: none; @@ -532,78 +535,84 @@ function TipTapEditor(props: TipTapEditorProps) { const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]); - useEffect(() => { - if (isJetBrains()) { - // This is only for VS Code .ipynb files - return; - } + /** + * This handles various issues with meta key actions + * - In JetBrains, when using "off screen rendering", there is a bug where using the meta key to + * highlight code using arrow keys is not working + * - In VS Code, while working with .ipynb files there is a problem where copy/paste/cut will affect + * the actual notebook cells, even when performing them in our GUI + */ + const handleKeyDown = async (e: KeyboardEvent) => { + if (!editor || !editorFocusedRef.current) return; - if (isWebEnvironment()) { - const handleKeyDown = async (event: KeyboardEvent) => { - if (!editor || !editorFocusedRef.current) return; - if ((event.metaKey || event.ctrlKey) && event.key === "x") { - // Cut - const selectedText = editor.state.doc.textBetween( - editor.state.selection.from, - editor.state.selection.to, - ); - navigator.clipboard.writeText(selectedText); - editor.commands.deleteSelection(); - event.preventDefault(); - } else if ((event.metaKey || event.ctrlKey) && event.key === "c") { - // Copy - const selectedText = editor.state.doc.textBetween( - editor.state.selection.from, - editor.state.selection.to, - ); - navigator.clipboard.writeText(selectedText); - event.preventDefault(); - } else if ((event.metaKey || event.ctrlKey) && event.key === "v") { - // Paste - event.preventDefault(); // Prevent default paste behavior - const clipboardText = await navigator.clipboard.readText(); - editor.commands.insertContent(clipboardText); + setActiveKey(e.key); + + if (isMetaEquivalentKeyPressed(e)) { + e.stopPropagation(); + e.preventDefault(); + + const { key, code } = e; + const isWebEnv = isWebEnvironment(); + const text = editor.state.doc.textBetween( + editor.state.selection.from, + editor.state.selection.to, + ); + + if (isJetBrains()) { + if (code === "KeyJ") { + setIgnoreHighlightedCode(true); + setTimeout(() => { + setIgnoreHighlightedCode(false); + }, 100); } - }; - document.addEventListener("keydown", handleKeyDown); + if (isMetaEquivalentKeyPressed(e)) { + handleMetaKeyPressJetBrains(e, text, editor.commands.setContent); + } + } else { + if (code === "KeyL") { + debugger; + setIgnoreHighlightedCode(true); + setTimeout(() => { + setIgnoreHighlightedCode(false); + }, 100); + return; + } - return () => { - document.removeEventListener("keydown", handleKeyDown); - }; - } - - const handleKeyDown = async (event: KeyboardEvent) => { - if (!editor || !editorFocusedRef.current) return; - - if (event.metaKey && event.key === "x") { - document.execCommand("cut"); - event.stopPropagation(); - event.preventDefault(); - } else if (event.metaKey && event.key === "v") { - document.execCommand("paste"); - event.stopPropagation(); - event.preventDefault(); - } else if (event.metaKey && event.key === "c") { - document.execCommand("copy"); - event.stopPropagation(); - event.preventDefault(); + switch (key) { + case "x": + if (isWebEnv) { + await navigator.clipboard.writeText(text); + editor.commands.deleteSelection(); + } else { + document.execCommand("cut"); + } + break; + case "c": + if (isWebEnv) { + await navigator.clipboard.writeText(text); + } else { + document.execCommand("copy"); + } + break; + case "v": + if (isWebEnv) { + const clipboardText = await navigator.clipboard.readText(); + editor.commands.insertContent(clipboardText); + } else { + document.execCommand("paste"); + } + break; + } } - }; - - document.addEventListener("keydown", handleKeyDown); - - return () => { - document.removeEventListener("keydown", handleKeyDown); - }; - }, [editor, editorFocusedRef]); - - useEffect(() => { - if (mainEditorContent && editor) { - editor.commands.setContent(mainEditorContent); - dispatch(consumeMainEditorContent()); + } else if (e.key === "Escape") { + ideMessenger.post("focusEditor", undefined); } - }, [mainEditorContent, editor]); + }; + + const handleKeyUp = () => { + setActiveKey(null); + }; const onEnterRef = useUpdatingRef( (modifiers: InputModifiers) => { @@ -632,28 +641,6 @@ function TipTapEditor(props: TipTapEditorProps) { // This is a mechanism for overriding the IDE keyboard shortcut when inside of the webview const [ignoreHighlightedCode, setIgnoreHighlightedCode] = useState(false); - useEffect(() => { - const handleKeyDown = (event: any) => { - if ( - isMetaEquivalentKeyPressed(event) && - (isJetBrains() ? event.code === "KeyJ" : event.code === "KeyL") - ) { - setIgnoreHighlightedCode(true); - setTimeout(() => { - setIgnoreHighlightedCode(false); - }, 100); - } else if (event.key === "Escape") { - ideMessenger.post("focusEditor", undefined); - } - }; - - window.addEventListener("keydown", handleKeyDown); - - return () => { - window.removeEventListener("keydown", handleKeyDown); - }; - }, []); - // Re-focus main input after done generating useEffect(() => { if (editor && !active && props.isMainInput && document.hasFocus()) { @@ -849,12 +836,8 @@ function TipTapEditor(props: TipTapEditorProps) { return ( { - setActiveKey(e.key); - }} - onKeyUp={(e) => { - setActiveKey(null); - }} + onKeyDown={handleKeyDown} + onKeyUp={handleKeyUp} className="cursor-text" onClick={() => { editor && editor.commands.focus(); diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 038510904..c41b80524 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -188,20 +188,20 @@ function ModelOption({ onMouseLeave={() => setHovered(false)} onClick={handleOptionClick} > -
-
-
- +
+
+
+ {option.title} {showMissingApiKeyMsg && ( - + (Missing API key) )}
-
+
{showDelete && ( @@ -258,7 +258,7 @@ function ModelSelect() { useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { - if (event.key === "'" && isMetaEquivalentKeyPressed(event)) { + if (event.key === "'" && isMetaEquivalentKeyPressed(event as any)) { const direction = event.shiftKey ? -1 : 1; const currentIndex = options.findIndex( (option) => option.value === defaultModel?.title, @@ -319,7 +319,7 @@ function ModelSelect() { style={{ padding: 0 }} onClick={calculatePosition} > -
+
{modelSelectTitle(defaultModel) || "Select model"}{" "} @@ -354,7 +354,7 @@ function ModelSelect() { value={"addModel" as any} >
- + Add Chat model
diff --git a/gui/src/util/handleMetaKeyPressJetBrains.ts b/gui/src/util/handleMetaKeyPressJetBrains.ts new file mode 100644 index 000000000..70740262c --- /dev/null +++ b/gui/src/util/handleMetaKeyPressJetBrains.ts @@ -0,0 +1,77 @@ +import { KeyboardEvent } from "react"; +import { getPlatform } from "."; + +export const handleMetaKeyPressJetBrains = ( + e: KeyboardEvent, + text: string, + setText: (text: string) => void, +) => { + const { selectionStart, selectionEnd } = e.target as HTMLTextAreaElement; + + if (e.key === "Backspace") { + handleMetaBackspace(e, text, setText, selectionStart, selectionEnd); + } + + if (getPlatform() === "mac") { + if (e.key === "ArrowLeft") { + handleMacArrowLeftKey(e); + } else if (e.key === "ArrowRight") { + handleMacArrowRightKey(e); + } + } +}; + +const handleMetaBackspace = ( + e: KeyboardEvent, + text: string, + setText: (text: string) => void, + start: number, + end: number, +) => { + const target = e.target as HTMLTextAreaElement; + let newStart = start; + + if (start !== end) { + setText(text.slice(0, start) + text.slice(end)); + } else { + newStart = + getPlatform() === "mac" + ? text.lastIndexOf("\n", start - 1) + 1 + : text.slice(0, start).trimEnd().lastIndexOf(" ") + 1; + setText(text.slice(0, newStart) + text.slice(start)); + } + + target.setSelectionRange(newStart, newStart); +}; + +const handleMacArrowLeftKey = (e: KeyboardEvent) => { + const target = e.target as HTMLDivElement; + const selection = window.getSelection(); + + const range = document.createRange(); + + if (e.shiftKey) { + selection.modify("extend", "backward", "character"); + } else { + range.setStart(target.firstChild, 0); + range.setEnd(target.firstChild, 0); + + selection.removeAllRanges(); + selection.addRange(range); + } +}; + +const handleMacArrowRightKey = (e: KeyboardEvent) => { + const selection = window.getSelection(); + const range = document.createRange(); + const target = e.target as HTMLDivElement; + + if (e.shiftKey) { + selection.modify("extend", "forward", "character"); + } else { + range.selectNodeContents(target); + range.collapse(false); + selection.removeAllRanges(); + selection.addRange(range); + } +}; diff --git a/gui/src/util/index.ts b/gui/src/util/index.ts index 663c8e7bc..e4f4c7cb6 100644 --- a/gui/src/util/index.ts +++ b/gui/src/util/index.ts @@ -1,5 +1,6 @@ import _ from "lodash"; import { getLocalStorage } from "./localStorage"; +import { KeyboardEvent } from "react"; type Platform = "mac" | "linux" | "windows" | "unknown"; @@ -16,19 +17,19 @@ export function getPlatform(): Platform { } } -export function isMetaEquivalentKeyPressed(event: { - metaKey: boolean; - ctrlKey: boolean; -}): boolean { +export function isMetaEquivalentKeyPressed({ + metaKey, + ctrlKey, +}: KeyboardEvent): boolean { const platform = getPlatform(); switch (platform) { case "mac": - return event.metaKey; + return metaKey; case "linux": case "windows": - return event.ctrlKey; + return ctrlKey; default: - return event.metaKey; + return metaKey; } } diff --git a/media/run-continue-intellij.png b/media/run-continue-intellij.png new file mode 100644 index 000000000..75d0a04f3 Binary files /dev/null and b/media/run-continue-intellij.png differ diff --git a/media/run-intellij-extension.png b/media/run-intellij-extension.png deleted file mode 100644 index 4c2a5a479..000000000 Binary files a/media/run-intellij-extension.png and /dev/null differ