Merge pull request #2609 from continuedev/pe/jb-esbuild-bugfix

bugfix(jb): remove permission set on esbuild binary
This commit is contained in:
Patrick Erichsen 2024-10-21 17:31:09 -07:00 • committed by GitHub
commit c42248f868
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 446 additions and 381 deletions

View file

@ -320,7 +320,6 @@ jobs:
chmod +x continue-binary
chmod +x build/Release/node_sqlite3.node
chmod +x index.node
chmod +x esbuild
if: ${{ matrix.platform }} != 'win32'
# Run tests for binary

View file

@ -11,6 +11,9 @@
<option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
<option name="SPACES_WITHIN_IMPORTS" value="true" />
</JSCodeStyleSettings>
<JetCodeStyleSettings>
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</JetCodeStyleSettings>
<TypeScriptCodeStyleSettings version="0">
<option name="FORCE_SEMICOLON_STYLE" value="true" />
<option name="SPACE_BEFORE_FUNCTION_LEFT_PARENTH" value="false" />
@ -53,5 +56,8 @@
<option name="CONTINUATION_INDENT_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="kotlin">
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</codeStyleSettings>
</code_scheme>
</component>

6
.idea/ktfmt.xml generated
View file

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KtfmtSettings">
<option name="enableKtfmt" value="Enabled" />
</component>
</project>

View file

