diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..bf7afcb --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,55 @@ +name: Recaf4Forge Release + +on: + push: + branches: [master] + +jobs: + validation: + name: "Post build - Validation" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2.3.4 + - name: Gradle Wrapper Validation + uses: gradle/wrapper-validation-action@v1.0.3 + + build: + needs: validation + runs-on: ubuntu-latest + env: + PROPERTIES_PATH: gradle.properties + steps: + - uses: actions/checkout@v2.3.4 + + - name: Step 1 - Setup JDK + uses: actions/setup-java@v1.4.3 + with: + java-version: 8 + java-package: jdk+fx + + - name: Step 2 - Grant execute permission for gradlew + run: chmod +x gradlew + + - name: Step 3 - Build with Gradle + run: ./gradlew build + + - name: Step 4 - Read version + id: read_property + uses: christian-draeger/read-properties@1.0.1 + with: + path: ${{ env.PROPERTIES_PATH }} + property: version + + - name: Step 5 - Upload artifact + uses: actions/upload-artifact@v2 + with: + name: Recaf4Forge-${{ steps.read_property.outputs.value }} + path: build/libs/*.jar + + - name: Step 6 - Create a Release + uses: elgohr/Github-Release-Action@master + env: + GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }} + with: + args: Recaf4Forge ${{ steps.read_property.outputs.value }} + diff --git a/.gitignore b/.gitignore index 238220f..c6f5eb1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,22 +1,11 @@ -.metadata/** -.recommenders/** -.settings/** -bin/** -target/** -**/psd/** -*.class -*.dtd -*.sh -*.bat -*.lnk - -.classpath -.project - -# IntelliJ IDEA Project stuff -.idea/ -out/ +# idea +out +*.ipr *.iws *.iml -*___jb_*___ -/target/ +.idea + +# gradle +build +.gradle +/.gradle/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index bdea0df..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,20 +0,0 @@ -# Recaf plugin workspace - -This is a sample maven workspace for creating plugins for Recaf `2.X`. - -## Plugin documentation - -The official documentation can be found here: [Recaf Docs:Plugins](https://col-e.github.io/Recaf/doc-advanced-plugin.html). - -The source and javadoc artifacts are also available and can be fetched in your IDE workspace. - -## Building & modification - -Once you've downloaded or cloned the repository, you can compile with `mvn clean package`. -This will generate the file `target/plugin-{VERSION}.jar`. To add your plugin to Recaf: - -1. Navigate to the `plugins` folder. - - Windows: `%HOMEPATH%/Recaf/plugins` - - Linux: `$HOME/Recaf/plugins` -2. Copy your plugin jar into this folder -3. Run Recaf to verify your plugin loads. \ No newline at end of file diff --git a/README.md b/README.md index 6f981cd..bd7e846 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ Inspired by [Luyten4Forge](https://github.com/KevinPriv/Luyten4Forge) ![VERSION](https://img.shields.io/github/v/release/1fxe/Recaf4Forge?style=flat-square) ![ISSUES](https://img.shields.io/github/issues/1fxe/Recaf4Forge?style=flat-square) +[![Recaf4Forge Release](https://github.com/1fxe/Recaf4Forge/actions/workflows/release.yml/badge.svg)](https://github.com/1fxe/Recaf4Forge/actions/workflows/release.yml) @@ -14,11 +15,23 @@ Inspired by [Luyten4Forge](https://github.com/KevinPriv/Luyten4Forge) This is a plugin for Recaf which can automatically detects a Minecraft Forge Mods version using the mcmod.info and applies the correct mapping. It also allows you to export the Forge MDK for the version. -The mappings are stored in this jar file, so you don't have to manually find them. +The mappings and mdks are stored in this jar file, so you don't have to manually find them. -The mappings currently work for 1.8, 1.8.9 and 1.9.4 +
-The Forge MDK export works for 1.8.9 and 1.9.4 +**Supported Versions** + +Version | Mappings | MDK + --- | --- | --- +**1.8** | ✔ | ❌ +**1.8.9** | ✔ | ✔ +**1.9.4** | ✔ | ✔ + +### Config + +Apply Mappings automatically - off by default, parses mcmod.info to try read the version + +Notifications - Off by default, Creates a popup when mappings are applied and/or source is extracted ### Example Usage @@ -36,12 +49,16 @@ The Forge MDK export works for 1.8.9 and 1.9.4 -## TODO +#### TODO -- Notifications - Add support for other versions - Add translations? +- Fix notifications disappearing too fast + +
+ +## Contributing -### Contributing +Contributors are welcome 👍🏽 -See [Contributing](CONTRIBUTING.md) \ No newline at end of file +Thanks [Recaf-development](https://github.com/videogame-player/recaf-development) for the gradle plugin diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..32fe7a7 --- /dev/null +++ b/build.gradle @@ -0,0 +1,30 @@ +import org.apache.tools.ant.filters.ReplaceTokens + +plugins { + id 'java' + id "me.videogame.recaf" version "1.2" +} + +group = project.group +version = project.version +description = project.description +sourceCompatibility = JavaVersion.VERSION_1_8 + +recaf { + mainClass = project.mainClass +} + +task processSource(type: Sync) { + from sourceSets.main.java + inputs.property '@VERSION@', version + filter(ReplaceTokens, tokens: [VERSION: version]) + into "$buildDir/src/" +} + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} + +compileJava { + source = processSource.outputs +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..b610665 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,7 @@ +name=Recaf4Forge +version=1.1.4 +group=dev.fxe +description=Recaf4Forge +mainClass=dev.fxe.recaf4forge.Recaf4Forge + +org.gradle.jvmargs=-Xmx2G diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e708b1c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..442d913 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..4f906e0 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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 execute + +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 execute + +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 + +: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 %* + +: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/pom.xml b/pom.xml deleted file mode 100644 index 6a8022a..0000000 --- a/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - 4.0.0 - - dev.fxe - recaf4forge - 1.0.9 - Recaf4Forge - - - Windows - - - Windows - - - - ${user.home}/AppData/Roaming/Recaf/plugins - - - - Linux - - - Linux - - - - ${user.home}/Library/Preferences/Recaf/plugins - - - - - UTF-8 - - - - - jitpack.io - https://jitpack.io - - - - - - com.github.Col-E - recaf - 2.4.0 - - - - - - maven-compiler-plugin - 3.7.0 - - 1.8 - 1.8 - - - - - org.apache.maven.plugins - maven-jar-plugin - 3.2.0 - - ${pluginDir} - - - - - \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..742b2df --- /dev/null +++ b/settings.gradle @@ -0,0 +1,17 @@ +pluginManagement { + repositories { + mavenLocal() + maven { url "https://jitpack.io/" } + maven { url "http://files.minecraftforge.net/maven" } + gradlePluginPortal() + } + resolutionStrategy { + eachPlugin { + if (requested.id.id == "me.videogame.recaf") { + useModule("com.github.videogame-player:recaf-development:${requested.version}") + } + } + } +} + +rootProject.name = 'recaf4forge' diff --git a/src/main/java/dev/fxe/recaf4forge/BuildInfo.java b/src/main/java/dev/fxe/recaf4forge/BuildInfo.java new file mode 100644 index 0000000..0af3823 --- /dev/null +++ b/src/main/java/dev/fxe/recaf4forge/BuildInfo.java @@ -0,0 +1,11 @@ +package dev.fxe.recaf4forge; + +public class BuildInfo { + + public static final String[] versions = {"1.8", "1.8.9", "1.9.4"}; + public static final String version = "@VERSION@"; + public static final String name = "Recaf4Forge"; + public static final String description = + "Recaf4Forge will automatically try apply the correct mappings for a forge mod, you are able to apply the mappings"; + +} diff --git a/src/main/java/dev/fxe/recaf4forge/Exporter.java b/src/main/java/dev/fxe/recaf4forge/Exporter.java new file mode 100644 index 0000000..5de375b --- /dev/null +++ b/src/main/java/dev/fxe/recaf4forge/Exporter.java @@ -0,0 +1,88 @@ +package dev.fxe.recaf4forge; + +import dev.fxe.recaf4forge.gui.Notification; +import me.coley.recaf.control.gui.GuiController; +import me.coley.recaf.decompile.DecompileImpl; +import me.coley.recaf.ui.MainWindow; +import me.coley.recaf.workspace.Workspace; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +public class Exporter { + + private final Recaf4Forge recaf4Forge; + + Exporter(Recaf4Forge recaf4Forge) { + this.recaf4Forge = recaf4Forge; + } + + public void exportMDK() { + final Workspace workspace = recaf4Forge.getCurrentWorkspace(); + final String version = recaf4Forge.getCurrentVersion(); + if (!version.equalsIgnoreCase("") & workspace != null) { + String path = this.getPluginResource(version, "/mdk.zip"); + String jarName = workspace.getPrimary().getShortName().toString(); + Path mdkPath = Extractor.getResourcePath(jarName, path); + if (mdkPath == null) { + Recaf4Forge.info("Failed to get MDK path"); + return; + } + Path extractedMDK = Extractor.extractMDK(mdkPath); + if (extractedMDK == null) { + Recaf4Forge.info("Failed to extract mdk"); + return; + } + CompletableFuture.runAsync(() -> { + exportResources(extractedMDK); + exportSrc(extractedMDK); + }).thenRunAsync(() -> { + String msg = "Successfully exported the source code to " + extractedMDK; + Recaf4Forge.info(msg); + if (recaf4Forge.getController() instanceof GuiController) { + MainWindow window = MainWindow.get((GuiController) recaf4Forge.getController()); + Notification.create(BuildInfo.name + " MDK export", msg).show(window.getRoot()); + } + }); + } + } + + + /** + * Exports resource files to the mdk + * + * @param extractedMDK the path of the mdk + */ + private void exportResources(Path extractedMDK) { + for (Map.Entry resources : recaf4Forge.getCurrentWorkspace().getPrimary().getFiles().entrySet()) { + String resourcePath = + extractedMDK.toString() + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + resources.getKey(); + Extractor.saveFile(Paths.get(resourcePath), resources.getValue()); + } + Recaf4Forge.info("Finished exporting resources"); + } + + /** + * Exports decompiled source code to the mdk + * + * @param extractedMDK the path of the mdk + */ + private void exportSrc(Path extractedMDK) { + for (Map.Entry resources : recaf4Forge.getCurrentWorkspace().getPrimary().getClasses().entrySet()) { + final String className = resources.getKey(); + String resourcePath = + extractedMDK.toString() + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator + className + ".java"; + byte[] code = DecompileImpl.CFR.create(recaf4Forge.getController()).decompile(className).getBytes(StandardCharsets.UTF_8); + Extractor.saveFile(Paths.get(resourcePath), code); + } + Recaf4Forge.info("Finished exporting source code"); + } + + public String getPluginResource(String version, String resource) { + return "/mdks/" + version.replaceAll("\\.", "_") + resource; + } +} diff --git a/src/main/java/dev/fxe/recaf_forge/Extractor.java b/src/main/java/dev/fxe/recaf4forge/Extractor.java similarity index 76% rename from src/main/java/dev/fxe/recaf_forge/Extractor.java rename to src/main/java/dev/fxe/recaf4forge/Extractor.java index a0ccdbc..39f8e32 100644 --- a/src/main/java/dev/fxe/recaf_forge/Extractor.java +++ b/src/main/java/dev/fxe/recaf4forge/Extractor.java @@ -1,9 +1,8 @@ -package dev.fxe.recaf_forge; +package dev.fxe.recaf4forge; import javafx.stage.DirectoryChooser; import me.coley.recaf.ui.controls.ExceptionAlert; import org.apache.commons.io.IOUtils; -import org.jline.utils.Log; import java.io.BufferedOutputStream; import java.io.File; @@ -22,15 +21,23 @@ public class Extractor { private static final DirectoryChooser dirChooser = new DirectoryChooser(); + /** + * Creates a temporary resource file from the jar + * + * @param name file name + * @param resourcePath path to the resource in the plugin + * @return the path of the temp file + */ public static Path getResourcePath(String name, String resourcePath) { Path resource = null; try (InputStream in = Extractor.class.getResourceAsStream(resourcePath)) { - String[] strings = resourcePath.split("\\."); - String suffix = strings[strings.length - 1]; if (in == null) { - Log.info("Failed to find resource"); + Recaf4Forge.info("Failed to find resource"); return null; } + + String[] strings = resourcePath.split("\\."); + String suffix = strings[strings.length - 1]; String fileName = name == null ? String.valueOf(in.hashCode()) : name; File tempFile = File.createTempFile(fileName, suffix); tempFile.deleteOnExit(); @@ -42,6 +49,12 @@ public static Path getResourcePath(String name, String resourcePath) { return resource; } + /** + * Extracts the mdk from this plugin + * + * @param mdkPath the mdk (e.g 1_8_9) + * @return the path of the extracted mdk + */ public static Path extractMDK(Path mdkPath) { Path exportDir = getExportDir(); if (exportDir == null) return null; @@ -65,14 +78,20 @@ public static Path extractMDK(Path mdkPath) { return exportDir; } + /** + * Saves a file to a specified location + * + * @param path location to save the file + * @param data the file data + */ public static void saveFile(Path path, byte[] data) { try { Files.createDirectories(path.getParent()); try ( - final BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream( - path, - StandardOpenOption.CREATE, - StandardOpenOption.APPEND)) + final BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream( + path, + StandardOpenOption.CREATE, + StandardOpenOption.APPEND)) ) { out.write(data); } diff --git a/src/main/java/dev/fxe/recaf_forge/Recaf4Forge.java b/src/main/java/dev/fxe/recaf4forge/Recaf4Forge.java similarity index 58% rename from src/main/java/dev/fxe/recaf_forge/Recaf4Forge.java rename to src/main/java/dev/fxe/recaf4forge/Recaf4Forge.java index 1c35317..12576a1 100644 --- a/src/main/java/dev/fxe/recaf_forge/Recaf4Forge.java +++ b/src/main/java/dev/fxe/recaf4forge/Recaf4Forge.java @@ -1,43 +1,44 @@ -package dev.fxe.recaf_forge; +package dev.fxe.recaf4forge; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonValue; +import dev.fxe.recaf4forge.gui.Notification; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import me.coley.recaf.config.Conf; import me.coley.recaf.control.Controller; -import me.coley.recaf.decompile.DecompileImpl; +import me.coley.recaf.control.gui.GuiController; import me.coley.recaf.mapping.MappingImpl; import me.coley.recaf.mapping.Mappings; import me.coley.recaf.plugin.api.ConfigurablePlugin; import me.coley.recaf.plugin.api.MenuProviderPlugin; import me.coley.recaf.plugin.api.StartupPlugin; import me.coley.recaf.plugin.api.WorkspacePlugin; +import me.coley.recaf.ui.MainWindow; import me.coley.recaf.ui.controls.ActionMenuItem; import me.coley.recaf.ui.controls.ExceptionAlert; +import me.coley.recaf.util.Log; import me.coley.recaf.util.struct.ListeningMap; import me.coley.recaf.workspace.Workspace; -import org.jline.utils.Log; import org.plugface.core.annotations.Plugin; -import java.io.File; -import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import static dev.fxe.recaf4forge.BuildInfo.*; + /** * @author Filip */ @SuppressWarnings("unused") -@Plugin(name = "Recaf4Forge") +@Plugin(name = name) public class Recaf4Forge implements ConfigurablePlugin, MenuProviderPlugin, WorkspacePlugin, StartupPlugin { - private final String[] versions = {"1.8", "1.8.9", "1.9.4"}; private final ExecutorService executor = Executors.newSingleThreadExecutor(); + private final Exporter exporter = new Exporter(this); + private Workspace currentWorkspace = null; private String currentVersion = ""; private Controller controller; @@ -45,19 +46,22 @@ public class Recaf4Forge implements ConfigurablePlugin, MenuProviderPlugin, Work @Conf(value = "Automatically apply mappings", noTranslate = true) private boolean autoApply = false; + @Conf(value = "Notifications", noTranslate = true) + private boolean notify = false; + @Override public String getName() { - return "Recaf4Forge"; + return name; } @Override public String getVersion() { - return "1.0.5"; + return version; } @Override public String getDescription() { - return "Recaf4Forge will automatically try apply the correct mappings for a forge mod"; + return description; } @Override @@ -74,11 +78,36 @@ public void onOpened(Workspace workspace) { } } + @Override + public String getConfigTabTitle() { + return name; + } + + @Override + public void onStart(Controller controller) { + this.controller = controller; + } + + @Override + public Menu createMenu() { + MenuItem[] itemList = new MenuItem[versions.length + 1]; + int index = 0; + for (String version : versions) { + itemList[index] = new ActionMenuItem(version, () -> { + currentVersion = version; + CompletableFuture.runAsync(this::applyMapping, executor); + }); + index++; + } + itemList[index] = new ActionMenuItem("Export MDK", exporter::exportMDK); + return new Menu(getName(), null, itemList); + } + private void applyMapping() { - String path = getResourcesPath("/mappings.srg"); + String path = exporter.getPluginResource(this.currentVersion, "/mappings.srg"); Path mappingPath = Extractor.getResourcePath(null, path); if (mappingPath == null) { - Log.info(getName() + " Could not find mappings"); + info("Could not find mappings, is the resource null?"); return; } try { @@ -86,49 +115,16 @@ private void applyMapping() { mappings.setCheckFieldHierarchy(true); mappings.setCheckMethodHierarchy(true); mappings.accept(currentWorkspace.getPrimary()); + info("Finished applying mappings"); + if (this.getController() instanceof GuiController && this.notify) { + MainWindow window = MainWindow.get((GuiController) this.getController()); + Notification.create(this.getName() + " Mappings", "Successfully applied mappings!").show(window.getRoot()); + } } catch (Exception ex) { ExceptionAlert.show(ex, getName() + " Failed to apply mappings"); } } - private void exportMDK() { - if (!currentVersion.equalsIgnoreCase("") && currentWorkspace != null) { - String path = getResourcesPath("/mdk.zip"); - String jarName = currentWorkspace.getPrimary().getShortName().toString(); - Path mdkPath = Extractor.getResourcePath(jarName, path); - if (mdkPath == null) return; - Path extractedMDK = Extractor.extractMDK(mdkPath); - if (extractedMDK == null) return; - CompletableFuture.runAsync(() -> { - exportResources(extractedMDK); - exportSrc(extractedMDK); - }); - } - } - - - private void exportResources(Path extractedMDK) { - for (Map.Entry resources : currentWorkspace.getPrimary().getFiles().entrySet()) { - String resourcePath = - extractedMDK.toString() + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + resources.getKey(); - Extractor.saveFile(Paths.get(resourcePath), resources.getValue()); - } - } - - private void exportSrc(Path extractedMDK) { - for (Map.Entry resources : currentWorkspace.getPrimary().getClasses().entrySet()) { - final String className = resources.getKey(); - String resourcePath = - extractedMDK.toString() + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator + className + ".java"; - byte[] code = DecompileImpl.CFR.create(this.controller).decompile(className).getBytes(StandardCharsets.UTF_8); - Extractor.saveFile(Paths.get(resourcePath), code); - } - } - - private String getResourcesPath(String resource) { - return "/mdks/" + currentVersion.replaceAll("\\.", "_") + resource; - } - private void detectVersion() { ListeningMap data = currentWorkspace.getPrimary().getFiles(); byte[] mcModInfo = data.get("mcmod.info"); @@ -136,38 +132,28 @@ private void detectVersion() { String version = jsonValue.asArray().get(0).asObject().get("mcversion").asString(); for (String s : versions) { if (s.equalsIgnoreCase(version)) { - currentVersion = version; + this.currentVersion = version; applyMapping(); return; } } - Log.info(getName() + " Failed to find mod version"); + info("Failed to find mod version"); currentVersion = ""; } - @Override - public Menu createMenu() { - MenuItem[] itemList = new MenuItem[versions.length + 1]; - int index = 0; - for (String version : versions) { - itemList[index] = new ActionMenuItem(version, () -> { - currentVersion = version; - CompletableFuture.runAsync(this::applyMapping, executor); - }); - index++; - } - itemList[index] = new ActionMenuItem("Export MDK", this::exportMDK); - return new Menu(getName(), null, itemList); + public String getCurrentVersion() { + return this.currentVersion; } - @Override - public String getConfigTabTitle() { - return getName(); + public Workspace getCurrentWorkspace() { + return this.currentWorkspace; } - @Override - public void onStart(Controller controller) { - this.controller = controller; + public Controller getController() { + return this.controller; + } + public static void info(String msg) { + Log.info(name + " " + msg); } } diff --git a/src/main/java/dev/fxe/recaf4forge/gui/Notification.java b/src/main/java/dev/fxe/recaf4forge/gui/Notification.java new file mode 100644 index 0000000..ebd36d1 --- /dev/null +++ b/src/main/java/dev/fxe/recaf4forge/gui/Notification.java @@ -0,0 +1,31 @@ +package dev.fxe.recaf4forge.gui; + +import javafx.geometry.HPos; +import javafx.geometry.Insets; +import javafx.geometry.Pos; +import javafx.scene.Node; +import javafx.scene.control.Control; +import javafx.scene.control.Label; +import javafx.scene.layout.GridPane; +import me.coley.recaf.ui.controls.popup.DragPopup; + +public class Notification extends DragPopup { + + public Notification(Node content, Control handle) { + super(content, handle); + } + + public static Notification create(String title, String msg) { + Label lblTitle = new Label(title); + Label lblMsg = new Label(msg); + lblTitle.getStyleClass().add("h1"); + GridPane grid = new GridPane(); + GridPane.setHalignment(lblMsg, HPos.CENTER); + grid.setPadding(new Insets(15)); + grid.setHgap(10); + grid.setVgap(10); + grid.setAlignment(Pos.CENTER); + grid.add(lblMsg, 0, 1, 2, 1); + return new Notification(grid, lblTitle); + } +}