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
* ^ (above two guarantee that all lines get represented)
* - 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(
oldLines: string[],

View file

@ -1,13 +1,15 @@
package com.github.continuedev.continueintellijextension.editor
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.command.WriteCommandAction
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.components.ServiceManager
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.markup.EffectType
import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.editor.markup.RangeHighlighter
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.project.Project
import com.intellij.ui.JBColor
import java.awt.event.KeyEvent
import javax.swing.BorderFactory
import javax.swing.JTextArea
import kotlin.math.min
@ -26,14 +28,15 @@ enum class DiffLineType {
}
class DiffStreamHandler(
private val project: Project,
private val editor: Editor,
private val textArea: JTextArea,
private val startLine: Int,
private val endLine: Int,
private val onClose: () -> Unit,
private val onFinish: () -> Unit
private val project: Project,
private val editor: Editor,
private val textArea: JTextArea,
private val startLine: Int,
private val endLine: Int,
private val onClose: () -> Unit,
private val onFinish: () -> Unit
) {
// Text attributes keys
private val greenKey = run {
val attributes = TextAttributes().apply {
backgroundColor = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt())
@ -61,64 +64,126 @@ class DiffStreamHandler(
key
}
private val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false)
// State variables
private var currentLine = startLine
private var currentLineHighlighter: RangeHighlighter? = null
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 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() {
// Highlight the range with unfinished color
for (i in startLine..endLine) {
val highlighter = editor.markupModel.addLineHighlighter(unfinishedKey, min(
val highlighter = editor.markupModel.addLineHighlighter(
unfinishedKey, min(
i, editor.document.lineCount - 1
), HighlighterLayer.FIRST)
), HighlighterLayer.LAST
)
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) {
println("DiffStreamHandler: handleDiffLine: $currentLine, $type, $line")
try {
when (type) {
DiffLineType.SAME -> {
currentLine++
}
DiffLineType.NEW -> {
// Insert new line
if (currentLine == editor.document.lineCount) {
editor.document.insertString(editor.document.textLength, "\n")
when (type) {
DiffLineType.SAME -> {
insertDeletionBuffer()
currentLine++
}
val offset = editor.document.getLineStartOffset(currentLine)
editor.document.insertString(offset, line + "\n")
// Highlight the new line green
editor.markupModel.addLineHighlighter(greenKey, currentLine, HighlighterLayer.LAST)
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")
currentLine++
changeCount++
// Highlight the new line green
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
if (currentLineHighlighter != null) {
editor.markupModel.removeHighlighter(currentLineHighlighter!!)
}
currentLineHighlighter = editor.markupModel.addLineHighlighter(currentLineKey, min(currentLine, editor.document.lineCount - 1), HighlighterLayer.LAST)
// Remove the unfinished highlighter top line
if (type != DiffLineType.OLD) {
if (unfinishedHighlighters.isNotEmpty()) {
editor.markupModel.removeHighlighter(unfinishedHighlighters.removeAt(0))
// Highlight the current line
if (currentLineHighlighter != null) {
editor.markupModel.removeHighlighter(currentLineHighlighter!!)
}
currentLineHighlighter = editor.markupModel.addLineHighlighter(
currentLineKey,
min(currentLine, editor.document.lineCount - 1),
HighlighterLayer.LAST
)
// Remove the unfinished highlighter top line
if (type != DiffLineType.OLD) {
if (unfinishedHighlighters.isNotEmpty()) {
editor.markupModel.removeHighlighter(unfinishedHighlighters.removeAt(0))
}
}
}
} catch (e: Exception) {
println("Error handling diff line: $currentLine, $type, $line, $e.message")
}
@ -128,6 +193,9 @@ class DiffStreamHandler(
// Remove all highlighters
editor.markupModel.removeAllHighlighters()
// Remove all of the deletion inlays
removeDeletionInlays()
// Undo changes just by using builtin undo
WriteCommandAction.runWriteCommandAction(project) {
val undoManager = UndoManager.getInstance(project)
@ -148,6 +216,7 @@ class DiffStreamHandler(
fun accept() {
// Accept the changes
editor.markupModel.removeAllHighlighters()
removeDeletionInlays()
onClose()
running = false
}
@ -155,6 +224,7 @@ class DiffStreamHandler(
fun reject() {
// Reject the changes
resetState()
removeDeletionInlays()
onClose()
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
resetState()
running = true
// Highlight the range with unfinished color
for (i in startLine..endLine) {
val highlighter = editor.markupModel.addLineHighlighter(unfinishedKey, min(
i, editor.document.lineCount - 1
), HighlighterLayer.FIRST)
unfinishedHighlighters.add(highlighter)
}
setup()
// Request diff stream from core
val continuePluginService = ServiceManager.getService(
this.project,
ContinuePluginService::class.java
this.project,
ContinuePluginService::class.java
)
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
continuePluginService.coreMessenger?.request("streamDiffLines", mapOf(
continuePluginService.coreMessenger?.request(
"streamDiffLines", mapOf(
"input" to input,
"prefix" to prefix,
"highlighted" to highlighted,
"suffix" to suffix,
"language" to virtualFile?.fileType?.name,
"modelTitle" to modelTitle
), null) { response ->
), null
) { response ->
if (!running) {
return@request
}
@ -206,12 +273,15 @@ class DiffStreamHandler(
onFinish()
ApplicationManager.getApplication().invokeLater {
// Clean up highlighters
// Clean up progress highlighters
if (currentLineHighlighter != null) {
editor.markupModel.removeHighlighter(currentLineHighlighter!!)
}
unfinishedHighlighters.forEach { editor.markupModel.removeHighlighter(it) }
// Flush deletion buffer
insertDeletionBuffer()
// Add ", " to the text area
textArea.document.insertString(textArea.caretPosition, ", ", null)
textArea.requestFocus()

View file

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

View file

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