Merge pull request #2443 from LLukas22/intellij-show-toast

Add `showToast` function to Intellij plugin
This commit is contained in:
Patrick Erichsen 2024-10-02 13:31:11 -07:00 • committed by GitHub
commit bf6ef749d4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 172 additions and 115 deletions

View file

@ -17,9 +17,9 @@
"**/binary": true,
"binary/": false,
"**/core/vendor/**": true,
"**/gui/dist": true
"**/gui/dist": true,
"**/extensions/vscode/gui/**": true,
"**/extensions/vscode/out/**": true
},
"eslint.workingDirectories": [
"./core"
]
"eslint.workingDirectories": ["./core"]
}

View file

@ -15,7 +15,13 @@ import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermission
class CoreMessenger(private val project: Project, esbuildPath: String, continueCorePath: String, ideProtocolClient: IdeProtocolClient, private val coroutineScope: CoroutineScope) {
class CoreMessenger(
private val project: Project,
esbuildPath: String,
continueCorePath: String,
ideProtocolClient: IdeProtocolClient,
private val coroutineScope: CoroutineScope
) {
private var writer: Writer? = null
private var reader: BufferedReader? = null
private var process: Process? = null
@ -42,11 +48,13 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) {
val id = messageId ?: uuid()
val message = gson.toJson(mapOf(
val message = gson.toJson(
mapOf(
"messageId" to id,
"messageType" to messageType,
"data" to data
))
)
)
responseListeners[id] = onResponse
write(message)
}
@ -60,11 +68,13 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
// IDE listeners
if (MessageTypes.ideMessageTypes.contains(messageType)) {
ideProtocolClient.handleMessage(json) { data ->
val message = gson.toJson(mapOf(
val message = gson.toJson(
mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to data
))
)
)
write(message)
};
}
@ -76,11 +86,13 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
if (messageType == "getDefaultModelTitle") {
val continueSettingsService = service<ContinueExtensionSettings>()
val defaultModelTitle = continueSettingsService.continueState.lastSelectedInlineEditModel;
val message = gson.toJson(mapOf(
val message = gson.toJson(
mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to defaultModelTitle
))
)
)
write(message)
}
val continuePluginService = project.service<ContinuePluginService>()
@ -94,7 +106,8 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
val done = (data as Map<String, Boolean?>)["done"]
if (done == true) {
responseListeners.remove(messageId)
} else {}
} else {
}
} else {
responseListeners.remove(messageId)
}
@ -106,10 +119,10 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
val osName = System.getProperty("os.name").toLowerCase()
if (osName.contains("mac") || osName.contains("darwin")) {
ProcessBuilder(
"xattr",
"-dr",
"com.apple.quarantine",
destination
"xattr",
"-dr",
"com.apple.quarantine",
destination
).start()
setFilePermissions(destination, "rwxr-xr-x")
} else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) {
@ -177,7 +190,7 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
// Start the subprocess
val processBuilder = ProcessBuilder(continueCorePath)
.directory(File(continueCorePath).parentFile)
.directory(File(continueCorePath).parentFile)
process = processBuilder.start()
val outputStream = process!!.outputStream
@ -200,14 +213,16 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
println("Core process exited with output: $err")
CoroutineScope(Dispatchers.Main).launch {
ideProtocolClient.showMessage("Core process exited with output: $err")
ideProtocolClient.showToast("error", "Core process exited with output: $err")
}
// Log the cause of the failure
val telemetryService = service<TelemetryService>()
telemetryService.capture("jetbrains_core_exit", mapOf(
"error" to err
))
telemetryService.capture(
"jetbrains_core_exit", mapOf(
"error" to err
)
)
// Clean up all resources
writer?.close()

View file

@ -14,6 +14,9 @@ import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
@ -154,8 +157,8 @@ private fun readConfigJson(): Map<String, Any> {
val configJsonPath = getConfigJsonPath()
val reader = FileReader(configJsonPath)
val config: Map<String, Any> = gson.fromJson(
reader,
object : TypeToken<Map<String, Any>>() {}.type
reader,
object : TypeToken<Map<String, Any>>() {}.type
)
reader.close()
return config
@ -167,9 +170,13 @@ class AsyncFileSaveListener : AsyncFileListener {
constructor(ideProtocolClient: IdeProtocolClient) {
this.ideProtocolClient = ideProtocolClient
}
override fun prepareChange(events: MutableList<out VFileEvent>): AsyncFileListener.ChangeApplier? {
for (event in events) {
if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(".continue\\config.json") || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json")) {
if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(
".continue\\config.json"
) || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json")
) {
return object : AsyncFileListener.ChangeApplier {
override fun afterVfsChange() {
val config = readConfigJson()
@ -183,14 +190,15 @@ class AsyncFileSaveListener : AsyncFileListener {
}
class IdeProtocolClient (
class IdeProtocolClient(
private val continuePluginService: ContinuePluginService,
private val textSelectionStrategy: TextSelectionStrategy,
private val coroutineScope: CoroutineScope,
private val workspacePath: String?,
private val project: Project
): DumbAware {
) : DumbAware {
val diffManager = DiffManager(project)
private val CONTINUE_NOTIFICATION_GROUP = NotificationGroup("Continue", NotificationDisplayType.BALLOON, true)
private val ripgrep: String
init {
@ -202,7 +210,8 @@ class IdeProtocolClient (
})
val myPluginId = "com.github.continuedev.continueintellijextension"
val pluginDescriptor = PluginManager.getPlugin(PluginId.getId(myPluginId)) ?: throw Exception("Plugin not found")
val pluginDescriptor =
PluginManager.getPlugin(PluginId.getId(myPluginId)) ?: throw Exception("Plugin not found")
val pluginPath = pluginDescriptor.pluginPath
val osName = System.getProperty("os.name").toLowerCase()
@ -213,7 +222,8 @@ class IdeProtocolClient (
else -> "linux"
}
ripgrep = Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + (if (os == "win32") ".exe" else "")).toString()
ripgrep =
Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + (if (os == "win32") ".exe" else "")).toString()
}
private fun send(messageType: String, data: Any?, messageId: String? = null) {
@ -224,8 +234,8 @@ class IdeProtocolClient (
fun handleMessage(text: String, respond: (Any?) -> Unit) {
coroutineScope.launch(Dispatchers.IO) {
val parsedMessage: Map<String, Any> = Gson().fromJson(
text,
object : TypeToken<Map<String, Any>>() {}.type
text,
object : TypeToken<Map<String, Any>>() {}.type
)
val messageType = parsedMessage["messageType"] as? String
if (messageType == null) {
@ -239,16 +249,20 @@ class IdeProtocolClient (
"uniqueId" -> respond(
mapOf("uniqueId" to uniqueId())
)
"getIdeSettings" -> {
val settings =
ServiceManager.getService(ContinueExtensionSettings::class.java)
respond(mapOf(
"remoteConfigServerUrl" to settings.continueState.remoteConfigServerUrl,
"remoteConfigSyncPeriod" to settings.continueState.remoteConfigSyncPeriod,
"userToken" to settings.continueState.userToken,
"enableControlServerBeta" to settings.continueState.enableContinueTeamsBeta
))
ServiceManager.getService(ContinueExtensionSettings::class.java)
respond(
mapOf(
"remoteConfigServerUrl" to settings.continueState.remoteConfigServerUrl,
"remoteConfigSyncPeriod" to settings.continueState.remoteConfigSyncPeriod,
"userToken" to settings.continueState.userToken,
"enableControlServerBeta" to settings.continueState.enableContinueTeamsBeta
)
)
}
"getControlPlaneSessionInfo" -> {
val silent = (data as? Map<String, Any>)?.get("silent") as? Boolean ?: false
@ -261,12 +275,15 @@ class IdeProtocolClient (
respond(null)
}
}
"logoutOfControlPlane" -> {
val authService = service<ContinueAuthService>()
authService.signOut()
ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC).handleUpdatedSessionInfo(null)
ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC)
.handleUpdatedSessionInfo(null)
respond(null)
}
"getIdeInfo" -> {
val applicationInfo = ApplicationInfo.getInstance()
val ideName: String = applicationInfo.fullApplicationName
@ -283,13 +300,15 @@ class IdeProtocolClient (
val plugin = PluginManagerCore.getPlugin(PluginId.getId(pluginId))
val extensionVersion = plugin?.version ?: "Unknown"
respond(mapOf(
"ideType" to "jetbrains",
"name" to ideName,
"version" to ideVersion,
"remoteName" to remoteName,
"extensionVersion" to extensionVersion
))
respond(
mapOf(
"ideType" to "jetbrains",
"name" to ideName,
"version" to ideVersion,
"remoteName" to remoteName,
"extensionVersion" to extensionVersion
)
)
}
"getUniqueId" -> {
@ -307,9 +326,9 @@ class IdeProtocolClient (
"showDiff" -> {
val data = data as Map<String, Any>
diffManager.showDiff(
data["filepath"] as String,
data["newContents"] as String,
(data["stepIndex"] as Double).toInt()
data["filepath"] as String,
data["newContents"] as String,
(data["stepIndex"] as Double).toInt()
)
respond(null)
}
@ -333,7 +352,8 @@ class IdeProtocolClient (
val endLine = end["line"] as Int
val endCharacter = end["character"] as Int
val firstLine = fullContents.split("\n")[startLine].slice(startCharacter until fullContents.split("\n")[startLine].length)
val firstLine =
fullContents.split("\n")[startLine].slice(startCharacter until fullContents.split("\n")[startLine].length)
val lastLine = fullContents.split("\n")[endLine].slice(0 until endCharacter)
val between = fullContents.split("\n").slice(startLine + 1 until endLine).joinToString("\n")
@ -391,6 +411,7 @@ class IdeProtocolClient (
saveFile((data as Map<String, String>)["filepath"] ?: throw Exception("No filepath provided"))
respond(null)
}
"showVirtualFile" -> {
val data = data as Map<String, Any>
showVirtualFile(
@ -401,15 +422,11 @@ class IdeProtocolClient (
}
"connected" -> {}
"showMessage" -> {
showMessage(data as String)
respond(null)
}
"setFileOpen" -> {
val data = data as Map<String, Any>
setFileOpen(
data["filepath"] as String,
data["open"] as Boolean
data["filepath"] as String,
data["open"] as Boolean
)
respond(null)
}
@ -420,14 +437,14 @@ class IdeProtocolClient (
val startLine = (data["startLine"] as Double).toInt()
val endLine = (data["endLine"] as Double).toInt()
highlightCode(
RangeInFile(
filepath,
Range(
Position(startLine, 0),
Position(endLine, 0)
)
),
data["color"] as String?
RangeInFile(
filepath,
Range(
Position(startLine, 0),
Position(endLine, 0)
)
),
data["color"] as String?
)
respond(null)
}
@ -438,7 +455,7 @@ class IdeProtocolClient (
val json = gson.toJson(data["rangeInFile"])
val type = object : TypeToken<RangeInFile>() {}.type
val rangeInFile =
gson.fromJson<RangeInFile>(json, type)
gson.fromJson<RangeInFile>(json, type)
highlightCode(rangeInFile, data["color"] as String)
respond(null)
}
@ -456,6 +473,7 @@ class IdeProtocolClient (
}.toMap()
respond(pathToLastModified)
}
"listDir" -> {
val data = data as Map<String, Any>
val dir = data["dir"] as String
@ -465,6 +483,7 @@ class IdeProtocolClient (
} ?: emptyList()
respond(files)
}
"getGitRootPath" -> {
val data = data as Map<String, Any>
val directory = data["dir"] as String
@ -478,12 +497,14 @@ class IdeProtocolClient (
respond(output)
}
"getBranch" -> {
// Get the current branch name
val dir = (data as Map<String, Any>)["dir"] as String
val branch = getBranch(dir)
respond(branch)
}
"getRepoName" -> {
// Get the current repository name
val dir = (data as Map<String, Any>)["dir"] as String
@ -522,6 +543,7 @@ class IdeProtocolClient (
respond(output.toString());
}
"getProblems" -> {
// Get currently active editor
var editor: Editor? = null
@ -570,46 +592,58 @@ class IdeProtocolClient (
// }
// respond(problems)
}
"getConfigJsUrl" -> {
// Calculate a data URL for the config.js file
val configJsPath = getConfigJsPath()
val configJsContents = File(configJsPath).readText()
val configJsDataUrl = "data:text/javascript;base64,${Base64.getEncoder().encodeToString(configJsContents.toByteArray())}"
val configJsDataUrl = "data:text/javascript;base64,${
Base64.getEncoder().encodeToString(configJsContents.toByteArray())
}"
respond(configJsDataUrl)
}
"writeFile" -> {
val msg = data as Map<String, String>;
val file = File(msg["path"])
file.writeText(msg["contents"] as String)
respond(null);
}
"fileExists" -> {
val msg = data as Map<String, String>;
val file = File(msg["filepath"])
respond(file.exists())
}
"getContinueDir" -> {
respond(getContinueGlobalPath())
}
"openFile" -> {
setFileOpen((data as Map<String, Any>)["path"] as String)
respond(null)
}
"runCommand" -> {
respond(null)
// Running commands not yet supported in JetBrains
}
"errorPopup" -> {
val data = data as Map<String, Any>
val message = data["message"] as String
showMessage(message)
"showToast" -> {
val data = data as ArrayList<String>
val toast_type = data[0]
val message = data[1]
showToast(toast_type, message)
respond(null)
}
"listFolders" -> {
val workspacePath = workspacePath ?: return@launch
val workspaceDir = File(workspacePath)
val folders = workspaceDir.listFiles { file -> file.isDirectory }?.map { file -> file.absolutePath } ?: emptyList()
val folders =
workspaceDir.listFiles { file -> file.isDirectory }?.map { file -> file.absolutePath }
?: emptyList()
respond(folders)
}
@ -623,16 +657,19 @@ class IdeProtocolClient (
val openFiles = visibleFiles()
respond(openFiles)
}
"getCurrentFile" -> {
val currentFile = currentFile()
respond(currentFile)
}
"getPinnedFiles" -> {
ApplicationManager.getApplication().invokeLater {
val pinnedFiles = pinnedFiles()
respond(pinnedFiles)
}
}
"insertAtCursor" -> {
val msg = data as Map<String, String>;
val text = msg["text"] as String
@ -649,8 +686,10 @@ class IdeProtocolClient (
}
}
}
"applyToFile" -> {
}
"getGitHubAuthToken" -> {
val continueSettingsService = service<ContinueExtensionSettings>()
val ghAuthToken = continueSettingsService.continueState.ghAuthToken;
@ -663,26 +702,30 @@ class IdeProtocolClient (
respond(ghAuthToken)
}
}
"setGitHubAuthToken" -> {
val continueSettingsService = service<ContinueExtensionSettings>()
val data = data as Map<String, String>
continueSettingsService.continueState.ghAuthToken = data["token"]
respond(null)
}
"openUrl" -> {
val url = data as String
java.awt.Desktop.getDesktop().browse(java.net.URI(url))
respond(null)
}
"pathSep" -> {
respond(File.separator)
}
else -> {
println("Unknown messageType: $messageType")
}
}
} catch (error: Exception) {
showMessage("Error handling message of type $messageType: $error")
showToast("error", "Error handling message of type $messageType: $error")
}
}
}
@ -696,8 +739,8 @@ class IdeProtocolClient (
val configJsonPath = getConfigJsonPath()
val reader = FileReader(configJsonPath)
val config: MutableMap<String, Any> = gson.fromJson(
reader,
object : TypeToken<Map<String, Any>>() {}.type
reader,
object : TypeToken<Map<String, Any>>() {}.type
)
reader.close()
@ -818,7 +861,8 @@ class IdeProtocolClient (
val result = ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> {
// Get the editor instance for the currently active editor window
val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return@runReadAction null
val virtualFile = editor.let { FileDocumentManager.getInstance().getFile(it.document) } ?: return@runReadAction null
val virtualFile =
editor.let { FileDocumentManager.getInstance().getFile(it.document) } ?: return@runReadAction null
// Get the selection range and content
val selectionModel: SelectionModel = editor.selectionModel
@ -838,10 +882,12 @@ class IdeProtocolClient (
val startChar = startOffset - document.getLineStartOffset(startLine)
val endChar = endOffset - document.getLineStartOffset(endLine)
return@runReadAction RangeInFileWithContents(virtualFile.path, Range(
return@runReadAction RangeInFileWithContents(
virtualFile.path, Range(
Position(startLine, startChar),
Position(endLine, endChar)
), selectedText)
), selectedText
)
}
return result
@ -856,8 +902,8 @@ class IdeProtocolClient (
// ))
continuePluginService.sendToWebview(
"highlightedCode",
mapOf(
"highlightedCode",
mapOf(
"rangeInFileWithContents" to rif,
"edit" to edit
)
@ -877,29 +923,30 @@ class IdeProtocolClient (
}
private val DEFAULT_IGNORE_DIRS = listOf(
".git",
".vscode",
".idea",
".vs",
"venv",
".venv",
"env",
".env",
"node_modules",
"dist",
"build",
"target",
"out",
"bin",
".pytest_cache",
".vscode-test",
".continue",
"__pycache__",
"site-packages",
".gradle",
".cache",
"gems",
".git",
".vscode",
".idea",
".vs",
"venv",
".venv",
"env",
".env",
"node_modules",
"dist",
"build",
"target",
"out",
"bin",
".pytest_cache",
".vscode-test",
".continue",
"__pycache__",
"site-packages",
".gradle",
".cache",
"gems",
)
private fun shouldIgnoreDirectory(name: String): Boolean {
val components = File(name).path.split(File.separator)
return DEFAULT_IGNORE_DIRS.any { dir ->
@ -976,21 +1023,16 @@ class IdeProtocolClient (
return virtualFile?.path
}
suspend fun showMessage(msg: String) {
withContext(Dispatchers.Main) {
val statusBar = WindowManager.getInstance().getStatusBar(project)
fun showToast(type: String, content: String) {
val notificationType = when (type.uppercase()) {
"ERROR" -> NotificationType.ERROR
"WARNING" -> NotificationType.WARNING
else -> NotificationType.INFORMATION
}
JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(msg, MessageType.INFO, null)
.setFadeoutTime(10000)
.setHideOnAction(false)
.createBalloon()
.show(
RelativePoint.getSouthEastOf(statusBar.component),
Balloon.Position.atRight
)
CONTINUE_NOTIFICATION_GROUP.createNotification(content, notificationType)
.notify(project);
}
}
fun highlightCode(rangeInFile: RangeInFile, color: String?) {
val file =

View file

@ -38,7 +38,6 @@ class MessageTypes {
"getTags",
"getIdeInfo",
"getIdeSettings",
"errorPopup",
"getRepoName",
"listDir",
"getGitRootPath",
@ -50,7 +49,8 @@ class MessageTypes {
"pathSep",
"getControlPlaneSessionInfo",
"logoutOfControlPlane",
"getTerminalContents"
"getTerminalContents",
"showToast"
)
val PASS_THROUGH_TO_WEBVIEW = listOf<String>(