├── .gitignore ├── README.md ├── build.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main ├── java │ └── cn │ │ └── mrdear │ │ └── intellij │ │ └── decompile │ │ ├── OpenDecompileSetting.java │ │ ├── OpenHelperWebSiteAction.java │ │ ├── ShowDecompileAction.java │ │ ├── ShowDiffAction.java │ │ ├── state │ │ ├── PluginSettingUIRegister.java │ │ ├── Setting.java │ │ ├── SettingConfigurationPanel.form │ │ └── SettingConfigurationPanel.java │ │ ├── ui │ │ ├── ASMifiedToolPanel.java │ │ ├── AbstractToolPanel.java │ │ ├── ByteCodeToolPanel.java │ │ ├── CFRToolPanel.java │ │ ├── DecompileToolWindowFactory.java │ │ └── JavapToolPanel.java │ │ └── util │ │ ├── ClassByteCodeSourceImpl.java │ │ ├── ExternalToolsProcessListener.java │ │ └── StringWriterDumperFactory.java └── resources │ ├── META-INF │ └── plugin.xml │ └── images │ └── java.svg └── test └── java └── cn └── mrdear └── test ├── EnumExample.java ├── StringBuilderExample.java └── SwitchCaseExample.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Project exclude paths 2 | /.gradle/ 3 | /build/ 4 | /build/classes/java/main/ 5 | /out/ 6 | .idea -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # class decompile 2 | 3 | use javap & asm & cfr decompile .class file and show 4 | 5 | ![](https://res.mrdear.cn/1583656954.png?imageMogr2/thumbnail/!60p) 6 | 7 | ## javap 8 | 9 | use javap need external tools support, like this picture config 10 | 11 | ![](https://res.mrdear.cn/1583656067.png?imageMogr2/thumbnail/!100p) 12 | 13 | 14 | ```bash 15 | -help --help -? 输出此用法消息 16 | -version 版本信息 17 | -v -verbose 输出附加信息 18 | -l 输出行号和本地变量表 19 | -public 仅显示公共类和成员 20 | -protected 显示受保护的/公共类和成员 21 | -package 显示程序包/受保护的/公共类 22 | 和成员 (默认) 23 | -p -private 显示所有类和成员 24 | -c 对代码进行反汇编 25 | -s 输出内部类型签名 26 | -sysinfo 显示正在处理的类的 27 | 系统信息 (路径, 大小, 日期, MD5 散列) 28 | -constants 显示最终常量 29 | -classpath 指定查找用户类文件的位置 30 | -cp 指定查找用户类文件的位置 31 | -bootclasspath 覆盖引导类文件的位置 32 | 33 | ``` 34 | 35 | ## cfr 36 | 37 | refer to [http://www.benf.org/other/cfr/](http://www.benf.org/other/cfr/) 38 | 39 | ```bash 40 | CFR 0.149 41 | 42 | --aexagg (boolean) 43 | --aggressivesizethreshold (int >= 0) default: 15000 44 | --allowcorrecting (boolean) default: true 45 | --analyseas (One of [DETECT, JAR, WAR, CLASS]) 46 | --arrayiter (boolean) default: true if class file from version 49.0 (Java 5) or greater 47 | --caseinsensitivefs (boolean) default: true 48 | --clobber (boolean) 49 | --collectioniter (boolean) default: true if class file from version 49.0 (Java 5) or greater 50 | --commentmonitors (boolean) default: false 51 | --comments (boolean) default: true 52 | --decodeenumswitch (boolean) default: true if class file from version 49.0 (Java 5) or greater 53 | --decodefinally (boolean) default: true 54 | --decodelambdas (boolean) default: true if class file from version 52.0 (Java 8) or greater 55 | --decodestringswitch (boolean) default: true if class file from version 51.0 (Java 7) or greater 56 | --dumpclasspath (boolean) default: false 57 | --eclipse (boolean) default: true 58 | --elidescala (boolean) default: false 59 | --extraclasspath (string) 60 | --forcecondpropagate (boolean) 61 | --forceexceptionprune (boolean) 62 | --forcereturningifs (boolean) 63 | --forcetopsort (boolean) 64 | --forcetopsortaggress (boolean) 65 | --forloopaggcapture (boolean) 66 | --hidebridgemethods (boolean) default: true 67 | --hidelangimports (boolean) default: true 68 | --hidelongstrings (boolean) default: false 69 | --hideutf (boolean) default: true 70 | --ignoreexceptions (boolean) default: false 71 | --ignoreexceptionsalways (boolean) default: false 72 | --importfilter (string) 73 | --innerclasses (boolean) default: true 74 | --instanceofpattern (boolean) default: true if class file from version 58.0 (Java 14) or greater, or experimental in 58.0 (Java 14) 75 | --j14classobj (boolean) default: false if class file from version 49.0 (Java 5) or greater 76 | --jarfilter (string) 77 | --labelledblocks (boolean) default: true 78 | --lenient (boolean) default: false 79 | --liftconstructorinit (boolean) default: true 80 | --methodname (string) 81 | --obfuscationpath (string) 82 | --outputdir (string) 83 | --outputpath (string) 84 | --override (boolean) default: true if class file from version 50.0 (Java 6) or greater 85 | --previewfeatures (boolean) default: true 86 | --pullcodecase (boolean) default: false 87 | --recordtypes (boolean) default: true if class file from version 58.0 (Java 14) or greater, or experimental in 58.0 (Java 14) 88 | --recover (boolean) default: true 89 | --recovertypeclash (boolean) 90 | --recovertypehints (boolean) 91 | --relinkconststring (boolean) default: true 92 | --removebadgenerics (boolean) default: true 93 | --removeboilerplate (boolean) default: true 94 | --removedeadmethods (boolean) default: true 95 | --removeinnerclasssynthetics (boolean) default: true 96 | --rename (boolean) default: false 97 | --renamedupmembers (boolean) default: Value of option 'rename' 98 | --renameenumidents (boolean) default: Value of option 'rename' 99 | --renameillegalidents (boolean) default: Value of option 'rename' 100 | --renamesmallmembers (int >= 0) default: 0 101 | --showinferrable (boolean) default: false if class file from version 51.0 (Java 7) or greater 102 | --showversion (boolean) default: true 103 | --silent (boolean) default: false 104 | --skipbatchinnerclasses (boolean) default: true 105 | --stringbuffer (boolean) default: false if class file from version 49.0 (Java 5) or greater 106 | --stringbuilder (boolean) default: true if class file from version 49.0 (Java 5) or greater 107 | --stringconcat (boolean) default: true if class file from version 53.0 (Java 9) or greater 108 | --sugarasserts (boolean) default: true 109 | --sugarboxing (boolean) default: true 110 | --sugarenums (boolean) default: true if class file from version 49.0 (Java 5) or greater 111 | --switchexpression (boolean) default: true if class file from version 57.0 (Java 13) or greater, or experimental in 56.0 (Java 12) 112 | --tidymonitors (boolean) default: true 113 | --tryresources (boolean) default: true if class file from version 51.0 (Java 7) or greater 114 | --usenametable (boolean) default: true 115 | --help (string) 116 | ``` 117 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("org.jetbrains.intellij") version "1.3.1" 3 | java 4 | idea 5 | } 6 | 7 | group = "cn.mrdear.intellij" 8 | version = "0.0.10" 9 | 10 | dependencies { 11 | // https://mvnrepository.com/artifact/org.benf/cfr 12 | implementation("org.benf:cfr:0.152") 13 | } 14 | 15 | // See https://github.com/JetBrains/gradle-intellij-plugin/ 16 | intellij { 17 | version.set("2021.2") 18 | plugins.addAll("java") 19 | } 20 | tasks { 21 | patchPluginXml { 22 | sinceBuild.set("212") 23 | untilBuild.set("223.*") 24 | changeNotes.set( """ 25 | 0.0.10:
26 | 1. upgrade gradle to gradle kts
27 | 2. upgrade cfr version to 152
28 | 0.0.9:
29 | 1. upgrade cfr version
30 | 0.0.8:
31 | 1. support intellij 2020.3
32 | """.trimIndent()) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/work-helper/class-decompile-intellij/29c3d30a9af9ef8f58abdc8cceeea89a932af13c/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | 88 | @rem Execute Gradle 89 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 90 | 91 | :end 92 | @rem End local scope for the variables with windows NT shell 93 | if "%ERRORLEVEL%"=="0" goto mainEnd 94 | 95 | :fail 96 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 97 | rem the _cmd.exe /c_ return code! 98 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 99 | exit /b 1 100 | 101 | :mainEnd 102 | if "%OS%"=="Windows_NT" endlocal 103 | 104 | :omega 105 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "class-decompile-intellij" 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/OpenDecompileSetting.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile; 2 | 3 | import com.intellij.openapi.actionSystem.AnAction; 4 | import com.intellij.openapi.actionSystem.AnActionEvent; 5 | import com.intellij.openapi.options.ShowSettingsUtil; 6 | import com.intellij.util.PlatformIcons; 7 | 8 | import cn.mrdear.intellij.decompile.state.PluginSettingUIRegister; 9 | 10 | public class OpenDecompileSetting extends AnAction { 11 | 12 | @Override 13 | public void actionPerformed(AnActionEvent e) { 14 | ShowSettingsUtil.getInstance() 15 | .showSettingsDialog(e.getProject(), PluginSettingUIRegister.class); 16 | } 17 | 18 | public OpenDecompileSetting() { 19 | super(PlatformIcons.SHOW_SETTINGS_ICON); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/OpenHelperWebSiteAction.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile; 2 | 3 | import com.intellij.ide.BrowserUtil; 4 | import com.intellij.openapi.actionSystem.AnAction; 5 | import com.intellij.openapi.actionSystem.AnActionEvent; 6 | import com.intellij.util.PlatformIcons; 7 | 8 | import org.jetbrains.annotations.NotNull; 9 | 10 | /** 11 | * @author Quding Ding 12 | * @since 2020/3/21 13 | */ 14 | public class OpenHelperWebSiteAction extends AnAction { 15 | 16 | private String website; 17 | 18 | public OpenHelperWebSiteAction(String website) { 19 | super(PlatformIcons.EXPORT_ICON); 20 | this.website = website; 21 | } 22 | 23 | @Override 24 | public void actionPerformed(@NotNull AnActionEvent e) { 25 | BrowserUtil.browse(website); 26 | } 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/ShowDecompileAction.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile; 2 | 3 | import com.intellij.openapi.actionSystem.AnAction; 4 | import com.intellij.openapi.actionSystem.AnActionEvent; 5 | import com.intellij.openapi.actionSystem.PlatformDataKeys; 6 | import com.intellij.openapi.application.Application; 7 | import com.intellij.openapi.application.ApplicationManager; 8 | import com.intellij.openapi.compiler.CompileScope; 9 | import com.intellij.openapi.compiler.CompilerManager; 10 | import com.intellij.openapi.fileEditor.FileDocumentManager; 11 | import com.intellij.openapi.fileEditor.FileEditor; 12 | import com.intellij.openapi.fileEditor.FileEditorManager; 13 | import com.intellij.openapi.fileEditor.impl.text.PsiAwareTextEditorImpl; 14 | import com.intellij.openapi.module.Module; 15 | import com.intellij.openapi.module.ModuleUtil; 16 | import com.intellij.openapi.project.Project; 17 | import com.intellij.openapi.roots.CompilerModuleExtension; 18 | import com.intellij.openapi.util.Computable; 19 | import com.intellij.openapi.vfs.VirtualFile; 20 | import com.intellij.openapi.wm.ToolWindowManager; 21 | import com.intellij.psi.PsiClass; 22 | import com.intellij.psi.PsiClassOwner; 23 | import com.intellij.psi.PsiElement; 24 | import com.intellij.psi.PsiFile; 25 | import com.intellij.psi.PsiManager; 26 | 27 | import org.jetbrains.annotations.Nullable; 28 | import org.jetbrains.org.objectweb.asm.ClassReader; 29 | 30 | import cn.mrdear.intellij.decompile.ui.ASMifiedToolPanel; 31 | import cn.mrdear.intellij.decompile.ui.ByteCodeToolPanel; 32 | import cn.mrdear.intellij.decompile.ui.CFRToolPanel; 33 | import cn.mrdear.intellij.decompile.ui.JavapToolPanel; 34 | 35 | import java.io.IOException; 36 | import java.io.StringWriter; 37 | import java.util.Objects; 38 | 39 | /** 40 | * 全局入口 41 | */ 42 | public class ShowDecompileAction extends AnAction { 43 | 44 | /** 45 | * 1. 获取当前指向文件,判断是否可编译为Class文件类型 46 | * 47 | * @param event 当前事件 48 | */ 49 | @Override 50 | public void actionPerformed(AnActionEvent event) { 51 | // 获取当前环境信息 52 | Project project = event.getData(PlatformDataKeys.PROJECT); 53 | VirtualFile file = event.getData(PlatformDataKeys.VIRTUAL_FILE); 54 | if (null == project || null == file) { 55 | return; 56 | } 57 | 58 | PsiFile psiFile = PsiManager.getInstance(project).findFile(file); 59 | // 校验可编译为class文件 60 | if (!(psiFile instanceof PsiClassOwner)) { 61 | return; 62 | } 63 | // this file is xxx.class, decompile this 64 | if ("class".equalsIgnoreCase(file.getExtension())) { 65 | decompileAndShowWindow(project, file); 66 | return; 67 | } 68 | 69 | // TODO 场景是什么? 70 | if (!file.isInLocalFileSystem() && !file.isWritable()) { 71 | PsiClass[] classes = ((PsiClassOwner) psiFile).getClasses(); 72 | if (classes.length > 0) { 73 | VirtualFile temp = classes[0].getOriginalElement().getContainingFile().getVirtualFile(); 74 | decompileAndShowWindow(project, temp); 75 | return; 76 | } 77 | } 78 | 79 | // 针对源文件处理, 先编译为class,再反编译class 80 | Application application = ApplicationManager.getApplication(); 81 | Module module = ModuleUtil.findModuleForPsiElement(psiFile); 82 | CompilerModuleExtension cme = null == module ? null : CompilerModuleExtension.getInstance(module); 83 | if (null == cme) { 84 | return; 85 | } 86 | CompilerManager compilerManager = CompilerManager.getInstance(project); 87 | 88 | // 文件,刷盘 89 | application.runWriteAction(() -> FileDocumentManager.getInstance().saveAllDocuments()); 90 | application.executeOnPooledThread(() -> { 91 | VirtualFile[] classFile = {null}; 92 | VirtualFile[] files = {file}; 93 | 94 | CompileScope compileScope = compilerManager.createFilesCompileScope(files); 95 | if (compilerManager.isUpToDate(compileScope)) { 96 | VirtualFile[] outputDirectories = cme.getOutputRoots(true); 97 | application.invokeLater(() -> { 98 | classFile[0] = findClassFile(project, outputDirectories, psiFile); 99 | decompileAndShowWindow(project, classFile[0]); 100 | }); 101 | } else { 102 | application.invokeLater(() -> { 103 | compilerManager.compile(files, (abort, errors, warnings, compileContext) -> { 104 | if (errors == 0) { 105 | VirtualFile[] outputRoots = cme.getOutputRoots(true); 106 | application.invokeLater(() -> { 107 | classFile[0] = findClassFile(project, outputRoots, psiFile); 108 | decompileAndShowWindow(project, classFile[0]); 109 | }); 110 | } 111 | }); 112 | }); 113 | } 114 | }); 115 | } 116 | 117 | /** 118 | * 在输出目录中找到对应的class类 119 | * 120 | * @param project 当前工程 121 | * @param outputDirectories 输出目录 122 | * @param psiFile class文件 123 | * @return 查找结果 124 | */ 125 | private VirtualFile findClassFile(Project project, VirtualFile[] outputDirectories, 126 | PsiFile psiFile) { 127 | return ApplicationManager.getApplication().runReadAction((Computable) () -> { 128 | FileEditor editor = FileEditorManager.getInstance(project).getSelectedEditor(psiFile.getVirtualFile()); 129 | int caretOffset = null == editor ? -1 : 130 | ((PsiAwareTextEditorImpl) editor).getEditor().getCaretModel().getOffset(); 131 | if (caretOffset >= 0) { 132 | // 找到对应的类名 133 | PsiElement elem = psiFile.findElementAt(caretOffset); 134 | while (elem != null) { 135 | if (elem instanceof PsiClass) { 136 | break; 137 | } 138 | elem = elem.getParent(); 139 | } 140 | if (null != elem) { 141 | return getClassFile(outputDirectories, (PsiClass) elem); 142 | } 143 | } 144 | 145 | PsiClass[] classes = ((PsiClassOwner) psiFile).getClasses(); 146 | for (PsiClass temp : classes) { 147 | VirtualFile file = getClassFile(outputDirectories, temp); 148 | if (null != file) { 149 | return file; 150 | } 151 | } 152 | return null; 153 | }); 154 | } 155 | 156 | private VirtualFile getClassFile(VirtualFile[] outputDirectories, PsiClass psiClass) { 157 | StringBuilder sb = new StringBuilder(Objects.requireNonNull(psiClass.getQualifiedName())); 158 | while (psiClass.getContainingClass() != null) { 159 | sb.setCharAt(sb.lastIndexOf("."), '$'); 160 | psiClass = psiClass.getContainingClass(); 161 | } 162 | String classFileName = sb.toString().replace('.', '/') + ".class"; 163 | for (VirtualFile outputDirectory : outputDirectories) { 164 | final VirtualFile file = outputDirectory.findFileByRelativePath(classFileName); 165 | if (file != null && file.exists()) { 166 | return file; 167 | } 168 | } 169 | return null; 170 | } 171 | 172 | /** 173 | * 反编译,并且展示到界面上 174 | * 175 | * @param project 当前工程文件 176 | * @param classFile 对应class类 177 | */ 178 | private void decompileAndShowWindow(Project project, @Nullable VirtualFile classFile) { 179 | if (classFile == null) { 180 | ApplicationManager.getApplication().runWriteAction(() -> { 181 | JavapToolPanel.getInstance(project).setCode("// couldn't generate Javap view, no .class file found"); 182 | ByteCodeToolPanel.getInstance(project).setCode("// couldn't generate ByteCode view, no .class file found"); 183 | ASMifiedToolPanel.getInstance(project).setCode("// couldn't generate ASMified view, no .class file found"); 184 | CFRToolPanel.getInstance(project).setCode("// couldn't generate CFR view, no .class file found"); 185 | ToolWindowManager.getInstance(project).getToolWindow("Decompile").activate(null); 186 | }); 187 | return; 188 | } 189 | 190 | ApplicationManager.getApplication().runWriteAction(() -> { 191 | StringWriter writer = new StringWriter(); 192 | String path = classFile.getPath(); 193 | ClassReader reader = null; 194 | classFile.refresh(false, false); 195 | 196 | try { 197 | reader = new ClassReader(classFile.contentsToByteArray()); 198 | } catch (IOException e) { 199 | return; 200 | } 201 | 202 | JavapToolPanel.getInstance(project).decompile(path); 203 | ByteCodeToolPanel.getInstance(project).decompile(writer, reader); 204 | ASMifiedToolPanel.getInstance(project).decompile(writer, reader); 205 | CFRToolPanel.getInstance(project).decompile(path, writer, reader); 206 | 207 | ToolWindowManager.getInstance(project).getToolWindow("Decompile").activate(null); 208 | // help gc 209 | reader = null; 210 | writer = null; 211 | }); 212 | } 213 | 214 | 215 | } 216 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/ShowDiffAction.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile; 2 | 3 | import com.google.common.collect.Lists; 4 | import com.intellij.diff.DiffManager; 5 | import com.intellij.diff.contents.DiffContent; 6 | import com.intellij.diff.contents.DocumentContentImpl; 7 | import com.intellij.diff.requests.ContentDiffRequest; 8 | import com.intellij.openapi.actionSystem.AnAction; 9 | import com.intellij.openapi.actionSystem.AnActionEvent; 10 | import com.intellij.openapi.editor.Document; 11 | import com.intellij.openapi.editor.impl.DocumentImpl; 12 | import com.intellij.openapi.util.IconLoader; 13 | import com.intellij.util.ReflectionUtil; 14 | 15 | import org.jetbrains.annotations.NotNull; 16 | 17 | import java.util.List; 18 | import java.util.Objects; 19 | 20 | public class ShowDiffAction extends AnAction { 21 | 22 | /** 23 | * 引用面板文档 24 | */ 25 | private Document document; 26 | /** 27 | * 上一个版本代码 28 | */ 29 | private String prevCode; 30 | 31 | public ShowDiffAction(Document document) { 32 | super("Show Differences", 33 | "Shows differences from the previous version of bytecode for this file", 34 | IconLoader.getIcon("/actions/diff.png", Objects.requireNonNull(ReflectionUtil.getGrandCallerClass()))); 35 | this.document = document; 36 | this.prevCode = ""; 37 | } 38 | 39 | @Override 40 | public void actionPerformed(AnActionEvent e) { 41 | DiffManager diffManager = DiffManager.getInstance(); 42 | 43 | diffManager.showDiff(e.getProject(),new ContentDiffRequest(){ 44 | 45 | @Override 46 | public String getTitle() { 47 | return "Class Decompile Diff"; 48 | } 49 | 50 | @NotNull 51 | @Override 52 | public List getContents() { 53 | DiffContent currentContent = new DocumentContentImpl(document); 54 | DiffContent pre = new DocumentContentImpl(new DocumentImpl(prevCode)); 55 | return Lists.newArrayList(currentContent, pre); 56 | } 57 | 58 | @NotNull 59 | @Override 60 | public List getContentTitles() { 61 | return Lists.newArrayList("current", "previous"); 62 | } 63 | }); 64 | 65 | 66 | } 67 | 68 | /** 69 | * 存储最新的code 70 | */ 71 | public void storeLatest() { 72 | prevCode = document.getText(); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/state/PluginSettingUIRegister.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile.state; 2 | 3 | import com.intellij.openapi.Disposable; 4 | import com.intellij.openapi.options.Configurable; 5 | import com.intellij.openapi.options.ConfigurationException; 6 | 7 | import org.jetbrains.annotations.Nls; 8 | import org.jetbrains.annotations.Nullable; 9 | 10 | import javax.swing.JComponent; 11 | 12 | /** 13 | * @author Quding Ding 14 | * @since 2020/3/7 15 | */ 16 | public class PluginSettingUIRegister implements Configurable, Disposable { 17 | 18 | private Setting setting; 19 | 20 | private SettingConfigurationPanel panel; 21 | 22 | public PluginSettingUIRegister() { 23 | this.setting = Setting.getInstance(); 24 | } 25 | 26 | @Override 27 | public void dispose() { 28 | panel = null; 29 | } 30 | 31 | @Nls(capitalization = Nls.Capitalization.Title) 32 | @Override 33 | public String getDisplayName() { 34 | return "Class Decompile Setting"; 35 | } 36 | 37 | @Nullable 38 | @Override 39 | public JComponent createComponent() { 40 | if (null == panel) { 41 | panel = new SettingConfigurationPanel(); 42 | } 43 | return panel.getContainer(); 44 | } 45 | 46 | @Override 47 | public void disposeUIResources() { 48 | this.panel = null; 49 | } 50 | 51 | @Override 52 | public boolean isModified() { 53 | if (panel != null) { 54 | return panel.isModified(setting); 55 | } 56 | return false; 57 | } 58 | 59 | @Override 60 | public void apply() throws ConfigurationException { 61 | if (panel != null) { 62 | panel.getData(setting); 63 | } 64 | } 65 | 66 | @Override 67 | public void reset() { 68 | if (panel != null) { 69 | panel.setData(setting); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/state/Setting.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile.state; 2 | 3 | import com.intellij.openapi.application.ApplicationManager; 4 | import com.intellij.openapi.components.PersistentStateComponent; 5 | import com.intellij.openapi.components.State; 6 | import com.intellij.openapi.components.Storage; 7 | import com.intellij.util.xmlb.XmlSerializerUtil; 8 | 9 | import org.jetbrains.annotations.NotNull; 10 | import org.jetbrains.annotations.Nullable; 11 | import org.jetbrains.org.objectweb.asm.ClassReader; 12 | 13 | /** 14 | * 持久化配置 15 | * @author Quding Ding 16 | * @since 2020/2/23 17 | */ 18 | @State(name = "ClassDecompileConfig", storages = {@Storage("ClassDecompilePlugin.xml")}) 19 | public final class Setting implements PersistentStateComponent { 20 | /** 21 | * default -c 22 | */ 23 | private String javap = "-c"; 24 | /** 25 | * default 26 | */ 27 | private String cfr = "--stringbuilder false --arrayiter fase --collectioniter false --decodelambdas false --sugarboxing false"; 28 | 29 | private boolean asmSkipDebug; 30 | private boolean asmSkipFrames; 31 | private boolean asmExpandFrames; 32 | private boolean asmSkipCode; 33 | 34 | /** 35 | * 全局单例 36 | */ 37 | public static Setting getInstance() { 38 | return ApplicationManager.getApplication().getService(Setting.class); 39 | } 40 | 41 | /** 42 | * 得到ASM flags 标识 43 | * @return 标识 44 | */ 45 | public int getAsmFlags() { 46 | int flags = 0; 47 | if (this.asmSkipDebug) flags = flags | ClassReader.SKIP_DEBUG; 48 | if (this.asmSkipFrames) flags = flags | ClassReader.SKIP_FRAMES; 49 | if (this.asmExpandFrames) flags = flags | ClassReader.EXPAND_FRAMES; 50 | if (this.asmSkipCode) flags = flags | ClassReader.SKIP_CODE; 51 | return flags; 52 | } 53 | 54 | @Nullable 55 | @Override 56 | public Setting getState() { 57 | return this; 58 | } 59 | 60 | @Override 61 | public void loadState(@NotNull Setting state) { 62 | XmlSerializerUtil.copyBean(state, this); 63 | } 64 | 65 | public String getJavap() { 66 | return javap; 67 | } 68 | 69 | public void setJavap(final String javap) { 70 | this.javap = javap; 71 | } 72 | 73 | public String getCfr() { 74 | return cfr; 75 | } 76 | 77 | public void setCfr(final String cfr) { 78 | this.cfr = cfr; 79 | } 80 | 81 | public boolean isAsmSkipDebug() { 82 | return asmSkipDebug; 83 | } 84 | 85 | public void setAsmSkipDebug(final boolean asmSkipDebug) { 86 | this.asmSkipDebug = asmSkipDebug; 87 | } 88 | 89 | public boolean isAsmSkipFrames() { 90 | return asmSkipFrames; 91 | } 92 | 93 | public void setAsmSkipFrames(final boolean asmSkipFrames) { 94 | this.asmSkipFrames = asmSkipFrames; 95 | } 96 | 97 | public boolean isAsmExpandFrames() { 98 | return asmExpandFrames; 99 | } 100 | 101 | public void setAsmExpandFrames(final boolean asmExpandFrames) { 102 | this.asmExpandFrames = asmExpandFrames; 103 | } 104 | 105 | public boolean isAsmSkipCode() { 106 | return asmSkipCode; 107 | } 108 | 109 | public void setAsmSkipCode(final boolean asmSkipCode) { 110 | this.asmSkipCode = asmSkipCode; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/state/SettingConfigurationPanel.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 |
91 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/state/SettingConfigurationPanel.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile.state; 2 | 3 | import javax.swing.JCheckBox; 4 | import javax.swing.JPanel; 5 | import javax.swing.JTextField; 6 | 7 | /** 8 | * @author Quding Ding 9 | * @since 2020/3/7 10 | */ 11 | public class SettingConfigurationPanel { 12 | 13 | private JTextField javapField; 14 | private JTextField cfrField; 15 | 16 | private JPanel container; 17 | 18 | private JCheckBox skipDebugCheckBox; 19 | private JCheckBox skipFrameCheckBox; 20 | private JCheckBox expandFramesCheckBox; 21 | private JCheckBox skipCodeCheckBox; 22 | 23 | public JPanel getContainer() { 24 | return container; 25 | } 26 | 27 | private void createUIComponents() { 28 | // TODO: place custom component creation code here 29 | } 30 | 31 | public void setData(Setting data) { 32 | javapField.setText(data.getJavap()); 33 | cfrField.setText(data.getCfr()); 34 | skipDebugCheckBox.setSelected(data.isAsmSkipDebug()); 35 | skipFrameCheckBox.setSelected(data.isAsmSkipFrames()); 36 | expandFramesCheckBox.setSelected(data.isAsmExpandFrames()); 37 | skipCodeCheckBox.setSelected(data.isAsmSkipCode()); 38 | } 39 | 40 | public void getData(Setting data) { 41 | data.setJavap(javapField.getText()); 42 | data.setCfr(cfrField.getText()); 43 | data.setAsmSkipDebug(skipDebugCheckBox.isSelected()); 44 | data.setAsmSkipFrames(skipFrameCheckBox.isSelected()); 45 | data.setAsmExpandFrames(expandFramesCheckBox.isSelected()); 46 | data.setAsmSkipCode(skipCodeCheckBox.isSelected()); 47 | } 48 | 49 | public boolean isModified(Setting data) { 50 | if (javapField.getText() != null ? !javapField.getText().equals(data.getJavap()) : data.getJavap() != null) 51 | return true; 52 | if (cfrField.getText() != null ? !cfrField.getText().equals(data.getCfr()) : data.getCfr() != null) 53 | return true; 54 | if (skipDebugCheckBox.isSelected() != data.isAsmSkipDebug()) return true; 55 | if (skipFrameCheckBox.isSelected() != data.isAsmSkipFrames()) return true; 56 | if (expandFramesCheckBox.isSelected() != data.isAsmExpandFrames()) return true; 57 | if (skipCodeCheckBox.isSelected() != data.isAsmSkipCode()) return true; 58 | return false; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/ui/ASMifiedToolPanel.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile.ui; 2 | 3 | import com.intellij.ide.highlighter.JavaFileType; 4 | import com.intellij.openapi.components.Service; 5 | import com.intellij.openapi.project.Project; 6 | import com.intellij.psi.PsiFile; 7 | import com.intellij.psi.PsiFileFactory; 8 | import com.intellij.psi.codeStyle.CodeStyleManager; 9 | 10 | import org.jetbrains.org.objectweb.asm.ClassReader; 11 | import org.jetbrains.org.objectweb.asm.util.ASMifier; 12 | import org.jetbrains.org.objectweb.asm.util.TraceClassVisitor; 13 | 14 | import java.io.PrintWriter; 15 | import java.io.StringWriter; 16 | 17 | /** 18 | * @author Quding Ding 19 | * @since 2020/3/7 20 | */ 21 | @Service 22 | public class ASMifiedToolPanel extends AbstractToolPanel { 23 | 24 | public ASMifiedToolPanel(Project project) { 25 | super(project); 26 | } 27 | 28 | /** 29 | * 得到当前实例 30 | * @param project 当前工程 31 | * @return 结果 32 | */ 33 | public static ASMifiedToolPanel getInstance(Project project) { 34 | return project.getService(ASMifiedToolPanel.class); 35 | } 36 | 37 | 38 | public void decompile(StringWriter stringWriter, ClassReader reader) { 39 | try (PrintWriter printWriter = new PrintWriter(stringWriter)) { 40 | reader.accept(new TraceClassVisitor(null, new ASMifier(), printWriter), SETTING.getAsmFlags()); 41 | 42 | PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText("temp.java", 43 | JavaFileType.INSTANCE, stringWriter.toString()); 44 | CodeStyleManager.getInstance(project).reformat(psiFile); 45 | this.setCode(psiFile.getText()); 46 | } catch (Exception e) { 47 | this.setCode("decompile fail" + e.getMessage()); 48 | } finally { 49 | stringWriter.getBuffer().setLength(0); 50 | } 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/ui/AbstractToolPanel.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile.ui; 2 | 3 | import com.intellij.openapi.Disposable; 4 | import com.intellij.openapi.actionSystem.ActionManager; 5 | import com.intellij.openapi.actionSystem.ActionToolbar; 6 | import com.intellij.openapi.actionSystem.AnAction; 7 | import com.intellij.openapi.actionSystem.DefaultActionGroup; 8 | import com.intellij.openapi.editor.Document; 9 | import com.intellij.openapi.editor.Editor; 10 | import com.intellij.openapi.editor.EditorFactory; 11 | import com.intellij.openapi.fileTypes.FileTypeManager; 12 | import com.intellij.openapi.project.Project; 13 | import com.intellij.openapi.ui.SimpleToolWindowPanel; 14 | 15 | import cn.mrdear.intellij.decompile.OpenDecompileSetting; 16 | import cn.mrdear.intellij.decompile.ShowDiffAction; 17 | import cn.mrdear.intellij.decompile.state.Setting; 18 | 19 | import java.awt.BorderLayout; 20 | 21 | import javax.swing.JPanel; 22 | 23 | /** 24 | * 展示面板 25 | * 26 | * @author Quding Ding 27 | * @since 2020/3/7 28 | */ 29 | public abstract class AbstractToolPanel extends SimpleToolWindowPanel implements Disposable { 30 | /** 31 | * 无状态,因此共享 32 | */ 33 | private static final OpenDecompileSetting OPEN_DECOMPILE_SETTING = new OpenDecompileSetting(); 34 | 35 | /** 36 | * 当前所在项目 37 | */ 38 | protected Project project; 39 | /** 40 | * 该面板所管理的文档 41 | */ 42 | private Document document; 43 | /** 44 | * 当前面板对应的编辑器 45 | */ 46 | private Editor editor; 47 | 48 | private ShowDiffAction diffAction; 49 | /** 50 | * 配置信息 51 | */ 52 | protected static final Setting SETTING = Setting.getInstance(); 53 | 54 | 55 | public AbstractToolPanel(Project project) { 56 | super(true); 57 | this.project = project; 58 | // 初始化面板 59 | this.setUI(); 60 | } 61 | 62 | /** 63 | * 设置代码 64 | * 65 | * @param code 代码 66 | */ 67 | public void setCode(String code) { 68 | // 存储上个版本 69 | diffAction.storeLatest(); 70 | // 最新版本 71 | this.document.setText(code); 72 | } 73 | 74 | /** 75 | * 初始化面板 76 | */ 77 | private void setUI() { 78 | EditorFactory editorFactory = EditorFactory.getInstance(); 79 | document = editorFactory.createDocument(""); 80 | diffAction = new ShowDiffAction(document); 81 | editor = editorFactory.createEditor(document, project, 82 | FileTypeManager.getInstance().getFileTypeByExtension("java"), true); 83 | // 主面板 84 | add(editor.getComponent()); 85 | 86 | // 添加工具栏 87 | DefaultActionGroup group = new DefaultActionGroup(); 88 | 89 | group.add(OPEN_DECOMPILE_SETTING); 90 | group.add(diffAction); 91 | AnAction action = internalToolAction(); 92 | if (null != action) { 93 | group.add(action); 94 | } 95 | 96 | ActionManager actionManager = ActionManager.getInstance(); 97 | 98 | ActionToolbar actionToolBar = actionManager.createActionToolbar("Decompile", group, true); 99 | actionToolBar.setTargetComponent(this); 100 | 101 | JPanel buttonsPanel = new JPanel(new BorderLayout()); 102 | buttonsPanel.add(actionToolBar.getComponent(), BorderLayout.CENTER); 103 | 104 | setToolbar(buttonsPanel); 105 | } 106 | 107 | /** 108 | * 子类的action 109 | * 110 | * @return action 111 | */ 112 | protected AnAction internalToolAction() { 113 | return null; 114 | } 115 | 116 | @Override 117 | public void dispose() { 118 | if (editor != null) { 119 | EditorFactory editorFactory = EditorFactory.getInstance(); 120 | editorFactory.releaseEditor(editor); 121 | editor = null; 122 | } 123 | } 124 | 125 | } 126 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/ui/ByteCodeToolPanel.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile.ui; 2 | 3 | import com.intellij.openapi.components.Service; 4 | import com.intellij.openapi.project.Project; 5 | 6 | import org.jetbrains.org.objectweb.asm.ClassReader; 7 | import org.jetbrains.org.objectweb.asm.ClassVisitor; 8 | import org.jetbrains.org.objectweb.asm.util.TraceClassVisitor; 9 | 10 | import java.io.PrintWriter; 11 | import java.io.StringWriter; 12 | 13 | /** 14 | * @author Quding Ding 15 | * @since 2020/3/7 16 | */ 17 | @Service 18 | public class ByteCodeToolPanel extends AbstractToolPanel { 19 | 20 | public ByteCodeToolPanel(Project project) { 21 | super(project); 22 | } 23 | 24 | /** 25 | * 得到当前实例 26 | * @param project 当前工程 27 | * @return 结果 28 | */ 29 | public static ByteCodeToolPanel getInstance(Project project) { 30 | return project.getService(ByteCodeToolPanel.class); 31 | } 32 | 33 | /** 34 | * 反编译为字节码 35 | * @param stringWriter 输出位置 36 | * @param reader class内容 37 | */ 38 | public void decompile(StringWriter stringWriter, ClassReader reader) { 39 | try (PrintWriter printWriter = new PrintWriter(stringWriter)) { 40 | ClassVisitor visitor = new TraceClassVisitor(printWriter); 41 | reader.accept(visitor, 0); 42 | setCode(stringWriter.toString()); 43 | } catch (Exception e) { 44 | setCode("decompile fail " + e.getMessage()); 45 | } finally { 46 | stringWriter.getBuffer().setLength(0); 47 | } 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/ui/CFRToolPanel.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile.ui; 2 | 3 | import com.intellij.openapi.actionSystem.AnAction; 4 | import com.intellij.openapi.components.Service; 5 | import com.intellij.openapi.project.Project; 6 | 7 | import org.apache.commons.lang3.StringUtils; 8 | import org.benf.cfr.reader.api.CfrDriver; 9 | import org.benf.cfr.reader.bytecode.analysis.parse.utils.Pair; 10 | import org.benf.cfr.reader.util.getopt.GetOptParser; 11 | import org.benf.cfr.reader.util.getopt.Options; 12 | import org.benf.cfr.reader.util.getopt.OptionsImpl; 13 | import org.jetbrains.org.objectweb.asm.ClassReader; 14 | 15 | import cn.mrdear.intellij.decompile.OpenHelperWebSiteAction; 16 | import cn.mrdear.intellij.decompile.util.ClassByteCodeSourceImpl; 17 | import cn.mrdear.intellij.decompile.util.StringWriterDumperFactory; 18 | 19 | import java.io.StringWriter; 20 | import java.util.List; 21 | 22 | /** 23 | * @author Quding Ding 24 | * @since 2020/3/7 25 | */ 26 | @Service 27 | public class CFRToolPanel extends AbstractToolPanel { 28 | 29 | public CFRToolPanel(Project project) { 30 | super(project); 31 | } 32 | 33 | @Override 34 | protected AnAction internalToolAction() { 35 | return new OpenHelperWebSiteAction("https://www.benf.org/other/cfr/"); 36 | } 37 | 38 | /** 39 | * 得到当前实例 40 | * 41 | * @param project 当前工程 42 | * @return 结果 43 | */ 44 | public static CFRToolPanel getInstance(Project project) { 45 | return project.getService(CFRToolPanel.class); 46 | } 47 | 48 | public void decompile(String path, StringWriter writer, ClassReader reader) { 49 | // fill args 50 | Pair, Options> optionsPair = null; 51 | try { 52 | String temp = path.concat(" ").concat(SETTING.getCfr()); 53 | String[] args = StringUtils.split(temp, ' '); 54 | 55 | GetOptParser getOptParser = new GetOptParser(); 56 | optionsPair = getOptParser.parse(args, OptionsImpl.getFactory()); 57 | } catch (Exception e) { 58 | this.setCode("parameter parse failed " + e.getMessage()); 59 | writer.getBuffer().setLength(0); 60 | return; 61 | } 62 | 63 | // cfr 64 | try { 65 | Options options = optionsPair.getSecond(); 66 | if (!options.optionIsSet(OptionsImpl.HELP)) { 67 | CfrDriver driver = new CfrDriver.Builder() 68 | .withBuiltOptions(options) 69 | .withOutputSink(new StringWriterDumperFactory(writer)) 70 | .withClassFileSource(new ClassByteCodeSourceImpl(options, reader.b, "temp.java")) 71 | .build(); 72 | driver.analyse(optionsPair.getFirst()); 73 | this.setCode(writer.toString()); 74 | return; 75 | } 76 | writer.append("decompile fail"); 77 | this.setCode(writer.toString()); 78 | } catch (Exception e) { 79 | this.setCode("decompile fail " + e.getMessage()); 80 | } finally { 81 | writer.getBuffer().setLength(0); 82 | } 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/ui/DecompileToolWindowFactory.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile.ui; 2 | 3 | import com.intellij.openapi.project.Project; 4 | import com.intellij.openapi.wm.ToolWindow; 5 | import com.intellij.openapi.wm.ToolWindowFactory; 6 | import com.intellij.ui.content.ContentFactory; 7 | import com.intellij.ui.content.ContentManager; 8 | 9 | import org.jetbrains.annotations.NotNull; 10 | 11 | /** 12 | * 创建对应window 13 | * 14 | * @author Quding Ding 15 | * @since 2020/3/7 16 | */ 17 | public class DecompileToolWindowFactory implements ToolWindowFactory { 18 | 19 | @Override 20 | public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) { 21 | ContentManager manager = toolWindow.getContentManager(); 22 | ContentFactory instance = ContentFactory.SERVICE.getInstance(); 23 | 24 | manager.addContent(instance.createContent(ByteCodeToolPanel.getInstance(project), "Bytecode", false)); 25 | manager.addContent(instance.createContent(ASMifiedToolPanel.getInstance(project), "ASMified", false)); 26 | manager.addContent(instance.createContent(CFRToolPanel.getInstance(project), "CFR", false)); 27 | manager.addContent(instance.createContent(JavapToolPanel.getInstance(project), "Javap", false)); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/ui/JavapToolPanel.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile.ui; 2 | 3 | import com.intellij.execution.configurations.GeneralCommandLine; 4 | import com.intellij.execution.process.OSProcessHandler; 5 | import com.intellij.openapi.actionSystem.AnAction; 6 | import com.intellij.openapi.actionSystem.CommonDataKeys; 7 | import com.intellij.openapi.project.Project; 8 | import com.intellij.tools.Tool; 9 | import com.intellij.tools.ToolManager; 10 | 11 | import org.apache.commons.lang3.StringUtils; 12 | 13 | import cn.mrdear.intellij.decompile.OpenHelperWebSiteAction; 14 | import cn.mrdear.intellij.decompile.util.ExternalToolsProcessListener; 15 | 16 | import java.io.StringWriter; 17 | import java.util.List; 18 | 19 | /** 20 | * @author Quding Ding 21 | * @since 2020/3/7 22 | */ 23 | public class JavapToolPanel extends AbstractToolPanel { 24 | 25 | public JavapToolPanel(Project project) { 26 | super(project); 27 | } 28 | 29 | @Override 30 | protected AnAction internalToolAction() { 31 | return new OpenHelperWebSiteAction("https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javap.html"); 32 | } 33 | 34 | /** 35 | * 得到当前实例 36 | * 37 | * @param project 当前工程 38 | * @return 结果 39 | */ 40 | public static JavapToolPanel getInstance(Project project) { 41 | return project.getService(JavapToolPanel.class); 42 | } 43 | 44 | /** 45 | * 反编译为字节码 46 | */ 47 | public void decompile(String path) { 48 | StringWriter writer = new StringWriter(); 49 | 50 | List tools = ToolManager.getInstance().getTools("External Tools"); 51 | 52 | Tool javap = tools.stream() 53 | .filter(x -> x.getName().equalsIgnoreCase("javap")) 54 | .findFirst().orElse(null); 55 | 56 | if (null == javap) { 57 | this.setCode("no javap command found on External Tools, you can refer to " + 58 | "https://github.com/mrdear/class-decompile-intellij"); 59 | return; 60 | } 61 | 62 | GeneralCommandLine commandLine = javap.createCommandLine((dataId) -> { 63 | if (CommonDataKeys.PROJECT.getName().equals(dataId)) { 64 | return project; 65 | } 66 | return null; 67 | }); 68 | 69 | if (null == commandLine) { 70 | return; 71 | } 72 | 73 | commandLine.withParameters(StringUtils.split(SETTING.getJavap()," ")); 74 | commandLine.addParameter(path); 75 | 76 | try { 77 | ExternalToolsProcessListener listener = new ExternalToolsProcessListener(writer, this); 78 | OSProcessHandler handler = new OSProcessHandler(commandLine); 79 | handler.addProcessListener(listener); 80 | handler.startNotify(); 81 | } catch (Exception e) { 82 | this.setCode("decompile fail " + e.getMessage()); 83 | } 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/util/ClassByteCodeSourceImpl.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile.util; 2 | 3 | import org.benf.cfr.reader.bytecode.analysis.parse.utils.Pair; 4 | import org.benf.cfr.reader.state.ClassFileSourceImpl; 5 | import org.benf.cfr.reader.util.getopt.Options; 6 | 7 | import java.io.IOException; 8 | 9 | /** 10 | * hack下ClassFileSourceImpl,使其支持直接读取字节码 11 | * @author Quding Ding 12 | * @since 2018/2/11 13 | */ 14 | public class ClassByteCodeSourceImpl extends ClassFileSourceImpl { 15 | 16 | private byte[] classSource; 17 | 18 | private String className; 19 | 20 | public ClassByteCodeSourceImpl(Options options,byte[] classSource,String className) { 21 | super(options); 22 | this.classSource = classSource; 23 | this.className = className; 24 | } 25 | 26 | public ClassByteCodeSourceImpl(Options options) { 27 | super(options); 28 | } 29 | 30 | 31 | @Override 32 | public Pair getClassFileContent(String inputPath) throws IOException { 33 | Pair fileContent = null; 34 | try { 35 | fileContent = super.getClassFileContent(inputPath); 36 | } catch (IOException e) { 37 | if (inputPath.lastIndexOf(className) > 0) { 38 | fileContent = Pair.make(classSource, inputPath); 39 | } else { 40 | throw e; 41 | } 42 | } 43 | return fileContent; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/util/ExternalToolsProcessListener.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile.util; 2 | 3 | import com.intellij.execution.process.ProcessAdapter; 4 | import com.intellij.execution.process.ProcessEvent; 5 | import com.intellij.execution.process.ProcessOutputType; 6 | import com.intellij.openapi.application.ApplicationManager; 7 | import com.intellij.openapi.util.Key; 8 | 9 | import org.jetbrains.annotations.NotNull; 10 | 11 | import cn.mrdear.intellij.decompile.ui.JavapToolPanel; 12 | 13 | import java.io.StringWriter; 14 | 15 | /** 16 | * @author Quding Ding 17 | * @since 2020/3/8 18 | */ 19 | public class ExternalToolsProcessListener extends ProcessAdapter { 20 | 21 | private StringWriter writer; 22 | 23 | private JavapToolPanel panel; 24 | 25 | public ExternalToolsProcessListener(StringWriter writer, JavapToolPanel panel) { 26 | this.writer = writer; 27 | this.panel = panel; 28 | } 29 | 30 | @Override 31 | public void processTerminated(@NotNull ProcessEvent event) { 32 | ApplicationManager.getApplication() 33 | .invokeLater(() -> ApplicationManager.getApplication() 34 | .runWriteAction(() -> panel.setCode(writer.toString()))); 35 | } 36 | 37 | @Override 38 | public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) { 39 | if (outputType.equals(ProcessOutputType.STDOUT) || outputType.equals(ProcessOutputType.STDERR)) { 40 | writer.append(event.getText()); 41 | } 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/cn/mrdear/intellij/decompile/util/StringWriterDumperFactory.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.intellij.decompile.util; 2 | 3 | import org.benf.cfr.reader.api.OutputSinkFactory; 4 | import org.benf.cfr.reader.api.SinkReturns; 5 | 6 | import java.io.StringWriter; 7 | import java.util.Arrays; 8 | import java.util.Collection; 9 | import java.util.Collections; 10 | import java.util.List; 11 | import java.util.function.Consumer; 12 | 13 | /** 14 | * @author Quding Ding 15 | * @since 2018/7/7 16 | */ 17 | public class StringWriterDumperFactory implements OutputSinkFactory { 18 | /** 19 | * 输出路径 20 | */ 21 | private StringWriter writer; 22 | 23 | public StringWriterDumperFactory(StringWriter writer) { 24 | this.writer = writer; 25 | } 26 | 27 | @Override 28 | public List getSupportedSinks(SinkType sinkType, Collection collection) { 29 | if (sinkType == SinkType.JAVA && collection.contains(SinkClass.DECOMPILED)) { 30 | // I'd like "Decompiled". If you can't do that, I'll take STRING. 31 | return Arrays.asList(SinkClass.DECOMPILED, SinkClass.STRING); 32 | } else { 33 | // I only understand how to sink strings, regardless of what you have to give me. 34 | return Collections.singletonList(SinkClass.STRING); 35 | } 36 | } 37 | 38 | @Override 39 | public Sink getSink(SinkType sinkType, SinkClass sinkClass) { 40 | if (sinkType == SinkType.JAVA && sinkClass == SinkClass.DECOMPILED) { 41 | return x -> dumpDecompiled.accept((SinkReturns.Decompiled) x); 42 | } 43 | if (sinkType == SinkType.EXCEPTION) { 44 | return x -> writer.append(((SinkReturns.ExceptionMessage) x).getMessage()); 45 | } 46 | return ignore -> {}; 47 | } 48 | 49 | 50 | private Consumer dumpDecompiled = d -> { 51 | writer.append("Package [").append(d.getPackageName()).append("] Class [").append(d.getClassName()).append("]"); 52 | writer.append(d.getJava()); 53 | }; 54 | } 55 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | cn.mrdear.intellij.class-decompile-intellij 3 | Class Decompile 4 | QuDing 5 | 6 | class-decompile-intellij base on asm-bytecode-intellij 9 | ]]> 10 | 11 | 13 | com.intellij.modules.platform 14 | com.intellij.modules.java 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/main/resources/images/java.svg: -------------------------------------------------------------------------------- 1 | 3 | 6 | 7 | 8 | 9 | 11 | -------------------------------------------------------------------------------- /src/test/java/cn/mrdear/test/EnumExample.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.test; 2 | 3 | /** 4 | * --sugarenums false 5 | */ 6 | public enum EnumExample { 7 | 8 | APPLE(1), 9 | BANANA(2),; 10 | 11 | private int value; 12 | 13 | EnumExample(int value) { 14 | this.value = value; 15 | } 16 | 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/cn/mrdear/test/StringBuilderExample.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.test; 2 | 3 | /** 4 | * --stringbuilder false 5 | */ 6 | public class StringBuilderExample { 7 | 8 | public static void main(String[] args) { 9 | 10 | // 常见错误写法 11 | String result = "num:"; 12 | 13 | for (int i = 0; i < 10; i++) { 14 | result = result + String.valueOf(i); 15 | } 16 | System.out.println(result); 17 | } 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/cn/mrdear/test/SwitchCaseExample.java: -------------------------------------------------------------------------------- 1 | package cn.mrdear.test; 2 | 3 | /** 4 | * 5 | * --decodestringswitch false 6 | * 7 | * @author Quding Ding 8 | * @since 2018/7/7 9 | */ 10 | public class SwitchCaseExample { 11 | 12 | public static void main(String[] args) { 13 | SwitchCaseExample example = new SwitchCaseExample(); 14 | example.switchCase("key1"); 15 | } 16 | 17 | private Integer switchCase(String key) { 18 | switch (key) { 19 | case "key1": 20 | return 1; 21 | case "key4": 22 | break; 23 | case "key3": 24 | case "key3.1": 25 | return 3; 26 | default: 27 | return 0; 28 | } 29 | return -1; 30 | } 31 | 32 | 33 | } 34 | --------------------------------------------------------------------------------