Merge pull request #2471 from continuedev/nate/jetbrains-inline-diff-red

Red in JetBrains inline diff
This commit is contained in:
Nate Sesti 2024-10-04 18:00:00 -07:00 • committed by GitHub
commit 226381223a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 174 additions and 92 deletions

View file

@ -8,6 +8,7 @@ import { LineStream, matchLine } from "./util.js";
* - old + same = oldLinesCopy.length * - old + same = oldLinesCopy.length
* ^ (above two guarantee that all lines get represented) * ^ (above two guarantee that all lines get represented)
* - Lines are always output in order, at least among old and new separately * - Lines are always output in order, at least among old and new separately
* - Old lines in a hunk are always output before the new lines
*/ */
export async function* streamDiff( export async function* streamDiff(
oldLines: string[], oldLines: string[],

View file

@ -1,13 +1,15 @@
package com.github.continuedev.continueintellijextension.editor package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.editor.markup.HighlighterLayer import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.editor.markup.RangeHighlighter import com.intellij.openapi.editor.markup.RangeHighlighter
import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.editor.markup.TextAttributes
@ -16,7 +18,7 @@ import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.ui.JBColor import com.intellij.ui.JBColor
import java.awt.event.KeyEvent import javax.swing.BorderFactory
import javax.swing.JTextArea import javax.swing.JTextArea
import kotlin.math.min import kotlin.math.min
@ -26,14 +28,15 @@ enum class DiffLineType {
} }
class DiffStreamHandler( class DiffStreamHandler(
private val project: Project, private val project: Project,
private val editor: Editor, private val editor: Editor,
private val textArea: JTextArea, private val textArea: JTextArea,
private val startLine: Int, private val startLine: Int,
private val endLine: Int, private val endLine: Int,
private val onClose: () -> Unit, private val onClose: () -> Unit,
private val onFinish: () -> Unit private val onFinish: () -> Unit
) { ) {
// Text attributes keys
private val greenKey = run { private val greenKey = run {
val attributes = TextAttributes().apply { val attributes = TextAttributes().apply {
backgroundColor = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt()) backgroundColor = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt())
@ -61,64 +64,126 @@ class DiffStreamHandler(
key key
} }
private val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false)
// State variables
private var currentLine = startLine private var currentLine = startLine
private var currentLineHighlighter: RangeHighlighter? = null private var currentLineHighlighter: RangeHighlighter? = null
private val unfinishedHighlighters: MutableList<RangeHighlighter> = mutableListOf() private val unfinishedHighlighters: MutableList<RangeHighlighter> = mutableListOf()
private var changeCount: Int = 0 private var changeCount: Int = 0 // Kept track of so we can count steps to undo when cancelling
private var running: Boolean = false private var running: Boolean = false
private var deletionBufferStartLine: Int = -1
private val deletionsBuffer: MutableList<String> = mutableListOf()
private val deletionInlays: MutableList<Disposable> = mutableListOf()
private fun removeDeletionInlays() {
deletionInlays.forEach {
it.dispose()
}
deletionInlays.clear()
}
fun setup() { fun setup() {
// Highlight the range with unfinished color // Highlight the range with unfinished color
for (i in startLine..endLine) { for (i in startLine..endLine) {
val highlighter = editor.markupModel.addLineHighlighter(unfinishedKey, min( val highlighter = editor.markupModel.addLineHighlighter(
unfinishedKey, min(
i, editor.document.lineCount - 1 i, editor.document.lineCount - 1
), HighlighterLayer.FIRST) ), HighlighterLayer.LAST
)
unfinishedHighlighters.add(highlighter) unfinishedHighlighters.add(highlighter)
} }
} }
private fun deleteLineAt(index: Int) {
val startOffset = editor.document.getLineStartOffset(index)
val endOffset = editor.document.getLineEndOffset(index) + 1
editor.document.deleteString(startOffset, min(endOffset, editor.document.textLength))
}
private fun insertDeletionBuffer() {
// Insert red highlighted code between the real lines in the editor
if (deletionBufferStartLine != -1 && deletionsBuffer.isNotEmpty()) {
val component = JTextArea().apply {
text = deletionsBuffer.joinToString("\n")
isEditable = false
background = JBColor(0x30FF0000.toInt(), 0x30FF0000.toInt())
foreground = JBColor.GRAY
border = BorderFactory.createEmptyBorder(0, 0, 0, 0)
lineWrap = false
wrapStyleWord = false
font = editor.colorsScheme.getFont(EditorFontType.PLAIN)
}
val disposable = editorComponentInlaysManager.insert(deletionBufferStartLine, component, true)
if (disposable != null) {
deletionInlays.add(disposable)
}
// Clear the buffer
deletionsBuffer.clear()
deletionBufferStartLine = -1
}
}
private fun handleDiffLine(type: DiffLineType, line: String) { private fun handleDiffLine(type: DiffLineType, line: String) {
println("DiffStreamHandler: handleDiffLine: $currentLine, $type, $line") println("DiffStreamHandler: handleDiffLine: $currentLine, $type, $line")
try { try {
when (type) { when (type) {
DiffLineType.SAME -> { DiffLineType.SAME -> {
currentLine++ insertDeletionBuffer()
} currentLine++
DiffLineType.NEW -> {
// Insert new line
if (currentLine == editor.document.lineCount) {
editor.document.insertString(editor.document.textLength, "\n")
} }
val offset = editor.document.getLineStartOffset(currentLine)
editor.document.insertString(offset, line + "\n")
// Highlight the new line green DiffLineType.NEW -> {
editor.markupModel.addLineHighlighter(greenKey, currentLine, HighlighterLayer.LAST) // Insert new line
if (currentLine == editor.document.lineCount) {
editor.document.insertString(editor.document.textLength, "\n")
}
val offset = editor.document.getLineStartOffset(currentLine)
editor.document.insertString(offset, line + "\n")
currentLine++ // Highlight the new line green
changeCount++ editor.markupModel.addLineHighlighter(greenKey, currentLine, HighlighterLayer.LAST)
insertDeletionBuffer()
currentLine++
changeCount++
}
DiffLineType.OLD -> {
// Remove old line
deleteLineAt(currentLine)
// Add to deletions buffer
deletionsBuffer.add(line)
if (deletionBufferStartLine == -1) {
deletionBufferStartLine = currentLine
}
changeCount++
}
} }
DiffLineType.OLD -> {
// Remove old line
val startOffset = editor.document.getLineStartOffset(currentLine)
val endOffset = editor.document.getLineEndOffset(currentLine) + 1
editor.document.deleteString(startOffset, min(endOffset, editor.document.textLength))
changeCount++
}
}
// Highlight the current line // Highlight the current line
if (currentLineHighlighter != null) { if (currentLineHighlighter != null) {
editor.markupModel.removeHighlighter(currentLineHighlighter!!) editor.markupModel.removeHighlighter(currentLineHighlighter!!)
} }
currentLineHighlighter = editor.markupModel.addLineHighlighter(currentLineKey, min(currentLine, editor.document.lineCount - 1), HighlighterLayer.LAST) currentLineHighlighter = editor.markupModel.addLineHighlighter(
currentLineKey,
// Remove the unfinished highlighter top line min(currentLine, editor.document.lineCount - 1),
if (type != DiffLineType.OLD) { HighlighterLayer.LAST
if (unfinishedHighlighters.isNotEmpty()) { )
editor.markupModel.removeHighlighter(unfinishedHighlighters.removeAt(0))
// Remove the unfinished highlighter top line
if (type != DiffLineType.OLD) {
if (unfinishedHighlighters.isNotEmpty()) {
editor.markupModel.removeHighlighter(unfinishedHighlighters.removeAt(0))
}
} }
}
} catch (e: Exception) { } catch (e: Exception) {
println("Error handling diff line: $currentLine, $type, $line, $e.message") println("Error handling diff line: $currentLine, $type, $line, $e.message")
} }
@ -128,6 +193,9 @@ class DiffStreamHandler(
// Remove all highlighters // Remove all highlighters
editor.markupModel.removeAllHighlighters() editor.markupModel.removeAllHighlighters()
// Remove all of the deletion inlays
removeDeletionInlays()
// Undo changes just by using builtin undo // Undo changes just by using builtin undo
WriteCommandAction.runWriteCommandAction(project) { WriteCommandAction.runWriteCommandAction(project) {
val undoManager = UndoManager.getInstance(project) val undoManager = UndoManager.getInstance(project)
@ -148,6 +216,7 @@ class DiffStreamHandler(
fun accept() { fun accept() {
// Accept the changes // Accept the changes
editor.markupModel.removeAllHighlighters() editor.markupModel.removeAllHighlighters()
removeDeletionInlays()
onClose() onClose()
running = false running = false
} }
@ -155,6 +224,7 @@ class DiffStreamHandler(
fun reject() { fun reject() {
// Reject the changes // Reject the changes
resetState() resetState()
removeDeletionInlays()
onClose() onClose()
running = false running = false
} }
@ -168,34 +238,31 @@ class DiffStreamHandler(
} }
} }
fun run(input : String, prefix : String, highlighted : String, suffix : String, modelTitle : String) { fun run(input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String) {
// Undo changes // Undo changes
resetState() resetState()
running = true running = true
// Highlight the range with unfinished color // Highlight the range with unfinished color
for (i in startLine..endLine) { setup()
val highlighter = editor.markupModel.addLineHighlighter(unfinishedKey, min(
i, editor.document.lineCount - 1
), HighlighterLayer.FIRST)
unfinishedHighlighters.add(highlighter)
}
// Request diff stream from core // Request diff stream from core
val continuePluginService = ServiceManager.getService( val continuePluginService = ServiceManager.getService(
this.project, this.project,
ContinuePluginService::class.java ContinuePluginService::class.java
) )
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
continuePluginService.coreMessenger?.request("streamDiffLines", mapOf( continuePluginService.coreMessenger?.request(
"streamDiffLines", mapOf(
"input" to input, "input" to input,
"prefix" to prefix, "prefix" to prefix,
"highlighted" to highlighted, "highlighted" to highlighted,
"suffix" to suffix, "suffix" to suffix,
"language" to virtualFile?.fileType?.name, "language" to virtualFile?.fileType?.name,
"modelTitle" to modelTitle "modelTitle" to modelTitle
), null) { response -> ), null
) { response ->
if (!running) { if (!running) {
return@request return@request
} }
@ -206,12 +273,15 @@ class DiffStreamHandler(
onFinish() onFinish()
ApplicationManager.getApplication().invokeLater { ApplicationManager.getApplication().invokeLater {
// Clean up highlighters // Clean up progress highlighters
if (currentLineHighlighter != null) { if (currentLineHighlighter != null) {
editor.markupModel.removeHighlighter(currentLineHighlighter!!) editor.markupModel.removeHighlighter(currentLineHighlighter!!)
} }
unfinishedHighlighters.forEach { editor.markupModel.removeHighlighter(it) } unfinishedHighlighters.forEach { editor.markupModel.removeHighlighter(it) }
// Flush deletion buffer
insertDeletionBuffer()
// Add ", " to the text area // Add ", " to the text area
textArea.document.insertString(textArea.caretPosition, ", ", null) textArea.document.insertString(textArea.caretPosition, ", ", null)
textArea.requestFocus() textArea.requestFocus()

View file

@ -14,8 +14,10 @@ import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.JBUI import com.intellij.util.ui.JBUI
import java.awt.Dimension import java.awt.Dimension
import java.awt.Font import java.awt.Font
import java.awt.Insets
import java.awt.event.ComponentAdapter import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent import java.awt.event.ComponentEvent
import javax.swing.BorderFactory
import javax.swing.JComponent import javax.swing.JComponent
import javax.swing.ScrollPaneConstants import javax.swing.ScrollPaneConstants
import kotlin.math.ceil import kotlin.math.ceil
@ -26,7 +28,7 @@ import kotlin.math.min
* Copied from com.intellij.util.ui.codereview.diff.EditorComponentInlaysManager * Copied from com.intellij.util.ui.codereview.diff.EditorComponentInlaysManager
* via https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/EditorComponentInlaysManager.kt * via https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/EditorComponentInlaysManager.kt
*/ */
class EditorComponentInlaysManager(val editor: EditorImpl) : Disposable { class EditorComponentInlaysManager(val editor: EditorImpl, private val onlyOneInlay: Boolean) : Disposable {
private val managedInlays = mutableMapOf<ComponentWrapper, Disposable>() private val managedInlays = mutableMapOf<ComponentWrapper, Disposable>()
private val editorWidthWatcher = EditorTextWidthWatcher() private val editorWidthWatcher = EditorTextWidthWatcher()
@ -41,26 +43,32 @@ class EditorComponentInlaysManager(val editor: EditorImpl) : Disposable {
} }
@RequiresEdt @RequiresEdt
fun insertAfter(lineIndex: Int, component: JComponent): Disposable? { fun insert(lineIndex: Int, component: JComponent, showAbove: Boolean = false): Disposable? {
if (Disposer.isDisposed(this)) return null if (Disposer.isDisposed(this)) return null
// Dispose all other inlays if (onlyOneInlay) {
managedInlays.values.forEach(Disposer::dispose) // Dispose all other inlays
managedInlays.values.forEach(Disposer::dispose)
}
val wrappedComponent = ComponentWrapper(component) val wrappedComponent = ComponentWrapper(component)
val offset = editor.document.getLineEndOffset(lineIndex) val offset = editor.document.getLineEndOffset(lineIndex)
return EditorEmbeddedComponentManager.getInstance() return EditorEmbeddedComponentManager.getInstance()
.addComponent(editor, wrappedComponent, .addComponent(
EditorEmbeddedComponentManager.Properties(EditorEmbeddedComponentManager.ResizePolicy.none(), editor, wrappedComponent,
null, EditorEmbeddedComponentManager.Properties(
true, EditorEmbeddedComponentManager.ResizePolicy.none(),
false, null,
0, true,
offset))?.also { showAbove,
managedInlays[wrappedComponent] = it 0,
Disposer.register(it, Disposable { managedInlays.remove(wrappedComponent) }) offset
} )
)?.also {
managedInlays[wrappedComponent] = it
Disposer.register(it, Disposable { managedInlays.remove(wrappedComponent) })
}
} }
private inner class ComponentWrapper(private val component: JComponent) : JBScrollPane(component) { private inner class ComponentWrapper(private val component: JComponent) : JBScrollPane(component) {
@ -77,12 +85,12 @@ class EditorComponentInlaysManager(val editor: EditorImpl) : Disposable {
component.addComponentListener(object : ComponentAdapter() { component.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent) = override fun componentResized(e: ComponentEvent) =
dispatchEvent(ComponentEvent(component, ComponentEvent.COMPONENT_RESIZED)) dispatchEvent(ComponentEvent(component, ComponentEvent.COMPONENT_RESIZED))
}) })
} }
override fun getPreferredSize(): Dimension { override fun getPreferredSize(): Dimension {
return Dimension(editorWidthWatcher.editorTextWidth, component.preferredSize.height) return Dimension(editor.contentComponent.width, component.preferredSize.height)
} }
} }
@ -105,7 +113,7 @@ class EditorComponentInlaysManager(val editor: EditorImpl) : Disposable {
val scrollbarFlip = editor.scrollPane.getClientProperty(JBScrollPane.Flip::class.java) val scrollbarFlip = editor.scrollPane.getClientProperty(JBScrollPane.Flip::class.java)
verticalScrollbarFlipped = verticalScrollbarFlipped =
scrollbarFlip == JBScrollPane.Flip.HORIZONTAL || scrollbarFlip == JBScrollPane.Flip.BOTH scrollbarFlip == JBScrollPane.Flip.HORIZONTAL || scrollbarFlip == JBScrollPane.Flip.BOTH
} }
override fun componentResized(e: ComponentEvent) = updateWidthForAllInlays() override fun componentResized(e: ComponentEvent) = updateWidthForAllInlays()
@ -124,7 +132,8 @@ class EditorComponentInlaysManager(val editor: EditorImpl) : Disposable {
} }
private fun calcWidth(): Int { private fun calcWidth(): Int {
val visibleEditorTextWidth = editor.scrollPane.viewport.width - getVerticalScrollbarWidth() - getGutterTextGap() val visibleEditorTextWidth =
editor.scrollPane.viewport.width - getVerticalScrollbarWidth() - getGutterTextGap()
return min(max(visibleEditorTextWidth, 0), maximumEditorTextWidth) return min(max(visibleEditorTextWidth, 0), maximumEditorTextWidth)
} }
@ -144,11 +153,11 @@ class EditorComponentInlaysManager(val editor: EditorImpl) : Disposable {
companion object { companion object {
val INLAYS_KEY: Key<EditorComponentInlaysManager> = Key.create("EditorComponentInlaysManager") val INLAYS_KEY: Key<EditorComponentInlaysManager> = Key.create("EditorComponentInlaysManager")
fun from(editor: Editor): EditorComponentInlaysManager { fun from(editor: Editor, onlyOneInlay: Boolean): EditorComponentInlaysManager {
return synchronized(editor) { return synchronized(editor) {
val manager = editor.getUserData(INLAYS_KEY) val manager = editor.getUserData(INLAYS_KEY)
if (manager == null) { if (manager == null) {
val newManager = EditorComponentInlaysManager(editor as EditorImpl) val newManager = EditorComponentInlaysManager(editor as EditorImpl, false)
editor.putUserData(INLAYS_KEY, newManager) editor.putUserData(INLAYS_KEY, newManager)
newManager newManager
} else manager } else manager

View file

@ -115,7 +115,7 @@ fun openInlineEdit(project: Project?, editor: Editor) {
return return
} }
val manager = EditorComponentInlaysManager.from(editor) val manager = EditorComponentInlaysManager.from(editor, true)
// Get list of model titles // Get list of model titles
val continuePluginService = project.service<ContinuePluginService>() val continuePluginService = project.service<ContinuePluginService>()
@ -183,18 +183,18 @@ fun openInlineEdit(project: Project?, editor: Editor) {
diffStreamHandler.run(textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret) diffStreamHandler.run(textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret)
} }
val panel = val panel = makePanel(project, customPanelRef, textArea, inlayRef, comboBoxRef, leftInset, modelTitles, {onEnter()}, {
makePanel(project, customPanelRef, textArea, inlayRef, comboBoxRef, leftInset, modelTitles, { onEnter() }, { diffStreamService.reject(editor)
diffStreamService.reject(editor) selectionModel.setSelection(start, end)
selectionModel.setSelection(start, end) }, {
}, { diffStreamService.accept(editor)
diffStreamService.accept(editor) inlayRef.get().dispose()
inlayRef.get().dispose() }, {
}, { diffStreamService.reject(editor)
diffStreamService.reject(editor) inlayRef.get().dispose()
inlayRef.get().dispose() })
}) val inlay = manager.insert(startLineNum, panel, true)
val inlay = manager.insertAfter(lineNumber, panel)
panel.revalidate() panel.revalidate()
inlayRef.set(inlay) inlayRef.set(inlay)
val viewport = (editor as? EditorImpl)?.scrollPane?.viewport val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
@ -362,8 +362,10 @@ class CustomPanel(
horizontalAlignment = SwingConstants.LEFT horizontalAlignment = SwingConstants.LEFT
} }
selectedIndex = continueSettingsService.continueState.lastSelectedInlineEditModel?.let { selectedIndex = continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
val index = modelTitles.indexOf(it) if (modelTitles.isEmpty()) -1 else {
if (index != -1) index else 0 val index = modelTitles.indexOf(it)
if (index != -1) index else 0
}
} ?: 0 } ?: 0
addActionListener { addActionListener {