Skip to content

Commit

Permalink
Rewrite modifyMessage method +more
Browse files Browse the repository at this point in the history
  • Loading branch information
mrbuilder1961 committed Feb 26, 2024
1 parent 869c630 commit 4a2a3e9
Show file tree
Hide file tree
Showing 10 changed files with 202 additions and 146 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ Once you contribute, [join the Discord server](https://discord.gg/3MqBvNEyMz) so
| Ignore hide message packet | `true` | Should hide message packets that delete chat messages be ignored? | `text.chatpatches.chatHidePacket` |
| Override chat width | `0` | The width of the chat box. This overrides vanilla's default and allows for a much larger width. Set to 0 to use the vanilla setting and not override it. | `text.chatpatches.chatWidth` |
| Maximum chat messages | `16384` | The max amount of chat messages allowed to save. Vanilla caps it at 100, this mod can increase it up to 32,767. Keep in mind a higher max equals higher memory usage. | `text.chatpatches.chatMaxMessages` |
| Playername text | `"<$>"` | The text that replaces the playername in chat messages. Vanilla is '<$>', name only is '$'; where '$' is a placeholder for the playername. Only applies to player-sent messages. Game won't format message if this is set to '<$>'. | `text.chatpatches.chatNameFormat` |
| Playername text | `"<$>"` | The text that replaces the playername in chat messages. Vanilla is '<$>', name only is '$'; where '$' is a placeholder for the playername. Only applies to player-sent messages. | `text.chatpatches.chatNameFormat` |
| Playername color | `0xffffff` | The color that's filled in where it would otherwise be blank white in the resulting formatted playername. To use this with other formatting modifiers, use '&r' in the decoration text option. | `text.chatpatches.chatNameColor` |
| Shift chat | `10` | Shifts the chat interface up to not obstruct the armor bar and/or health. Default is 10, set to 0 for no shift. | `text.chatpatches.shiftChat` |
| Chat drafting toggle | `false` | Should any text in the chat field persist after closing and reopening the chat? | `text.chatpatches.messageDrafting` |
Expand All @@ -134,4 +134,4 @@ This mod is available under the GNU LGPLv3 license. Check out [this](https://cho
## Sponsor me!
- Ko-Fi: https://ko-fi.com/obro1961

[![15% off your first month with code OBRO15!](https://i.imgur.com/9mjs77B.png)](https://billing.kinetichosting.net/aff.php?aff=234)
[![15% off your first month with code OBRO15!](https://i.imgur.com/9mjs77B.png)](https://billing.kinetichosting.net/aff.php?aff=234)
7 changes: 7 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
- Made ChatSearchSettings save when the chat screen is closed then reopened; resets on game restart
- Fixed team name colors, prefixes, and suffixes being ignored when `chatNameFormat` is customized ([#115](https://www.github.com/mrbuilder1961/ChatPatches/issues/115))
- Added a new runnable config option to reload the config from disk
- Added a minor optimization to the way messages are modified to largely simplify the process in a few scenarios [prepub impl]
- Switched the text in the search settings screen to use pre-bundled translations (ON/OFF instead of a visual switch)
- Fixed the Copy String > Copy Raw String button in the copy menu removing &<code> formattings
- **Dev notes:**
- Changed the `CONFIG_PATH` and `CHATLOG_PATH` variables to use the `Path#resolve(String)` method instead of concatenating strings
- Removed some (now) redundant file constants and references (in `StringTextUtils` and `Config`)
Expand All @@ -13,6 +16,10 @@
- Capitalized some static final variables
- Changed some stuff about how the config is initialized, read, and written to disk
- Refactor StringTextUtils to TextUtils
- Restructured the powerhouse `ChatHudMixin#modifyMessage(Text, boolean)` method to be more modular with message reconstruction
- Moved the bulk of the `modifyMessage` method to ChatUtils to help development and greatly ease future troubleshooting
- Tweaked the `MessageHandlerMixin#cacheGameData` method to use built-in methods instead of rewriting the same thing
- Removed the `VANILLA_MESSAGE` matcher in `ChatUtils` because it was redundant

## Chat Patches `202.6.3` for Minecraft 1.20.2 on Fabric, Quilt
- Should be compatible with Quilt again! (requires Loader 0.23.0+)
Expand Down
4 changes: 2 additions & 2 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ mrId=MOqt4Z5n
# Required dependencies - https://fabricmc.net/develop
minecraft=1.20.2
yarn=+build.4
loader=0.15.6
api=0.91.5+1.20.2
loader=0.15.7
api=0.91.6+1.20.2

# Dependencies - modmenu: https://modrinth.com/mod/modmenu/versions?l=fabric and yacl: https://modrinth.com/mod/yacl/versions?l=fabric
modmenu=8.0.1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,12 @@
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.tooltip.Tooltip;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.screen.ScreenTexts;
import net.minecraft.text.Text;
import obro1961.chatpatches.mixin.gui.ChatScreenMixin;

import java.util.function.Function;

/** Represents a search setting pertaining to the {@link ChatScreenMixin} screen. */
public class ChatSearchSetting {
public static final Function<Boolean, Text> TOGGLE_FORMATTER = on -> on ? Text.of(": §7[§2=§aO§7]") : Text.of(": §7[§cX§4=§7]");

public static ChatSearchSetting caseSensitive = new ChatSearchSetting("caseSensitive", true),
modifiers = new ChatSearchSetting("modifiers", false),
regex = new ChatSearchSetting("regex", false);
Expand All @@ -30,11 +27,11 @@ private ChatSearchSetting(String key, boolean on) {
}

public void update(int yWithOffset, ButtonWidget.PressAction onPress) {
Text text = name.copy().append( TOGGLE_FORMATTER.apply(on) );
Text text = ScreenTexts.composeToggleText(name, on);

ButtonWidget.PressAction UPDATE_BUTTON = button -> {
on = !on;
button.setMessage( name.copy().append(TOGGLE_FORMATTER.apply(on)) );
button.setMessage(ScreenTexts.composeToggleText(name, on));
onPress.onPress(button); // flags ChatScreenMixin to update the search text color
};

Expand Down
17 changes: 9 additions & 8 deletions src/main/java/obro1961/chatpatches/config/Config.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package obro1961.chatpatches.config;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.mojang.authlib.GameProfile;
Expand All @@ -10,6 +12,7 @@
import net.minecraft.scoreboard.Team;
import net.minecraft.text.*;
import obro1961.chatpatches.ChatPatches;
import obro1961.chatpatches.util.ChatUtils;

import java.io.FileWriter;
import java.io.IOException;
Expand All @@ -31,9 +34,9 @@

public class Config {
public static final Path PATH = FabricLoader.getInstance().getConfigDir().resolve("chatpatches.json");
public static final Config DEFAULTS = new Config();

private static final com.google.gson.Gson GSON = new com.google.gson.GsonBuilder().setPrettyPrinting().create();
private static final Config DEFAULTS = new Config();
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();

// categories: time, hover, counter, counter.compact, boundary, chatlog, chat.hud, chat.screen, copy
public boolean time = true; public String timeDate = "HH:mm:ss"; public String timeFormat = "[$]"; public int timeColor = 0xff55ff;
Expand Down Expand Up @@ -117,11 +120,11 @@ public Style makeHoverStyle(Date when) {
* player entity and have both a valid name and UUID.
*/
public MutableText formatPlayername(GameProfile player) {
// todo add some error handling here
PlayerEntity entity = MinecraftClient.getInstance().world.getPlayerByUuid(player.getId());
Team team = entity.getScoreboard().getPlayerTeam(player.getName());
Style style = entity.getDisplayName().getStyle().withColor( entity.getTeamColorValue() != 0xffffff ? entity.getTeamColorValue() : chatNameColor );


if(team != null) {
// note: doesn't set the style on every append, as it's already set in the parent text. might cause issues?
// if the player is on a team, add the prefix and suffixes from the config AND team (if they exist) to the formatted name
Expand All @@ -146,7 +149,8 @@ public MutableText makeDupeCounter(int dupes) {

public Text makeBoundaryLine(String levelName) {
// constructs w empty texts to not throw errors when comparing for the dupe counter
return Text.empty().append( makeObject(boundaryFormat, levelName, "", "", BLANK_STYLE.withColor(boundaryColor)) ).append(Text.empty());
MutableText boundary = makeObject(boundaryFormat, levelName, "", "", BLANK_STYLE.withColor(boundaryColor));
return ChatUtils.buildMessage(null, null, boundary, null);
}


Expand All @@ -157,11 +161,8 @@ public static void read() {
LOGGER.info("[Config.read] No config file found; using default values.");
} else {
try {
// sets each config option to the loaded value
String rawData = Files.readString(PATH);
config = GSON.fromJson(rawData, config.getClass());
//Config loaded = GSON.fromJson(rawData, config.getClass());
//getOptions().forEach(opt -> config.getOption(opt.key).set( loaded.getOption(opt.key).val ));
LOGGER.info("[Config.read] Loaded config info from '{}'!", PATH);
} catch(JsonIOException | JsonSyntaxException e) {
writeCopy();
Expand Down Expand Up @@ -190,7 +191,7 @@ public static void write() {
* log any changes nor does it write to disk.
*/
public static void reset() {
getOptions().forEach(opt -> config.getOption(opt.key).set(opt.def));
getOptions().forEach(opt -> getOption(opt.key).set(opt.def));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.mojang.authlib.GameProfile;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.message.MessageHandler;
import net.minecraft.network.message.MessageType;
import net.minecraft.network.message.SignedMessage;
Expand All @@ -14,7 +13,6 @@
import obro1961.chatpatches.mixin.gui.ChatHudMixin;
import obro1961.chatpatches.util.ChatUtils;
import org.apache.commons.lang3.StringUtils;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
Expand All @@ -34,8 +32,7 @@
@Environment(EnvType.CLIENT)
@Mixin(MessageHandler.class)
public abstract class MessageHandlerMixin {
@Shadow @Final private MinecraftClient client;

@Shadow protected abstract UUID extractSender(Text text);

/**
* Caches the metadata of the last *player* message received by the client.
Expand All @@ -57,12 +54,11 @@ private void cacheChatData(SignedMessage message, GameProfile sender, MessageTyp
*/
@Inject(method = "onGameMessage", at = @At("HEAD"))
private void cacheGameData(Text message, boolean overlay, CallbackInfo ci) {
String string = TextVisitFactory.removeFormattingCodes(message);
String name = ChatUtils.VANILLA_MESSAGE.matcher(string).matches() ? StringUtils.substringBetween(string, "<", ">") : null;
UUID uuid = name == null ? Util.NIL_UUID : client.getSocialInteractionsManager().getUuid(name);
String name = StringUtils.substringBetween(TextVisitFactory.removeFormattingCodes(message), "<", ">");
UUID id = extractSender(message);

ChatPatches.msgData = !uuid.equals(Util.NIL_UUID)
? new ChatUtils.MessageData(new GameProfile(uuid, name), new Date(), true)
ChatPatches.msgData = !id.equals(Util.NIL_UUID)
? new ChatUtils.MessageData(new GameProfile(id, name), new Date(), true)
: ChatUtils.NIL_MSG_DATA;
}
}
Loading

0 comments on commit 4a2a3e9

Please sign in to comment.