@ -14,8 +14,6 @@
}
},
"search.exclude": {
"**/binary": true,
"binary/": false,
"**/core/vendor/**": true,
"**/gui/dist": true,
"**/extensions/vscode/gui/**": true,

View file

@ -674,7 +674,7 @@ function readConfigJs(): string | undefined {
return fs.readFileSync(configJsPath, "utf8");
}
async function buildConfigTs(ide: IDE, ideType: IdeType) {
async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) {
const configTsPath = getConfigTsPath();
if (!fs.existsSync(configTsPath)) {
@ -724,7 +724,7 @@ async function loadFullConfigNode(
let intermediate = await serializedToIntermediateConfig(serialized, ide);
// Apply config.ts to modify intermediate config
const configJsContents = await buildConfigTs(ide, ideType);
const configJsContents = await buildConfigTsandReadConfigJs(ide, ideType);
if (configJsContents) {
try {
// Try config.ts first

View file

@ -70,6 +70,7 @@ export const DEFAULT_IGNORE_FILETYPES = [
"*.bin",
"*.pag",
"*.swp",
"*.jsonl",
// "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
];

View file

@ -1,7 +1,8 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Continue" type="CompoundRunConfigurationType">
<toRun name="Run Extension" type="GradleRunConfiguration" />
<toRun name="GUI: Start dev server" type="js.build_tools.npm" />
<toRun name="GUI: Start Dev Server" type="js.build_tools.npm" />
<toRun name="Tail Dev Logs" type="ShConfigurationType" />
<method v="2" />
</configuration>
</component>
</component>

View file

@ -0,0 +1,17 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Tail Dev Logs" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="tail -f ./binary/.continue/logs/core.log" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="/bin/zsh" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="EXECUTE_IN_TERMINAL" value="false" />
<option name="EXECUTE_SCRIPT_FILE" value="false" />
<envs />
<method v="2" />
</configuration>
</component>

View file

@ -1,7 +1,6 @@
# Contributing to Continue (JetBrains extension) <!-- omit in toc -->
This file is for contribution guidelines specific to the JetBrains extension. See the root [
`CONTRIBUTING.md`](../../CONTRIBUTING.md) for general contribution guidelines.
This file is for contribution guidelines specific to the JetBrains extension. See the root [`CONTRIBUTING.md`](../../CONTRIBUTING.md) for general contribution guidelines.
## Table of Contents <!-- omit in toc -->
@ -18,6 +17,7 @@ This file is for contribution guidelines specific to the JetBrains extension. Se
- [Setting breakpoints](#setting-breakpoints)
- [Available Gradle tasks](#available-gradle-tasks)
- [Packaging](#packaging)
- [Testing the packaged extension](#testing-the-packaged-extension)
## Architecture Overview
@ -57,22 +57,27 @@ This project requires Node.js version 20.11.0 (LTS) or higher. You have two opti
## Development Workflow
Because the `gui` and `core` are written in TypeScript, our development workflow is built around the assumption that you have VS Code installed.
Because the `gui` and `core` are written in TypeScript, our development workflow is built around the assumption that you
have VS Code installed.
### Running the extension
- Open the project in VS Code and star the `Core binary` task
- Switch back to Intellij and select the "Run Continue" configuration in the top-right corner of the IDE
- Click the "Debug" button
- The first time running this will install the IDE version specified by the `platformVersion` property in [`./run/Run Extension.run.xml`](./.run/Run%20Extension.run.xml). This will take a moment as the installation size can be close to 1GB.
- The first time running this will install the IDE version specified by the `platformVersion` property in [
`./run/Run Extension.run.xml`](./.run/Run%20Extension.run.xml). This will take a moment as the installation size
can be close to 1GB.
![run-extension-screenshot](../../media/run-intellij-extension.png)\
This should open a new instance on IntelliJ with the extension installed and connected via TCP to the server started through the `Core binary` task.
This should open a new instance on IntelliJ with the extension installed and connected via TCP to the server started
through the `Core binary` task.
### Reloading changes
- `extensions/intellij`: Attempt to reload changed classes by selecting `Run | Debugging Actions | Reload Changed Classes`
- `extensions/intellij`: Attempt to reload changed classes by selecting
_Run | Debugging Actions | Reload Changed Classes`_
- This will often fail on new imports, schema changes etc. In that case, you need to stop and restart the extension
- `gui`: Changes will be reloaded automatically
- `core`: Run `npm run build` from the `binary` directory and restart the `Core binary` task in VS Code
@ -103,8 +108,13 @@ verifyPluginConfiguration - Checks if Java and Kotlin compilers configuration me
### Packaging
- Unix: `./gradlew build`
- Windows: `./gradlew.bat build`
- Unix: `./gradlew buildPlugin`
- Windows: `./gradlew.bat buildPlugin`
This will generate a .zip file in `./build/distributions` with the version defined in [
`./gradle.properties`](./gradle.properties)
This will generate a .zip file in `./build/distributions` with the version defined in [`./gradle.properties`](./gradle.properties)
#### Testing the packaged extension
- Navigate to the Plugins settings page (_Settings | Plugins_)
- Click on the gear icon
- Click _Install from disk_ and select the ZIP file in `./build/distributions`

View file

@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=0.0.76
pluginVersion=0.0.77
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension

View file

@ -17,7 +17,6 @@ import kotlinx.coroutines.*
class CoreMessenger(
private val project: Project,
esbuildPath: String,
continueCorePath: String,
private val ideProtocolClient: IdeProtocolClient,
coroutineScope: CoroutineScope
@ -162,10 +161,7 @@ class CoreMessenger(
}
} else {
// Set proper permissions
coroutineScope.launch(Dispatchers.IO) {
setPermissions(continueCorePath)
setPermissions(esbuildPath)
}
coroutineScope.launch(Dispatchers.IO) { setPermissions(continueCorePath) }
// Start the subprocess
val processBuilder =

View file

@ -7,8 +7,8 @@ import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.Project
import kotlinx.coroutines.*
import java.nio.file.Paths
import kotlinx.coroutines.*
class CoreMessengerManager(
private val project: Project,
@ -16,69 +16,67 @@ class CoreMessengerManager(
private val coroutineScope: CoroutineScope
) {
var coreMessenger: CoreMessenger? = null
var lastBackoffInterval = 0.5
var coreMessenger: CoreMessenger? = null
var lastBackoffInterval = 0.5
init {
coroutineScope.launch {
val continuePluginService = ServiceManager.getService(
project,
ContinuePluginService::class.java
)
init {
coroutineScope.launch {
val continuePluginService =
ServiceManager.getService(project, ContinuePluginService::class.java)
val myPluginId = "com.github.continuedev.continueintellijextension"
val pluginDescriptor =
PluginManager.getPlugin(PluginId.getId(myPluginId)) ?: throw Exception("Plugin not found")
val myPluginId = "com.github.continuedev.continueintellijextension"
val pluginDescriptor =
PluginManager.getPlugin(PluginId.getId(myPluginId)) ?: throw Exception("Plugin not found")
val pluginPath = pluginDescriptor.pluginPath
val osName = System.getProperty("os.name").toLowerCase()
val os = when {
osName.contains("mac") || osName.contains("darwin") -> "darwin"
osName.contains("win") -> "win32"
osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux"
else -> "linux"
}
val osArch = System.getProperty("os.arch").toLowerCase()
val arch = when {
osArch.contains("aarch64") || (osArch.contains("arm") && osArch.contains("64")) -> "arm64"
osArch.contains("amd64") || osArch.contains("x86_64") -> "x64"
else -> "x64"
}
val target = "$os-$arch"
val pluginPath = pluginDescriptor.pluginPath
val osName = System.getProperty("os.name").toLowerCase()
val os =
when {
osName.contains("mac") || osName.contains("darwin") -> "darwin"
osName.contains("win") -> "win32"
osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux"
else -> "linux"
}
val osArch = System.getProperty("os.arch").toLowerCase()
val arch =
when {
osArch.contains("aarch64") || (osArch.contains("arm") && osArch.contains("64")) ->
"arm64"
osArch.contains("amd64") || osArch.contains("x86_64") -> "x64"
else -> "x64"
}
val target = "$os-$arch"
println("Identified OS: $os, Arch: $arch")
println("Identified OS: $os, Arch: $arch")
val corePath = Paths.get(pluginPath.toString(), "core").toString()
val targetPath = Paths.get(corePath, target).toString()
val continueCorePath =
Paths.get(targetPath, "continue-binary" + (if (os == "win32") ".exe" else "")).toString()
val corePath = Paths.get(pluginPath.toString(), "core").toString()
val targetPath = Paths.get(corePath, target).toString()
val continueCorePath =
Paths.get(targetPath, "continue-binary" + (if (os == "win32") ".exe" else "")).toString()
// esbuild needs permissions
val esbuildPath = Paths.get(targetPath, "esbuild" + (if (os == "win32") ".exe" else "")).toString()
setupCoreMessenger(continueCorePath)
}
}
setupCoreMessenger(esbuildPath, continueCorePath)
}
private fun setupCoreMessenger(continueCorePath: String): Unit {
coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope)
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { resp ->
val data = resp as? Map<String, Any>
val profileInfo = data?.get("config") as? Map<String, Any>
val allowAnonymousTelemetry = profileInfo?.get("allowAnonymousTelemetry") as? Boolean
val telemetryService = service<TelemetryService>()
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
telemetryService.setup(getMachineUniqueID())
}
}
private fun setupCoreMessenger(esbuildPath: String, continueCorePath: String): Unit {
coreMessenger = CoreMessenger(project, esbuildPath, continueCorePath, ideProtocolClient, coroutineScope)
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { resp ->
val data = resp as? Map<String, Any>
val profileInfo = data?.get("config") as? Map<String, Any>
val allowAnonymousTelemetry = profileInfo?.get("allowAnonymousTelemetry") as? Boolean
val telemetryService = service<TelemetryService>()
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
telemetryService.setup(getMachineUniqueID())
}
}
// On exit, use exponential backoff to create another CoreMessenger
coreMessenger?.onDidExit {
lastBackoffInterval *= 2
println("CoreMessenger exited, retrying in $lastBackoffInterval seconds")
Thread.sleep((lastBackoffInterval * 1000).toLong())
setupCoreMessenger(esbuildPath, continueCorePath)
}
// On exit, use exponential backoff to create another CoreMessenger
coreMessenger?.onDidExit {
lastBackoffInterval *= 2
println("CoreMessenger exited, retrying in $lastBackoffInterval seconds")
Thread.sleep((lastBackoffInterval * 1000).toLong())
setupCoreMessenger(continueCorePath)
}
}
}
}

View file

@ -16,40 +16,42 @@ import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.TextRange
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import net.miginfocom.swing.MigLayout
import org.jdesktop.swingx.JXPanel
import org.jdesktop.swingx.JXTextArea
import java.awt.*
import java.awt.event.*
import java.awt.geom.AffineTransform
import java.awt.geom.Path2D
import java.awt.geom.RoundRectangle2D
import javax.swing.*
import javax.swing.border.EmptyBorder
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.event.ListDataListener
import javax.swing.plaf.basic.BasicComboBoxUI
import kotlin.math.max
import java.awt.geom.RoundRectangle2D
import java.awt.geom.AffineTransform
import javax.swing.event.ListDataListener
import net.miginfocom.swing.MigLayout
import org.jdesktop.swingx.JXPanel
import org.jdesktop.swingx.JXTextArea
const val MAIN_FONT_SIZE = 13
fun makeTextArea(): JTextArea {
val textArea = CustomTextArea(1, 40).apply {
lineWrap = true
wrapStyleWord = true
isOpaque = false
background = GetTheme().getSecondaryDark()
maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
margin = JBUI.insets(6, 4, 6, 4)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
preferredSize = Dimension(400, 75)
}
val textArea =
CustomTextArea(1, 40).apply {
lineWrap = true
wrapStyleWord = true
isOpaque = false
background = GetTheme().getSecondaryDark()
maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
margin = JBUI.insets(6, 4, 6, 4)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
preferredSize = Dimension(400, 75)
}
textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
return textArea
}
@ -67,40 +69,44 @@ fun makePanel(
onAccept: () -> Unit,
onReject: () -> Unit
): JPanel {
val topPanel = ShadowPanel(MigLayout("wrap 1, insets 2 ${leftInset} 2 2, gap 0!")).apply {
background = JBColor(0x20888888.toInt(), 0x20888888.toInt())
isOpaque = false
}
val topPanel =
ShadowPanel(MigLayout("wrap 1, insets 2 ${leftInset} 2 2, gap 0!")).apply {
background = JBColor(0x20888888.toInt(), 0x20888888.toInt())
isOpaque = false
}
val panel = CustomPanel(
MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"),
project,
modelTitles,
comboBoxRef,
onEnter,
onCancel,
onAccept,
onReject,
textArea
).apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
background = defaultBackground
add(textArea, "grow, gap 0!, height 100%")
val panel =
CustomPanel(
MigLayout("wrap 1, insets 4 10 0 2, gap 0!, fillx"),
project,
modelTitles,
comboBoxRef,
onEnter,
onCancel,
onAccept,
onReject,
textArea
)
.apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
background = defaultBackground
add(textArea, "grow, gap 0!, height 100%")
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
preferredSize = textArea.preferredSize
setup()
}
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
preferredSize = textArea.preferredSize
setup()
}
customPanelRef.set(panel)
textArea.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
panel.revalidate()
panel.repaint()
}
})
textArea.addComponentListener(
object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
panel.revalidate()
panel.repaint()
}
})
topPanel.add(panel, "grow, gap 0!")
@ -138,13 +144,15 @@ fun openInlineEdit(project: Project?, editor: Editor) {
val startLineNumber = editor.document.getLineNumber(startOffset)
var endLineNumber = editor.document.getLineNumber(endOffset)
// Doesn't seem to be any built-in methods to check for a line selection that contains trailing newlines.
// The only case this matters is when a user double-clicks to highlight a full line. Without this check.
// Doesn't seem to be any built-in methods to check for a line selection that contains trailing
// newlines.
// The only case this matters is when a user double-clicks to highlight a full line. Without this
// check.
// the highlighted range will continue to the following line.
val isSingleLineSelection = endLineNumber > startLineNumber &&
endLineNumber < editor.document.lineCount &&
editor.document.getLineStartOffset(endLineNumber) == endOffset
val isSingleLineSelection =
endLineNumber > startLineNumber &&
endLineNumber < editor.document.lineCount &&
editor.document.getLineStartOffset(endLineNumber) == endOffset
if (isSingleLineSelection) {
endLineNumber--
@ -155,7 +163,6 @@ fun openInlineEdit(project: Project?, editor: Editor) {
val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
val lineNumber = max(0, startLineNumber - 1)
// Un-highlight the selected text
selectionModel.removeSelection()
@ -166,7 +173,9 @@ fun openInlineEdit(project: Project?, editor: Editor) {
val text = editor.document.getText(TextRange(lineStart, lineEnd))
val indentation = text.takeWhile { it == ' ' }.length
val charWidth =
editor.contentComponent.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)).charWidth(' ')
editor.contentComponent
.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN))
.charWidth(' ')
val leftInset = indentation * charWidth * 2 / 3
val inlayRef = Ref<Disposable>()
@ -176,13 +185,18 @@ fun openInlineEdit(project: Project?, editor: Editor) {
val textArea = makeTextArea()
// Create diff stream handler
val diffStreamHandler = DiffStreamHandler(project, editor, startLineNumber, endLineNumber, {
inlayRef.get().dispose()
}, {
textArea.document.insertString(textArea.caretPosition, ", ", null)
textArea.requestFocus()
customPanelRef.get().finish()
})
val diffStreamHandler =
DiffStreamHandler(
project,
editor,
startLineNumber,
endLineNumber,
{ inlayRef.get().dispose() },
{
textArea.document.insertString(textArea.caretPosition, ", ", null)
textArea.requestFocus()
customPanelRef.get().finish()
})
val diffStreamService = project.service<DiffStreamService>()
diffStreamService.register(diffStreamHandler, editor)
@ -193,25 +207,32 @@ fun openInlineEdit(project: Project?, editor: Editor) {
val selectedModelStrippedOfCaret = (comboBoxRef.get().selectedItem as String).removeSuffix(" ▾")
customPanelRef.get().enter()
diffStreamHandler.streamDiffLinesToEditor(
textArea.text,
prefix,
highlighted,
suffix,
selectedModelStrippedOfCaret
textArea.text, prefix, highlighted, suffix, selectedModelStrippedOfCaret
)
}
val panel =
makePanel(project, customPanelRef, textArea, inlayRef, comboBoxRef, leftInset, modelTitles, { onEnter() }, {
diffStreamService.reject(editor)
selectionModel.setSelection(startOffset, endOffset)
}, {
diffStreamService.accept(editor)
inlayRef.get().dispose()
}, {
diffStreamService.reject(editor)
inlayRef.get().dispose()
})
makePanel(
project,
customPanelRef,
textArea,
inlayRef,
comboBoxRef,
leftInset,
modelTitles,
{ onEnter() },
{
diffStreamService.reject(editor)
selectionModel.setSelection(startOffset, endOffset)
},
{
diffStreamService.accept(editor)
inlayRef.get().dispose()
},
{
diffStreamService.reject(editor)
inlayRef.get().dispose()
})
val inlay = manager.insert(startLineNumber, panel, true)
@ -224,76 +245,79 @@ fun openInlineEdit(project: Project?, editor: Editor) {
editor.scrollingModel.scrollVertically(editor.visualLineToY(startLineNumber) - panel.height)
// Add key listener to text area
textArea.addKeyListener(object : KeyAdapter() {
override fun keyTyped(e: KeyEvent) {
if (customPanelRef.get().isFinished) {
customPanelRef.get().setup()
}
}
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> {
diffStreamService.reject(editor)
selectionModel.setSelection(startOffset, endOffset)
}
KeyEvent.VK_ENTER -> {
when (e.modifiersEx) {
KeyEvent.SHIFT_DOWN_MASK -> {
textArea.document.insertString(textArea.caretPosition, "\n", null)
}
0 -> {
onEnter()
e.consume()
}
}
}
}
}
// We need this because backspace/delete is not registering properly on keyPressed for an unknown reason
override fun keyReleased(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) {
textArea.addKeyListener(
object : KeyAdapter() {
override fun keyTyped(e: KeyEvent) {
if (customPanelRef.get().isFinished) {
customPanelRef.get().setup()
}
}
}
})
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> {
diffStreamService.reject(editor)
selectionModel.setSelection(startOffset, endOffset)
}
KeyEvent.VK_ENTER -> {
when (e.modifiersEx) {
KeyEvent.SHIFT_DOWN_MASK -> {
textArea.document.insertString(textArea.caretPosition, "\n", null)
}
0 -> {
onEnter()
e.consume()
}
}
}
}
}
// We need this because backspace/delete is not registering properly on keyPressed for an
// unknown reason
override fun keyReleased(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_BACK_SPACE || e.keyCode == KeyEvent.VK_DELETE) {
if (customPanelRef.get().isFinished) {
customPanelRef.get().setup()
}
}
}
})
// Listen for changes to textarea line count
textArea.document.addDocumentListener(object : DocumentListener {
private var lastNumLines: Int = 0
private fun updateSize() {
val numLines = textArea.text.lines().size
if (numLines != lastNumLines) {
lastNumLines = numLines
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
textArea.document.addDocumentListener(
object : DocumentListener {
private var lastNumLines: Int = 0
private fun updateSize() {
val numLines = textArea.text.lines().size
if (numLines != lastNumLines) {
lastNumLines = numLines
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
}
}
}
override fun insertUpdate(e: DocumentEvent?) {
updateSize()
}
override fun insertUpdate(e: DocumentEvent?) {
updateSize()
}
override fun removeUpdate(e: DocumentEvent?) {
updateSize()
}
override fun changedUpdate(e: DocumentEvent?) {
updateSize()
}
})
override fun removeUpdate(e: DocumentEvent?) {
updateSize()
}
override fun changedUpdate(e: DocumentEvent?) {
updateSize()
}
})
textArea.requestFocus()
}
/**
* Adapted from https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/InlineEditAction.kt
* Adapted from
* https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/InlineEditAction.kt
*/
class InlineEditAction : AnAction(), DumbAware {
override fun update(e: AnActionEvent) {
@ -337,130 +361,140 @@ class CustomPanel(
init {
isOpaque = false
add(closeButton, "pos 100%-20 0 -3 3, w 20!, h 20!")
add(closeButton, "pos 100%-33 0 -3 3, w 20!, h 20!")
}
private fun createCloseButton(): JComponent {
return JLabel("X").apply {
foreground = Color(128, 128, 128, 128)
val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass)
return JLabel(closeIcon).apply {
background = Color(0, 0, 0, 0)
font = UIUtil.getFontWithFallback("Arial", Font.BOLD, 10)
border = EmptyBorder(2, 6, 2, 0)
toolTipText = "`esc` to cancel"
isOpaque = false
addMouseListener(
object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent) {
cursor = Cursor(Cursor.HAND_CURSOR)
}
addMouseListener(object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent) {
foreground = Color(128, 128, 128, 255)
cursor = Cursor(Cursor.HAND_CURSOR)
}
override fun mouseExited(e: MouseEvent) {
cursor = Cursor.getDefaultCursor()
}
override fun mouseExited(e: MouseEvent) {
foreground = Color(128, 128, 128, 128)
cursor = Cursor.getDefaultCursor()
}
override fun mouseClicked(e: MouseEvent) {
onCancel()
}
})
override fun mouseClicked(e: MouseEvent) {
onCancel()
}
})
}
}
private val subPanelA: JPanel = JPanel(MigLayout("insets 0, fillx")).apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
val continueSettingsService = service<ContinueExtensionSettings>()
val dropdown = JComboBox(modelTitles.toTypedArray()).apply {
setUI(TransparentArrowButtonUI())
isEditable = true
background = defaultBackground
foreground = Color(128, 128, 128, 200)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = EmptyBorder(2, 4, 2, 4)
private val subPanelA: JPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
val continueSettingsService = service<ContinueExtensionSettings>()
val dropdown =
JComboBox(modelTitles.toTypedArray()).apply {
setUI(TransparentArrowButtonUI())
isEditable = true
background = defaultBackground
foreground = Color(128, 128, 128, 200)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = EmptyBorder(2, 4, 2, 4)
isOpaque = false
isEditable = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
renderer =
DefaultListCellRenderer().apply { horizontalAlignment = SwingConstants.LEFT }
selectedIndex =
continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
if (modelTitles.isEmpty()) -1
else {
val index = modelTitles.indexOf(it)
if (index != -1) index else 0
}
} ?: 0
addActionListener {
continueSettingsService.continueState.lastSelectedInlineEditModel =
selectedItem as String
}
}
comboBoxRef.set(dropdown)
val rightButton =
CustomButton("⏎ Enter") { onEnter() }
.apply {
background = JBColor(0x999998.toInt(), 0x999998.toInt())
foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt())
border = EmptyBorder(2, 6, 2, 6)
}
val rightPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
border = EmptyBorder(0, 0, 0, 0)
add(dropdown, "align right")
add(rightButton, "align right")
}
border = EmptyBorder(0, 0, 16, 12)
add(dropdown, "align left")
add(rightPanel, "align right, split 2")
isOpaque = false
isEditable = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
renderer = DefaultListCellRenderer().apply {
horizontalAlignment = SwingConstants.LEFT
}
selectedIndex = continueSettingsService.continueState.lastSelectedInlineEditModel?.let {
if (modelTitles.isEmpty()) -1 else {
val index = modelTitles.indexOf(it)
if (index != -1) index else 0
cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
}
private val subPanelB: JPanel =
JPanel(BorderLayout()).apply {
isOpaque = false
val progressBar = JProgressBar().apply { isIndeterminate = true }
add(progressBar, BorderLayout.CENTER)
border = BorderFactory.createEmptyBorder(0, 0, 16, 12)
}
private val subPanelC: JPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
val leftLabel =
JLabel("Type to re-prompt").apply {
foreground = Color(156, 163, 175) // text-gray-400
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = EmptyBorder(0, 4, 0, 0)
}
} ?: 0
addActionListener {
continueSettingsService.continueState.lastSelectedInlineEditModel = selectedItem as String
}
}
val leftButton =
CustomButton("Reject All (${getMetaKeyLabel()}⇧⌫)") { onReject() }
.apply {
background = JBColor(0x30FF0000.toInt(), 0x30FF0000.toInt())
foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt())
}
comboBoxRef.set(dropdown)
val rightButton =
CustomButton("Accept All (${getMetaKeyLabel()}⇧⏎)") { onAccept() }
.apply {
background = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt())
foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt())
}
val rightButton = CustomButton("⏎ Enter") { onEnter() }.apply {
background = JBColor(0x999998.toInt(), 0x999998.toInt())
foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt())
border = EmptyBorder(2, 6, 2, 6)
}
val rightPanel =
JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
add(leftButton, "align right")
add(rightButton, "align right")
border = EmptyBorder(0, 0, 0, 0)
}
val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
add(leftLabel, "align left")
add(rightPanel, "align right")
border = BorderFactory.createEmptyBorder(0, 0, 16, 12)
isOpaque = false
border = EmptyBorder(0, 0, 0, 0)
add(dropdown, "align right")
add(rightButton, "align right")
}
border = EmptyBorder(0, 0, 16, 12)
add(dropdown, "align left")
add(rightPanel, "align right, split 2")
isOpaque = false
cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
}
private val subPanelB: JPanel = JPanel(BorderLayout()).apply {
isOpaque = false
val progressBar = JProgressBar().apply {
isIndeterminate = true
}
add(progressBar, BorderLayout.CENTER)
border = BorderFactory.createEmptyBorder(0, 0, 16, 12)
}
private val subPanelC: JPanel = JPanel(MigLayout("insets 0, fillx")).apply {
val leftLabel = JLabel("Type to re-prompt").apply {
foreground = Color(156, 163, 175) // text-gray-400
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = EmptyBorder(0, 4, 0, 0)
}
val leftButton = CustomButton("Reject All (${getMetaKeyLabel()}⇧⌫)") { onReject() }.apply {
background = JBColor(0x30FF0000.toInt(), 0x30FF0000.toInt())
foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt())
}
val rightButton = CustomButton("Accept All (${getMetaKeyLabel()}⇧⏎)") { onAccept() }.apply {
background = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt())
foreground = JBColor(0xF5F5F5.toInt(), 0xF5F5F5.toInt())
}
val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
add(leftButton, "align right")
add(rightButton, "align right")
border = EmptyBorder(0, 0, 0, 0)
}
add(leftLabel, "align left")
add(rightPanel, "align right")
border = BorderFactory.createEmptyBorder(0, 0, 16, 12)
isOpaque = false
}
fun setup() {
remove(subPanelB)
remove(subPanelC)
@ -500,7 +534,12 @@ class CustomPanel(
// Create the shape for the tooltip/triangle
val shape = Path2D.Double()
shape.moveTo(borderThickness / 2.0, cornerRadius.toDouble())
shape.quadTo(borderThickness / 2.0, borderThickness / 2.0, cornerRadius.toDouble(), borderThickness / 2.0)
shape.quadTo(
borderThickness / 2.0,
borderThickness / 2.0,
cornerRadius.toDouble(),
borderThickness / 2.0
)
shape.lineTo(w - cornerRadius.toDouble() - rightMargin, borderThickness / 2.0)
shape.quadTo(
w - borderThickness / 2.0 - rightMargin,
@ -508,7 +547,9 @@ class CustomPanel(
w - borderThickness / 2.0 - rightMargin,
cornerRadius.toDouble()
)
shape.lineTo(w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble())
shape.lineTo(
w - borderThickness / 2.0 - rightMargin, h - cornerRadius - triangleSize.toDouble()
)
shape.quadTo(
w - borderThickness / 2.0 - rightMargin,
h - triangleSize.toDouble(),
@ -523,10 +564,7 @@ class CustomPanel(
g2.color = shadowColor
g2.fill(
shape.createTransformedShape(
AffineTransform.getTranslateInstance(
shadowSize.toDouble(),
shadowSize.toDouble()
)
AffineTransform.getTranslateInstance(shadowSize.toDouble(), shadowSize.toDouble())
)
)
@ -547,21 +585,22 @@ class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
init {
isOpaque = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
addMouseListener(object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent?) {
isHovered = true
repaint()
}
addMouseListener(
object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent?) {
isHovered = true
repaint()
}
override fun mouseExited(e: MouseEvent?) {
isHovered = false
repaint()
}
override fun mouseExited(e: MouseEvent?) {
isHovered = false
repaint()
}
override fun mouseClicked(e: MouseEvent?) {
onClick()
}
})
override fun mouseClicked(e: MouseEvent?) {
onClick()
}
})
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = EmptyBorder(2, 6, 2, 6)
@ -573,21 +612,23 @@ class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
val cornerRadius = 8
val rect = Rectangle(0, 0, width, height)
val roundRect = RoundRectangle2D.Float(
rect.x.toFloat(),
rect.y.toFloat(),
rect.width.toFloat(),
rect.height.toFloat(),
cornerRadius.toFloat(),
cornerRadius.toFloat()
)
val roundRect =
RoundRectangle2D.Float(
rect.x.toFloat(),
rect.y.toFloat(),
rect.width.toFloat(),
rect.height.toFloat(),
cornerRadius.toFloat(),
cornerRadius.toFloat()
)
if (isHovered) {
val brightenFactor = 1.1f
val brighterColor = Color(
(background.red * brightenFactor).coerceIn(0f, 255f).toInt(),
(background.green * brightenFactor).coerceIn(0f, 255f).toInt(),
(background.blue * brightenFactor).coerceIn(0f, 255f).toInt()
)
val brighterColor =
Color(
(background.red * brightenFactor).coerceIn(0f, 255f).toInt(),
(background.green * brightenFactor).coerceIn(0f, 255f).toInt(),
(background.blue * brightenFactor).coerceIn(0f, 255f).toInt()
)
g2.color = brighterColor
} else {
g2.color = background
@ -595,7 +636,8 @@ class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
g2.fill(roundRect)
g2.color = foreground
g2.drawString(
text, (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
text,
(width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
(height / 2 + g.fontMetrics.ascent / 2).toFloat()
)
}
@ -634,10 +676,11 @@ class ShadowPanel(layout: LayoutManager) : JXPanel(layout) {
}
class TransparentArrowButtonUI : BasicComboBoxUI() {
override fun createArrowButton() = JButton().apply {
isVisible = false
preferredSize = Dimension(0, 0)
}
override fun createArrowButton() =
JButton().apply {
isVisible = false
preferredSize = Dimension(0, 0)
}
override fun getInsets(): Insets {
return JBUI.insets(0, 6, 0, 0)
@ -652,34 +695,35 @@ class TransparentArrowButtonUI : BasicComboBoxUI() {
// Modify the ComboBoxModel to include the down symbol
val originalModel = comboBox.model
comboBox.model = object : ComboBoxModel<Any> {
override fun getSize(): Int = originalModel.size
override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index)
override fun setSelectedItem(anItem: Any?) {
originalModel.selectedItem = anItem
}
comboBox.model =
object : ComboBoxModel<Any> {
override fun getSize(): Int = originalModel.size
override fun getSelectedItem(): Any? {
val item = originalModel.selectedItem
return "$item ▾"
}
override fun getElementAt(index: Int): Any? = originalModel.getElementAt(index)
override fun addListDataListener(l: ListDataListener?) {
originalModel.addListDataListener(l)
}
override fun setSelectedItem(anItem: Any?) {
originalModel.selectedItem = anItem
}
override fun removeListDataListener(l: ListDataListener?) {
originalModel.removeListDataListener(l)
override fun getSelectedItem(): Any? {
val item = originalModel.selectedItem
return "$item ▾"
}
override fun addListDataListener(l: ListDataListener?) {
originalModel.addListDataListener(l)
}
override fun removeListDataListener(l: ListDataListener?) {
originalModel.removeListDataListener(l)
}
}
}
}
override fun paintCurrentValueBackground(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
// Do nothing to prevent painting the background
}
override fun paintCurrentValue(g: Graphics, bounds: Rectangle, hasFocus: Boolean) {
val renderer = comboBox.renderer
val item = comboBox.selectedItem
@ -695,8 +739,9 @@ class TransparentArrowButtonUI : BasicComboBoxUI() {
}
val currentValuePane = currentValuePane
currentValuePane.paintComponent(g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true)
currentValuePane.paintComponent(
g, c, comboBox, bounds.x, bounds.y, bounds.width, bounds.height, true
)
}
}
}

View file

@ -9,15 +9,15 @@ interface MoreHelpRowProps {
function MoreHelpRow({ title, description, onClick, Icon }: MoreHelpRowProps) {
return (
<div
className="flex items-center gap-2 justify-between cursor-pointer"
className="flex cursor-pointer items-center justify-between gap-2"
onClick={onClick}
>
<div className="w-4/5 flex flex-col justify-center">
<h3 className="text-sm my-0">{title}</h3>
<span className="text-stone-500 py-1">{description}</span>
<div className="flex w-4/5 flex-col justify-center">
<h3 className="my-0 text-sm">{title}</h3>
<span className="py-1 text-xs text-stone-500">{description}</span>
</div>
<div className="flex justify-end w-1/5 cursor-pointer w-5 h-5 text-stone-500">
<div className="flex h-5 w-1/5 w-5 cursor-pointer justify-end text-stone-500">
<Icon />
</div>
</div>