diff --git a/intellij-plugin/build.gradle.kts b/intellij-plugin/build.gradle.kts index 33558763a..ace7adb38 100644 --- a/intellij-plugin/build.gradle.kts +++ b/intellij-plugin/build.gradle.kts @@ -33,7 +33,7 @@ intellij { updateSinceUntilBuild = false setPlugins( - "org.jetbrains.kotlin:1.4.10-release-IJ2020.2.1-1@staging" + "org.jetbrains.kotlin:1.4.10-release-IJ2020.2-1@staging" ) } diff --git a/intellij-plugin/run/projects/.gitignore b/intellij-plugin/run/projects/.gitignore new file mode 100644 index 000000000..3d1806f15 --- /dev/null +++ b/intellij-plugin/run/projects/.gitignore @@ -0,0 +1,5 @@ +local.properties +build/ +build +.gradle +.idea diff --git a/intellij-plugin/run/projects/test-project/build.gradle.kts b/intellij-plugin/run/projects/test-project/build.gradle.kts new file mode 100644 index 000000000..e134da7b7 --- /dev/null +++ b/intellij-plugin/run/projects/test-project/build.gradle.kts @@ -0,0 +1,43 @@ +plugins { + kotlin("jvm") version "1.4.0" + kotlin("plugin.serialization") version "1.4.0" + kotlin("kapt") version "1.4.0" + id("com.github.johnrengelman.shadow") version "5.2.0" +} + +group = "org.example" +version = "1.0-SNAPSHOT" + +repositories { + mavenLocal() + jcenter() + mavenCentral() +} + +kotlin.sourceSets.all { + languageSettings.useExperimentalAnnotation("kotlin.RequiresOptIn") +} + +dependencies { + compileOnly(kotlin("stdlib-jdk8")) + + val core = "1.2.3" + val console = "1.0-M4" + + compileOnly("net.mamoe:mirai-console:$console") + compileOnly("net.mamoe:mirai-core:$core") + + val autoService = "1.0-rc7" + kapt("com.google.auto.service", "auto-service", autoService) + compileOnly("com.google.auto.service", "auto-service-annotations", autoService) + + testImplementation("net.mamoe:mirai-console:$console") + testImplementation("net.mamoe:mirai-core:$core") + testImplementation("net.mamoe:mirai-console-pure:$console") + testImplementation(kotlin("stdlib-jdk8")) +} + +kotlin.target.compilations.all { + kotlinOptions.freeCompilerArgs += "-Xjvm-default=enable" + kotlinOptions.jvmTarget = "1.8" +} \ No newline at end of file diff --git a/intellij-plugin/run/projects/test-project/gradle.properties b/intellij-plugin/run/projects/test-project/gradle.properties new file mode 100644 index 000000000..7fc6f1ff2 --- /dev/null +++ b/intellij-plugin/run/projects/test-project/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/intellij-plugin/run/projects/test-project/gradle/wrapper/gradle-wrapper.jar b/intellij-plugin/run/projects/test-project/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..490fda857 Binary files /dev/null and b/intellij-plugin/run/projects/test-project/gradle/wrapper/gradle-wrapper.jar differ diff --git a/intellij-plugin/run/projects/test-project/gradle/wrapper/gradle-wrapper.properties b/intellij-plugin/run/projects/test-project/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..a4b442974 --- /dev/null +++ b/intellij-plugin/run/projects/test-project/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/intellij-plugin/run/projects/test-project/gradlew b/intellij-plugin/run/projects/test-project/gradlew new file mode 100644 index 000000000..2fe81a7d9 --- /dev/null +++ b/intellij-plugin/run/projects/test-project/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/intellij-plugin/run/projects/test-project/gradlew.bat b/intellij-plugin/run/projects/test-project/gradlew.bat new file mode 100644 index 000000000..62bd9b9cc --- /dev/null +++ b/intellij-plugin/run/projects/test-project/gradlew.bat @@ -0,0 +1,103 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/intellij-plugin/run/projects/test-project/settings.gradle.kts b/intellij-plugin/run/projects/test-project/settings.gradle.kts new file mode 100644 index 000000000..0e9d380ad --- /dev/null +++ b/intellij-plugin/run/projects/test-project/settings.gradle.kts @@ -0,0 +1,2 @@ +rootProject.name = "test-project" + diff --git a/intellij-plugin/run/projects/test-project/src/main/kotlin/org/example/myplugin/MyPluginMain.kt b/intellij-plugin/run/projects/test-project/src/main/kotlin/org/example/myplugin/MyPluginMain.kt new file mode 100644 index 000000000..4a39b56e5 --- /dev/null +++ b/intellij-plugin/run/projects/test-project/src/main/kotlin/org/example/myplugin/MyPluginMain.kt @@ -0,0 +1,165 @@ +@file:Suppress("unused") + +package org.example.myplugin + +import com.google.auto.service.AutoService +import kotlinx.serialization.Serializable +import net.mamoe.mirai.Bot +import net.mamoe.mirai.console.command.CommandManager.INSTANCE.register +import net.mamoe.mirai.console.command.CommandManager.INSTANCE.unregister +import net.mamoe.mirai.console.command.CommandSender +import net.mamoe.mirai.console.command.CompositeCommand +import net.mamoe.mirai.console.command.ConsoleCommandSender +import net.mamoe.mirai.console.command.SimpleCommand +import net.mamoe.mirai.console.data.AutoSavePluginConfig +import net.mamoe.mirai.console.data.AutoSavePluginData +import net.mamoe.mirai.console.data.PluginDataExtensions.mapKeys +import net.mamoe.mirai.console.data.PluginDataExtensions.withEmptyDefault +import net.mamoe.mirai.console.data.value +import net.mamoe.mirai.console.permission.PermissionService +import net.mamoe.mirai.console.permission.PermissionService.Companion.hasPermission +import net.mamoe.mirai.console.plugin.jvm.JvmPlugin +import net.mamoe.mirai.console.plugin.jvm.JvmPluginDescription +import net.mamoe.mirai.console.plugin.jvm.KotlinPlugin +import net.mamoe.mirai.console.util.scopeWith +import net.mamoe.mirai.contact.Member +import net.mamoe.mirai.message.data.Image +import net.mamoe.mirai.utils.info + +@AutoService(JvmPlugin::class) +object MyPluginMain : KotlinPlugin( + JvmPluginDescription( + "org.example.example-plugin", + "0.1.0" + ) +) { + + val PERMISSION_EXECUTE_1 = PermissionService.INSTANCE.register( + permissionId("execute1"), + "注册权限的示例" + ) + + + override fun onEnable() { + MySetting.reload() // 从数据库自动读取配置实例 + MyPluginData.reload() + + logger.info { "Hi: ${MySetting.name}" } // 输出一条日志. + logger.info("Hi: ${MySetting.name}") // 输出一条日志. 与上面一条相同, 但更推荐上面一条. + logger.verbose("Hi: ${MySetting.name}") // 多种日志级别可选 + + // 请不要使用 println, System.out.println 等标准输出方式. 请总是使用 logger. + + + MySetting.count++ // 对 Setting 的改动会自动在合适的时间保存 + + MySimpleCommand.register() // 注册指令 + } + + override fun onDisable() { + MySimpleCommand.unregister() // 取消注册指令 + } +} + +// 定义插件数据 +// 插件 +object MyPluginData : AutoSavePluginData() { + var list: MutableList by value(mutableListOf("a", "b")) // mutableListOf("a", "b") 是初始值, 可以省略 + var long: Long by value(0L) // 允许 var + var int by value(0) // 可以使用类型推断, 但更推荐使用 `var long: Long by value(0)` 这种定义方式. + + + // 带默认值的非空 map. + // notnullMap[1] 的返回值总是非 null 的 MutableMap + var notnullMap + by value>>().withEmptyDefault() + + // 可将 MutableMap 映射到 MutableMap. + val botToLongMap: MutableMap by value>().mapKeys(Bot::getInstance, Bot::id) +} + +// 定义一个配置. 所有属性都会被追踪修改, 并自动保存. +// 配置是插件与用户交互的接口, 但不能用来保存插件的数据. +object MySetting : AutoSavePluginConfig() { + val name by value("test") + + var count by value(0) + + val nested by value() // 嵌套类型是支持的 +} + +@Serializable +data class MyNestedData( + val list: List = listOf(), +) + +// 简单指令 +object MySimpleCommand : SimpleCommand( + MyPluginMain, "foo", + description = "示例指令" +) { + // 会自动创建一个 ID 为 "org.example.example-plugin:command.foo" 的权限. + + + // 通过 /foo 调用, 参数自动解析 + @Handler + suspend fun CommandSender.handle(int: Int, str: String) { // 函数名随意, 但参数需要按顺序放置. + + if (this.hasPermission(MyPluginMain.PERMISSION_EXECUTE_1)) { + sendMessage("你有 ${MyPluginMain.PERMISSION_EXECUTE_1.id} 权限.") + } else { + sendMessage( + """ + 你没有 ${MyPluginMain.PERMISSION_EXECUTE_1.id} 权限. + 可以在控制台使用 /permission 管理权限. + """.trimIndent() + ) + } + + sendMessage("/foo 的第一个参数是 $int, 第二个是 $str") + } +} + +// 复合指令 +object MyCompositeCommand : CompositeCommand( + MyPluginMain, "manage", + description = "示例指令", + // prefixOptional = true // 还有更多参数可填, 此处忽略 +) { + // 会自动创建一个 ID 为 "org.example.example-plugin:command.manage" 的权限. + + // [参数智能解析] + // + // 在控制台执行 "/manage <群号>.<群员> <持续时间>", + // 或在聊天群内发送 "/manage <@一个群员> <持续时间>", + // 或在聊天群内发送 "/manage <目标群员的群名> <持续时间>", + // 或在聊天群内发送 "/manage <目标群员的账号> <持续时间>" + // 时调用这个函数 + @SubCommand + suspend fun CommandSender.mute(target: Member, duration: Int) { // 通过 /manage mute 调用 + sendMessage("/manage mute 被调用了, 参数为: $target, $duration") + + val result = kotlin.runCatching { + target.mute(duration).toString() + }.getOrElse { + it.stackTraceToString() + } // 失败时返回堆栈信息 + + + // 表示对 this 和 ConsoleCommandSender 一起操作 + this.scopeWith(ConsoleCommandSender) { + sendMessage("结果: $result") // 同时发送给 this@CommandSender 和 ConsoleCommandSender + } + } + + @SubCommand + suspend fun CommandSender.list() { // 执行 "/manage list" 时调用这个函数 + sendMessage("/manage list 被调用了") + } + + // 支持 Image 类型, 需在聊天中执行此指令. + @SubCommand + suspend fun CommandSender.test(image: Image) { // 执行 "/manage test <一张图片>" 时调用这个函数 + sendMessage("/manage image 被调用了, 图片是 ${image.imageId}") + } +} \ No newline at end of file diff --git a/intellij-plugin/run/projects/test-project/src/test/kotlin/RunConsole.kt b/intellij-plugin/run/projects/test-project/src/test/kotlin/RunConsole.kt new file mode 100644 index 000000000..c4856993e --- /dev/null +++ b/intellij-plugin/run/projects/test-project/src/test/kotlin/RunConsole.kt @@ -0,0 +1,17 @@ +import net.mamoe.mirai.alsoLogin +import net.mamoe.mirai.console.MiraiConsole +import net.mamoe.mirai.console.plugin.PluginManager.INSTANCE.enable +import net.mamoe.mirai.console.plugin.PluginManager.INSTANCE.load +import net.mamoe.mirai.console.pure.MiraiConsolePureLoader +import org.example.myplugin.MyPluginMain + +suspend fun main() { + MiraiConsolePureLoader.startAsDaemon() + + MyPluginMain.load() // 主动加载插件, Console 会调用 MyPluginMain.onLoad + MyPluginMain.enable() // 主动启用插件, Console 会调用 MyPluginMain.onEnable + + val bot = MiraiConsole.addBot(123456, "").alsoLogin() // 登录一个测试环境的 Bot + + MiraiConsole.job.join() +} \ No newline at end of file diff --git a/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/BlockingBridgeLineMarkerProvider.kt b/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/BlockingBridgeLineMarkerProvider.kt deleted file mode 100644 index ccaf76327..000000000 --- a/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/BlockingBridgeLineMarkerProvider.kt +++ /dev/null @@ -1,94 +0,0 @@ -package net.mamoe.mirai.console.intellij - -import com.intellij.codeHighlighting.Pass -import com.intellij.codeInsight.daemon.LineMarkerInfo -import com.intellij.codeInsight.daemon.LineMarkerProvider -import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.editor.markup.GutterIconRenderer -import com.intellij.openapi.progress.ProgressManager -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiJavaCodeReferenceCodeFragment -import com.intellij.psi.PsiJavaFile -import com.intellij.psi.PsiReferenceExpression -import org.jetbrains.kotlin.asJava.elements.KtLightMethod -import org.jetbrains.kotlin.idea.core.util.getLineNumber -import org.jetbrains.kotlin.psi.KtForExpression -import org.jetbrains.kotlin.psi.KtSimpleNameExpression - -class MiraiConsoleLineMarkerProvider : LineMarkerProvider { - override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? { - return null - } - - override fun collectSlowLineMarkers( - elements: MutableList, - result: MutableCollection>, - ) { - val markedLineNumbers = HashSet() - - for (element in elements) { - ProgressManager.checkCanceled() - - if (element !is PsiReferenceExpression) continue - - val containingFile = element.containingFile - if (containingFile !is PsiJavaFile || containingFile is PsiJavaCodeReferenceCodeFragment) { - continue - } - - val lineNumber = element.getLineNumber() - if (lineNumber in markedLineNumbers) continue - if (!element.hasBridgeCalls()) continue - - - markedLineNumbers += lineNumber - result += if (element is KtForExpression) { - CommandDeclarationLineMarkerInfo( - getElementForLineMark(element.loopRange!!), - // KotlinBundle.message("highlighter.message.suspending.iteration") - ) - } else { - CommandDeclarationLineMarkerInfo( - getElementForLineMark(element), - //KotlinBundle.message("highlighter.message.suspend.function.call") - ) - } - } - } - - @Suppress("DEPRECATION") - class CommandDeclarationLineMarkerInfo( - callElement: PsiElement, - ) : LineMarkerInfo( - callElement, - callElement.textRange, - Icons.CommandDeclaration, - Pass.LINE_MARKERS, - { - "Mirai Console Command" - }, - null, - GutterIconRenderer.Alignment.RIGHT - ) { - override fun createGutterRenderer(): GutterIconRenderer? { - return object : LineMarkerInfo.LineMarkerGutterIconRenderer(this) { - override fun getClickAction(): AnAction? = null - } - } - } -} - -fun PsiReferenceExpression.hasBridgeCalls(): Boolean { - val resolved = this.resolve() as? KtLightMethod ?: return false - - TODO() -} - -internal fun getElementForLineMark(callElement: PsiElement): PsiElement = - when (callElement) { - is KtSimpleNameExpression -> callElement.getReferencedNameElement() - else -> - // a fallback, - //but who knows what to reference in KtArrayAccessExpression ? - generateSequence(callElement, { it.firstChild }).last() - } \ No newline at end of file diff --git a/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/Icons.kt b/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/Icons.kt index b4551fe87..ae7217290 100644 --- a/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/Icons.kt +++ b/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/Icons.kt @@ -14,4 +14,5 @@ import javax.swing.Icon object Icons { val CommandDeclaration: Icon = IconLoader.getIcon("/icons/commandDeclaration.svg") + val PluginMainDeclaration: Icon = IconLoader.getIcon("/icons/pluginMainDeclaration.png") } \ No newline at end of file diff --git a/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/Mirai.kt b/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/Mirai.kt new file mode 100644 index 000000000..595f0f2e7 --- /dev/null +++ b/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/Mirai.kt @@ -0,0 +1,14 @@ +/* + * Copyright 2020 Mamoe Technologies and contributors. + * + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证. + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link. + * + * https://github.com/mamoe/mirai/blob/master/LICENSE + */ + +package net.mamoe.mirai.console.intellij + +import org.jetbrains.kotlin.name.FqName + +val Plugin_FQ_NAME = FqName("net.mamoe.mirai.console.plugin.Plugin") \ No newline at end of file diff --git a/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/line/marker/PluginMainLineMarkerProvider.kt b/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/line/marker/PluginMainLineMarkerProvider.kt new file mode 100644 index 000000000..45c6b1aed --- /dev/null +++ b/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/line/marker/PluginMainLineMarkerProvider.kt @@ -0,0 +1,88 @@ +package net.mamoe.mirai.console.intellij.line.marker + +import com.intellij.codeHighlighting.Pass +import com.intellij.codeInsight.daemon.LineMarkerInfo +import com.intellij.codeInsight.daemon.LineMarkerProvider +import com.intellij.openapi.actionSystem.AnAction +import com.intellij.openapi.editor.markup.GutterIconRenderer +import com.intellij.openapi.progress.ProgressManager +import com.intellij.psi.PsiElement +import com.intellij.psi.PsiJavaCodeReferenceCodeFragment +import net.mamoe.mirai.console.intellij.Icons +import net.mamoe.mirai.console.intellij.Plugin_FQ_NAME +import org.jetbrains.kotlin.idea.core.util.getLineNumber +import org.jetbrains.kotlin.nj2k.postProcessing.resolve +import org.jetbrains.kotlin.psi.KtClass +import org.jetbrains.kotlin.psi.KtConstructor +import org.jetbrains.kotlin.psi.KtObjectDeclaration +import org.jetbrains.kotlin.psi.KtReferenceExpression + +class PluginMainLineMarkerProvider : LineMarkerProvider { + override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? { + return null + } + + override fun collectSlowLineMarkers( + elements: MutableList, + result: MutableCollection>, + ) { + val markedLineNumbers = HashSet() + + for (element in elements) { + ProgressManager.checkCanceled() + + + val containingFile = element.containingFile + if (containingFile is PsiJavaCodeReferenceCodeFragment) { + continue + } + + + + + when { + element is KtReferenceExpression // constructor call + -> { + val objectDeclaration = + element.parents.filterIsInstance().firstOrNull() ?: continue + + val resolved = element.resolve() as? KtConstructor<*> ?: continue + + val kotlinPluginClass = resolved.parent as? KtClass ?: continue + + if (kotlinPluginClass.allSuperNames.none { it == Plugin_FQ_NAME }) continue + + val lineNumber = objectDeclaration.getLineNumber() + if (lineNumber in markedLineNumbers) continue + + markedLineNumbers += lineNumber + result += Info(getElementForLineMark(objectDeclaration)) + } + } + + // if (!element.hasBridgeCalls()) continue + + } + } + + @Suppress("DEPRECATION") + class Info( + callElement: PsiElement, + ) : LineMarkerInfo( + callElement, + callElement.textRange, + Icons.PluginMainDeclaration, + Pass.LINE_MARKERS, + { + "Mirai Console Plugin" + }, + null, + GutterIconRenderer.Alignment.RIGHT + ) { + override fun createGutterRenderer(): GutterIconRenderer? { + return object : LineMarkerInfo.LineMarkerGutterIconRenderer(this) { + override fun getClickAction(): AnAction? = null + } + } + } +} \ No newline at end of file diff --git a/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/line/marker/util.kt b/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/line/marker/util.kt new file mode 100644 index 000000000..38c96eb3c --- /dev/null +++ b/intellij-plugin/src/main/kotlin/net/mamoe/mirai/console/intellij/line/marker/util.kt @@ -0,0 +1,52 @@ +/* + * Copyright 2020 Mamoe Technologies and contributors. + * + * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证. + * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link. + * + * https://github.com/mamoe/mirai/blob/master/LICENSE + */ +package net.mamoe.mirai.console.intellij.line.marker + +import com.intellij.psi.PsiElement +import com.intellij.psi.PsiFile +import com.intellij.psi.PsiReferenceExpression +import org.jetbrains.kotlin.asJava.elements.KtLightMethod +import org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName +import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.nj2k.postProcessing.resolve +import org.jetbrains.kotlin.psi.* + + +internal val KtPureClassOrObject.allSuperTypes: Sequence + get() = sequence { + yieldAll(superTypeListEntries) + for (list in superTypeListEntries.asSequence()) { + yieldAll((list.typeAsUserType?.referenceExpression?.resolve() as? KtClass)?.allSuperTypes.orEmpty()) + } + } + +internal inline fun PsiElement.findParent(): E? = this.parents.filterIsInstance().firstOrNull() + +internal val KtClassOrObject.allSuperNames: Sequence get() = allSuperTypes.mapNotNull { it.getKotlinFqName() } + +fun PsiReferenceExpression.hasBridgeCalls(): Boolean { + val resolved = this.resolve() as? KtLightMethod ?: return false + + TODO() +} + +val PsiElement.parents: Sequence + get() { + val seed = if (this is PsiFile) null else parent + return generateSequence(seed) { if (it is PsiFile) null else it.parent } + } + +internal fun getElementForLineMark(callElement: PsiElement): PsiElement = + when (callElement) { + is KtSimpleNameExpression -> callElement.getReferencedNameElement() + else -> + // a fallback, + //but who knows what to reference in KtArrayAccessExpression ? + generateSequence(callElement, { it.firstChild }).last() + } \ No newline at end of file diff --git a/intellij-plugin/src/main/resources/META-INF/plugin.xml b/intellij-plugin/src/main/resources/META-INF/plugin.xml index 54c5f4070..969686c19 100644 --- a/intellij-plugin/src/main/resources/META-INF/plugin.xml +++ b/intellij-plugin/src/main/resources/META-INF/plugin.xml @@ -14,7 +14,9 @@ + implementationClass="net.mamoe.mirai.console.intellij.line.marker.PluginMainLineMarkerProvider"/> + diff --git a/intellij-plugin/src/main/resources/icons/pluginMainDeclaration.png b/intellij-plugin/src/main/resources/icons/pluginMainDeclaration.png new file mode 100644 index 000000000..7b107ff3d Binary files /dev/null and b/intellij-plugin/src/main/resources/icons/pluginMainDeclaration.png differ