diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..48f6c91 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,39 @@ +# Automatically build the project and run any configured tests for every push +# and submitted pull request. This can help catch issues that only occur on +# certain platforms or Java versions, and provides a first line of defence +# against bad commits. + +name: build +on: [pull_request, push] + +jobs: + build: + strategy: + matrix: + # Use these Java versions + java: [ + 16 # Minimum supported by Minecraft + ] + # and run on both Linux and Windows + os: [ubuntu-20.04, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - name: checkout repository + uses: actions/checkout@v2 + - name: validate gradle wrapper + uses: gradle/wrapper-validation-action@v1 + - name: setup jdk ${{ matrix.java }} + uses: actions/setup-java@v1 + with: + java-version: ${{ matrix.java }} + - name: make gradle wrapper executable + if: ${{ runner.os != 'Windows' }} + run: chmod +x ./gradlew + - name: build + run: ./gradlew build + - name: capture build artifacts + if: ${{ runner.os == 'Linux' && matrix.java == '16' }} # Only upload artifacts built from latest java on one OS + uses: actions/upload-artifact@v2 + with: + name: Artifacts + path: build/libs/ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..09cd281 --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +# gradle + +.gradle/ +build/ +out/ +classes/ + +# eclipse + +*.launch + +# idea + +.idea/ +*.iml +*.ipr +*.iws + +# vscode + +.settings/ +.vscode/ +bin/ +.classpath +.project + +# macos + +*.DS_Store + +# fabric + +run/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..153d416 --- /dev/null +++ b/LICENSE @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..f477dac --- /dev/null +++ b/README.md @@ -0,0 +1,73 @@ +# Styled Chat +It's a simple mod that allows server owners to change how their chat looks! +It supports changing style per player with permissions (supports LuckPerms and PlayerRoles) +If you have any questions, you can ask them on my [Discord](https://discord.com/invite/AbqPPppgrd) + +![Example image](https://i.imgur.com/y0KGyVT.png) +![Example image2](https://i.imgur.com/ObepOhW.png) + + +## Commands (and permissions): +- `/styledchat` - Main command (`styledchat.main`, available by default) +- `/styledchatreload` - Reloads configuration and styles (requires `styledchat.reload`) + +## Configuration: +You can find config file in `./config/styled-chat.json`. +[Formatting uses PlaceholderAPI's Text Parser for which docs you can find here](https://github.com/Patbox/FabricPlaceholderAPI/blob/1.17/TEXT_FORMATTING.md). +It supports usage of placeholders from [Placeholder API](https://github.com/Patbox/FabricPlaceholderAPI/wiki). +Additionally, every message type has few own local variables. + +```json5 +{ + "CONFIG_VERSION_DONT_TOUCH_THIS": 1, + "defaultStyle": { // Default style settings + "displayName": "...", // Display name (local variables: ${vanillaDisplayName}, ${name}) + "chat": "...", // Chat message style (local variables: ${player}, ${message}) + "join": "...", // Join message (local variables: ${player}) + "joinRenamed": "...", // Join message after name change (local variables: ${player}, ${old_name}) + "left": "...", // Player leaving server (local variables: ${player}) + "death": "...", // Player death message (local variables: ${player}, ${default_message}) + "advancementTask": "...", // Finishing advancement task (local variables: ${player}, ${advancement}) + "advancementChallenge": "...", // Finishing advancement challenge (local variables: ${player}, ${advancement}) + "advancementGoal": "...", // Finishing advancement goal (local variables: ${player}, ${advancement}) + }, + "permissionStyles": { // Permission based overrides, applied from highest to lowest + "permission.test": { // Permission string required to use + // The same values as in "defaultStyle", however it will handle missing ones just fine + // By applying next valid + } + } +} +``` + +## In chat formatting +If player has a required permissions (`styledchat.format.[tag_name]`, where `[tagname]` is Text Parser tag), then they can use Text Parser's formatting tags from within their chat. +It supports all default ones with addition of `` tag. + + +## Example config +```json +{ + "CONFIG_VERSION_DONT_TOUCH_THIS": 1, + "_comment": "Before changing anything, see https://github.com/Patbox/StyledChat#configuration", + "defaultStyle": { + "displayName": "${vanillaDisplayName}", + "chat": "${player} » ${message}", + "join": " ", + "joinRenamed": " ", + "left": " ", + "death": " ${default_message}", + "advancementTask": " ", + "advancementChallenge": " ", + "advancementGoal": " " + }, + "permissionStyles": { + "group.admin": { + "chat": "${player} » ${message}" + }, + "group.test": { + "displayName": "[Admin | %player:playtime%] ${vanillaDisplayName}" + } + } +} +``` \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..86d9463 --- /dev/null +++ b/build.gradle @@ -0,0 +1,97 @@ +plugins { + id 'fabric-loom' version '0.8-SNAPSHOT' + id 'maven-publish' +} + +sourceCompatibility = JavaVersion.VERSION_16 +targetCompatibility = JavaVersion.VERSION_16 + +archivesBaseName = project.archives_base_name +version = project.mod_version +group = project.maven_group + +repositories { + // Add repositories to retrieve artifacts from in here. + // You should only use this when depending on other mods because + // Loom adds the essential maven repositories to download Minecraft and libraries from automatically. + // See https://docs.gradle.org/current/userguide/declaring_repositories.html + // for more information about repositories. + + maven { url 'https://oss.sonatype.org/content/repositories/snapshots' } + maven { url 'https://maven.nucleoid.xyz' } + maven { url 'https://maven.gegy.dev' } + +} + +dependencies { + // To change the versions see the gradle.properties file + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + + // Fabric API. This is technically optional, but you probably want it anyway. + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + + + modImplementation include("eu.pb4:placeholder-api:1.0.0-rc1-1.17") + modImplementation include("me.lucko:fabric-permissions-api:0.1-SNAPSHOT") + + modRuntime "supercoder79:databreaker:0.2.7" + // PSA: Some older mods, compiled on Loom 0.2.1, might have outdated Maven POMs. + // You may need to force-disable transitiveness on them. +} + +processResources { + inputs.property "version", project.version + + filesMatching("fabric.mod.json") { + expand "version": project.version + } +} + +tasks.withType(JavaCompile).configureEach { + // ensure that the encoding is set to UTF-8, no matter what the system default is + // this fixes some edge cases with special characters not displaying correctly + // see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html + // If Javadoc is generated, this must be specified in that task too. + it.options.encoding = "UTF-8" + + // Minecraft 1.17 (21w19a) upwards uses Java 16. + it.options.release = 16 +} + +java { + // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task + // if it is present. + // If you remove this line, sources will not be generated. + withSourcesJar() +} + +jar { + from("LICENSE") { + rename { "${it}_${project.archivesBaseName}"} + } +} + +// configure the maven publication +publishing { + publications { + mavenJava(MavenPublication) { + // add all the jars that should be included when publishing to maven + artifact(remapJar) { + builtBy remapJar + } + artifact(sourcesJar) { + builtBy remapSourcesJar + } + } + } + + // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. + repositories { + // Add repositories to publish to here. + // Notice: This block does NOT have the same function as the block in the top level. + // The repositories here will be used for publishing your artifact, not for + // retrieving dependencies. + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..a8acb15 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,16 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs=-Xmx1G + +# Fabric Properties + # check these on https://fabricmc.net/use + minecraft_version=1.17 + yarn_mappings=1.17+build.1 + loader_version=0.11.3 + +# Mod Properties + mod_version = 1.0.0 + maven_group = eu.pb4 + archives_base_name = styled-chat + +# Dependencies + fabric_version=0.34.9+1.17 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..0f80bbf --- /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-7.0.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 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/logo.png b/logo.png new file mode 100644 index 0000000..84c34c3 Binary files /dev/null and b/logo.png differ diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..f91a4fe --- /dev/null +++ b/settings.gradle @@ -0,0 +1,9 @@ +pluginManagement { + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + gradlePluginPortal() + } +} diff --git a/src/main/java/eu/pb4/styledchat/StyledChatMod.java b/src/main/java/eu/pb4/styledchat/StyledChatMod.java new file mode 100644 index 0000000..359e7e6 --- /dev/null +++ b/src/main/java/eu/pb4/styledchat/StyledChatMod.java @@ -0,0 +1,21 @@ +package eu.pb4.styledchat; + +import eu.pb4.styledchat.command.Commands; +import eu.pb4.styledchat.config.ConfigManager; +import net.fabricmc.api.ModInitializer; +import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; +import net.fabricmc.loader.api.FabricLoader; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + + +public class StyledChatMod implements ModInitializer { + public static final Logger LOGGER = LogManager.getLogger("Styled Chat"); + public static String VERSION = FabricLoader.getInstance().getModContainer("styledchat").get().getMetadata().getVersion().getFriendlyString(); + + @Override + public void onInitialize() { + Commands.register(); + ServerLifecycleEvents.SERVER_STARTING.register((s) -> ConfigManager.loadConfig()); + } +} diff --git a/src/main/java/eu/pb4/styledchat/command/Commands.java b/src/main/java/eu/pb4/styledchat/command/Commands.java new file mode 100644 index 0000000..d365500 --- /dev/null +++ b/src/main/java/eu/pb4/styledchat/command/Commands.java @@ -0,0 +1,59 @@ +package eu.pb4.styledchat.command; + + +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.RequiredArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import eu.pb4.styledchat.StyledChatMod; +import eu.pb4.styledchat.config.ConfigManager; +import me.lucko.fabric.api.permissions.v0.Permissions; +import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback; +import net.minecraft.command.argument.EntityArgumentType; +import net.minecraft.server.command.CommandManager; +import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.text.LiteralText; +import net.minecraft.util.Formatting; + +import java.util.Collection; +import java.util.Locale; + +import static net.minecraft.server.command.CommandManager.literal; + +public class Commands { + public static void register() { + CommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> { + dispatcher.register( + literal("styledchat") + .requires(Permissions.require("styledchat.main", true)) + .executes(Commands::about) + + .then(literal("reload") + .requires(Permissions.require("styledchat.reload", 3)) + .executes(Commands::reloadConfig) + ) + ); + }); + } + + private static int reloadConfig(CommandContext context) { + if (ConfigManager.loadConfig()) { + context.getSource().sendFeedback(new LiteralText("Reloaded config!"), false); + } else { + context.getSource().sendError(new LiteralText("Error accrued while reloading config!").formatted(Formatting.RED)); + + } + return 1; + } + + private static int about(CommandContext context) { + context.getSource().sendFeedback(new LiteralText("Styled Chat") + .formatted(Formatting.YELLOW) + .append(new LiteralText( " - " + StyledChatMod.VERSION) + .formatted(Formatting.WHITE) + ), false); + + return 1; + } +} diff --git a/src/main/java/eu/pb4/styledchat/config/ChatStyle.java b/src/main/java/eu/pb4/styledchat/config/ChatStyle.java new file mode 100644 index 0000000..9507c11 --- /dev/null +++ b/src/main/java/eu/pb4/styledchat/config/ChatStyle.java @@ -0,0 +1,163 @@ +package eu.pb4.styledchat.config; + +import eu.pb4.placeholders.PlaceholderAPI; +import eu.pb4.placeholders.TextParser; +import eu.pb4.styledchat.config.data.ChatStyleData; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.text.LiteralText; +import net.minecraft.text.Text; + +import java.util.Map; + +public class ChatStyle { + public final Text displayName; + public final Text chat; + public final Text join; + public final Text joinRenamed; + public final Text left; + public final Text death; + public final Text advancementTask; + public final Text advancementChallenge; + public final Text advancementGoal; + + public ChatStyle(ChatStyleData data, ChatStyle defaultStyle) { + this.displayName = data.displayName != null ? TextParser.parse(data.displayName.replace("%player:displayname%", "")) : defaultStyle.displayName; + this.chat = data.chat != null ? TextParser.parse(data.chat) : defaultStyle.chat; + this.join = data.join != null ? TextParser.parse(data.join) : defaultStyle.join; + this.joinRenamed = data.joinRenamed != null ? TextParser.parse(data.joinRenamed) : defaultStyle.joinRenamed; + this.left = data.left != null ? TextParser.parse(data.left) : defaultStyle.left; + this.death = data.death != null ? TextParser.parse(data.death) : defaultStyle.death; + this.advancementTask = data.advancementTask != null ? TextParser.parse(data.advancementTask) : defaultStyle.advancementTask; + this.advancementChallenge = data.advancementChallenge != null ? TextParser.parse(data.advancementChallenge) : defaultStyle.advancementChallenge; + this.advancementGoal = data.advancementGoal != null ? TextParser.parse(data.advancementGoal) : defaultStyle.advancementGoal; + + } + + public ChatStyle(ChatStyleData data) { + this.displayName = data.displayName != null ? TextParser.parse(data.displayName.replace("%player:displayname%", "")) : null; + this.chat = data.chat != null ? TextParser.parse(data.chat) : null; + this.join = data.join != null ? TextParser.parse(data.join) : null; + this.joinRenamed = data.joinRenamed != null ? TextParser.parse(data.joinRenamed) : null; + this.left = data.left != null ? TextParser.parse(data.left) : null; + this.death = data.death != null ? TextParser.parse(data.death) : null; + this.advancementTask = data.advancementTask != null ? TextParser.parse(data.advancementTask) : null; + this.advancementChallenge = data.advancementChallenge != null ? TextParser.parse(data.advancementChallenge) : null; + this.advancementGoal = data.advancementGoal != null ? TextParser.parse(data.advancementGoal) : null; + + } + + public Text getDisplayName(ServerPlayerEntity player, Text vanillaDisplayName) { + if (this.displayName == null) { + return null; + } + + return PlaceholderAPI.parsePredefinedText( + PlaceholderAPI.parseText(this.displayName, player), + PlaceholderAPI.PREDEFINED_PLACEHOLDER_PATTERN, + Map.of("vanillaDisplayName", vanillaDisplayName, + "name", player.getName()) + ); + } + + public Text getChat(ServerPlayerEntity player, Text message) { + if (this.chat == null) { + return null; + } + + return PlaceholderAPI.parsePredefinedText( + PlaceholderAPI.parseText(this.chat, player), + PlaceholderAPI.PREDEFINED_PLACEHOLDER_PATTERN, + Map.of("player", player.getDisplayName(), + "message", message) + ); + } + + public Text getJoin(ServerPlayerEntity player) { + if (this.join == null) { + return null; + } + + return PlaceholderAPI.parsePredefinedText( + PlaceholderAPI.parseText(this.join, player), + PlaceholderAPI.PREDEFINED_PLACEHOLDER_PATTERN, + Map.of("player", player.getDisplayName()) + ); + } + + public Text getJoinRenamed(ServerPlayerEntity player, String oldName) { + if (this.joinRenamed == null) { + return null; + } + + return PlaceholderAPI.parsePredefinedText( + PlaceholderAPI.parseText(this.joinRenamed, player), + PlaceholderAPI.PREDEFINED_PLACEHOLDER_PATTERN, + Map.of("player", player.getDisplayName(), + "old_name", new LiteralText(oldName)) + ); + } + + public Text getLeft(ServerPlayerEntity player) { + if (this.left == null) { + return null; + } + + return PlaceholderAPI.parsePredefinedText( + PlaceholderAPI.parseText(this.left, player), + PlaceholderAPI.PREDEFINED_PLACEHOLDER_PATTERN, + Map.of("player", player.getDisplayName()) + ); + } + + public Text getDeath(ServerPlayerEntity player, Text vanillaMessage) { + if (this.death == null) { + return null; + } + + return PlaceholderAPI.parsePredefinedText( + PlaceholderAPI.parseText(this.death, player), + PlaceholderAPI.PREDEFINED_PLACEHOLDER_PATTERN, + Map.of("player", player.getDisplayName(), + "default_message", vanillaMessage) + ); + } + + public Text getAdvancementGoal(ServerPlayerEntity player, Text advancement) { + if (this.advancementGoal == null) { + return null; + } + + return PlaceholderAPI.parsePredefinedText( + PlaceholderAPI.parseText(this.advancementGoal, player), + PlaceholderAPI.PREDEFINED_PLACEHOLDER_PATTERN, + Map.of("player", player.getDisplayName(), + "advancement", advancement) + ); + } + + public Text getAdvancementTask(ServerPlayerEntity player, Text advancement) { + if (this.advancementTask == null) { + return null; + } + + return PlaceholderAPI.parsePredefinedText( + PlaceholderAPI.parseText(this.advancementTask, player), + PlaceholderAPI.PREDEFINED_PLACEHOLDER_PATTERN, + Map.of("player", player.getDisplayName(), + "advancement", advancement) + ); + } + + public Text getAdvancementChallenge(ServerPlayerEntity player, Text advancement) { + if (this.advancementChallenge == null) { + return null; + } + + return PlaceholderAPI.parsePredefinedText( + PlaceholderAPI.parseText(this.advancementChallenge, player), + PlaceholderAPI.PREDEFINED_PLACEHOLDER_PATTERN, + Map.of("player", player.getDisplayName(), + "advancement", advancement) + ); + } +} diff --git a/src/main/java/eu/pb4/styledchat/config/Config.java b/src/main/java/eu/pb4/styledchat/config/Config.java new file mode 100644 index 0000000..35f2577 --- /dev/null +++ b/src/main/java/eu/pb4/styledchat/config/Config.java @@ -0,0 +1,159 @@ +package eu.pb4.styledchat.config; + + +import com.google.common.collect.ImmutableMap; +import eu.pb4.placeholders.TextParser; +import eu.pb4.styledchat.config.data.ChatStyleData; +import eu.pb4.styledchat.config.data.ConfigData; +import me.lucko.fabric.api.permissions.v0.Permissions; +import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.text.Text; +import net.minecraft.util.math.MathHelper; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public final class Config { + //private final ConfigData configData; + private final ChatStyle defaultStyle; + private final List permissionStyle; + + public Config(ConfigData data) { + //this.configData = data; + this.defaultStyle = new ChatStyle(data.defaultStyle, new ChatStyle(ChatStyleData.getDefault())); + + this.permissionStyle = new ArrayList<>(); + + for (Map.Entry entry : data.permissionStyles.entrySet()) { + try { + this.permissionStyle.add(new PermissionStyle(entry.getKey(), MathHelper.clamp(Integer.parseInt(entry.getKey()), 1, 4), new ChatStyle(entry.getValue()))); + } catch (Exception e) { + this.permissionStyle.add(new PermissionStyle(entry.getKey(), 4, new ChatStyle(entry.getValue()))); + } + } + + } + + public Text getDisplayName(ServerPlayerEntity player, Text vanillaDisplayName) { + ServerCommandSource source = player.getCommandSource(); + for (PermissionStyle entry : this.permissionStyle) { + if (Permissions.check(source, entry.permission, entry.opLevel)) { + Text text = entry.style.getDisplayName(player, vanillaDisplayName); + if (text != null) { + return text; + } + } + } + return this.defaultStyle.getDisplayName(player, vanillaDisplayName); + } + + public Text getChat(ServerPlayerEntity player, Text message) { + ServerCommandSource source = player.getCommandSource(); + for (PermissionStyle entry : this.permissionStyle) { + if (Permissions.check(source, entry.permission, entry.opLevel)) { + Text text = entry.style.getChat(player, message); + if (text != null) { + return text; + } + } + } + return this.defaultStyle.getChat(player, message); + } + + public Text getJoin(ServerPlayerEntity player) { + ServerCommandSource source = player.getCommandSource(); + for (PermissionStyle entry : this.permissionStyle) { + if (Permissions.check(source, entry.permission, entry.opLevel)) { + Text text = entry.style.getJoin(player); + if (text != null) { + return text; + } + } + } + return this.defaultStyle.getJoin(player); + } + + public Text getJoinRenamed(ServerPlayerEntity player, String oldName) { + ServerCommandSource source = player.getCommandSource(); + for (PermissionStyle entry : this.permissionStyle) { + if (Permissions.check(source, entry.permission, entry.opLevel)) { + Text text = entry.style.getJoinRenamed(player, oldName); + if (text != null) { + return text; + } + } + } + return this.defaultStyle.getJoinRenamed(player, oldName); + } + + public Text getLeft(ServerPlayerEntity player) { + ServerCommandSource source = player.getCommandSource(); + for (PermissionStyle entry : this.permissionStyle) { + if (Permissions.check(source, entry.permission, entry.opLevel)) { + Text text = entry.style.getLeft(player); + if (text != null) { + return text; + } + } + } + return this.defaultStyle.getLeft(player); + } + + public Text getDeath(ServerPlayerEntity player, Text vanillaMessage) { + ServerCommandSource source = player.getCommandSource(); + for (PermissionStyle entry : this.permissionStyle) { + if (Permissions.check(source, entry.permission, entry.opLevel)) { + Text text = entry.style.getDeath(player, vanillaMessage); + if (text != null) { + return text; + } + } + } + return this.defaultStyle.getDeath(player, vanillaMessage); + } + + public Text getAdvancementTask(ServerPlayerEntity player, Text advancement) { + ServerCommandSource source = player.getCommandSource(); + for (PermissionStyle entry : this.permissionStyle) { + if (Permissions.check(source, entry.permission, entry.opLevel)) { + Text text = entry.style.getAdvancementTask(player, advancement); + if (text != null) { + return text; + } + } + } + return this.defaultStyle.getAdvancementTask(player, advancement); + } + + public Text getAdvancementGoal(ServerPlayerEntity player, Text advancement) { + ServerCommandSource source = player.getCommandSource(); + for (PermissionStyle entry : this.permissionStyle) { + if (Permissions.check(source, entry.permission, entry.opLevel)) { + Text text = entry.style.getAdvancementGoal(player, advancement); + if (text != null) { + return text; + } + } + } + return this.defaultStyle.getAdvancementGoal(player, advancement); + } + + public Text getAdvancementChallenge(ServerPlayerEntity player, Text advancement) { + ServerCommandSource source = player.getCommandSource(); + for (PermissionStyle entry : this.permissionStyle) { + if (Permissions.check(source, entry.permission, entry.opLevel)) { + Text text = entry.style.getAdvancementChallenge(player, advancement); + if (text != null) { + return text; + } + } + } + return this.defaultStyle.getAdvancementChallenge(player, advancement); + } + + private static record PermissionStyle(String permission, int opLevel, ChatStyle style) { + } +} diff --git a/src/main/java/eu/pb4/styledchat/config/ConfigManager.java b/src/main/java/eu/pb4/styledchat/config/ConfigManager.java new file mode 100644 index 0000000..2137336 --- /dev/null +++ b/src/main/java/eu/pb4/styledchat/config/ConfigManager.java @@ -0,0 +1,56 @@ +package eu.pb4.styledchat.config; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import eu.pb4.styledchat.StyledChatMod; +import eu.pb4.styledchat.config.data.ConfigData; +import net.fabricmc.loader.api.FabricLoader; + +import java.io.*; + +public class ConfigManager { + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); + + private static Config CONFIG; + private static boolean ENABLED = false; + + public static Config getConfig() { + return CONFIG; + } + + public static boolean isEnabled() { + return ENABLED; + } + + public static boolean loadConfig() { + ENABLED = false; + + CONFIG = null; + try { + ConfigData config; + File configFile = new File(FabricLoader.getInstance().getConfigDir().toFile(), "styled-chat.json"); + + + if (configFile.exists()) { + config = GSON.fromJson(new InputStreamReader(new FileInputStream(configFile), "UTF-8"), ConfigData.class); + } else { + config = new ConfigData(); + } + + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(configFile), "UTF-8")); + writer.write(GSON.toJson(config)); + writer.close(); + + + CONFIG = new Config(config); + ENABLED = true; + } + catch(IOException exception) { + ENABLED = false; + StyledChatMod.LOGGER.error("Something went wrong while reading config!"); + exception.printStackTrace(); + } + + return ENABLED; + } +} diff --git a/src/main/java/eu/pb4/styledchat/config/data/ChatStyleData.java b/src/main/java/eu/pb4/styledchat/config/data/ChatStyleData.java new file mode 100644 index 0000000..4caf0da --- /dev/null +++ b/src/main/java/eu/pb4/styledchat/config/data/ChatStyleData.java @@ -0,0 +1,30 @@ +package eu.pb4.styledchat.config.data; + + +public class ChatStyleData { + public String displayName; + public String chat; + public String join; + public String joinRenamed; + public String left; + public String death; + public String advancementTask; + public String advancementChallenge; + public String advancementGoal; + + + public static ChatStyleData getDefault() { + ChatStyleData data = new ChatStyleData(); + data.displayName = "${vanillaDisplayName}"; + data.chat = "<${player}> ${message}"; + data.join = ""; + data.joinRenamed = ""; + data.left = ""; + data.death = "${default_message}"; + data.advancementTask = ""; + data.advancementGoal = ""; + data.advancementChallenge = ""; + + return data; + } +} diff --git a/src/main/java/eu/pb4/styledchat/config/data/ConfigData.java b/src/main/java/eu/pb4/styledchat/config/data/ConfigData.java new file mode 100644 index 0000000..1630787 --- /dev/null +++ b/src/main/java/eu/pb4/styledchat/config/data/ConfigData.java @@ -0,0 +1,9 @@ +package eu.pb4.styledchat.config.data; + +import java.util.HashMap; +public class ConfigData { + public int CONFIG_VERSION_DONT_TOUCH_THIS = 1; + public String _comment = "Before changing anything, see https://github.com/Patbox/StyledChat#configuration"; + public ChatStyleData defaultStyle = ChatStyleData.getDefault(); + public HashMap permissionStyles = new HashMap<>(); +} diff --git a/src/main/java/eu/pb4/styledchat/mixin/PlayerAdvancementTrackerMixin.java b/src/main/java/eu/pb4/styledchat/mixin/PlayerAdvancementTrackerMixin.java new file mode 100644 index 0000000..e121fc3 --- /dev/null +++ b/src/main/java/eu/pb4/styledchat/mixin/PlayerAdvancementTrackerMixin.java @@ -0,0 +1,33 @@ +package eu.pb4.styledchat.mixin; + +import eu.pb4.styledchat.config.Config; +import eu.pb4.styledchat.config.ConfigManager; +import net.minecraft.advancement.PlayerAdvancementTracker; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.text.Text; +import net.minecraft.text.TranslatableText; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; + +@Mixin(PlayerAdvancementTracker.class) +public class PlayerAdvancementTrackerMixin { + + @Shadow private ServerPlayerEntity owner; + + @ModifyArg(method = "grantCriterion", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/PlayerManager;broadcastChatMessage(Lnet/minecraft/text/Text;Lnet/minecraft/network/MessageType;Ljava/util/UUID;)V")) + private Text changeAdvancementMessage(Text text) { + TranslatableText translatableText = (TranslatableText) text; + + Config config = ConfigManager.getConfig(); + Text advancement = (Text) translatableText.getArgs()[1]; + + return switch (translatableText.getKey()) { + case "chat.type.advancement.task" -> config.getAdvancementTask(this.owner, advancement); + case "chat.type.advancement.goal" -> config.getAdvancementGoal(this.owner, advancement); + case "chat.type.advancement.challenge" -> config.getAdvancementChallenge(this.owner, advancement); + default -> text; + }; + } +} diff --git a/src/main/java/eu/pb4/styledchat/mixin/PlayerEntityMixin.java b/src/main/java/eu/pb4/styledchat/mixin/PlayerEntityMixin.java new file mode 100644 index 0000000..bea02d3 --- /dev/null +++ b/src/main/java/eu/pb4/styledchat/mixin/PlayerEntityMixin.java @@ -0,0 +1,25 @@ +package eu.pb4.styledchat.mixin; + +import eu.pb4.styledchat.config.ConfigManager; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.text.Text; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +@Mixin(PlayerEntity.class) +public class PlayerEntityMixin { + @Unique private boolean ignoreNextCalls = false; + + @Inject(method = "getDisplayName", at = @At("RETURN"), cancellable = true) + private void replaceDisplayName(CallbackInfoReturnable cir) { + if (!this.ignoreNextCalls && ((Object) this) instanceof ServerPlayerEntity player) { + this.ignoreNextCalls = true; + cir.setReturnValue(ConfigManager.getConfig().getDisplayName(player, cir.getReturnValue())); + this.ignoreNextCalls = false; + } + } +} diff --git a/src/main/java/eu/pb4/styledchat/mixin/PlayerManagerMixin.java b/src/main/java/eu/pb4/styledchat/mixin/PlayerManagerMixin.java new file mode 100644 index 0000000..4e2cb29 --- /dev/null +++ b/src/main/java/eu/pb4/styledchat/mixin/PlayerManagerMixin.java @@ -0,0 +1,42 @@ +package eu.pb4.styledchat.mixin; + +import eu.pb4.styledchat.config.ConfigManager; +import net.minecraft.network.ClientConnection; +import net.minecraft.server.PlayerManager; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.text.Text; +import net.minecraft.text.TranslatableText; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + + +@Mixin(PlayerManager.class) +public class PlayerManagerMixin { + + @Unique private ServerPlayerEntity temporaryPlayer = null; + + @Inject(method = "onPlayerConnect", at = @At(value = "HEAD")) + private void storePlayer(ClientConnection connection, ServerPlayerEntity player, CallbackInfo ci) { + this.temporaryPlayer = player; + } + + @Inject(method = "onPlayerConnect", at = @At("RETURN")) + private void removeStoredPlayer(ClientConnection connection, ServerPlayerEntity player, CallbackInfo ci) { + this.temporaryPlayer = null; + } + + @ModifyArg(method = "onPlayerConnect", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/PlayerManager;broadcastChatMessage(Lnet/minecraft/text/Text;Lnet/minecraft/network/MessageType;Ljava/util/UUID;)V")) + private Text updatePlayerNameAfterMessage(Text text) { + Object[] args = ((TranslatableText) text).getArgs(); + + if (args.length == 1) { + return ConfigManager.getConfig().getJoin(this.temporaryPlayer); + } else { + return ConfigManager.getConfig().getJoinRenamed(this.temporaryPlayer, (String) args[1]); + } + } +} diff --git a/src/main/java/eu/pb4/styledchat/mixin/ServerPlayNetworkManagerMixin.java b/src/main/java/eu/pb4/styledchat/mixin/ServerPlayNetworkManagerMixin.java new file mode 100644 index 0000000..c32be97 --- /dev/null +++ b/src/main/java/eu/pb4/styledchat/mixin/ServerPlayNetworkManagerMixin.java @@ -0,0 +1,61 @@ +package eu.pb4.styledchat.mixin; + + +import eu.pb4.placeholders.TextParser; +import eu.pb4.placeholders.util.GeneralUtils; +import eu.pb4.styledchat.config.ConfigManager; +import me.lucko.fabric.api.permissions.v0.Permissions; +import net.minecraft.network.MessageType; +import net.minecraft.server.PlayerManager; +import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.server.filter.TextStream; +import net.minecraft.server.network.ServerPlayNetworkHandler; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.text.LiteralText; +import net.minecraft.text.MutableText; +import net.minecraft.text.Text; +import net.minecraft.text.TranslatableText; +import net.minecraft.util.Hand; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.Redirect; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; + + +@Mixin(ServerPlayNetworkHandler.class) +public class ServerPlayNetworkManagerMixin { + + @Shadow + public ServerPlayerEntity player; + + @ModifyArg(method = "onDisconnected", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/PlayerManager;broadcastChatMessage(Lnet/minecraft/text/Text;Lnet/minecraft/network/MessageType;Ljava/util/UUID;)V")) + private Text replaceDisconnectMessage(Text text) { + return ConfigManager.getConfig().getLeft(this.player); + } + + @Redirect(method = "handleMessage", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/PlayerManager;broadcast(Lnet/minecraft/text/Text;Ljava/util/function/Function;Lnet/minecraft/network/MessageType;Ljava/util/UUID;)V")) + private void replaceChatMessage(PlayerManager playerManager, Text serverMessage, Function playerMessageFactory, MessageType playerMessageType, UUID sender, TextStream.Message message) { + HashMap handlers = new HashMap<>(); + ServerCommandSource source = this.player.getCommandSource(); + for (Map.Entry entry : TextParser.getRegisteredTags().entrySet()) { + if (Permissions.check(source, "styledchat.format." + entry.getKey(), 2)) { + handlers.put(entry.getKey(), entry.getValue()); + } + } + + if (Permissions.check(source, "styledchat.format.item", 1)) { + handlers.put("item", (tag, data, input, buildInHandlers, endAt) -> new GeneralUtils.TextLengthPair((MutableText) player.getStackInHand(Hand.MAIN_HAND).toHoverableText(), 0)); + } + + Text rawText = ConfigManager.getConfig().getChat(this.player, handlers.size() > 0 ? TextParser.parse(message.getRaw(), handlers) : new LiteralText(message.getRaw())); + Text filteredText = ConfigManager.getConfig().getChat(this.player, handlers.size() > 0 ? TextParser.parse(message.getFiltered(), handlers) : new LiteralText(message.getFiltered())); + + playerManager.broadcast(rawText, (player) -> this.player.shouldFilterMessagesSentTo(player) ? filteredText : rawText, playerMessageType, sender); + } +} diff --git a/src/main/java/eu/pb4/styledchat/mixin/ServerPlayerEntityMixin.java b/src/main/java/eu/pb4/styledchat/mixin/ServerPlayerEntityMixin.java new file mode 100644 index 0000000..f175321 --- /dev/null +++ b/src/main/java/eu/pb4/styledchat/mixin/ServerPlayerEntityMixin.java @@ -0,0 +1,19 @@ +package eu.pb4.styledchat.mixin; + +import eu.pb4.styledchat.config.ConfigManager; +import net.minecraft.server.network.ServerPlayerEntity; +import net.minecraft.text.Text; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyArg; + + +@Mixin(ServerPlayerEntity.class) +public class ServerPlayerEntityMixin { + + @ModifyArg(method = "onDeath", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/PlayerManager;broadcastChatMessage(Lnet/minecraft/text/Text;Lnet/minecraft/network/MessageType;Ljava/util/UUID;)V")) + private Text replaceDeathMessage(Text text) { + return ConfigManager.getConfig().getDeath((ServerPlayerEntity) (Object) this, text); + } +} diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..fb7c409 --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,33 @@ +{ + "schemaVersion": 1, + "id": "styledchat", + "version": "${version}", + + "name": "Styled Chat", + "description": "Change look of yours server chat!", + "authors": [ + "Patbox" + ], + "contact": { + "homepage": "https://pb4.eu", + "sources": "https://github.com/Patbox/StyledChat" + }, + + "license": "LGPLv3", + + "environment": "*", + "entrypoints": { + "main": [ + "eu.pb4.styledchat.StyledChatMod" + ] + }, + "mixins": [ + "styledchat.mixins.json" + ], + + "depends": { + "fabricloader": ">=0.11.3", + "fabric": "*", + "minecraft": "1.17.x" + } +} diff --git a/src/main/resources/styledchat.mixins.json b/src/main/resources/styledchat.mixins.json new file mode 100644 index 0000000..dab4693 --- /dev/null +++ b/src/main/resources/styledchat.mixins.json @@ -0,0 +1,18 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "eu.pb4.styledchat.mixin", + "compatibilityLevel": "JAVA_16", + "mixins": [ + "PlayerAdvancementTrackerMixin", + "PlayerEntityMixin", + "PlayerManagerMixin", + "ServerPlayerEntityMixin", + "ServerPlayNetworkManagerMixin" + ], + "client": [ + ], + "injectors": { + "defaultRequire": 1 + } +}