Skip to content

Commit

Permalink
fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
acharneski committed Dec 6, 2023
1 parent 025ea09 commit b6f07f2
Show file tree
Hide file tree
Showing 35 changed files with 2,530 additions and 2,396 deletions.
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@

## [Unreleased]

## [1.2.23]

### Improved

- Fixed Kotlin dynamic evaluation
- Replaced all Groovy with Kotlin
- Revised configuration UI
- Various fixes

## [1.2.22]

### Improved
Expand Down
5 changes: 4 additions & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,15 @@ dependencies {
implementation(group = "org.eclipse.jetty.websocket", name = "websocket-servlet", version = jetty_version)

implementation(group = "org.slf4j", name = "slf4j-api", version = slf4j_version)
testImplementation(group = "org.slf4j", name = "slf4j-simple", version = slf4j_version)

testImplementation(group = "org.slf4j", name = "slf4j-simple", version = slf4j_version)
testImplementation(group = "com.intellij.remoterobot", name = "remote-robot", version = "0.11.16")
testImplementation(group = "com.intellij.remoterobot", name = "remote-fixtures", version = "0.11.16")
testImplementation(group = "com.squareup.okhttp3", name = "okhttp", version = "3.14.9")

testImplementation(group = "org.junit.jupiter", name = "junit-jupiter-api", version = "5.10.1")
testRuntimeOnly(group = "org.junit.jupiter", name = "junit-jupiter-engine", version = "5.10.1")


}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,10 @@ abstract class SelectionAction<T : Any>(
var selectedText = primaryCaret.selectedText
val editorState = editorState(editor)
val (start, end) = retarget(editorState, selectedText, selectionStart, selectionEnd) ?: return
selectedText = editorState.text.substring(start, end)
selectionEnd = end
selectionStart = start
val text = editorState.text
selectedText = text.substring(start.coerceIn(0, text.length), end.coerceIn(0, text.length))
selectionEnd = end.coerceIn(0, text.length)
selectionStart = start.coerceIn(0, text.length)

UITools.redoableTask(e) {
val document = e.getData(CommonDataKeys.EDITOR)?.document
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import com.simiacryptus.jopenai.proxy.ChatProxy
import java.awt.Toolkit
import java.awt.datatransfer.DataFlavor

class PasteAction : SelectionAction<String>(false) {
open class PasteAction : SelectionAction<String>(false) {

interface VirtualAPI {
fun convert(text: String, from_language: String, to_language: String): ConvertedText
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.simiacryptus.jopenai.proxy.ChatProxy

class RenameVariablesAction : SelectionAction<String>() {
open class RenameVariablesAction : SelectionAction<String>() {

interface RenameAPI {
fun suggestRenames(
Expand Down Expand Up @@ -64,7 +64,7 @@ class RenameVariablesAction : SelectionAction<String>() {
}
}

private fun choose(renameSuggestions: Map<String, String>): Set<String> {
open fun choose(renameSuggestions: Map<String, String>): Set<String> {
return UITools.showCheckboxDialog(
"Select which items to rename",
renameSuggestions.keys.toTypedArray(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
import com.github.simiacryptus.aicoder.actions.SelectionAction
import com.github.simiacryptus.aicoder.config.AppSettingsState
import com.intellij.openapi.project.Project
import com.simiacryptus.jopenai.ApiModel.ChatMessage
import com.simiacryptus.jopenai.ApiModel.Role
import com.simiacryptus.jopenai.ApiModel.*
import com.simiacryptus.jopenai.ClientUtil.toContentList

class AppendAction : SelectionAction<String>() {
Expand All @@ -13,17 +12,20 @@ import com.simiacryptus.jopenai.ClientUtil.toContentList
}

override fun processSelection(state: SelectionState, config: String?): String {
val settings = AppSettingsState.instance
val request = settings.createChatRequest().copy(
temperature = settings.temperature,
messages = listOf(
ChatMessage(Role.system, "Append text to the end of the user's prompt".toContentList(), null),
ChatMessage(Role.user, state.selectedText.toString().toContentList(), null)
),
)
val chatResponse = api.chat(request, settings.defaultChatModel())
val b4 = state.selectedText ?: ""
val str = chatResponse.choices[0].message?.content ?: ""
return b4 + if (str.startsWith(b4)) str.substring(b4.length) else str
val settings = AppSettingsState.instance
val request = ChatRequest(
model = settings.defaultChatModel().modelName,
temperature = settings.temperature
).copy(
temperature = settings.temperature,
messages = listOf(
ChatMessage(Role.system, "Append text to the end of the user's prompt".toContentList(), null),
ChatMessage(Role.user, state.selectedText.toString().toContentList(), null)
),
)
val chatResponse = api.chat(request, settings.defaultChatModel())
val b4 = state.selectedText ?: ""
val str = chatResponse.choices[0].message?.content ?: ""
return b4 + if (str.startsWith(b4)) str.substring(b4.length) else str
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import kotlin.math.ceil
import kotlin.math.ln
import kotlin.math.pow

class ReplaceOptionsAction : SelectionAction<String>() {
open class ReplaceOptionsAction : SelectionAction<String>() {
interface VirtualAPI {
fun suggestText(template: String, examples: List<String>): Suggestions

Expand Down Expand Up @@ -52,7 +52,7 @@ class ReplaceOptionsAction : SelectionAction<String>() {
return choose(choices ?: listOf())
}

private fun choose(choices: List<String>): String {
open fun choose(choices: List<String>): String {
return UITools.showRadioButtonDialog("Select an option to fill in the blank:", *choices.toTypedArray())?.toString() ?: ""
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class MarkdownImplementActionGroup : ActionGroup() {
return actions.toTypedArray()
}

class MarkdownImplementAction(private val language: String) : SelectionAction<String>(true) {
open class MarkdownImplementAction(private val language: String) : SelectionAction<String>(true) {
init {
templatePresentation.text = language
templatePresentation.description = language
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,44 @@ import java.util.stream.Collectors
class ActionSettingsRegistry {

val actionSettings: MutableMap<String, ActionSettings> = HashMap()
private val version = 2.0005
private val version = 2.0006

fun edit(superChildren: Array<out AnAction>): Array<AnAction> {
val children = superChildren.toList().toMutableList()
children.toTypedArray().forEach {
children.toTypedArray().forEach { action ->
val language = "kt"
val code: String? = load(it.javaClass, language)
val code: String? = load(action.javaClass, language)
if (null != code) {
try {
val actionConfig = this.getActionConfig(it)
val actionConfig = this.getActionConfig(action)
actionConfig.language = language
actionConfig.isDynamic = false
with(it) {
with(action) {
templatePresentation.text = actionConfig.displayText
templatePresentation.description = actionConfig.displayText
}
if (!actionConfig.enabled) {
children.remove(it)
children.remove(action)
} else if (!actionConfig.file.exists()
|| actionConfig.file.readText().isBlank()
|| (actionConfig.version ?: 0.0) < version
) {
actionConfig.file.writeText(code)
actionConfig.version = version
} else if (!(actionConfig.isDynamic || (actionConfig.version ?: 0.0) >= version)) {
} else {
if (actionConfig.isDynamic || (actionConfig.version ?: 0.0) >= version) {
val localCode = actionConfig.file.readText().dropWhile { !it.isLetter() }
if (!localCode.equals(code)) {
try {
val element = actionConfig.buildAction(localCode)
children.remove(action)
children.add(element)
return@forEach
} catch (e: Throwable) {
log.info("Error loading dynamic ${action.javaClass}", e)
}
}
}
val canLoad = try {
ActionSettingsRegistry::class.java.classLoader.loadClass(actionConfig.id)
true
Expand All @@ -46,19 +59,12 @@ class ActionSettingsRegistry {
actionConfig.file.writeText(code)
actionConfig.version = version
} else {
children.remove(it)
}
} else {
val localCode = actionConfig.file.readText().drop(1)
if (!localCode.equals(code)) {
val element = actionConfig.buildAction(localCode)
children.remove(it)
children.add(element)
children.remove(action)
}
}
actionConfig.version = version
} catch (e: Throwable) {
UITools.error(log, "Error loading ${it.javaClass}", e)
UITools.error(log, "Error loading ${action.javaClass}", e)
}
}
}
Expand Down Expand Up @@ -193,7 +199,7 @@ class ActionSettingsRegistry {

private fun load(path: String): String? {
val bytes = EditorMenu::class.java.getResourceAsStream(path)?.readAllBytes()
return bytes?.toString(Charsets.UTF_8)?.drop(1) // XXX Why? '\uFEFF' is first byte
return bytes?.toString(Charsets.UTF_8)?.dropWhile { !it.isLetter() }
}

fun load(clazz: Class<AnAction>, language: String) =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.ui.BooleanTableCellEditor
Expand Down Expand Up @@ -155,14 +156,17 @@ class ActionTable(
override fun actionPerformed(e: ActionEvent?) {
val id = dataModel.getValueAt(jtable.selectedRow, 2)
val actionSetting = actionSettings.find { it.id == id }
val projectManager = ProjectManager.getInstance()
actionSetting?.file?.let {
val project = ApplicationManager.getApplication().runReadAction<Project> {
com.intellij.openapi.project.ProjectManager.getInstance().openProjects.firstOrNull()
projectManager.openProjects.firstOrNull() ?: projectManager.defaultProject
}

if (it.exists()) {
ApplicationManager.getApplication().invokeLater {
val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(it)
FileEditorManager.getInstance(project!!).openFile(virtualFile!!, true)
val fileEditorManager = FileEditorManager.getInstance(project!!)
val editor = fileEditorManager.openFile(virtualFile!!, true).firstOrNull()
}
} else {
log.warn("File not found: ${it.absolutePath}")
Expand Down Expand Up @@ -207,6 +211,17 @@ class ActionTable(
jtable.columnModel.getColumn(1).headerRenderer = DefaultTableCellRenderer()
jtable.columnModel.getColumn(2).headerRenderer = DefaultTableCellRenderer()

// Set the preferred width for the first column (checkboxes) to the header label width
val headerRenderer = jtable.tableHeader.defaultRenderer
val headerValue = jtable.columnModel.getColumn(0).headerValue
val headerComp = headerRenderer.getTableCellRendererComponent(jtable, headerValue, false, false, 0, 0)
jtable.columnModel.getColumn(0).preferredWidth = headerComp.preferredSize.width

// Set the minimum width for the second column (display text) to accommodate 100 characters
val metrics = jtable.getFontMetrics(jtable.font)
val minWidth = metrics.charWidth('m') * 32
jtable.columnModel.getColumn(1).minWidth = minWidth

jtable.tableHeader.defaultRenderer = DefaultTableCellRenderer()

add(scrollpane, BorderLayout.CENTER)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,34 +1,31 @@
@file:Suppress("unused")

package com.github.simiacryptus.aicoder.config

import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBPasswordField
import com.intellij.ui.components.JBTextField
import com.simiacryptus.jopenai.ClientUtil
import com.simiacryptus.jopenai.models.ChatModels

import org.slf4j.LoggerFactory
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.JButton
import javax.swing.JComponent

class AppSettingsComponent {
class AppSettingsComponent : com.intellij.openapi.Disposable {

@Name("Token Counter")
val tokenCounter = JBTextField()

@Suppress("unused")
val clearCounter = JButton(object : AbstractAction("Clear Token Counter") {
override fun actionPerformed(e: ActionEvent) {
tokenCounter.text = "0"
}
override fun actionPerformed(e: ActionEvent) {
tokenCounter.text = "0"
}
})

@Suppress("unused")
Expand Down Expand Up @@ -57,21 +54,21 @@ class AppSettingsComponent {

@Suppress("unused")
val openApiLog = JButton(object : AbstractAction("Open API Log") {
override fun actionPerformed(e: ActionEvent) {
ClientUtil.auxiliaryLog?.let {
val project = ApplicationManager.getApplication().runReadAction<Project> {
com.intellij.openapi.project.ProjectManager.getInstance().openProjects.firstOrNull()
}
if (it.exists()) {
ApplicationManager.getApplication().invokeLater {
val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(it)
FileEditorManager.getInstance(project!!).openFile(virtualFile!!, true)
}
} else {
log.warn("Log file not found: ${it.absolutePath}")
}
override fun actionPerformed(e: ActionEvent) {
ClientUtil.auxiliaryLog?.let {
val project = ApplicationManager.getApplication().runReadAction<Project> {
ProjectManager.getInstance().openProjects.firstOrNull()
}
if (it.exists()) {
ApplicationManager.getApplication().invokeLater {
val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(it)
FileEditorManager.getInstance(project!!).openFile(virtualFile!!, true)
}
} else {
log.warn("Log file not found: ${it.absolutePath}")
}
}
}
})


Expand All @@ -96,11 +93,11 @@ class AppSettingsComponent {

@Name("File Actions")
var fileActions = ActionTable(AppSettingsState.instance.fileActions.actionSettings.values.map { it.copy() }
.toTypedArray().toMutableList())
.toTypedArray().toMutableList())

@Name("Editor Actions")
var editorActions = ActionTable(AppSettingsState.instance.editorActions.actionSettings.values.map { it.copy() }
.toTypedArray().toMutableList())
.toTypedArray().toMutableList())

init {
tokenCounter.isEditable = false
Expand All @@ -109,16 +106,10 @@ class AppSettingsComponent {
this.modelName.addItem(ChatModels.GPT4Turbo.modelName)
}

val preferredFocusedComponent: JComponent
get() = apiKey

class ActionChangedListener {
fun actionChanged() {
}
}

companion object {
companion object {
private val log = LoggerFactory.getLogger(AppSettingsComponent::class.java)
//val ACTIONS_TOPIC = Topic.create("Actions", ActionChangedListener::class.java)
}
}

override fun dispose() {
}
}
Loading

0 comments on commit b6f07f2

Please sign in to comment.