Elffuss BraidHub

kikocis/continue public

Merge pull request #5761 from continuedev/pe/jb-inline-edit-keys

fix(JB): misc inline edit bugs
Changeset9ab91e53598a4edb858087faabf501f163fce70e41bc6f8a28a5a9351b551ab9
AuthorDallin Romney <dallinromney@gmail.com> · 2025-05-21 11:55 -07:00
CommitterGitHub <noreply@github.com> · 2025-05-21 11:55 -07:00
Parents9f9d0321be58, d68db71210a9

Browse the files at this changeset

15 files changed

modified binary/package-lock.json +2 −0
@@ -93,6 +93,7 @@
9393 "p-limit": "^6.1.0",
9494 "partial-json": "^0.1.7",
9595 "pg": "^8.11.3",
96+ "plist": "^3.1.0",
9697 "posthog-node": "^3.6.3",
9798 "puppeteer": "^22.4.0",
9899 "puppeteer-chromium-resolver": "^23.0.0",
@@ -129,6 +130,7 @@
129130 "@types/mustache": "^4.2.5",
130131 "@types/node-fetch": "^2.6.11",
131132 "@types/pg": "^8.11.6",
133+ "@types/plist": "^3.0.5",
132134 "@types/request": "^2.48.12",
133135 "@types/tar": "^6.1.13",
134136 "@types/uuid": "^9.0.7",
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt +11 −7
@@ -11,15 +11,19 @@
1111 class ContinueActionPromote : ActionPromoter {
1212
1313 override fun promote(@NotNull actions: List<AnAction>, @NotNull context: DataContext): List<AnAction>? {
14-
15- if (actions.none { it is AcceptAutocompleteAction }) {
16- return null
17- } else {
14+ // For autocomplete actions
15+ if (actions.any { it is AcceptAutocompleteAction }) {
1816 val settings = ServiceManager.getService(ContinueExtensionSettings::class.java)
19- if (!settings.continueState.showIDECompletionSideBySide) {
20- return null;
17+ if (settings.continueState.showIDECompletionSideBySide) {
18+ return actions.filterIsInstance<AcceptAutocompleteAction>()
2119 }
22- return actions.filterIsInstance<AcceptAutocompleteAction>()
2320 }
21+
22+ val rejectDiffActions = actions.filterIsInstance<RejectDiffAction>()
23+ if (rejectDiffActions.isNotEmpty()) {
24+ return rejectDiffActions
25+ }
26+
27+ return null
2428 }
2529 }
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt +6 −38
@@ -1,25 +1,12 @@
11 package com.github.continuedev.continueintellijextension.actions
22
33 import com.github.continuedev.continueintellijextension.editor.DiffStreamService
4-import com.github.continuedev.continueintellijextension.services.ContinuePluginService
54 import com.intellij.openapi.actionSystem.AnAction
65 import com.intellij.openapi.actionSystem.AnActionEvent
76 import com.intellij.openapi.actionSystem.PlatformDataKeys
8-import com.intellij.openapi.components.ServiceManager
97 import com.intellij.openapi.components.service
108 import com.intellij.openapi.fileEditor.FileEditorManager
11-import com.intellij.openapi.project.Project
12-import com.intellij.openapi.wm.ToolWindowManager
13-
14-fun getPluginService(project: Project?): ContinuePluginService? {
15- if (project == null) {
16- return null
17- }
18- return ServiceManager.getService(
19- project,
20- ContinuePluginService::class.java
21- )
22-}
9+
2310
2411 class AcceptDiffAction : AnAction() {
2512 override fun actionPerformed(e: AnActionEvent) {
@@ -29,7 +16,7 @@
2916
3017 private fun acceptHorizontalDiff(e: AnActionEvent) {
3118 val continuePluginService = getPluginService(e.project) ?: return
32- continuePluginService?.diffManager?.acceptDiff(null)
19+ continuePluginService.diffManager?.acceptDiff(null)
3320 }
3421
3522 private fun acceptVerticalDiff(e: AnActionEvent) {
@@ -61,28 +48,6 @@
6148 }
6249 }
6350
64-fun getContinuePluginService(project: Project?): ContinuePluginService? {
65- if (project != null) {
66- val toolWindowManager = ToolWindowManager.getInstance(project)
67- val toolWindow = toolWindowManager.getToolWindow("Continue")
68-
69- if (toolWindow != null) {
70- if (!toolWindow.isVisible) {
71- toolWindow.activate(null)
72- }
73- }
74- }
75-
76- return getPluginService(project)
77-}
78-
79-fun focusContinueInput(project: Project?) {
80- val continuePluginService = getContinuePluginService(project) ?: return
81- continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
82- continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
83-
84- continuePluginService.ideProtocolClient?.sendHighlightedCode()
85-}
8651
8752 class FocusContinueInputWithoutClearAction : AnAction() {
8853 override fun actionPerformed(e: AnActionEvent) {
@@ -134,8 +99,11 @@
13499 if (logFile.exists()) {
135100 val virtualFile = com.intellij.openapi.vfs.LocalFileSystem.getInstance().findFileByIoFile(logFile)
136101 if (virtualFile != null) {
137- com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).openFile(virtualFile, true)
102+ FileEditorManager.getInstance(project).openFile(virtualFile, true)
138103 }
139104 }
140105 }
141106 }
107+
108+
109+
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt +39 −0
@@ -0,0 +1,39 @@
1+package com.github.continuedev.continueintellijextension.actions
2+
3+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
4+import com.intellij.openapi.components.ServiceManager
5+import com.intellij.openapi.project.Project
6+import com.intellij.openapi.wm.ToolWindowManager
7+
8+fun getContinuePluginService(project: Project?): ContinuePluginService? {
9+ if (project != null) {
10+ val toolWindowManager = ToolWindowManager.getInstance(project)
11+ val toolWindow = toolWindowManager.getToolWindow("Continue")
12+
13+ if (toolWindow != null) {
14+ if (!toolWindow.isVisible) {
15+ toolWindow.activate(null)
16+ }
17+ }
18+ }
19+
20+ return getPluginService(project)
21+}
22+
23+fun focusContinueInput(project: Project?) {
24+ val continuePluginService = getContinuePluginService(project) ?: return
25+ continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
26+ continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
27+
28+ continuePluginService.ideProtocolClient?.sendHighlightedCode()
29+}
30+
31+fun getPluginService(project: Project?): ContinuePluginService? {
32+ if (project == null) {
33+ return null
34+ }
35+ return ServiceManager.getService(
36+ project,
37+ ContinuePluginService::class.java
38+ )
39+}
No newline at the end of the file
deleted extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteActionGroup.kt +0 −29
@@ -1,29 +0,0 @@
1-package com.github.continuedev.continueintellijextension.autocomplete
2-
3-import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
4-import com.intellij.openapi.actionSystem.ActionUpdateThread
5-import com.intellij.openapi.actionSystem.AnActionEvent
6-import com.intellij.openapi.actionSystem.DefaultActionGroup
7-import com.intellij.openapi.components.service
8-
9-class AutocompleteActionGroup : DefaultActionGroup() {
10- override fun getActionUpdateThread(): ActionUpdateThread {
11- return ActionUpdateThread.EDT
12- }
13-
14- override fun update(e: AnActionEvent) {
15- super.update(e)
16- removeAll()
17-
18- val continueSettingsService = service<ContinueExtensionSettings>()
19- if (continueSettingsService.continueState.enableTabAutocomplete) {
20- addAll(
21- DisableTabAutocompleteAction(),
22- )
23- } else {
24- addAll(
25- EnableTabAutocompleteAction(),
26- )
27- }
28- }
29-}
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +2 −2
@@ -121,10 +121,10 @@
121121 val prompt = buildApplyPrompt()
122122
123123 // Extract the code ranges (highlighted or full document)
124- val (prefix, highlighted, suffix) = editorUtils.extractCodeRanges()
124+ val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet()
125125
126126 // Get the line range for the diff stream
127- val rif = editorUtils.getHighlightedCode()
127+ val rif = editorUtils.getHighlightedRIF()
128128 val startLine = rif?.range?.start?.line ?: 0
129129 val endLine = rif?.range?.end?.line ?: (editorUtils.getLineCount() - 1)
130130
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +1 −1
@@ -502,7 +502,7 @@
502502
503503 fun sendHighlightedCode(edit: Boolean = false) {
504504 val editor = EditorUtils.getEditor(project)
505- val rif = editor?.getHighlightedCode() ?: return
505+ val rif = editor?.getHighlightedRIF() ?: return
506506
507507 continuePluginService.sendToWebview(
508508 "highlightedCode",
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +0 −1
@@ -337,6 +337,5 @@
337337 private fun setClosed() {
338338 sendUpdate(ApplyStateStatus.CLOSED)
339339 resetState()
340- onClose()
341340 }
342341 }
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt +14 −11
@@ -1,7 +1,5 @@
11 package com.github.continuedev.continueintellijextension.editor
22
3-import com.github.continuedev.continueintellijextension.Position
4-import com.github.continuedev.continueintellijextension.Range
53 import com.github.continuedev.continueintellijextension.utils.toUriOrNull
64 import com.intellij.openapi.application.ApplicationManager
75 import com.intellij.openapi.command.WriteCommandAction
@@ -72,28 +70,33 @@
7270 editor.scrollingModel.scrollTo(logicalPosition, ScrollType.CENTER_UP)
7371 }
7472
73+ /**
74+ * Remove the selected range in a thread-safe manner
75+ */
76+ fun removeSelection() {
77+ ApplicationManager.getApplication().invokeLater {
78+ editor.selectionModel.removeSelection()
79+ }
80+ }
7581
7682 /**
7783 * Extracts code ranges from the editor: (prefix, highlighted/selected text, suffix)
7884 */
79- fun extractCodeRanges(): Triple<String, String, String> {
80- val rif = getHighlightedCode()
85+ fun getHighlightedRangeTriplet(): Triple<String, String, String> {
86+ val rif = getHighlightedRIF()
8187
8288 return if (rif == null) {
8389 // If no highlight, use the whole document as highlighted
8490 Triple("", editor.document.text, "")
8591 } else {
8692 // Use the RangeInFileWithContents to get absolute offsets
87- val startOffset = rif.getStartOffset(editor.document)
88- val endOffset = rif.getEndOffset(editor.document)
93+ val (startOffset, endOffset) = rif.offsets
94+
8995 val prefix = editor.document.getText(TextRange(0, startOffset))
9096 val highlighted = rif.contents
9197 val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
9298
93- // Remove the selection after processing
94- ApplicationManager.getApplication().invokeLater {
95- editor.selectionModel.removeSelection()
96- }
99+ removeSelection()
97100
98101 Triple(prefix, highlighted, suffix)
99102 }
@@ -103,7 +106,7 @@
103106 * Gets the selected code from the current editor.
104107 * Returns null if there is no selection.
105108 */
106- fun getHighlightedCode(): RangeInFileWithContents? {
109+ fun getHighlightedRIF(): RangeInFileWithContents? {
107110 return ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> {
108111 val virtualFile =
109112 FileDocumentManager.getInstance().getFile(editor.document) ?: return@runReadAction null
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +1 −740
@@ -1,337 +1,11 @@
11 package com.github.continuedev.continueintellijextension.editor
22
3-import com.github.continuedev.continueintellijextension.`continue`.GetTheme
4-import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
5-import com.github.continuedev.continueintellijextension.services.ContinuePluginService
6-import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
7-import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel
8-import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
9-import com.intellij.openapi.Disposable
103 import com.intellij.openapi.actionSystem.ActionUpdateThread
114 import com.intellij.openapi.actionSystem.AnAction
125 import com.intellij.openapi.actionSystem.AnActionEvent
136 import com.intellij.openapi.actionSystem.PlatformDataKeys
14-import com.intellij.openapi.components.service
15-import com.intellij.openapi.editor.Editor
16-import com.intellij.openapi.editor.colors.EditorColorsManager
17-import com.intellij.openapi.editor.colors.EditorFontType
18-import com.intellij.openapi.editor.impl.EditorImpl
197 import com.intellij.openapi.project.DumbAware
20-import com.intellij.openapi.project.Project
21-import com.intellij.openapi.util.IconLoader
22-import com.intellij.openapi.util.Ref
23-import com.intellij.openapi.util.TextRange
24-import com.intellij.ui.JBColor
25-import com.intellij.util.ui.JBUI
26-import com.intellij.util.ui.UIUtil
27-import java.awt.*
28-import java.awt.event.*
29-import java.awt.geom.AffineTransform
30-import java.awt.geom.Path2D
31-import java.awt.geom.RoundRectangle2D
32-import javax.swing.*
33-import javax.swing.event.DocumentEvent
34-import javax.swing.event.DocumentListener
35-import javax.swing.event.ListDataListener
36-import javax.swing.plaf.basic.BasicComboBoxUI
37-import kotlin.math.max
38-import net.miginfocom.swing.MigLayout
39-import org.jdesktop.swingx.JXPanel
40-import org.jdesktop.swingx.JXTextArea
418
42-const val MAIN_FONT_SIZE = 13
43-
44-const val DOWN_ARROW = " ▾"
45-
46-fun makeTextArea(): JTextArea {
47- val textArea =
48- CustomTextArea(1, 40).apply {
49- lineWrap = true
50- wrapStyleWord = true
51- isOpaque = false
52- background = GetTheme().getSecondaryDark()
53- maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
54- margin = JBUI.insets(6, 8, 2, 4)
55- font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
56- preferredSize = Dimension(400, 75)
57- }
58- textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
59- return textArea
60-}
61-
62-fun makePanel(
63- project: Project,
64- customPanelRef: Ref<CustomPanel>,
65- textArea: JTextArea,
66- inlayRef: Ref<Disposable>,
67- comboBoxRef: Ref<JComboBox<String>>,
68- leftInset: Int,
69- modelTitles: List<String>,
70- onEnter: () -> Unit,
71- onCancel: () -> Unit,
72- onAccept: () -> Unit,
73- onReject: () -> Unit
74-): JPanel {
75- val topPanel =
76- ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply {
77- background = JBColor(0x20888888, 0x20888888)
78- isOpaque = false
79- }
80-
81- val panel =
82- CustomPanel(
83- MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"),
84- project,
85- modelTitles,
86- comboBoxRef,
87- onEnter,
88- onCancel,
89- onAccept,
90- onReject,
91- textArea
92- )
93- .apply {
94- val globalScheme = EditorColorsManager.getInstance().globalScheme
95- val defaultBackground = globalScheme.defaultBackground
96- background = defaultBackground
97- add(textArea, "grow, gap 0!, height 100%")
98-
99- putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
100- preferredSize = textArea.preferredSize
101- setup()
102- }
103-
104- customPanelRef.set(panel)
105-
106- textArea.addComponentListener(
107- object : ComponentAdapter() {
108- override fun componentResized(e: ComponentEvent?) {
109- panel.revalidate()
110- panel.repaint()
111- }
112- })
113-
114- topPanel.add(panel, "grow, gap 0!")
115-
116- return topPanel
117-}
118-
119-fun openInlineEdit(project: Project?, editor: Editor) {
120- if (project == null) return
121-
122- // Don't open in terminal
123- if (EditorUtils(editor).isTerminal()) {
124- return
125- }
126-
127- val manager = EditorComponentInlaysManager.from(editor, true)
128-
129- // Get list of model titles
130- val continuePluginService = project.service<ContinuePluginService>()
131- val modelTitles = mutableListOf<String>()
132-
133- continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
134- val modelsByRole =
135- response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
136- val role = if (modelsByRole.containsKey("edit")) "edit" else "chat"
137- modelsByRole.castNestedOrNull<List<*>>(role)
138- ?.mapNotNull { it.castNestedOrNull<String>("title") }
139- ?.let(modelTitles::addAll)
140- }
141-
142- // This is a hacky way to not complicate getting model titles with coroutines
143- // 1500 feels like way upper limit of "would be weird if panel showed up after that long"
144- // And should always allow enough time to load config
145- val maxWaitTime = 1500
146- val startTime = System.currentTimeMillis()
147- while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) {
148- Thread.sleep(20)
149- }
150-
151- // Get highlighted range
152- val selectionModel = editor.selectionModel
153- val startOffset = selectionModel.selectionStart
154- val endOffset = selectionModel.selectionEnd
155- val startLineNumber = editor.document.getLineNumber(startOffset)
156- var endLineNumber = editor.document.getLineNumber(endOffset)
157-
158- // Doesn't seem to be any built-in methods to check for a line selection that contains trailing
159- // newlines.
160- // The only case this matters is when a user double-clicks to highlight a full line. Without this
161- // check.
162- // the highlighted range will continue to the following line.
163- val isSingleLineSelection =
164- endLineNumber > startLineNumber &&
165- endLineNumber < editor.document.lineCount &&
166- editor.document.getLineStartOffset(endLineNumber) == endOffset
167-
168- if (isSingleLineSelection) {
169- endLineNumber--
170- }
171-
172- val prefix = editor.document.getText(TextRange(0, startOffset))
173- val highlighted = editor.document.getText(TextRange(startOffset, endOffset))
174- val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
175- val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1)
176-
177- // Un-highlight the selected text
178- selectionModel.removeSelection()
179-
180- // Get indentation width in pixels
181- val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1
182- val lineStart = editor.document.getLineStartOffset(indentationLineNum)
183- val lineEnd = editor.document.getLineEndOffset(indentationLineNum)
184- val text = editor.document.getText(TextRange(lineStart, lineEnd))
185- val indentation = text.takeWhile { it == ' ' }.length
186- val charWidth =
187- editor.contentComponent
188- .getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN))
189- .charWidth(' ')
190- val leftInset = indentation * charWidth * 2 / 3
191-
192- val inlayRef = Ref<Disposable>()
193- val customPanelRef = Ref<CustomPanel>()
194-
195- // Create text area, attach key listener
196- val textArea = makeTextArea()
197-
198- // Create diff stream handler
199- val diffStreamHandler =
200- DiffStreamHandler(
201- project,
202- editor,
203- startLineNumber,
204- endLineNumber,
205- {
206- inlayRef.get()?.dispose()
207- },
208- {
209- textArea.document.insertString(textArea.caretPosition, ", ", null)
210- textArea.requestFocus()
211- customPanelRef.get().finish()
212- },
213- null,
214- null
215- )
216-
217- val diffStreamService = project.service<DiffStreamService>()
218- diffStreamService.register(diffStreamHandler, editor)
219-
220- val comboBoxRef = Ref<JComboBox<String>>()
221-
222- fun onEnter() {
223- val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW)
224- customPanelRef.get().enter()
225- diffStreamHandler.streamDiffLinesToEditor(
226- textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true
227- )
228- }
229-
230- val panel =
231- makePanel(
232- project,
233- customPanelRef,
234- textArea,
235- inlayRef,
236- comboBoxRef,
237- leftInset,
238- modelTitles,
239- { onEnter() },
240- {
241- diffStreamService.reject(editor)
242- selectionModel.setSelection(startOffset, endOffset)
243- },
244- {
245- diffStreamService.accept(editor)
246- inlayRef.get().dispose()
247- },
248- {
249- diffStreamService.reject(editor)
250- inlayRef.get().dispose()
251- })
252-
253- val inlay = manager.insert(startLineNumber, panel, true)
254-
255- panel.revalidate()
256- inlayRef.set(inlay)
257- val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
258- viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
259-
260- // Add key listener to text area
261- textArea.addKeyListener(
262- object : KeyAdapter() {
263- override fun keyTyped(e: KeyEvent) {
264- if (customPanelRef.get().isFinished) {
265- customPanelRef.get().setup()
266- }
267- }
268-
269- override fun keyPressed(e: KeyEvent) {
270- when (e.keyCode) {
271- KeyEvent.VK_ESCAPE -> {
272- diffStreamService.reject(editor)
273- selectionModel.setSelection(startOffset, endOffset)
274- }
275-
276- KeyEvent.VK_ENTER -> {
277- when (e.modifiersEx) {
278- KeyEvent.SHIFT_DOWN_MASK -> {
279- textArea.document.insertString(textArea.caretPosition, "\n", null)
280- }
281-
282- 0 -> {
283- onEnter()
284- e.consume()
285- }
286- }
287- }
288- }
289- }
290-
291- // We need this because backspace/delete is not registering properly on keyPressed for an
292- // unknown reason
293- override fun keyReleased(e: KeyEvent) {
294- if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) {
295- if (customPanelRef.get().isFinished) {
296- customPanelRef.get().setup()
297- }
298- }
299- }
300- })
301-
302- // Listen for changes to textarea line count
303- textArea.document.addDocumentListener(
304- object : DocumentListener {
305- private var lastNumLines: Int = 0
306-
307- private fun updateSize() {
308- val numLines = textArea.text.lines().size
309- if (numLines != lastNumLines) {
310- lastNumLines = numLines
311- viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
312- }
313- }
314-
315- override fun insertUpdate(e: DocumentEvent?) {
316- updateSize()
317- }
318-
319- override fun removeUpdate(e: DocumentEvent?) {
320- updateSize()
321- }
322-
323- override fun changedUpdate(e: DocumentEvent?) {
324- updateSize()
325- }
326- })
327-
328- textArea.requestFocus()
329-}
330-
331-/**
332- * Adapted from
333- * https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/InlineEditAction.kt
334- */
3359 class InlineEditAction : AnAction(), DumbAware {
33610 override fun update(e: AnActionEvent) {
33711 e.presentation.isEnabled = true
@@ -347,417 +21,4 @@
34721 val project = e.getData(PlatformDataKeys.PROJECT) ?: return
34822 openInlineEdit(project, editor)
34923 }
350-}
351-
352-class CustomPanel(
353- layout: MigLayout,
354- project: Project,
355- modelTitles: List<String>,
356- comboBoxRef: Ref<JComboBox<String>>,
357- private val onEnter: () -> Unit,
358- private val onCancel: () -> Unit,
359- private val onAccept: () -> Unit,
360- private val onReject: () -> Unit,
361- private val textArea: JTextArea
362-) : JPanel(layout) {
363- private val shadowSize = 5
364- private val cornerRadius = 8
365- private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow
366- private val borderColor = Color(128, 128, 128, 128)
367- private val borderThickness = 1
368- private val triangleSize = 6
369- private val rightMargin = 3.0
370- private val closeButton: JComponent = createCloseButton()
371- private val originalTextColor: Color = textArea.foreground
372- private val greyTextColor: Color = Color(128, 128, 128, 200)
373- var isFinished = false
374-
375- init {
376- isOpaque = false
377- add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!")
378- }
379-
380- private fun createCloseButton(): JComponent {
381- val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass)
382- return JLabel(closeIcon).apply {
383- background = Color(0, 0, 0, 0)
384- border = JBUI.Borders.empty(2, 6, 2, 0)
385- toolTipText = "`esc` to cancel"
386- isOpaque = false
387- addMouseListener(
388- object : MouseAdapter() {
389- override fun mouseEntered(e: MouseEvent) {
390- cursor = Cursor(Cursor.HAND_CURSOR)
391- }
392-
393- override fun mouseExited(e: MouseEvent) {
394- cursor = Cursor.getDefaultCursor()
395- }
396-
397- override fun mouseClicked(e: MouseEvent) {
398- onCancel()
399- }
400- })
401- }
402- }
403-
404- private val subPanelA: JPanel =
405- JPanel(MigLayout("insets 0, fillx")).apply {
406- val globalScheme = EditorColorsManager.getInstance().globalScheme
407- val defaultBackground = globalScheme.defaultBackground
408- val continueSettingsService = service<ContinueExtensionSettings>()
409- val dropdown =
410- JComboBox(modelTitles.toTypedArray()).apply {
411- setUI(TransparentArrowButtonUI())
412- isEditable = true
413- background = defaultBackground
414- foreground = Color(128, 128, 128, 200)
415- font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12)
416- border = JBUI.Borders.empty(8)
417- isOpaque = false
418- isEditable = false
419- cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
420- preferredSize = Dimension(200, 30)
421-
422- renderer = object : DefaultListCellRenderer() {
423- override fun getListCellRendererComponent(
424- list: JList<*>?,
425- value: Any?,
426- index: Int,
427- isSelected: Boolean,
428- cellHasFocus: Boolean
429- ): Component {
430- val component =
431- super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
432- if (component is JLabel) {
433- component.border = JBUI.Borders.empty(4, 6)
434- }
435- return component
436- }
437- }.apply {
438- horizontalAlignment = SwingConstants.LEFT
439- }
440-
441- selectedIndex =
442- if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
443- if (modelTitles.isEmpty()) -1
444- else {
445- val index = modelTitles.indexOf(it)
446- if (index != -1) index else 0
447- }
448- } ?: 0
449-
450- addActionListener {
451- continueSettingsService.continueState.lastSelectedInlineEditModel =
452- (selectedItem as String).removeSuffix(DOWN_ARROW)
453- }
454- }
455-
456- comboBoxRef.set(dropdown)
457-
458- val rightButton =
459- CustomButton("⏎ Enter") { onEnter() }
460- .apply {
461- background = globalScheme.defaultForeground
462- foreground = globalScheme.defaultBackground
463- border = JBUI.Borders.empty(2, 6)
464- }
465-
466- val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
467- isOpaque = false
468- add(rightButton, "align right")
469- }
470-
471- border = JBUI.Borders.empty(0, 0, 16, 12)
472- isOpaque = false
473-
474- add(dropdown, "align left")
475- add(rightPanel, "align right")
476-
477- cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
478- }
479-
480- private val subPanelB: JPanel =
481- JPanel(BorderLayout()).apply {
482- isOpaque = false
483-
484- val progressBar = JProgressBar().apply { isIndeterminate = true }
485-
486- add(progressBar, BorderLayout.CENTER)
487- border = JBUI.Borders.empty(0, 0, 16, 12)
488- }
489-
490- private val subPanelC: JPanel =
491- JPanel(MigLayout("insets 0, fillx")).apply {
492- val leftLabel =
493- JLabel("Type to re-prompt").apply {
494- foreground = Color(156, 163, 175) // text-gray-400
495- font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
496- border = JBUI.Borders.emptyLeft(4)
497- }
498-
499- val leftButton =
500- CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() }
501- .apply {
502- background = JBColor(0x30FF0000, 0x30FF0000)
503- }
504-
505- val rightButton =
506- CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() }
507- .apply {
508- background = JBColor(0x3000FF00, 0x3000FF00)
509- }
510-
511- val rightPanel =
512- JPanel(MigLayout("insets 0, fillx")).apply {
513- isOpaque = false
514- add(leftButton, "align right")
515- add(rightButton, "align right")
516- border = JBUI.Borders.empty()
517- }
518-
519- add(leftLabel, "align left")
520- add(rightPanel, "align right")
521- border = JBUI.Borders.empty(0, 0, 16, 12)
522- isOpaque = false
523- }
524-
525- fun setup() {
526- remove(subPanelB)
527- remove(subPanelC)
528- add(subPanelA, "grow, gap 0!")
529- isFinished = false
530- revalidate()
531- repaint()
532- textArea.foreground = originalTextColor
533- }
534-
535- fun enter() {
536- remove(subPanelA)
537- remove(subPanelC)
538- add(subPanelB, "grow, gap 0!")
539- revalidate()
540- repaint()
541- }
542-
543- fun finish() {
544- remove(subPanelB)
545- add(subPanelC, "grow, gap 0!")
546- revalidate()
547- repaint()
548- isFinished = true
549- textArea.foreground = greyTextColor
550- }
551-
552- override fun paintComponent(g: Graphics) {
553- super.paintComponent(g)
554-
555- val g2 = g as Graphics2D
556- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
557-
558- val w = width - shadowSize
559- val h = height - shadowSize
560-
561- // Create the shape for the tooltip/triangle
562- val shape = Path2D.Double()
563- shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble())
564- shape.quadTo(
565- borderThickness / 2.0,
566- borderThickness / 2.0,
567- cornerRadius.toDouble(),
568- borderThickness / 2.0
569- )
570- shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0)
571- shape.quadTo(
572- w - borderThickness / 2.0 - rightMargin,
573- borderThickness / 2.0,
574- w - borderThickness / 2.0 - rightMargin,
575- cornerRadius.toDouble()
576- )
577- shape.lineTo(
578- w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()
579- )
580- shape.quadTo(
581- w - borderThickness / 2.0 - rightMargin,
582- h - triangleSize.toDouble(),
583- w - cornerRadius.toDouble() - rightMargin,
584- h - triangleSize.toDouble()
585- )
586- shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble())
587- shape.lineTo(borderThickness / 2.0, h.toDouble())
588- shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble())
589-
590- // Draw shadow
591- g2.color = shadowColor
592- g2.fill(
593- shape.createTransformedShape(
594- AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble())
595- )
596- )
597-
598- // Draw main shape
599- g2.color = background
600- g2.fill(shape)
601-
602- // Draw border
603- g2.color = borderColor
604- g2.stroke = BasicStroke(borderThickness.toFloat())
605- g2.draw(shape)
606- }
607-}
608-
609-class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
610- private var isHovered = false
611-
612- init {
613- isOpaque = false
614- cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
615- addMouseListener(
616- object : MouseAdapter() {
617- override fun mouseEntered(e: MouseEvent?) {
618- isHovered = true
619- repaint()
620- }
621-
622- override fun mouseExited(e: MouseEvent?) {
623- isHovered = false
624- repaint()
625- }
626-
627- override fun mouseClicked(e: MouseEvent?) {
628- onClick()
629- }
630- })
631-
632- font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
633- border = JBUI.Borders.empty(2, 6)
634- }
635-
636- override fun paintComponent(g: Graphics) {
637- val g2 = g as Graphics2D
638- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
639-
640- val cornerRadius = 8
641- val rect = Rectangle(0, 0, width, height)
642- val roundRect =
643- RoundRectangle2D.Float(
644- rect.x.toFloat(),
645- rect.y.toFloat(),
646- rect.width.toFloat(),
647- rect.height.toFloat(),
648- cornerRadius.toFloat(),
649- cornerRadius.toFloat()
650- )
651- g2.color = background
652- g2.fill(roundRect)
653- g2.color = foreground
654- g2.drawString(
655- text,
656- (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
657- (height / 2 + g.fontMetrics.ascent / 2).toFloat()
658- )
659- }
660-}
661-
662-class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") {
663- init {
664- setRows(rows)
665- setColumns(columns)
666- }
667-
668- override fun paintComponent(g: Graphics) {
669- // Draw placeholder
670- if (text.isEmpty()) {
671- g.color = Color(128, 128, 128, 255)
672- g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
673- g.drawString("Enter instructions...", 8, 20)
674- }
675-
676- super.paintComponent(g)
677- }
678-}
679-
680-class ShadowPanel(layout: LayoutManager) : JXPanel(layout) {
681- override fun getPreferredSize(): Dimension {
682- val prefSize = super.getPreferredSize()
683- val insets = getInsets()
684- prefSize.width += insets.left + insets.right
685- prefSize.height += insets.top + insets.bottom
686- return prefSize
687- }
688-
689- override fun paintComponent(g: Graphics) {
690- super.paintComponent(g)
691- }
692-}
693-
694-class TransparentArrowButtonUI : BasicComboBoxUI() {
695- override fun createArrowButton() =
696- JButton().apply {
697- isVisible = false
698- preferredSize = Dimension(0, 0)
699- }
700-
701- override fun getInsets(): Insets {
702- return JBUI.insetsLeft(6)
703- }
704-
705- override fun installUI(c: JComponent?) {
706- super.installUI(c)
707- comboBox.isOpaque = false
708- val globalScheme = EditorColorsManager.getInstance().globalScheme
709- val defaultBackground = globalScheme.defaultBackground
710- comboBox.background = defaultBackground
711-
712- // Modify the ComboBoxModel to include the down symbol
713- val originalModel = comboBox.model
714- comboBox.model =
715- object : ComboBoxModel<Any> {
716- override fun getSize(): Int = originalModel.size
717-
718- override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index)
719-
720- override fun setSelectedItem(anItem: Any?) {
721- originalModel.selectedItem = anItem
722- }
723-
724- override fun getSelectedItem(): Any? {
725- val item = originalModel.selectedItem
726- return "$item$DOWN_ARROW"
727- }
728-
729- override fun addListDataListener(l: ListDataListener?) {
730- originalModel.addListDataListener(l)
731- }
732-
733- override fun removeListDataListener(l: ListDataListener?) {
734- originalModel.removeListDataListener(l)
735- }
736- }
737- }
738-
739- override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
740- // Do nothing to prevent painting the background
741- }
742-
743- override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
744- val renderer = comboBox.renderer
745- val item = comboBox.selectedItem
746-
747- if (item != null) {
748- val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false)
749- c.font = comboBox.font
750- c.foreground = Color(156, 163, 175) // text-gray-400
751- c.background = comboBox.background
752-
753- if (c is JComponent) {
754- c.isOpaque = false
755- }
756-
757- val currentValuePane = currentValuePane
758- currentValuePane.paintComponent(
759- g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true
760- )
761- }
762- }
763-}
24+}
No newline at the end of the file
added extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditPanel.kt +746 −0
@@ -0,0 +1,746 @@
1+package com.github.continuedev.continueintellijextension.editor
2+
3+import com.github.continuedev.continueintellijextension.`continue`.GetTheme
4+import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
5+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
6+import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
7+import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel
8+import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
9+import com.intellij.openapi.Disposable
10+import com.intellij.openapi.components.service
11+import com.intellij.openapi.editor.Editor
12+import com.intellij.openapi.editor.colors.EditorColorsManager
13+import com.intellij.openapi.editor.colors.EditorFontType
14+import com.intellij.openapi.editor.impl.EditorImpl
15+import com.intellij.openapi.project.Project
16+import com.intellij.openapi.util.IconLoader
17+import com.intellij.openapi.util.Ref
18+import com.intellij.openapi.util.TextRange
19+import com.intellij.ui.JBColor
20+import com.intellij.util.ui.JBUI
21+import com.intellij.util.ui.UIUtil
22+import java.awt.*
23+import java.awt.event.*
24+import java.awt.geom.AffineTransform
25+import java.awt.geom.Path2D
26+import java.awt.geom.RoundRectangle2D
27+import javax.swing.*
28+import javax.swing.event.DocumentEvent
29+import javax.swing.event.DocumentListener
30+import javax.swing.event.ListDataListener
31+import javax.swing.plaf.basic.BasicComboBoxUI
32+import kotlin.math.max
33+import net.miginfocom.swing.MigLayout
34+import org.jdesktop.swingx.JXPanel
35+import org.jdesktop.swingx.JXTextArea
36+
37+const val MAIN_FONT_SIZE = 13
38+const val DOWN_ARROW = " ▾"
39+const val MAX_MODEL_WAIT_TIME = 1500
40+
41+/**
42+ * Fetches and combines available model titles from both "edit" and "chat" roles.
43+ * Edit models are prioritized and appear first in the returned list.
44+ * Handles duplicate models by only including them once (prioritizing edit role).
45+ *
46+ * @param continuePluginService The service used to fetch config information
47+ * @return List of model titles with edit models first, duplicates removed
48+ * @throws No exceptions, but will return empty list if request fails or times out after 1.5 seconds
49+ */
50+fun getModelTitles(continuePluginService: ContinuePluginService): List<String> {
51+ val modelTitles = mutableListOf<String>()
52+
53+ continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
54+ val modelsByRole =
55+ response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
56+
57+ // Get edit models first
58+ val editModels = modelsByRole.castNestedOrNull<List<*>>("edit")
59+ ?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList()
60+
61+ // Then get chat models
62+ val chatModels = modelsByRole.castNestedOrNull<List<*>>("chat")
63+ ?.mapNotNull { it.castNestedOrNull<String>("title") } ?: emptyList()
64+
65+ // Add edit models first, then chat models (avoiding duplicates)
66+ modelTitles.addAll(editModels)
67+ modelTitles.addAll(chatModels.filter { it !in editModels })
68+ }
69+
70+ val startTime = System.currentTimeMillis()
71+ while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < MAX_MODEL_WAIT_TIME) {
72+ Thread.sleep(20)
73+ }
74+
75+ return modelTitles
76+}
77+
78+fun makeTextArea(): JTextArea {
79+ val textArea =
80+ CustomTextArea(1, 40).apply {
81+ lineWrap = true
82+ wrapStyleWord = true
83+ isOpaque = false
84+ background = GetTheme().getSecondaryDark()
85+ maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
86+ margin = JBUI.insets(6, 8, 2, 4)
87+ font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
88+ preferredSize = Dimension(400, 75)
89+ }
90+ textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
91+ return textArea
92+}
93+
94+fun makePanel(
95+ project: Project,
96+ customPanelRef: Ref<CustomPanel>,
97+ textArea: JTextArea,
98+ inlayRef: Ref<Disposable>,
99+ comboBoxRef: Ref<JComboBox<String>>,
100+ leftInset: Int,
101+ modelTitles: List<String>,
102+ onEnter: () -> Unit,
103+ onCancel: () -> Unit,
104+ onAccept: () -> Unit,
105+ onReject: () -> Unit
106+): JPanel {
107+ val topPanel =
108+ ShadowPanel(MigLayout("wrap 1, insets 2 $leftInset 2 2, gap 0!")).apply {
109+ background = JBColor(0x20888888, 0x20888888)
110+ isOpaque = false
111+ }
112+
113+ val panel =
114+ CustomPanel(
115+ MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"),
116+ project,
117+ modelTitles,
118+ comboBoxRef,
119+ onEnter,
120+ onCancel,
121+ onAccept,
122+ onReject,
123+ textArea
124+ )
125+ .apply {
126+ val globalScheme = EditorColorsManager.getInstance().globalScheme
127+ val defaultBackground = globalScheme.defaultBackground
128+ background = defaultBackground
129+ add(textArea, "grow, gap 0!, height 100%")
130+
131+ putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
132+ preferredSize = textArea.preferredSize
133+ setup()
134+ }
135+
136+ customPanelRef.set(panel)
137+
138+ textArea.addComponentListener(
139+ object : ComponentAdapter() {
140+ override fun componentResized(e: ComponentEvent?) {
141+ panel.revalidate()
142+ panel.repaint()
143+ }
144+ })
145+
146+ topPanel.add(panel, "grow, gap 0!")
147+
148+ return topPanel
149+}
150+
151+fun openInlineEdit(project: Project?, editor: Editor) {
152+ if (project == null) return
153+
154+ val editorUtils = EditorUtils(editor)
155+
156+ // Don't open in terminal
157+ if (editorUtils.isTerminal()) {
158+ return
159+ }
160+
161+ val manager = EditorComponentInlaysManager.from(editor, true)
162+
163+ val continuePluginService = project.service<ContinuePluginService>()
164+ val modelTitles = getModelTitles(continuePluginService)
165+
166+ val highlightedRIF = editorUtils.getHighlightedRIF() ?: return
167+ val (startLineNumber, endLineNumber) = highlightedRIF.lines
168+ val (highlightedStartOffset, highlightedEndOffset) = highlightedRIF.offsets
169+
170+
171+ val (prefix, highlighted, suffix) = editorUtils.getHighlightedRangeTriplet()
172+ val lineNumber = if (startLineNumber == 0) 0 else max(0, startLineNumber - 1)
173+
174+ editorUtils.removeSelection()
175+
176+ // Get indentation width in pixels
177+ val indentationLineNum = if (startLineNumber == 0) 0 else lineNumber + 1
178+ val lineStart = editor.document.getLineStartOffset(indentationLineNum)
179+ val lineEnd = editor.document.getLineEndOffset(indentationLineNum)
180+ val text = editor.document.getText(TextRange(lineStart, lineEnd))
181+ val indentation = text.takeWhile { it == ' ' }.length
182+ val charWidth =
183+ editor.contentComponent
184+ .getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN))
185+ .charWidth(' ')
186+ val leftInset = indentation * charWidth * 2 / 3
187+
188+ val inlayRef = Ref<Disposable>()
189+ val customPanelRef = Ref<CustomPanel>()
190+
191+ // Create text area, attach key listener
192+ val textArea = makeTextArea()
193+
194+ // Create diff stream handler
195+ val diffStreamHandler =
196+ DiffStreamHandler(
197+ project,
198+ editor,
199+ startLineNumber,
200+ endLineNumber,
201+ {
202+ inlayRef.get()?.dispose()
203+ },
204+ {
205+ textArea.document.insertString(textArea.caretPosition, ", ", null)
206+ textArea.requestFocus()
207+ customPanelRef.get().finish()
208+ },
209+ null,
210+ null
211+ )
212+
213+ val diffStreamService = project.service<DiffStreamService>()
214+ diffStreamService.register(diffStreamHandler, editor)
215+
216+ val comboBoxRef = Ref<JComboBox<String>>()
217+
218+ fun onEnter() {
219+ val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(DOWN_ARROW)
220+ customPanelRef.get().enter()
221+ diffStreamHandler.streamDiffLinesToEditor(
222+ textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret, true
223+ )
224+ }
225+
226+ val panel =
227+ makePanel(
228+ project,
229+ customPanelRef,
230+ textArea,
231+ inlayRef,
232+ comboBoxRef,
233+ leftInset,
234+ modelTitles,
235+ { onEnter() },
236+ {
237+ diffStreamService.reject(editor)
238+ editorUtils.editor.selectionModel.setSelection(highlightedStartOffset, highlightedEndOffset)
239+ },
240+ {
241+ diffStreamService.accept(editor)
242+ inlayRef.get().dispose()
243+ },
244+ {
245+ diffStreamService.reject(editor)
246+ inlayRef.get().dispose()
247+ })
248+
249+ val inlay = manager.insert(startLineNumber, panel, true)
250+
251+ panel.revalidate()
252+ inlayRef.set(inlay)
253+ val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
254+ viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
255+
256+ // Add key listener to text area
257+ textArea.addKeyListener(
258+ object : KeyAdapter() {
259+ override fun keyTyped(e: KeyEvent) {
260+ if (customPanelRef.get().isFinished) {
261+ customPanelRef.get().setup()
262+ }
263+ }
264+
265+ override fun keyPressed(e: KeyEvent) {
266+ when (e.keyCode) {
267+ KeyEvent.VK_ESCAPE -> {
268+ diffStreamService.reject(editor)
269+ editorUtils.editor.selectionModel.setSelection(
270+ highlightedStartOffset,
271+ highlightedEndOffset
272+ )
273+ }
274+
275+ KeyEvent.VK_ENTER -> {
276+ when (e.modifiersEx) {
277+ KeyEvent.SHIFT_DOWN_MASK -> {
278+ textArea.document.insertString(textArea.caretPosition, "\n", null)
279+ }
280+
281+ 0 -> {
282+ onEnter()
283+ e.consume()
284+ }
285+ }
286+ }
287+ }
288+ }
289+
290+ // We need this because backspace/delete is not registering properly on keyPressed for an
291+ // unknown reason
292+ override fun keyReleased(e: KeyEvent) {
293+ if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) {
294+ if (customPanelRef.get().isFinished) {
295+ customPanelRef.get().setup()
296+ }
297+ }
298+ }
299+ })
300+
301+ // Listen for changes to textarea line count
302+ textArea.document.addDocumentListener(
303+ object : DocumentListener {
304+ private var lastNumLines: Int = 0
305+
306+ private fun updateSize() {
307+ val numLines = textArea.text.lines().size
308+ if (numLines != lastNumLines) {
309+ lastNumLines = numLines
310+ viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
311+ }
312+ }
313+
314+ override fun insertUpdate(e: DocumentEvent?) {
315+ updateSize()
316+ }
317+
318+ override fun removeUpdate(e: DocumentEvent?) {
319+ updateSize()
320+ }
321+
322+ override fun changedUpdate(e: DocumentEvent?) {
323+ updateSize()
324+ }
325+ })
326+
327+ textArea.requestFocus()
328+}
329+
330+
331+class CustomPanel(
332+ layout: MigLayout,
333+ project: Project,
334+ modelTitles: List<String>,
335+ comboBoxRef: Ref<JComboBox<String>>,
336+ private val onEnter: () -> Unit,
337+ private val onCancel: () -> Unit,
338+ private val onAccept: () -> Unit,
339+ private val onReject: () -> Unit,
340+ private val textArea: JTextArea
341+) : JPanel(layout) {
342+ private val shadowSize = 5
343+ private val cornerRadius = 8
344+ private val shadowColor = Color(0, 0, 0, 40) // Lighter shadow
345+ private val borderColor = Color(128, 128, 128, 128)
346+ private val borderThickness = 1
347+ private val triangleSize = 6
348+ private val rightMargin = 3.0
349+ private val closeButton: JComponent = createCloseButton()
350+ private val originalTextColor: Color = textArea.foreground
351+ private val greyTextColor: Color = Color(128, 128, 128, 200)
352+ var isFinished = false
353+
354+ init {
355+ isOpaque = false
356+ add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!")
357+ }
358+
359+ private fun createCloseButton(): JComponent {
360+ val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass)
361+ return JLabel(closeIcon).apply {
362+ background = Color(0, 0, 0, 0)
363+ border = JBUI.Borders.empty(2, 6, 2, 0)
364+ toolTipText = "`esc` to cancel"
365+ isOpaque = false
366+ addMouseListener(
367+ object : MouseAdapter() {
368+ override fun mouseEntered(e: MouseEvent) {
369+ cursor = Cursor(Cursor.HAND_CURSOR)
370+ }
371+
372+ override fun mouseExited(e: MouseEvent) {
373+ cursor = Cursor.getDefaultCursor()
374+ }
375+
376+ override fun mouseClicked(e: MouseEvent) {
377+ onCancel()
378+ }
379+ })
380+ }
381+ }
382+
383+ private val subPanelA: JPanel =
384+ JPanel(MigLayout("insets 0, fillx")).apply {
385+ val globalScheme = EditorColorsManager.getInstance().globalScheme
386+ val defaultBackground = globalScheme.defaultBackground
387+ val continueSettingsService = service<ContinueExtensionSettings>()
388+ val dropdown =
389+ JComboBox(modelTitles.toTypedArray()).apply {
390+ setUI(TransparentArrowButtonUI())
391+ isEditable = true
392+ background = defaultBackground
393+ foreground = Color(128, 128, 128, 200)
394+ font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 12)
395+ border = JBUI.Borders.empty(8)
396+ isOpaque = false
397+ isEditable = false
398+ cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
399+ preferredSize = Dimension(200, 30)
400+
401+ renderer = object : DefaultListCellRenderer() {
402+ override fun getListCellRendererComponent(
403+ list: JList<*>?,
404+ value: Any?,
405+ index: Int,
406+ isSelected: Boolean,
407+ cellHasFocus: Boolean
408+ ): Component {
409+ val component =
410+ super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
411+ if (component is JLabel) {
412+ component.border = JBUI.Borders.empty(4, 6)
413+ }
414+ return component
415+ }
416+ }.apply {
417+ horizontalAlignment = SwingConstants.LEFT
418+ }
419+
420+ selectedIndex =
421+ if (itemCount == 0) -1 else continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
422+ if (modelTitles.isEmpty()) -1
423+ else {
424+ val index = modelTitles.indexOf(it)
425+ if (index != -1) index else 0
426+ }
427+ } ?: 0
428+
429+ addActionListener {
430+ continueSettingsService.continueState.lastSelectedInlineEditModel =
431+ (selectedItem as String).removeSuffix(DOWN_ARROW)
432+ }
433+ }
434+
435+ comboBoxRef.set(dropdown)
436+
437+ val rightButton =
438+ CustomButton("⏎ Enter") { onEnter() }
439+ .apply {
440+ background = JBColor.namedColor("Button.startBackground")
441+ foreground = JBColor.namedColor("Button.foreground")
442+ border = JBUI.Borders.empty(2, 6)
443+ }
444+
445+ val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
446+ isOpaque = false
447+ add(rightButton, "align right")
448+ }
449+
450+ border = JBUI.Borders.empty(0, 0, 16, 12)
451+ isOpaque = false
452+
453+ add(dropdown, "align left")
454+ add(rightPanel, "align right")
455+
456+ cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
457+ }
458+
459+ private val subPanelB: JPanel =
460+ JPanel(BorderLayout()).apply {
461+ isOpaque = false
462+
463+ val progressBar = JProgressBar().apply { isIndeterminate = true }
464+
465+ add(progressBar, BorderLayout.CENTER)
466+ border = JBUI.Borders.empty(0, 0, 16, 12)
467+ }
468+
469+ private val subPanelC: JPanel =
470+ JPanel(MigLayout("insets 0, fillx")).apply {
471+ val leftLabel =
472+ JLabel("Type to re-prompt").apply {
473+ foreground = Color(156, 163, 175) // text-gray-400
474+ font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
475+ border = JBUI.Borders.emptyLeft(4)
476+ }
477+
478+ val leftButton =
479+ CustomButton("Reject All (${getMetaKeyLabel()}${getShiftKeyLabel()}⌫)") { onReject() }
480+ .apply {
481+ background = Color(0, 0, 0, 0)
482+ foreground = JBColor.foreground()
483+ border = JBUI.Borders.empty(2, 6)
484+ }
485+
486+ val rightButton =
487+ CustomButton("Accept All (${getMetaKeyLabel()}${getShiftKeyLabel()}⏎)") { onAccept() }
488+ .apply {
489+ background = JBColor.namedColor("Button.startBackground")
490+ foreground = JBColor.namedColor("Button.foreground")
491+ border = JBUI.Borders.empty(2, 6)
492+ }
493+
494+ val rightPanel =
495+ JPanel(MigLayout("insets 0, fillx")).apply {
496+ isOpaque = false
497+ add(leftButton, "align right")
498+ add(rightButton, "align right")
499+ border = JBUI.Borders.empty()
500+ }
501+
502+ add(leftLabel, "align left")
503+ add(rightPanel, "align right")
504+ border = JBUI.Borders.empty(0, 0, 16, 12)
505+ isOpaque = false
506+ }
507+
508+ fun setup() {
509+ remove(subPanelB)
510+ remove(subPanelC)
511+ add(subPanelA, "grow, gap 0!")
512+ isFinished = false
513+ revalidate()
514+ repaint()
515+ textArea.foreground = originalTextColor
516+ }
517+
518+ fun enter() {
519+ remove(subPanelA)
520+ remove(subPanelC)
521+ add(subPanelB, "grow, gap 0!")
522+ revalidate()
523+ repaint()
524+ }
525+
526+ fun finish() {
527+ remove(subPanelB)
528+ add(subPanelC, "grow, gap 0!")
529+ revalidate()
530+ repaint()
531+ isFinished = true
532+ textArea.foreground = greyTextColor
533+ }
534+
535+ override fun paintComponent(g: Graphics) {
536+ super.paintComponent(g)
537+
538+ val g2 = g as Graphics2D
539+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
540+
541+ val w = width - shadowSize
542+ val h = height - shadowSize
543+
544+ // Create the shape for the tooltip/triangle
545+ val shape = Path2D.Double()
546+ shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble())
547+ shape.quadTo(
548+ borderThickness / 2.0,
549+ borderThickness / 2.0,
550+ cornerRadius.toDouble(),
551+ borderThickness / 2.0
552+ )
553+ shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0)
554+ shape.quadTo(
555+ w - borderThickness / 2.0 - rightMargin,
556+ borderThickness / 2.0,
557+ w - borderThickness / 2.0 - rightMargin,
558+ cornerRadius.toDouble()
559+ )
560+ shape.lineTo(
561+ w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()
562+ )
563+ shape.quadTo(
564+ w - borderThickness / 2.0 - rightMargin,
565+ h - triangleSize.toDouble(),
566+ w - cornerRadius.toDouble() - rightMargin,
567+ h - triangleSize.toDouble()
568+ )
569+ shape.lineTo(triangleSize.toDouble(), h - triangleSize.toDouble())
570+ shape.lineTo(borderThickness / 2.0, h.toDouble())
571+ shape.lineTo(borderThickness / 2.0, cornerRadius.toDouble())
572+
573+ // Draw shadow
574+ g2.color = shadowColor
575+ g2.fill(
576+ shape.createTransformedShape(
577+ AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble())
578+ )
579+ )
580+
581+ // Draw main shape
582+ g2.color = background
583+ g2.fill(shape)
584+
585+ // Draw border
586+ g2.color = borderColor
587+ g2.stroke = BasicStroke(borderThickness.toFloat())
588+ g2.draw(shape)
589+ }
590+}
591+
592+class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
593+ private var isHovered = false
594+
595+ init {
596+ isOpaque = false
597+ cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
598+ addMouseListener(
599+ object : MouseAdapter() {
600+ override fun mouseEntered(e: MouseEvent?) {
601+ isHovered = true
602+ repaint()
603+ }
604+
605+ override fun mouseExited(e: MouseEvent?) {
606+ isHovered = false
607+ repaint()
608+ }
609+
610+ override fun mouseClicked(e: MouseEvent?) {
611+ onClick()
612+ }
613+ })
614+
615+ font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
616+ border = JBUI.Borders.empty(2, 6)
617+ }
618+
619+ override fun paintComponent(g: Graphics) {
620+ val g2 = g as Graphics2D
621+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
622+
623+ val cornerRadius = 8
624+ val rect = Rectangle(0, 0, width, height)
625+ val roundRect =
626+ RoundRectangle2D.Float(
627+ rect.x.toFloat(),
628+ rect.y.toFloat(),
629+ rect.width.toFloat(),
630+ rect.height.toFloat(),
631+ cornerRadius.toFloat(),
632+ cornerRadius.toFloat()
633+ )
634+ g2.color = background
635+ g2.fill(roundRect)
636+ g2.color = foreground
637+ g2.drawString(
638+ text,
639+ (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
640+ (height / 2 + g.fontMetrics.ascent / 2).toFloat()
641+ )
642+ }
643+}
644+
645+class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") {
646+ init {
647+ setRows(rows)
648+ setColumns(columns)
649+ }
650+
651+ override fun paintComponent(g: Graphics) {
652+ // Draw placeholder
653+ if (text.isEmpty()) {
654+ g.color = Color(128, 128, 128, 255)
655+ g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
656+ g.drawString("Enter instructions...", 8, 20)
657+ }
658+
659+ super.paintComponent(g)
660+ }
661+}
662+
663+class ShadowPanel(layout: LayoutManager) : JXPanel(layout) {
664+ override fun getPreferredSize(): Dimension {
665+ val prefSize = super.getPreferredSize()
666+ val insets = getInsets()
667+ prefSize.width += insets.left + insets.right
668+ prefSize.height += insets.top + insets.bottom
669+ return prefSize
670+ }
671+
672+ override fun paintComponent(g: Graphics) {
673+ super.paintComponent(g)
674+ }
675+}
676+
677+class TransparentArrowButtonUI : BasicComboBoxUI() {
678+ override fun createArrowButton() =
679+ JButton().apply {
680+ isVisible = false
681+ preferredSize = Dimension(0, 0)
682+ }
683+
684+ override fun getInsets(): Insets {
685+ return JBUI.insetsLeft(6)
686+ }
687+
688+ override fun installUI(c: JComponent?) {
689+ super.installUI(c)
690+ comboBox.isOpaque = false
691+ val globalScheme = EditorColorsManager.getInstance().globalScheme
692+ val defaultBackground = globalScheme.defaultBackground
693+ comboBox.background = defaultBackground
694+
695+ // Modify the ComboBoxModel to include the down symbol
696+ val originalModel = comboBox.model
697+ comboBox.model =
698+ object : ComboBoxModel<Any> {
699+ override fun getSize(): Int = originalModel.size
700+
701+ override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index)
702+
703+ override fun setSelectedItem(anItem: Any?) {
704+ originalModel.selectedItem = anItem
705+ }
706+
707+ override fun getSelectedItem(): Any? {
708+ val item = originalModel.selectedItem
709+ return "$item$DOWN_ARROW"
710+ }
711+
712+ override fun addListDataListener(l: ListDataListener?) {
713+ originalModel.addListDataListener(l)
714+ }
715+
716+ override fun removeListDataListener(l: ListDataListener?) {
717+ originalModel.removeListDataListener(l)
718+ }
719+ }
720+ }
721+
722+ override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
723+ // Do nothing to prevent painting the background
724+ }
725+
726+ override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
727+ val renderer = comboBox.renderer
728+ val item = comboBox.selectedItem
729+
730+ if (item != null) {
731+ val c = renderer.getListCellRendererComponent(listBox, item, -1, false, false)
732+ c.font = comboBox.font
733+ c.foreground = Color(156, 163, 175) // text-gray-400
734+ c.background = comboBox.background
735+
736+ if (c is JComponent) {
737+ c.isOpaque = false
738+ }
739+
740+ val currentValuePane = currentValuePane
741+ currentValuePane.paintComponent(
742+ g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true
743+ )
744+ }
745+ }
746+}
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/RangeInFileWithContents.kt +59 −11
@@ -12,22 +12,43 @@
1212 class RangeInFileWithContents(
1313 val filepath: String,
1414 val range: Range,
15- val contents: String
15+ val contents: String,
16+ val document: Document
17+
1618 ) {
1719 /**
18- * Returns the absolute document offset for the start position
20+ * The absolute document offset for the start position
21+ */
22+ val startOffset: Int
23+ get() = document.getLineStartOffset(range.start.line) + range.start.character
24+
25+ /**
26+ * The absolute document offset for the end position
27+ */
28+ val endOffset: Int
29+ get() = document.getLineStartOffset(range.end.line) + range.end.character
30+
31+ /**
32+ * The line number where the highlighted range starts (zero-based)
33+ */
34+ val startLine: Int
35+ get() = range.start.line
36+
37+ /**
38+ * The line number where the highlighted range ends (zero-based)
39+ * This already accounts for proper line ending calculations.
1940 */
20- fun getStartOffset(document: Document): Int {
21- return document.getLineStartOffset(range.start.line) + range.start.character
22- }
41+ val endLine: Int
42+ get() = range.end.line
2343
2444 /**
25- * Returns the absolute document offset for the end position
45+ * Both the start and end line numbers of the highlighted range as a pair
2646 */
27- fun getEndOffset(document: Document): Int {
28- return document.getLineStartOffset(range.end.line) + range.end.character
29- }
47+ val lines: Pair<Int, Int>
48+ get() = Pair(startLine, endLine)
3049
50+ val offsets: Pair<Int, Int>
51+ get() = Pair(startOffset, endOffset)
3152
3253 companion object {
3354 /**
@@ -45,6 +66,13 @@
4566 val startChar = selectionStart - document.getLineStartOffset(startLine)
4667 val endChar = selectionEnd - document.getLineStartOffset(endLine)
4768
69+ // Adjust end line if it's a single line selection with trailing newlines
70+ val adjustedEndLine = if (isSelectionWithTrailingNewline(document, selectionStart, selectionEnd)) {
71+ endLine - 1
72+ } else {
73+ endLine
74+ }
75+
4876 val selectedText = document.getText(
4977 TextRange(selectionStart, selectionEnd)
5078 )
@@ -53,10 +81,30 @@
5381 filepath,
5482 Range(
5583 Position(startLine, startChar),
56- Position(endLine, endChar)
84+ Position(adjustedEndLine, endChar)
5785 ),
58- selectedText
86+ selectedText,
87+ document
5988 )
6089 }
90+
91+ /**
92+ * Checks if the selection spans to the next line only because of trailing newlines.
93+ * This matters when a user double-clicks to highlight a full line.
94+ *
95+ * @return true if the selection is actually a single line selection with trailing newline
96+ */
97+ fun isSelectionWithTrailingNewline(
98+ document: Document,
99+ selectionStart: Int,
100+ selectionEnd: Int
101+ ): Boolean {
102+ val startLine = document.getLineNumber(selectionStart)
103+ val endLine = document.getLineNumber(selectionEnd)
104+
105+ return endLine > startLine &&
106+ endLine < document.lineCount &&
107+ document.getLineStartOffset(endLine) == selectionEnd
108+ }
61109 }
62110 }
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt +3 −2
@@ -166,7 +166,7 @@
166166 val rejectBtn =
167167 createButton(
168168 "${getAltKeyLabel()}${getShiftKeyLabel()}N",
169- JBColor(0x77FF0000, 0x77FF0000)
169+ JBColor(0xFF0000, 0xFF0000)
170170 ).apply {
171171 addActionListener {
172172 handleReject()
@@ -178,13 +178,14 @@
178178 createButton(
179179 "${getAltKeyLabel()}${
180180 getShiftKeyLabel()
181- }Y", JBColor(0x7700BB00, 0x7700BB00)
181+ }Y", JBColor(0x00BB00, 0x00BB00)
182182 ).apply {
183183 addActionListener {
184184 handleAccept()
185185 }
186186 }
187187
188+
188189 return Pair(acceptBtn, rejectBtn)
189190 }
190191
modified extensions/intellij/src/main/resources/META-INF/plugin.xml +2 −2
@@ -78,9 +78,9 @@
7878 class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction"
7979 text="Reject Diff" description="Reject Diff">
8080 <keyboard-shortcut keymap="$default"
81- first-keystroke="shift ctrl DELETE"/>
81+ first-keystroke="shift ctrl BACK_SPACE"/>
8282 <keyboard-shortcut keymap="Mac OS X"
83- first-keystroke="shift meta DELETE"/>
83+ first-keystroke="shift meta BACK_SPACE"/>
8484 <override-text place="GoToAction" text="Continue: Reject Diff"/>
8585 </action>
8686
modified manual-testing-sandbox/test.ts +2 −2
@@ -9,7 +9,7 @@
99 this.result += number;
1010 return this;
1111 }
12-
12+
1313 subtract(number: number): Calculator {
1414 this.result -= number;
1515 return this;
@@ -38,4 +38,4 @@
3838 }
3939 }
4040
41-export default Calculator;
No newline at the end of the file
41+export default Calculator;