repo_id
stringclasses 383
values | file_path
stringlengths 7
168
| content
stringlengths 0
1.75M
|
|---|---|---|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\chat\AdvancedTextField.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.chat;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import fi.dy.masa.malilib.util.KeyCodes;
import io.github.darkkronicle.advancedchatcore.config.ConfigStorage;
import io.github.darkkronicle.advancedchatcore.util.StringMatch;
import io.github.darkkronicle.advancedchatcore.util.StyleFormatter;
import io.github.darkkronicle.advancedchatcore.util.TextBuilder;
import io.github.darkkronicle.advancedchatcore.util.TextUtil;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.DrawableHelper;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.client.render.*;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.OrderedText;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.util.math.MathHelper;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
public class AdvancedTextField extends TextFieldWidget {
private final static int MAX_HISTORY = 50;
/**
* Stores the last saved snapshot of the box. This ensures that not every character update is
* put in, but instead groups.
*/
private String lastSaved = "";
/** Snapshots of chat box */
private final List<String> history = new ArrayList<>();
private int focusedTicks = 0;
private List<Text> renderLines = new ArrayList<>();
private TextRenderer textRenderer;
private String suggestion = null;
private int maxLength = 32;
private int selectionEnd;
private int selectionStart;
// TODO Split?
private BiFunction<String, Integer, OrderedText> renderTextProvider = (string, firstCharacterIndex) -> OrderedText.styledForwardsVisitedString(string, Style.EMPTY);
private int historyIndex = -1;
public AdvancedTextField(TextRenderer textRenderer, int x, int y, int width, int height, Text text) {
this(textRenderer, x, y, width, height, null, text);
}
public AdvancedTextField(
TextRenderer textRenderer,
int x,
int y,
int width,
int height,
@Nullable TextFieldWidget copyFrom,
Text text) {
super(textRenderer, x, y, width, height, copyFrom, text);
history.add("");
this.textRenderer = textRenderer;
updateRender();
}
@Override
public void tick() {
focusedTicks++;
}
@Override
public void setRenderTextProvider(BiFunction<String, Integer, OrderedText> renderTextProvider) {
this.renderTextProvider = renderTextProvider;
}
@Override
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
super.setMaxLength(maxLength);
}
public static boolean isUndo(int code) {
// Undo (Ctrl + Z)
return code == KeyCodes.KEY_Z && Screen.hasControlDown() && !Screen.hasAltDown();
}
/** Triggers undo for the text box */
public void undo() {
// Save the current snapshot if it's been edited
if (!this.lastSaved.equals(this.getText()) && historyIndex < 0) {
addToHistory(getText());
}
// History index < 0 means not in the middle of undoing
if (historyIndex < 0) {
historyIndex = history.size() - 1;
}
// Check that we're not at index 0
if (historyIndex != 0) {
historyIndex--;
}
// Set the text but don't update
setText(history.get(historyIndex), false);
}
public void redo() {
if (historyIndex < 0 || historyIndex >= history.size() - 1) {
// No stuff to redo...
return;
}
historyIndex++;
setText(history.get(historyIndex), false);
}
@Override
public void write(String text) {
super.write(text);
updateHistory();
updateRender();
}
@Override
public void eraseCharacters(int characterOffset) {
super.eraseCharacters(characterOffset);
updateHistory();
updateRender();
}
@Override
public void setSuggestion(@Nullable String suggestion) {
this.suggestion = suggestion;
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
int renderY = getY() - (renderLines.size() - 1) * (textRenderer.fontHeight + 2);
if (mouseY < renderY - 2 || mouseY > getY() + height + 2 || mouseX < getX() - 2 || mouseX > getX() + width + 4) {
return false;
}
return super.mouseClicked(mouseX, mouseY, button);
}
@Override
public void renderButton(MatrixStack matrices, int mouseX, int mouseY, float delta) {
int color = 0xE0E0E0;
int cursor = getCursor();
int cursorRow = renderLines.size() - 1;
boolean renderCursor = this.isFocused() && focusedTicks / 6 % 2 == 0;
int renderY = getY() - (renderLines.size() - 1) * (textRenderer.fontHeight + 2);
int endX = 0;
int charCount = 0;
int cursorX = -1;
boolean selection = selectionStart != selectionEnd;
boolean started = false;
boolean ended = false;
int selStart;
int selEnd;
if (this.selectionStart < this.selectionEnd) {
selStart = this.selectionStart;
selEnd = this.selectionEnd;
} else {
selStart = this.selectionEnd;
selEnd = this.selectionStart;
}
int x = getX();
int y = getY() ;
fill(matrices, getX() - 2, renderY - 2, getX() + width + 4, getY() + height + 4, ConfigStorage.ChatScreen.COLOR.config.get().color());
for (int line = 0; line < renderLines.size(); line++) {
Text text = renderLines.get(line);
if (cursor >= charCount && cursor < text.getString().length() + charCount) {
cursorX = textRenderer.getWidth(text.getString().substring(0, cursor - charCount));
cursorRow = line;
}
endX = textRenderer.drawWithShadow(matrices, text, x, renderY, color);
if (selection) {
if (!started && selStart >= charCount && selStart <= text.getString().length() + charCount) {
started = true;
int startX = textRenderer.getWidth(TextUtil.truncate(text, new StringMatch("", 0, selStart - charCount)));
if (selEnd > charCount && selEnd <= text.getString().length() + charCount) {
ended = true;
int sEndX = textRenderer.getWidth(TextUtil.truncate(text, new StringMatch("", 0, selEnd - charCount)));
drawSelectionHighlight(x + startX, renderY - 1, x + sEndX, renderY + textRenderer.fontHeight);
} else {
int sEndX = textRenderer.getWidth(text);
drawSelectionHighlight(x + startX, renderY - 1, x + sEndX, renderY + textRenderer.fontHeight);
}
} else if (started && !ended) {
if (selEnd >= charCount && selEnd <= text.getString().length() + charCount) {
ended = true;
int sEndX = textRenderer.getWidth(TextUtil.truncate(text, new StringMatch("", 0, selEnd - charCount)));
drawSelectionHighlight(x, renderY - 1, x + sEndX, renderY + textRenderer.fontHeight);
} else {
int sEndX = textRenderer.getWidth(text);
drawSelectionHighlight(x, renderY - 1, x + sEndX, renderY + textRenderer.fontHeight);
}
}
}
renderY += textRenderer.fontHeight + 2;
charCount += text.getString().length();
}
if (cursorX < 0) {
cursorX = endX;
}
boolean cursorAtEnd = getCursor() == getText().length();
if (!cursorAtEnd && this.suggestion != null) {
this.textRenderer.drawWithShadow(matrices, this.suggestion, endX - 1, y, -8355712);
}
if (renderCursor) {
int cursorY = y - (renderLines.size() - 1 - cursorRow) * (textRenderer.fontHeight + 2);
if (cursorAtEnd) {
DrawableHelper.fill(matrices, cursorX, cursorY - 1, cursorX + 1, cursorY + 1 + this.textRenderer.fontHeight, -3092272);
} else {
this.textRenderer.drawWithShadow(matrices, "_", x + cursorX, cursorY, color);
}
}
}
private void drawSelectionHighlight(int x1, int y1, int x2, int y2) {
int x = getX();
int y = getY();
int i;
if (x1 < x2) {
i = x1;
x1 = x2;
x2 = i;
}
if (y1 < y2) {
i = y1;
y1 = y2;
y2 = i;
}
if (x2 > x + this.width) {
x2 = x + this.width;
}
if (x1 > x + this.width) {
x1 = x + this.width;
}
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder bufferBuilder = tessellator.getBuffer();
RenderSystem.setShader(GameRenderer::getPositionProgram);
RenderSystem.setShaderColor(0.0f, 0.0f, 1.0f, 1.0f);
// RenderSystem.disableTexture();
RenderSystem.enableColorLogicOp();
RenderSystem.logicOp(GlStateManager.LogicOp.OR_REVERSE);
bufferBuilder.begin(VertexFormat.DrawMode.QUADS, VertexFormats.POSITION);
bufferBuilder.vertex(x1, y2, 0.0).next();
bufferBuilder.vertex(x2, y2, 0.0).next();
bufferBuilder.vertex(x2, y1, 0.0).next();
bufferBuilder.vertex(x1, y1, 0.0).next();
tessellator.draw();
RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
RenderSystem.disableColorLogicOp();
// RenderSystem.enableTexture();
}
@Override
public void setSelectionStart(int cursor) {
this.selectionStart = MathHelper.clamp(cursor, 0, getText().length());
super.setSelectionStart(cursor);
}
@Override
public void setSelectionEnd(int index) {
int i = getText().length();
this.selectionEnd = MathHelper.clamp(index, 0, i);
super.setSelectionEnd(index);
}
@Override
public SelectionType getType() {
return super.getType();
}
/**
* Sets the text for the text field
*
* @param text Text to set
* @param update Updates the history
*/
public void setText(String text, boolean update) {
// Wrapper class for setText
super.setText(text);
if (update) {
updateHistory();
}
updateRender();
}
@Override
public void setText(String text) {
setText(text, true);
}
private void updateRender() {
OrderedText formatted = renderTextProvider.apply(getText(), 0);
renderLines = StyleFormatter.wrapText(textRenderer, getWidth(), new TextBuilder().append(formatted).build());
}
private void updateHistory() {
if (historyIndex >= 0) {
// Remove all history after what has gone back
pruneHistory(historyIndex + 1);
historyIndex = -1;
}
// Check to see if it should log
int dif = getText().length() - lastSaved.length();
double sim = TextUtil.similarity(getText(), lastSaved);
if (sim >= .3 && (dif < 5 && dif * -1 < 5) || (sim >= .9)) {
return;
}
addToHistory(getText());
}
private void addToHistory(String text) {
this.lastSaved = text;
this.history.add(text);
while (this.history.size() > MAX_HISTORY) {
this.history.remove(0);
}
}
/**
* Remove's all history past a certain index
*
* @param index Index to prune from. Non-inclusive.
*/
private void pruneHistory(int index) {
if (index == 0) {
history.clear();
return;
}
while (history.size() > index) {
history.remove(history.size() - 1);
}
}
@Override
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
if (!this.isActive()) {
return false;
}
if (!isUndo(keyCode)) {
return super.keyPressed(keyCode, scanCode, modifiers);
}
if (Screen.hasShiftDown()) {
redo();
} else {
undo();
}
return true;
}
@Override
public void appendClickableNarrations(NarrationMessageBuilder builder) {
// Crashes here because Text is null
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\chat\ChatHistory.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.chat;
import io.github.darkkronicle.advancedchatcore.config.ConfigStorage;
import io.github.darkkronicle.advancedchatcore.interfaces.IChatMessageProcessor;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import lombok.Getter;
import lombok.Setter;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
/** A utility class to maintain the storage of the chat. */
@Environment(EnvType.CLIENT)
public class ChatHistory {
private static final ChatHistory INSTANCE = new ChatHistory();
/** Stored lines */
@Getter private final List<ChatMessage> messages = new ArrayList<>();
/** Maximum lines for storage */
@Getter @Setter private int maxLines = 500;
/** Runnable's to run when chat history is cleared */
@Getter private final List<Runnable> onClear = new ArrayList<>();
/** {@link IChatMessageProcessor} for when history is updated. */
@Getter private final List<IChatMessageProcessor> onUpdate = new ArrayList<>();
public static ChatHistory getInstance() {
return INSTANCE;
}
private ChatHistory() {}
/**
* Add's a runnable that will trigger when all chat messages should be cleared.
*
* @param runnable Runnable to run
*/
public void addOnClear(Runnable runnable) {
onClear.add(runnable);
}
/**
* Add's a {@link IChatMessageProcessor} that get's called on new messages, added messages,
* stacked messages, or removed messages.
*
* @param processor Processor ot add
*/
public void addOnUpdate(IChatMessageProcessor processor) {
onUpdate.add(processor);
}
/** Goes through and clears all message data from everywhere. */
public void clearAll() {
this.messages.clear();
for (Runnable r : onClear) {
r.run();
}
}
/** Clear's all the chat messages from the history */
public void clear() {
messages.clear();
}
private void sendUpdate(ChatMessage message, IChatMessageProcessor.UpdateType type) {
for (IChatMessageProcessor consumer : onUpdate) {
consumer.onMessageUpdate(message, type);
}
}
/**
* Add's a chat message to the history.
*
* @param message
*/
public boolean add(ChatMessage message) {
sendUpdate(message, IChatMessageProcessor.UpdateType.NEW);
for (int i = 0;
i < ConfigStorage.General.CHAT_STACK.config.getIntegerValue()
&& i < messages.size();
i++) {
// Check for stacks
ChatMessage chatLine = messages.get(i);
if (message.isSimilar(chatLine)) {
chatLine.setStacks(chatLine.getStacks() + 1);
sendUpdate(chatLine, IChatMessageProcessor.UpdateType.STACK);
return false;
}
}
sendUpdate(message, IChatMessageProcessor.UpdateType.ADDED);
messages.add(0, message);
while (this.messages.size() > maxLines) {
sendUpdate(
this.messages.remove(this.messages.size() - 1),
IChatMessageProcessor.UpdateType.REMOVE);
}
return true;
}
/**
* Remove's a message based off of it's messageId.
*
* @param messageId Message ID to find and remove
*/
public void removeMessage(int messageId) {
List<ChatMessage> toRemove =
this.messages.stream()
.filter(line -> line.getId() == messageId)
.collect(Collectors.toList());
this.messages.removeAll(toRemove);
for (ChatMessage m : toRemove) {
sendUpdate(m, IChatMessageProcessor.UpdateType.REMOVE);
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\chat\ChatHistoryProcessor.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.chat;
import io.github.darkkronicle.advancedchatcore.AdvancedChatCore;
import io.github.darkkronicle.advancedchatcore.config.ConfigStorage;
import io.github.darkkronicle.advancedchatcore.interfaces.IMessageProcessor;
import io.github.darkkronicle.advancedchatcore.mixin.MixinChatHudInvoker;
import io.github.darkkronicle.advancedchatcore.util.Color;
import io.github.darkkronicle.advancedchatcore.util.SearchUtils;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.hud.MessageIndicator;
import net.minecraft.network.message.MessageSignatureData;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.text.TextColor;
import org.jetbrains.annotations.Nullable;
@Environment(EnvType.CLIENT)
public class ChatHistoryProcessor implements IMessageProcessor {
private static boolean sendToHud(Text text, @Nullable MessageSignatureData signature, MessageIndicator indicator) {
if (AdvancedChatCore.FORWARD_TO_HUD) {
((MixinChatHudInvoker) MinecraftClient.getInstance().inGameHud.getChatHud()).invokeAddMessage(
text, signature, MinecraftClient.getInstance().inGameHud.getTicks(), indicator, false);
return true;
}
return false;
}
@Override
public boolean process(Text text, @Nullable Text unfiltered) {
return process(text, unfiltered, null, MessageIndicator.system());
}
@Override
public boolean process(Text text, @Nullable Text unfiltered, @Nullable MessageSignatureData signature, @Nullable MessageIndicator indicator) {
if (unfiltered == null) {
unfiltered = text;
}
// Put the time in
LocalTime time = LocalTime.now();
boolean showtime = ConfigStorage.General.SHOW_TIME.config.getBooleanValue();
// Store original so we can get stuff without the time
Text original = text.copy();
if (showtime) {
DateTimeFormatter format =
DateTimeFormatter.ofPattern(
ConfigStorage.General.TIME_FORMAT.config.getStringValue());
String replaceFormat =
ConfigStorage.General.TIME_TEXT_FORMAT.config.getStringValue().replaceAll("&", "§");
Color color = ConfigStorage.General.TIME_COLOR.config.get();
Style style = Style.EMPTY;
TextColor textColor = TextColor.fromRgb(color.color());
style = style.withColor(textColor);
text.getSiblings().add(0, Text.literal(replaceFormat.replaceAll("%TIME%", time.format(format))).fillStyle(style));
}
int width = 0;
// Find player
MessageOwner player =
SearchUtils.getAuthor(
MinecraftClient.getInstance().getNetworkHandler(), unfiltered.getString());
ChatMessage line = ChatMessage.builder()
.displayText(text)
.originalText(original)
.owner(player)
.id(0)
.width(width)
.creationTick(MinecraftClient.getInstance().inGameHud.getTicks())
.time(time)
.backgroundColor(null)
.build();
if (ChatHistory.getInstance().add(line)) {
sendToHud(line.getDisplayText(), line.getSignature(), line.getIndicator());
}
return true;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\chat\ChatMessage.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.chat;
import io.github.darkkronicle.advancedchatcore.util.Color;
import io.github.darkkronicle.advancedchatcore.util.StyleFormatter;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import lombok.Builder;
import lombok.Data;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.hud.MessageIndicator;
import net.minecraft.network.message.MessageSignatureData;
import net.minecraft.text.Text;
import org.jetbrains.annotations.Nullable;
/** A message from chat with data stored within it. */
@Environment(EnvType.CLIENT)
@Data
public class ChatMessage {
/** Tick the message was created. */
protected int creationTick;
/** The text that will be displayed on render. */
protected Text displayText;
/** The unmodified original text. Used to keep time stamp off of. */
protected Text originalText;
/** ID of the message. */
protected int id;
/** The time the message was created. */
protected LocalTime time;
/** The background color of the message. */
protected Color backgroundColor;
/** The amount of times the message has been stacked. */
protected int stacks;
/** Unique ID of the message. */
protected UUID uuid;
/** The owner of the message. */
@Nullable protected MessageOwner owner;
/** Split up lines for line breaks. */
protected List<AdvancedChatLine> lines;
@Nullable
protected MessageSignatureData signature;
protected MessageIndicator indicator;
/**
* Set's the display text of the message and formats the line breaks.
*
* @param text Text to set to
* @param width The width that a line break should be enforced
*/
public void setDisplayText(Text text, int width) {
this.displayText = text;
formatChildren(width);
}
/**
* Clones the object
*
* @param width Width for the line breaks to be enforced
* @return Cloned object
*/
public ChatMessage shallowClone(int width) {
ChatMessage message =
new ChatMessage(
creationTick,
displayText,
originalText,
id,
time,
backgroundColor,
width,
owner,
signature,
indicator);
message.setStacks(getStacks());
return message;
}
/** A sub section of {@link ChatMessage} which contains a renderable line. */
@Data
public static class AdvancedChatLine {
/** Render text */
private Text text;
private final ChatMessage parent;
private int width;
private AdvancedChatLine(ChatMessage parent, Text text) {
this.parent = parent;
this.text = text;
this.width = MinecraftClient.getInstance().textRenderer.getWidth(text);
}
@Override
public String toString() {
return ("AdvancedChatLine{" + "text=" + text + ", width=" + width + '}');
}
}
@Builder
protected ChatMessage(
int creationTick,
Text displayText,
Text originalText,
int id,
LocalTime time,
Color backgroundColor,
int width,
MessageOwner owner,
@Nullable MessageSignatureData signature,
@Nullable MessageIndicator indicator) {
this.creationTick = creationTick;
this.displayText = displayText;
this.id = id;
this.time = time;
this.backgroundColor = backgroundColor;
this.stacks = 0;
this.uuid = UUID.randomUUID();
this.owner = owner;
this.originalText = originalText == null ? displayText : originalText;
this.signature = signature;
this.indicator = indicator == null ? MessageIndicator.system() : indicator;
formatChildren(width);
}
/**
* Reformat's the line breaks
*
* @param width Width that the line breaks should be enforced
*/
public void formatChildren(int width) {
this.lines = new ArrayList<>();
if (width == 0) {
this.lines.add(new AdvancedChatLine(this, displayText));
} else {
for (Text t :
StyleFormatter.wrapText(
MinecraftClient.getInstance().textRenderer, width, displayText)) {
this.lines.add(new AdvancedChatLine(this, t));
}
}
}
/**
* Check if the original text is similar to another's original text
*
* @param message Message to compare to
* @return If it's similar
*/
public boolean isSimilar(ChatMessage message) {
return message.getOriginalText().getString().equals(this.getOriginalText().getString());
}
/**
* Get's the total amount of lines
*
* @return Line count
*/
public int getLineCount() {
return this.lines.size();
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\chat\ChatScreenSectionHolder.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.chat;
import io.github.darkkronicle.advancedchatcore.interfaces.AdvancedChatScreenSection;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import lombok.Getter;
/**
* A class to handle the construction and distribution of {@link AdvancedChatScreenSection} when
* {@link AdvancedChatScreen} is created.
*/
public class ChatScreenSectionHolder {
private static final ChatScreenSectionHolder INSTANCE = new ChatScreenSectionHolder();
/** All suppliers for the sections */
@Getter
private final List<Function<AdvancedChatScreen, AdvancedChatScreenSection>> sectionSuppliers =
new ArrayList<>();
public static ChatScreenSectionHolder getInstance() {
return INSTANCE;
}
private ChatScreenSectionHolder() {}
public void addSectionSupplier(
Function<AdvancedChatScreen, AdvancedChatScreenSection> sectionSupplier) {
sectionSuppliers.add(sectionSupplier);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\chat\DefaultChatSuggestor.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.chat;
import io.github.darkkronicle.advancedchatcore.interfaces.AdvancedChatScreenSection;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.ChatInputSuggestor;
import net.minecraft.client.util.math.MatrixStack;
/** Handles the CommandSuggestor for the chat */
@Environment(EnvType.CLIENT)
public class DefaultChatSuggestor extends AdvancedChatScreenSection {
private ChatInputSuggestor commandSuggestor;
public DefaultChatSuggestor(AdvancedChatScreen screen) {
super(screen);
}
@Override
public void onChatFieldUpdate(String chatText, String text) {
this.commandSuggestor.setWindowActive(!text.equals(getScreen().getOriginalChatText()));
this.commandSuggestor.refresh();
}
@Override
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
return this.commandSuggestor.keyPressed(keyCode, scanCode, modifiers);
}
@Override
public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
this.commandSuggestor.render(matrixStack, mouseX, mouseY);
}
@Override
public void setChatFromHistory(String hist) {
this.commandSuggestor.setWindowActive(false);
}
@Override
public boolean mouseScrolled(double mouseX, double mouseY, double amount) {
return this.commandSuggestor.mouseScrolled(amount);
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
return this.commandSuggestor.mouseClicked(mouseX, mouseY, button);
}
@Override
public void resize(int width, int height) {
this.commandSuggestor.refresh();
}
@Override
public void initGui() {
MinecraftClient client = MinecraftClient.getInstance();
AdvancedChatScreen screen = getScreen();
this.commandSuggestor =
new ChatInputSuggestor(
client,
screen,
screen.chatField,
client.textRenderer,
false,
false,
1,
10,
true,
-805306368);
this.commandSuggestor.refresh();
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\chat\MessageDispatcher.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.chat;
import io.github.darkkronicle.advancedchatcore.interfaces.IMessageFilter;
import io.github.darkkronicle.advancedchatcore.interfaces.IMessageProcessor;
import io.github.darkkronicle.advancedchatcore.util.FindType;
import io.github.darkkronicle.advancedchatcore.util.SearchResult;
import io.github.darkkronicle.advancedchatcore.util.SearchUtils;
import io.github.darkkronicle.advancedchatcore.util.StringInsert;
import io.github.darkkronicle.advancedchatcore.util.StringMatch;
import io.github.darkkronicle.advancedchatcore.util.StyleFormatter;
import io.github.darkkronicle.advancedchatcore.util.TextUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.gui.hud.MessageIndicator;
import net.minecraft.network.message.MessageSignatureData;
import net.minecraft.text.ClickEvent;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import org.apache.logging.log4j.LogManager;
import org.jetbrains.annotations.Nullable;
/**
* A class to handle chat events.
*
* <p>Different events and hooks can be registered in here.
*/
@Environment(EnvType.CLIENT)
public class MessageDispatcher {
private static final MessageDispatcher INSTANCE = new MessageDispatcher();
private ArrayList<IMessageProcessor> processors = new ArrayList<>();
private ArrayList<IMessageFilter> preFilters = new ArrayList<>();
public static MessageDispatcher getInstance() {
return INSTANCE;
}
private MessageDispatcher() {
// We don't really want this to be reconstructed or changed because it will lead to problems
// of not having everything registered
registerPreFilter(text -> Optional.of(StyleFormatter.formatText(text)), -1);
registerPreFilter(
text -> {
String string = text.getString();
if (string.isEmpty()) {
return Optional.empty();
}
SearchResult search =
SearchResult.searchOf(
string,
"(http(s)?:\\/\\/.)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&\\/=]*)",
FindType.REGEX);
if (search.size() == 0) {
return Optional.empty();
}
Map<StringMatch, StringInsert> insert = new HashMap<>();
for (StringMatch match : search.getMatches()) {
insert.put(
match,
(current, match1) -> {
String url = match1.match;
if (!SearchUtils.isMatch(
match1.match, "(http(s)?:\\/\\/.)", FindType.REGEX)) {
url = "https://" + url;
}
if (current.getStyle().getClickEvent() == null) {
return Text.literal(match1.match).fillStyle(current.getStyle().withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url)));
}
return MutableText.of(current.getContent()).fillStyle(current.getStyle());
});
}
text = TextUtil.replaceStrings(text, insert);
return Optional.of(text);
},
-1);
registerPreFilter(
(IMessageProcessor)
(text, orig) -> {
LogManager.getLogger()
.info(
"[CHAT] {}",
text.getString()
.replaceAll("\r", "\\\\r")
.replaceAll("\n", "\\\\n"));
return true;
},
-1);
}
/**
* This is ONLY used for new messages in chat
*
* <p>Note: It is not recommended to call this method to force add new text. Typically, grabbing
* the {@link net.minecraft.client.gui.hud.ChatHud} from {@link
* net.minecraft.client.MinecraftClient} and calling addText is a safer way.
*
* @param text Text that is received
*/
public void handleText(Text text, @Nullable MessageSignatureData signature, @Nullable MessageIndicator indicator) {
boolean previouslyBlank = text.getString().length() == 0;
text = preFilter(text, signature, indicator);
if (text.getString().length() == 0 && !previouslyBlank) {
// No more
return;
}
process(text, signature, indicator);
}
private Text preFilter(Text text, @Nullable MessageSignatureData signature, @Nullable MessageIndicator indicator) {
for (IMessageFilter f : preFilters) {
Optional<Text> t = f.filter(text);
if (t.isPresent()) {
text = t.get();
}
}
return text;
}
private void process(Text text, @Nullable MessageSignatureData signature, @Nullable MessageIndicator indicator) {
for (IMessageFilter f : processors) {
f.filter(text);
}
}
/**
* Registers a {@link IMessageFilter} to be called to modify the text. This is to keep
* formatting consistent, or to stop a message from being sent.
*
* <p>If text of zero length is returned by the MessageFilter the text won't be sent to the
* processors.
*
* <p>Note: It's discouraged to add a IMessageFilter that doesn't modify text. For that use
* registerProcess
*
* @param processor IMessageFilter to modify text
* @param index Index to add it. Supplying a negative value will put it at the end.
*/
public void registerPreFilter(IMessageFilter processor, int index) {
if (index < 0) {
index = preFilters.size();
}
if (!preFilters.contains(processor)) {
preFilters.add(index, processor);
}
}
/**
* Register's a {@link IMessageProcessor} to handle a chat event after the message has been
* preprocessed.
*
* @param processor IMessageProcessor to get called back
* @param index Index that it will be added to. Supplying a negative value will put it at the
* end.
*/
public void register(IMessageProcessor processor, int index) {
if (index < 0) {
index = processors.size();
}
if (!processors.contains(processor)) {
processors.add(index, processor);
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\chat\MessageOwner.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.chat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Value;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.network.PlayerListEntry;
import net.minecraft.util.Identifier;
/** Stores data about a message owner */
@Data
@Value
@AllArgsConstructor
@Environment(EnvType.CLIENT)
public class MessageOwner {
/** Player name */
String name;
/** Entry that has player data */
PlayerListEntry entry;
/**
* The texture of the player's skin
*
* @return Identifier with texture data
*/
public Identifier getTexture() {
return entry.getSkinTexture();
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\chat\MessageSender.java
|
/*
* Copyright (C) 2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.chat;
import io.github.darkkronicle.advancedchatcore.AdvancedChatCore;
import io.github.darkkronicle.advancedchatcore.interfaces.IStringFilter;
import net.minecraft.client.MinecraftClient;
import org.apache.logging.log4j.Level;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class MessageSender {
private static final MessageSender INSTANCE = new MessageSender();
private final MinecraftClient client = MinecraftClient.getInstance();
public static MessageSender getInstance() {
return INSTANCE;
}
private MessageSender() {}
private final List<IStringFilter> filters = new ArrayList<>();
public void addFilter(IStringFilter filter) {
filters.add(filter);
}
public void addFilter(IStringFilter filter, int index) {
filters.add(index, filter);
}
public void sendMessage(String string) {
String unfiltered = string;
for (IStringFilter filter : filters) {
Optional<String> filtered = filter.filter(string);
if (filtered.isPresent()) {
string = filtered.get().strip();
}
}
if (string.length() > 256) {
string = string.substring(0, 256);
}
this.client.inGameHud.getChatHud().addToMessageHistory(unfiltered);
if (string.length() == 0) {
AdvancedChatCore.LOGGER.log(Level.WARN, "Blank message was attempted to be sent. " + unfiltered);
return;
}
if (client.player != null) {
if (string.startsWith("/")) {
this.client.getNetworkHandler().sendChatCommand(string.substring(1));
} else {
this.client.getNetworkHandler().sendChatMessage(string);
}
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\ConfigStorage.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.config;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import fi.dy.masa.malilib.MaLiLib;
import fi.dy.masa.malilib.config.IConfigBase;
import fi.dy.masa.malilib.config.IConfigHandler;
import fi.dy.masa.malilib.config.IConfigOptionListEntry;
import fi.dy.masa.malilib.config.options.*;
import fi.dy.masa.malilib.hotkeys.KeyAction;
import fi.dy.masa.malilib.hotkeys.KeybindSettings;
import fi.dy.masa.malilib.util.FileUtils;
import fi.dy.masa.malilib.util.JsonUtils;
import fi.dy.masa.malilib.util.StringUtils;
import io.github.darkkronicle.advancedchatcore.AdvancedChatCore;
import io.github.darkkronicle.advancedchatcore.config.options.ConfigColor;
import io.github.darkkronicle.advancedchatcore.interfaces.ConfigRegistryOption;
import io.github.darkkronicle.advancedchatcore.util.AbstractRegistry;
import io.github.darkkronicle.advancedchatcore.util.Color;
import io.github.darkkronicle.advancedchatcore.util.Colors;
import io.github.darkkronicle.advancedchatcore.util.EasingMethod;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
// Used to store values into config.json
@Environment(EnvType.CLIENT)
public class ConfigStorage implements IConfigHandler {
public static final String CONFIG_FILE_NAME = AdvancedChatCore.MOD_ID + ".json";
private static final int CONFIG_VERSION = 1;
public static class General {
public static final String NAME = "general";
public static String translate(String key) {
return StringUtils.translate("advancedchat.config.general." + key);
}
public static final SaveableConfig<ConfigString> TIME_FORMAT =
SaveableConfig.fromConfig(
"timeFormat",
new ConfigString(
translate("timeformat"), "hh:mm", translate("info.timeformat")));
public static final SaveableConfig<ConfigString> TIME_TEXT_FORMAT =
SaveableConfig.fromConfig(
"timeTextFormat",
new ConfigString(
translate("timetextformat"),
"[%TIME%] ",
translate("info.timetextformat")));
public static final SaveableConfig<ConfigColor> TIME_COLOR =
SaveableConfig.fromConfig(
"time_color",
new ConfigColor(
translate("timecolor"),
Colors.getInstance().getColor("white").get(),
translate("info.timecolor")));
public static final SaveableConfig<ConfigBoolean> SHOW_TIME =
SaveableConfig.fromConfig(
"show_time",
new ConfigBoolean(
translate("showtime"), false, translate("info.showtime")));
public static final SaveableConfig<ConfigBoolean> CLEAR_ON_DISCONNECT =
SaveableConfig.fromConfig(
"clearOnDisconnect",
new ConfigBoolean(
translate("clearondisconnect"),
true,
translate("info.clearondisconnect")));
public static final SaveableConfig<ConfigInteger> CHAT_STACK =
SaveableConfig.fromConfig(
"chatStack",
new ConfigInteger(
translate("chatstack"), 0, 0, 20, translate("info.chatstack")));
public static final SaveableConfig<ConfigBoolean> CHAT_STACK_UPDATE =
SaveableConfig.fromConfig(
"chatStackUpdate",
new ConfigBoolean(
translate("chatstackupdate"),
false,
translate("info.chatstackupdate")));
public static final SaveableConfig<ConfigString> MESSAGE_OWNER_REGEX =
SaveableConfig.fromConfig(
"messageOwnerRegex",
new ConfigString(
translate("messageownerregex"),
"(?<!\\[)\\b[A-Za-z0-9_§]{3,16}\\b(?!\\])",
translate("info.messageownerregex")));
public static final SaveableConfig<ConfigBoolean> FILTER_PROFANITY =
SaveableConfig.fromConfig(
"filterProfanity",
new ConfigBoolean(
translate("filterprofanity"),
false,
translate("info.filterprofanity")));
public static final SaveableConfig<ConfigBoolean> PROFANITY_ON_WORD_BOUNDARIES =
SaveableConfig.fromConfig(
"profanityWordBoundaries",
new ConfigBoolean(
translate("profanitywordboundaries"),
false,
translate("info.profanitywordboundaries")));
public static final SaveableConfig<ConfigDouble> PROFANITY_ABOVE =
SaveableConfig.fromConfig(
"profanityAbove",
new ConfigDouble(
translate("profanityabove"),
0,
0,
3,
translate("info.profanityabove")));
public static final ImmutableList<SaveableConfig<? extends IConfigBase>> OPTIONS =
ImmutableList.of(
TIME_FORMAT,
TIME_TEXT_FORMAT,
TIME_COLOR,
SHOW_TIME,
CLEAR_ON_DISCONNECT,
CHAT_STACK,
CHAT_STACK_UPDATE,
MESSAGE_OWNER_REGEX,
FILTER_PROFANITY,
PROFANITY_ABOVE,
PROFANITY_ON_WORD_BOUNDARIES
);
}
public static class ChatScreen {
public static final String NAME = "chatscreen";
public static String translate(String key) {
return StringUtils.translate("advancedchat.config.chatscreen." + key);
}
public static final SaveableConfig<ConfigBoolean> PERSISTENT_TEXT =
SaveableConfig.fromConfig(
"persistentText",
new ConfigBoolean(
translate("persistenttext"),
false,
translate("info.persistenttext")));
public static final SaveableConfig<ConfigColor> COLOR =
SaveableConfig.fromConfig(
"color",
new ConfigColor(
translate("color"),
Colors.getInstance().getColor("black").get().withAlpha(100),
translate("info.color")));
public static final SaveableConfig<ConfigBoolean> MORE_TEXT =
SaveableConfig.fromConfig(
"moreText",
new ConfigBoolean(
translate("moretext"), false, translate("info.moretext")));
public static final SaveableConfig<ConfigBoolean> SHOW_CHAT_ICONS =
SaveableConfig.fromConfig(
"showChatIcons",
new ConfigBoolean(
translate("showchaticons"), true, translate("info.showchaticons")));
public static final SaveableConfig<ConfigColor> MODIFIED =
SaveableConfig.fromConfig(
"modified",
new ConfigColor(
translate("modified"), new Color(15386724), translate("info.modified")));
public static final SaveableConfig<ConfigColor> SYSTEM =
SaveableConfig.fromConfig(
"system",
new ConfigColor(
translate("system"), new Color(10526880), translate("info.system")));
public static final SaveableConfig<ConfigColor> FILTERED =
SaveableConfig.fromConfig(
"filtered",
new ConfigColor(
translate("filtered"), new Color(15386724), translate("info.filtered")));
public static final SaveableConfig<ConfigColor> NOT_SECURE =
SaveableConfig.fromConfig(
"notSecure",
new ConfigColor(
translate("notsecure"), new Color(15224664), translate("info.notsecure")));
public static final ImmutableList<SaveableConfig<? extends IConfigBase>> OPTIONS =
ImmutableList.of(PERSISTENT_TEXT, COLOR, MORE_TEXT, SHOW_CHAT_ICONS, MODIFIED, SYSTEM, FILTERED, NOT_SECURE);
}
public static class Hotkeys {
public static final String NAME = "hotkeys";
public static String translate(String key) {
return StringUtils.translate("advancedchat.config.hotkeys." + key);
}
public static final SaveableConfig<ConfigHotkey> OPEN_CHAT = SaveableConfig.fromConfig("openChat",
new ConfigHotkey(translate("openchat"), "", KeybindSettings.create(
KeybindSettings.Context.INGAME, KeyAction.PRESS, false, true, false, true
), translate("info.openchat")));
public static final SaveableConfig<ConfigHotkey> TOGGLE_PERMANENT = SaveableConfig.fromConfig("togglePermanent",
new ConfigHotkey(translate("togglepermanentfocus"), "", KeybindSettings.create(
KeybindSettings.Context.INGAME, KeyAction.PRESS, false, true, false, true
), translate("info.togglepermanentfocus")));
public static final SaveableConfig<ConfigHotkey> OPEN_CHAT_WITH_LAST = SaveableConfig.fromConfig("openChatWithLast",
new ConfigHotkey(translate("openchatwithlast"), "UP", KeybindSettings.create(
KeybindSettings.Context.INGAME, KeyAction.PRESS, true, true, false, true
), translate("info.openchatwithlast")));
public static final SaveableConfig<ConfigHotkey> OPEN_CHAT_FREE_MOVEMENT = SaveableConfig.fromConfig("openChatFreeMovement",
new ConfigHotkey(translate("openchatfreemovement"), "", KeybindSettings.create(
KeybindSettings.Context.INGAME, KeyAction.PRESS, true, true, false, true
), translate("info.openchatfreemovement")));
public static final SaveableConfig<ConfigHotkey> OPEN_SETTINGS = SaveableConfig.fromConfig("openSettings",
new ConfigHotkey(translate("opensettings"), "", KeybindSettings.create(
KeybindSettings.Context.ANY, KeyAction.PRESS, false, true, false, true
), translate("info.opensettings")));
public static final ImmutableList<SaveableConfig<? extends IConfigBase>> OPTIONS =
ImmutableList.of(OPEN_SETTINGS, OPEN_CHAT, OPEN_CHAT_FREE_MOVEMENT, TOGGLE_PERMANENT, OPEN_CHAT_WITH_LAST);
}
public static void loadFromFile() {
File v3 = FileUtils.getConfigDirectory().toPath().resolve(CONFIG_FILE_NAME).toFile();
File configFile;
if (v3.exists()
&& !FileUtils.getConfigDirectory()
.toPath()
.resolve("advancedchat")
.resolve(CONFIG_FILE_NAME)
.toFile()
.exists()) {
configFile = v3;
} else {
configFile =
FileUtils.getConfigDirectory()
.toPath()
.resolve("advancedchat")
.resolve(CONFIG_FILE_NAME)
.toFile();
}
if (configFile.exists() && configFile.isFile() && configFile.canRead()) {
JsonElement element = parseJsonFile(configFile);
if (element != null && element.isJsonObject()) {
JsonObject root = element.getAsJsonObject();
readOptions(root, General.NAME, General.OPTIONS);
readOptions(root, ChatScreen.NAME, ChatScreen.OPTIONS);
readOptions(root, Hotkeys.NAME, Hotkeys.OPTIONS);
int version = JsonUtils.getIntegerOrDefault(root, "configVersion", 0);
}
}
}
/**
* Applies a JSON element into a registry
*
* @param element Element in key
* @param registry Registry to apply too
*/
public static void applyRegistry(
JsonElement element, AbstractRegistry<?, ? extends ConfigRegistryOption<?>> registry) {
if (element == null || !element.isJsonObject()) {
return;
}
JsonObject obj = element.getAsJsonObject();
for (ConfigRegistryOption<?> option : registry.getAll()) {
if (obj.has(option.getSaveString())) {
option.load(obj.get(option.getSaveString()));
}
}
}
/**
* Creates a {@link JsonObject} containing registry data
*
* @param registry
* @return
*/
public static JsonObject saveRegistry(
AbstractRegistry<?, ? extends ConfigRegistryOption<?>> registry) {
JsonObject object = new JsonObject();
for (ConfigRegistryOption<?> option : registry.getAll()) {
object.add(option.getSaveString(), option.save());
}
return object;
}
public static void saveFromFile() {
File dir = FileUtils.getConfigDirectory().toPath().resolve("advancedchat").toFile();
if ((dir.exists() && dir.isDirectory()) || dir.mkdirs()) {
JsonObject root = new JsonObject();
writeOptions(root, General.NAME, General.OPTIONS);
writeOptions(root, ChatScreen.NAME, ChatScreen.OPTIONS);
writeOptions(root, Hotkeys.NAME, Hotkeys.OPTIONS);
root.add("config_version", new JsonPrimitive(CONFIG_VERSION));
writeJsonToFile(root, new File(dir, CONFIG_FILE_NAME));
}
}
public static void readOptions(
JsonObject root, String category, List<SaveableConfig<?>> options) {
JsonObject obj = JsonUtils.getNestedObject(root, category, false);
if (obj != null) {
for (SaveableConfig<?> conf : options) {
IConfigBase option = conf.config;
if (obj.has(conf.key)) {
option.setValueFromJsonElement(obj.get(conf.key));
}
}
}
}
// WINDOWS BAD AND MINECRAFT LIKES UTF-16
public static JsonElement parseJsonFile(File file) {
if (file != null && file.exists() && file.isFile() && file.canRead()) {
String fileName = file.getAbsolutePath();
try {
JsonParser parser = new JsonParser();
Charset[] sets =
new Charset[] {
StandardCharsets.UTF_8, Charset.defaultCharset(),
};
// Start to enforce UTF 8. Old files may be UTF-16
for (Charset s : sets) {
JsonElement element;
InputStreamReader reader = new InputStreamReader(new FileInputStream(file), s);
try {
element = parser.parse(reader);
} catch (Exception e) {
reader.close();
MaLiLib.logger.error(
"Failed to parse the JSON file '{}'. Attempting different charset."
+ " ",
fileName,
e);
continue;
}
reader.close();
return element;
}
} catch (Exception e) {
MaLiLib.logger.error("Failed to parse the JSON file '{}'", fileName, e);
}
}
return null;
}
// WINDOWS BAD AND MINECRAFT LIKES UTF-16
public static boolean writeJsonToFile(JsonObject root, File file) {
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
writer.write(JsonUtils.GSON.toJson(root));
writer.close();
return true;
} catch (IOException e) {
MaLiLib.logger.warn(
"Failed to write JSON data to file '{}'", file.getAbsolutePath(), e);
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (Exception e) {
MaLiLib.logger.warn("Failed to close JSON file", e);
}
}
return false;
}
public static void writeOptions(
JsonObject root, String category, List<SaveableConfig<?>> options) {
JsonObject obj = JsonUtils.getNestedObject(root, category, true);
for (SaveableConfig<?> option : options) {
obj.add(option.key, option.config.getAsJsonElement());
}
}
@Override
public void load() {
loadFromFile();
}
@Override
public void save() {
saveFromFile();
}
/** Serializable easing data */
public enum Easing implements IConfigOptionListEntry, EasingMethod {
LINEAR("linear", Method.LINEAR),
SINE("sine", Method.SINE),
QUAD("quad", Method.QUAD),
QUART("quart", Method.QUART),
CIRC("circ", Method.CIRC);
public final EasingMethod ease;
public final String configString;
private static String translate(String key) {
return StringUtils.translate("advancedchat.config.easing." + key);
}
Easing(String configString, EasingMethod ease) {
this.ease = ease;
this.configString = configString;
}
@Override
public String getStringValue() {
return configString;
}
@Override
public String getDisplayName() {
return translate(configString);
}
@Override
public IConfigOptionListEntry cycle(boolean forward) {
int id = this.ordinal();
if (forward) {
id++;
} else {
id--;
}
if (id >= values().length) {
id = 0;
} else if (id < 0) {
id = values().length - 1;
}
return values()[id % values().length];
}
@Override
public IConfigOptionListEntry fromString(String value) {
return fromEasingString(value);
}
public static Easing fromEasingString(String visibility) {
for (Easing e : Easing.values()) {
if (e.configString.equals(visibility)) {
return e;
}
}
return Easing.LINEAR;
}
@Override
public double apply(double v) {
return ease.apply(v);
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\SaveableConfig.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.config;
import fi.dy.masa.malilib.config.IConfigBase;
public class SaveableConfig<T extends IConfigBase> {
public final T config;
public final String key;
private SaveableConfig(String key, T config) {
this.key = key;
this.config = config;
}
public static <C extends IConfigBase> SaveableConfig<C> fromConfig(String key, C config) {
return new SaveableConfig<>(key, config);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\finder\CustomFinder.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.finder;
import io.github.darkkronicle.advancedchatcore.AdvancedChatCore;
import io.github.darkkronicle.advancedchatcore.interfaces.IFinder;
import io.github.darkkronicle.advancedchatcore.interfaces.RegistryOption;
import io.github.darkkronicle.advancedchatcore.util.AbstractRegistry;
import io.github.darkkronicle.advancedchatcore.util.StringMatch;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import org.apache.logging.log4j.Level;
@Environment(EnvType.CLIENT)
public class CustomFinder extends AbstractRegistry<IFinder, CustomFinder.CustomFinderOption>
implements IFinder {
private static final CustomFinder INSTANCE = new CustomFinder();
public static CustomFinder getInstance() {
return INSTANCE;
}
private CustomFinder() {}
public static final String NAME = "customfind";
@Override
public boolean isMatch(String input, String toMatch) {
Optional<IFinder> option = getFinder(toMatch);
if (option.isEmpty()) {
// Invalid :(
AdvancedChatCore.LOGGER.log(Level.WARN, getHelp(toMatch));
return false;
}
return option.get().isMatch(input, toMatch);
}
private String getHelp(String toMatch) {
StringBuilder builder =
new StringBuilder()
.append("Custom find type was used but the match ")
.append(toMatch)
.append(" does not exist in the registry! Possible correct options: ");
for (CustomFinderOption o : getAll()) {
builder.append(o.saveString).append(", ");
}
return builder.substring(0, builder.length() - 2);
}
@Override
public List<StringMatch> getMatches(String input, String toMatch) {
Optional<IFinder> option = getFinder(toMatch);
if (option.isEmpty()) {
// Invalid :(
AdvancedChatCore.LOGGER.log(Level.WARN, getHelp(toMatch));
return new ArrayList<>();
}
return option.get().getMatches(input, toMatch);
}
public Optional<IFinder> getFinder(String toMatch) {
for (CustomFinderOption o : getAll()) {
if (toMatch.startsWith(o.saveString)) {
return Optional.of(o.getOption());
}
}
return Optional.empty();
}
@Override
public CustomFinder clone() {
CustomFinder finder = new CustomFinder();
for (CustomFinderOption o : getAll()) {
finder.add(o.copy(this));
}
return finder;
}
@Override
public CustomFinderOption constructOption(
Supplier<IFinder> type,
String saveString,
String translation,
String infoTranslation,
boolean active,
boolean setDefault,
boolean hidden) {
return new CustomFinderOption(
type, saveString, translation, infoTranslation, active, hidden, this);
}
public static class CustomFinderOption implements RegistryOption<IFinder> {
private final IFinder finder;
private final String saveString;
private final String translation;
private final CustomFinder registry;
private final String infoTranslation;
private final boolean hidden;
private final boolean active;
private CustomFinderOption(
Supplier<IFinder> finder,
String saveString,
String translation,
String infoTranslation,
boolean active,
boolean hidden,
CustomFinder registry) {
this(finder.get(), saveString, translation, infoTranslation, active, hidden, registry);
}
// Only register
private CustomFinderOption(
IFinder finder,
String saveString,
String translation,
String infoTranslation,
boolean active,
boolean hidden,
CustomFinder registry) {
this.finder = finder;
this.saveString = saveString;
this.translation = translation;
this.registry = registry;
this.infoTranslation = infoTranslation;
this.hidden = hidden;
this.active = active;
}
@Override
public IFinder getOption() {
return finder;
}
@Override
public boolean isActive() {
return active;
}
@Override
public String getSaveString() {
return saveString;
}
@Override
public CustomFinderOption copy(AbstractRegistry<IFinder, ?> registry) {
return new CustomFinderOption(
finder,
saveString,
translation,
infoTranslation,
isActive(),
isHidden(),
registry == null ? this.registry : (CustomFinder) registry);
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\finder\LiteralFinder.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.finder;
import java.util.regex.Pattern;
public class LiteralFinder extends PatternFinder {
@Override
public Pattern getPattern(String toMatch) {
return Pattern.compile(Pattern.quote(toMatch));
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\finder\PatternFinder.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.finder;
import io.github.darkkronicle.advancedchatcore.interfaces.IFinder;
import io.github.darkkronicle.advancedchatcore.util.StringMatch;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class PatternFinder implements IFinder {
@Nullable
public abstract Pattern getPattern(String toMatch);
@Override
public boolean isMatch(String input, String toMatch) {
Pattern pattern = getPattern(toMatch);
if (pattern == null) {
return false;
}
return pattern.matcher(input).find();
}
@Override
public List<StringMatch> getMatches(String input, String toMatch) {
List<StringMatch> matches = new ArrayList<>();
Pattern pattern = getPattern(toMatch);
if (pattern == null) {
return matches;
}
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
matches.add(new StringMatch(matcher.group(), matcher.start(), matcher.end()));
}
matcher.reset();
return matches;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\finder\RegexFinder.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.finder;
import io.github.darkkronicle.advancedchatcore.AdvancedChatCore;
import io.github.darkkronicle.advancedchatcore.util.*;
import net.minecraft.text.ClickEvent;
import net.minecraft.text.MutableText;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.text.TextColor;
import net.minecraft.util.Formatting;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class RegexFinder extends PatternFinder {
@Override
public Pattern getPattern(String toMatch) {
try {
return Pattern.compile(toMatch);
} catch (PatternSyntaxException e) {
AdvancedChatCore.LOGGER.error("The regex " + toMatch + " is invalid!");
return null;
}
}
@Override
public List<StringMatch> getMatches(Text input, String toMatch) {
// Find named groups
Optional<List<StringMatch>> optionalGroups = SearchUtils.findMatches(toMatch, "\\(\\?<([a-zA-Z][a-zA-Z0-9]*)>", FindType.REGEX);
if (optionalGroups.isEmpty()) {
// No named groups, go back to just text
return getMatches(input.getString(), toMatch);
}
String string = input.getString();
Pattern pattern = getPattern(toMatch);
if (pattern == null) {
return new ArrayList<>();
}
Matcher matcher = pattern.matcher(string);
List<String> groups = optionalGroups.get().stream().map((match) -> match.match.substring(3, match.end - match.start - 1)).filter((match) -> match.startsWith("adv")).toList();
List<StringMatch> matches = new ArrayList<>();
while (matcher.find()) {
String total = matcher.group();
int start = matcher.start();
int stop = matcher.end();
if (groups.isEmpty()) {
matches.add(new StringMatch(total, start, stop));
continue;
}
boolean stillMatches = true;
for (String group : groups) {
try {
if (!isAllowed(input, group, matcher)) {
stillMatches = false;
break;
}
} catch (IllegalArgumentException e) {
// Group does not exist
}
}
if (stillMatches) {
matches.add(new StringMatch(total, start, stop));
}
}
matcher.reset();
return matches;
}
public static boolean isAllowed(Text input, String group, Matcher matcher) {
group = group.toLowerCase(Locale.ROOT);
String groupText = matcher.group(group);
String groupCondition = group.substring(3);
if (groupText == null || groupCondition.isEmpty() || groupText.isEmpty()) {
return true;
}
int start = matcher.start(group);
int end = matcher.end(group);
if (groupCondition.startsWith("0")) {
groupCondition = groupCondition.substring(1);
while (groupCondition.length() != 0) {
MutableText truncated = TextUtil.truncate(input, new StringMatch("", start, end));
char val = groupCondition.charAt(0);
groupCondition = groupCondition.substring(1);
if (val == 'l') {
if (!TextUtil.styleChanges(truncated, (style1, style2) -> style1.isBold() && style2.isBold())) {
return true;
}
continue;
}
if (val == 'o') {
if (!TextUtil.styleChanges(truncated, (style1, style2) -> style1.isItalic() && style2.isItalic())) {
return true;
}
continue;
}
if (val == 'k') {
if (!TextUtil.styleChanges(truncated, (style1, style2) -> style1.isObfuscated() && style2.isObfuscated())) {
return true;
}
continue;
}
if (val == 'n') {
if (!TextUtil.styleChanges(truncated, (style1, style2) -> style1.isUnderlined() && style2.isUnderlined())) {
return true;
}
continue;
}
if (val == 'm') {
if (!TextUtil.styleChanges(truncated, (style1, style2) -> style1.isStrikethrough() && style2.isStrikethrough())) {
return true;
}
continue;
}
if (val == 'z') {
if (!TextUtil.styleChanges(
truncated, (style1, style2) -> style1.getClickEvent() != null && style1.getClickEvent().getAction() == ClickEvent.Action.OPEN_URL
&& style2.getClickEvent() != null && style2.getClickEvent().getAction() == ClickEvent.Action.OPEN_URL)
) {
return true;
}
continue;
}
if (val == 'x') {
if (!TextUtil.styleChanges(
truncated, (style1, style2) -> style1.getClickEvent() != null && style1.getClickEvent().getAction() == ClickEvent.Action.COPY_TO_CLIPBOARD
&& style2.getClickEvent() != null && style2.getClickEvent().getAction() == ClickEvent.Action.COPY_TO_CLIPBOARD)
) {
return true;
}
continue;
}
if (val == 'y') {
if (!TextUtil.styleChanges(
truncated, (style1, style2) -> style1.getClickEvent() != null && style1.getClickEvent().getAction() == ClickEvent.Action.OPEN_FILE
&& style2.getClickEvent() != null && style2.getClickEvent().getAction() == ClickEvent.Action.OPEN_FILE)
) {
return true;
}
continue;
}
if (val == 'w') {
if (!TextUtil.styleChanges(
truncated, (style1, style2) -> style1.getClickEvent() != null && style1.getClickEvent().getAction() == ClickEvent.Action.RUN_COMMAND
&& style2.getClickEvent() != null && style2.getClickEvent().getAction() == ClickEvent.Action.RUN_COMMAND)
) {
return true;
}
continue;
}
if (val == 'v') {
if (!TextUtil.styleChanges(
truncated, (style1, style2) -> style1.getClickEvent() != null && style1.getClickEvent().getAction() == ClickEvent.Action.SUGGEST_COMMAND
&& style2.getClickEvent() != null && style2.getClickEvent().getAction() == ClickEvent.Action.SUGGEST_COMMAND)
) {
return true;
}
continue;
}
if (val == 'h') {
if (!TextUtil.styleChanges(
truncated, (style1, style2) -> style1.getHoverEvent() != null
&& style2.getHoverEvent() != null)
) {
return true;
}
continue;
}
if (TextUtil.styleChanges(truncated, (style1, style2) -> Objects.equals(style1.getColor(), style2.getColor()))) {
continue;
}
Style current = truncated.getStyle();
TextColor color = current.getColor();
if (color == null) {
if (val == 'f') {
return true;
}
continue;
}
Formatting formatting = Formatting.byCode(val);
if (formatting == null || !formatting.isColor()) {
continue;
}
if (color.getRgb() == formatting.getColorValue()) {
return true;
}
}
return false;
}
return true;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\finder\UpperLowerFinder.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.finder;
import java.util.regex.Pattern;
public class UpperLowerFinder extends PatternFinder {
@Override
public Pattern getPattern(String toMatch) {
return Pattern.compile(Pattern.quote(toMatch), Pattern.CASE_INSENSITIVE);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\gui\CleanButton.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.gui;
import fi.dy.masa.malilib.gui.button.ButtonBase;
import fi.dy.masa.malilib.render.RenderUtils;
import io.github.darkkronicle.advancedchatcore.util.Color;
import io.github.darkkronicle.advancedchatcore.util.Colors;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.util.math.MatrixStack;
/** A simple button */
@EqualsAndHashCode(callSuper = false)
@ToString
@Environment(EnvType.CLIENT)
public class CleanButton extends ButtonBase {
protected Color baseColor;
private MinecraftClient client = MinecraftClient.getInstance();
/**
* Constructs a new simple clean button
*
* @param x X
* @param y Y
* @param width Width
* @param height Height
* @param baseColor Color that it should render when not hovered
* @param text Text to render
*/
public CleanButton(int x, int y, int width, int height, Color baseColor, String text) {
super(x, y, width, height, text);
this.x = x;
this.y = y;
this.baseColor = baseColor;
}
@Override
public void render(int mouseX, int mouseY, boolean selected, MatrixStack matrixStack) {
int relMX = mouseX - x;
int relMY = mouseY - y;
hovered = relMX >= 0 && relMX <= width && relMY >= 0 && relMY <= height;
Color color = baseColor;
if (hovered) {
color = Colors.getInstance().getColor("white").get().withAlpha(color.alpha());
}
RenderUtils.drawRect(x, y, width, height, color.color());
drawCenteredString(
(x + (width / 2)),
(y + (height / 2) - 3),
Colors.getInstance().getColorOrWhite("white").color(),
displayString,
matrixStack);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\gui\ConfigGuiListBase.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.gui;
import fi.dy.masa.malilib.gui.widgets.WidgetListBase;
import fi.dy.masa.malilib.gui.widgets.WidgetListEntryBase;
import io.github.darkkronicle.advancedchatcore.config.gui.GuiConfig;
import io.github.darkkronicle.advancedchatcore.config.gui.GuiConfigHandler;
import java.util.List;
/** GUI list base to work in a configuration screen */
public abstract class ConfigGuiListBase<
TYPE,
WIDGET extends WidgetListEntryBase<TYPE>,
WIDGETLIST extends WidgetListBase<TYPE, WIDGET>>
extends CoreGuiListBase<TYPE, WIDGET, WIDGETLIST> {
public ConfigGuiListBase(List<GuiConfigHandler.TabButton> tabButtons) {
this(10, 60, tabButtons);
}
public ConfigGuiListBase() {
this(10, 60, null);
}
public ConfigGuiListBase(int listX, int listY, List<GuiConfigHandler.TabButton> tabButtons) {
super(listX, listY);
}
@Override
public void initGui() {
super.initGui();
int x = 10;
int y = 26;
y += (22 * GuiConfig.addTabButtons(this, 10, y));
if (GuiConfig.TAB.getChildren() != null && GuiConfig.TAB.getChildren().size() > 0) {
y += (22 * GuiConfig.addAllChildrenButtons(this, GuiConfig.TAB, 10, y));
}
this.setListPosition(this.getListX(), y);
this.reCreateListWidget();
this.getListWidget().refreshEntries();
y += 24;
initGuiConfig(x, y);
}
/** Method when the GUI is initialized. This one takes an X,Y that is away from the buttons */
public void initGuiConfig(int x, int y) {}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\gui\ContextMenu.java
|
package io.github.darkkronicle.advancedchatcore.gui;
import fi.dy.masa.malilib.gui.widgets.WidgetBase;
import io.github.darkkronicle.advancedchatcore.util.Color;
import io.github.darkkronicle.advancedchatcore.util.TextUtil;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawableHelper;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.Text;
import java.util.LinkedHashMap;
public class ContextMenu extends WidgetBase {
private final LinkedHashMap<Text, ContextConsumer> options;
private Text hoveredEntry = null;
@Getter
private final int contextX;
@Getter
private final int contextY;
@Getter
@Setter
private Runnable close;
@Setter
@Getter
private Color background;
@Setter
@Getter
private Color hover;
public ContextMenu(int x, int y, LinkedHashMap<Text, ContextConsumer> options, Runnable close) {
this(x, y, options, close, new Color(0, 0, 0, 200), new Color(255, 255, 255, 100));
}
public ContextMenu(int x, int y, LinkedHashMap<Text, ContextConsumer> options, Runnable close, Color background, Color hover) {
super(x, y, 10, 10);
this.contextX = x;
this.contextY = y;
this.options = options;
updateDimensions();
this.close = close;
this.background = background;
this.hover = hover;
}
public void updateDimensions() {
setWidth(TextUtil.getMaxLengthString(options.keySet().stream().map(Text::getString).toList()) + 4);
setHeight(options.size() * (textRenderer.fontHeight + 2));
int windowWidth = MinecraftClient.getInstance().getWindow().getScaledWidth();
int windowHeight = MinecraftClient.getInstance().getWindow().getScaledHeight();
if (x + width > windowWidth) {
x = windowWidth - width;
}
if (y + height > windowHeight) {
y = windowHeight - height;
}
}
@Override
public boolean onMouseClicked(int mouseX, int mouseY, int mouseButton) {
boolean success = super.onMouseClicked(mouseX, mouseY, mouseButton);
if (success) {
return true;
}
// Didn't click on this
close.run();
return false;
}
@Override
protected boolean onMouseClickedImpl(int mouseX, int mouseY, int mouseButton) {
if (mouseButton != 0) {
return false;
}
if (hoveredEntry == null) {
return false;
}
options.get(hoveredEntry).takeAction(contextX, contextY);
close.run();
return true;
}
@Override
public void render(int mouseX, int mouseY, boolean selected, MatrixStack matrixStack) {
drawRect(matrixStack, x, y, width, height, background.color());
int rX = x + 2;
int rY = y + 2;
hoveredEntry = null;
for (Text option : options.keySet()) {
if (mouseX >= x && mouseX <= x + width && mouseY >= rY - 2 && mouseY < rY + fontHeight + 1) {
hoveredEntry = option;
drawRect(matrixStack, rX - 2, rY - 2, width, textRenderer.fontHeight + 2, hover.color());
}
textRenderer.drawWithShadow(matrixStack, option, rX, rY, -1);
rY += textRenderer.fontHeight + 2;
}
}
private static void drawRect(MatrixStack stack, int x, int y, int width, int height, int color) {
DrawableHelper.fill(stack, x, y, x + width, y + height, color);
}
public interface ContextConsumer {
void takeAction(int x, int y);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\gui\CoreGuiListBase.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.gui;
import fi.dy.masa.malilib.gui.GuiListBase;
import fi.dy.masa.malilib.gui.button.ButtonBase;
import fi.dy.masa.malilib.gui.interfaces.ISelectionListener;
import fi.dy.masa.malilib.gui.widgets.WidgetListBase;
import fi.dy.masa.malilib.gui.widgets.WidgetListEntryBase;
import io.github.darkkronicle.advancedchatcore.interfaces.IClosable;
public abstract class CoreGuiListBase<
TYPE,
WIDGET extends WidgetListEntryBase<TYPE>,
WIDGETLIST extends WidgetListBase<TYPE, WIDGET>>
extends GuiListBase<TYPE, WIDGET, WIDGETLIST>
implements ISelectionListener<TYPE>, IClosable {
public CoreGuiListBase(int listX, int listY) {
super(listX, listY);
}
@Override
protected WIDGETLIST createListWidget(int listX, int listY) {
return null;
}
@Override
protected int getBrowserWidth() {
return this.width - 20;
}
@Override
protected int getBrowserHeight() {
return this.height - 6 - this.getListY();
}
@Override
public void onSelectionChange(TYPE entry) {}
@Override
public void close(ButtonBase button) {
this.closeGui(true);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\gui\IconButton.java
|
package io.github.darkkronicle.advancedchatcore.gui;
import fi.dy.masa.malilib.render.RenderUtils;
import io.github.darkkronicle.advancedchatcore.util.Color;
import io.github.darkkronicle.advancedchatcore.util.Colors;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawableHelper;
import net.minecraft.client.sound.PositionedSoundInstance;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.Identifier;
import java.util.function.Consumer;
public class IconButton extends CleanButton {
@Setter
@Getter
private int padding;
@Setter
@Getter
private Identifier icon;
@Setter
@Getter
private int iconWidth;
@Setter
@Getter
private int iconHeight;
@Setter
@Getter
private Consumer<IconButton> onClick;
@Getter
@Setter
private String onHover;
public IconButton(int x, int y, int sideLength, int iconLength, Identifier icon, Consumer<IconButton> mouseClick) {
this(x, y, sideLength, sideLength, iconLength, iconLength, icon, mouseClick);
}
public IconButton(int x, int y, int width, int height, int iconWidth, int iconHeight, Identifier icon, Consumer<IconButton> mouseClick) {
this(x, y, width, height, 2, iconWidth, iconHeight, icon, mouseClick, null);
}
public IconButton(int x, int y, int width, int height, int padding, int iconWidth, int iconHeight, Identifier icon, Consumer<IconButton> mouseClick, String onHover) {
super(x, y, width, height, null, null);
this.padding = padding;
this.iconWidth = iconWidth;
this.iconHeight = iconHeight;
this.icon = icon;
this.onClick = mouseClick;
this.onHover = onHover;
}
@Override
public void render(int mouseX, int mouseY, boolean unused, MatrixStack matrixStack) {
int relMX = mouseX - x;
int relMY = mouseY - y;
hovered = relMX >= 0 && relMX <= width && relMY >= 0 && relMY <= height;
Color plusBack = Colors.getInstance().getColorOrWhite("background").withAlpha(100);
if (hovered) {
plusBack = Colors.getInstance().getColorOrWhite("hover").withAlpha(plusBack.alpha());
}
RenderUtils.drawRect(x, y, width, height, plusBack.color());
RenderUtils.color(1, 1, 1, 1);
RenderUtils.bindTexture(icon);
DrawableHelper.drawTexture(matrixStack, x + padding, y + padding, width - (padding * 2), height - (padding * 2),
0, 0, iconWidth, iconHeight, iconWidth, iconHeight);
if (hovered && onHover != null) {
DrawableHelper.drawCenteredTextWithShadow(
matrixStack,
MinecraftClient.getInstance().textRenderer,
onHover,
mouseX + 4,
mouseY - 16,
Colors.getInstance().getColorOrWhite("white").color());
}
}
@Override
protected boolean onMouseClickedImpl(int mouseX, int mouseY, int mouseButton) {
this.mc.getSoundManager().play(PositionedSoundInstance.master(SoundEvents.UI_BUTTON_CLICK, 1.0F));
onClick.accept(this);
return true;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\gui\WidgetConfigList.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.gui;
import fi.dy.masa.malilib.gui.GuiTextFieldGeneric;
import fi.dy.masa.malilib.gui.interfaces.ISelectionListener;
import fi.dy.masa.malilib.gui.widgets.WidgetListBase;
import fi.dy.masa.malilib.gui.wrappers.TextFieldWrapper;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.gui.screen.Screen;
public abstract class WidgetConfigList<TYPE, WIDGET extends WidgetConfigListEntry<TYPE>>
extends WidgetListBase<TYPE, WIDGET> {
protected List<TextFieldWrapper<GuiTextFieldGeneric>> textFields = new ArrayList<>();
public WidgetConfigList(
int x,
int y,
int width,
int height,
ISelectionListener<TYPE> selectionListener,
Screen parent) {
super(x, y, width, height, selectionListener);
this.browserEntryHeight = 22;
this.setParent(parent);
}
@Override
protected void reCreateListEntryWidgets() {
textFields.clear();
super.reCreateListEntryWidgets();
}
public void addTextField(TextFieldWrapper<GuiTextFieldGeneric> text) {
textFields.add(text);
}
protected void clearTextFieldFocus() {
for (TextFieldWrapper<GuiTextFieldGeneric> field : this.textFields) {
GuiTextFieldGeneric textField = field.getTextField();
if (textField.isFocused()) {
textField.setFocused(false);
break;
}
}
}
@Override
public boolean onMouseClicked(int mouseX, int mouseY, int mouseButton) {
clearTextFieldFocus();
return super.onMouseClicked(mouseX, mouseY, mouseButton);
}
@Override
public boolean onKeyTyped(int keyCode, int scanCode, int modifiers) {
for (WidgetConfigListEntry<TYPE> widget : this.listWidgets) {
if (widget.onKeyTyped(keyCode, scanCode, modifiers)) {
return true;
}
}
return super.onKeyTyped(keyCode, scanCode, modifiers);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\gui\WidgetConfigListEntry.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.gui;
import com.mojang.blaze3d.systems.RenderSystem;
import fi.dy.masa.malilib.gui.GuiTextFieldGeneric;
import fi.dy.masa.malilib.gui.widgets.WidgetBase;
import fi.dy.masa.malilib.gui.widgets.WidgetListEntryBase;
import fi.dy.masa.malilib.gui.wrappers.TextFieldWrapper;
import fi.dy.masa.malilib.render.RenderUtils;
import io.github.darkkronicle.advancedchatcore.util.Colors;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.util.math.MatrixStack;
@Environment(EnvType.CLIENT)
public abstract class WidgetConfigListEntry<TYPE> extends WidgetListEntryBase<TYPE> {
private final boolean odd;
private final List<String> hoverLines;
@Setter @Getter private int buttonStartX;
public WidgetConfigListEntry(
int x, int y, int width, int height, boolean isOdd, TYPE entry, int listIndex) {
this(x, y, width, height, isOdd, entry, listIndex, null);
}
public WidgetConfigListEntry(
int x,
int y,
int width,
int height,
boolean isOdd,
TYPE entry,
int listIndex,
List<String> hoverLines) {
super(x, y, width, height, entry, listIndex);
this.odd = isOdd;
this.hoverLines = hoverLines;
this.buttonStartX = x + width;
}
/** Get's the name to render for the entry. */
public String getName() {
return "";
}
public List<TextFieldWrapper<GuiTextFieldGeneric>> getTextFields() {
return null;
}
@Override
public void render(int mouseX, int mouseY, boolean selected, MatrixStack matrixStack) {
RenderUtils.color(1f, 1f, 1f, 1f);
// Draw a lighter background for the hovered and the selected entry
if (selected || this.isMouseOver(mouseX, mouseY)) {
RenderUtils.drawRect(
this.x,
this.y,
this.width,
this.height,
Colors.getInstance().getColorOrWhite("white").withAlpha(150).color());
} else if (this.odd) {
RenderUtils.drawRect(
this.x,
this.y,
this.width,
this.height,
Colors.getInstance().getColorOrWhite("white").withAlpha(70).color());
} else {
RenderUtils.drawRect(
this.x,
this.y,
this.width,
this.height,
Colors.getInstance().getColorOrWhite("white").withAlpha(50).color());
}
renderEntry(mouseX, mouseY, selected, matrixStack);
RenderUtils.color(1f, 1f, 1f, 1f);
RenderSystem.disableBlend();
this.drawTextFields(mouseX, mouseY, matrixStack);
super.render(mouseX, mouseY, selected, matrixStack);
RenderUtils.disableDiffuseLighting();
}
/**
* Render's in the middle of the rendering cycle. After the background, but before it goes to
* super.
*/
public void renderEntry(int mouseX, int mouseY, boolean selected, MatrixStack matrixStack) {
String name = getName();
this.drawString(
this.x + 4,
this.y + 7,
Colors.getInstance().getColorOrWhite("white").color(),
name,
matrixStack);
}
@Override
public void postRenderHovered(
int mouseX, int mouseY, boolean selected, MatrixStack matrixStack) {
super.postRenderHovered(mouseX, mouseY, selected, matrixStack);
if (hoverLines == null) {
return;
}
if (mouseX >= this.x
&& mouseX < this.buttonStartX
&& mouseY >= this.y
&& mouseY <= this.y + this.height) {
RenderUtils.drawHoverText(mouseX, mouseY, this.hoverLines, matrixStack);
}
}
@Override
protected boolean onKeyTypedImpl(int keyCode, int scanCode, int modifiers) {
if (getTextFields() == null) {
return false;
}
for (TextFieldWrapper<GuiTextFieldGeneric> field : getTextFields()) {
if (field != null && field.isFocused()) {
return field.onKeyTyped(keyCode, scanCode, modifiers);
}
}
return false;
}
@Override
protected boolean onCharTypedImpl(char charIn, int modifiers) {
if (getTextFields() != null) {
for (TextFieldWrapper<GuiTextFieldGeneric> field : getTextFields()) {
if (field != null && field.onCharTyped(charIn, modifiers)) {
return true;
}
}
}
return super.onCharTypedImpl(charIn, modifiers);
}
@Override
protected boolean onMouseClickedImpl(int mouseX, int mouseY, int mouseButton) {
if (super.onMouseClickedImpl(mouseX, mouseY, mouseButton)) {
return true;
}
boolean ret = false;
if (getTextFields() != null) {
for (TextFieldWrapper<GuiTextFieldGeneric> field : getTextFields()) {
if (field != null) {
ret = field.getTextField().mouseClicked(mouseX, mouseY, mouseButton);
}
}
}
if (!this.subWidgets.isEmpty()) {
for (WidgetBase widget : this.subWidgets) {
ret |=
widget.isMouseOver(mouseX, mouseY)
&& widget.onMouseClicked(mouseX, mouseY, mouseButton);
}
}
return ret;
}
protected void drawTextFields(int mouseX, int mouseY, MatrixStack matrixStack) {
if (getTextFields() == null) {
return;
}
for (TextFieldWrapper<GuiTextFieldGeneric> field : getTextFields()) {
field.getTextField().render(matrixStack, mouseX, mouseY, 0f);
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\hotkeys\InputHandler.java
|
package io.github.darkkronicle.advancedchatcore.hotkeys;
import fi.dy.masa.malilib.config.options.ConfigHotkey;
import fi.dy.masa.malilib.event.InputEventHandler;
import fi.dy.masa.malilib.hotkeys.*;
import lombok.Getter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class InputHandler implements IKeybindProvider, IKeyboardInputHandler, IMouseInputHandler {
private final static InputHandler INSTANCE = new InputHandler();
@Getter
private final Map<String, List<ConfigHotkey>> hotkeys = new HashMap<>();
@Getter
private final Map<String, String> translation = new HashMap<>();
public static InputHandler getInstance() {
return INSTANCE;
}
private InputHandler() {}
public void clear(String modId) {
hotkeys.remove(modId);
}
public void addDisplayName(String modId, String displayName) {
translation.put(modId, displayName);
}
public void add(String modId, ConfigHotkey hotkey) {
if (!hotkeys.containsKey(modId)) {
hotkeys.put(modId, new ArrayList<>());
}
hotkeys.get(modId).add(hotkey);
}
public void add(String modId, ConfigHotkey hotkey, IHotkeyCallback callback) {
hotkey.getKeybind().setCallback(callback);
add(modId, hotkey);
}
@Override
public void addKeysToMap(IKeybindManager manager) {
for (List<ConfigHotkey> hots : hotkeys.values()) {
for (IHotkey hotkey : hots) {
manager.addKeybindToMap(hotkey.getKeybind());
}
}
}
@Override
public void addHotkeys(IKeybindManager manager) {
for (Map.Entry<String, List<ConfigHotkey>> hots : hotkeys.entrySet()) {
manager.addHotkeysForCategory(hots.getKey(), "hotkeys", hots.getValue());
}
}
public void reload() {
InputEventHandler.getKeybindManager().updateUsedKeys();
}
public String getDisplayName(String key) {
return translation.getOrDefault(key, key);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\AdvancedChatScreenSection.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import io.github.darkkronicle.advancedchatcore.chat.AdvancedChatScreen;
import lombok.Getter;
import net.minecraft.client.gui.Drawable;
import net.minecraft.client.util.math.MatrixStack;
/**
* A class meant to extend onto the {@link AdvancedChatScreen}
*
* <p>This is used so that many modules can add onto the screen without problems occuring.
*/
public abstract class AdvancedChatScreenSection implements Drawable {
/** The {@link AdvancedChatScreen} that is linked to this section */
@Getter private final AdvancedChatScreen screen;
public AdvancedChatScreenSection(AdvancedChatScreen screen) {
this.screen = screen;
}
/** Triggers when the gui is initiated */
public void initGui() {}
/**
* Triggered when the window is resized
*
* @param width Window width
* @param height Window height
*/
public void resize(int width, int height) {}
/** Triggered when the GUI is closed */
public void removed() {}
/**
* Triggered when the chatfield text is pudated
*
* @param chatText Updated value (?)
* @param text The text of the chatfield
*/
public void onChatFieldUpdate(String chatText, String text) {}
/**
* Triggered when a key is pressed
*
* @param keyCode Keycode
* @param scanCode Scancode
* @param modifiers Modifiers
* @return If it was handled and should stop.
*/
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
return false;
}
/**
* Triggered when the mouse is scrolled
*
* @param mouseX MouseX
* @param mouseY MouseY
* @param amount Scroll amount
* @return If it was handled and should stop.
*/
public boolean mouseScrolled(double mouseX, double mouseY, double amount) {
return false;
}
/**
* Triggered when the mouse is clicked
*
* @param mouseX MouseX
* @param mouseY MouseY
* @param button Mouse button
* @return If it was handled and should stop.
*/
public boolean mouseClicked(double mouseX, double mouseY, int button) {
return false;
}
/**
* Triggered when the mouse click is released
*
* @param mouseX MouseX
* @param mouseY MouseY
* @param mouseButton Mouse button
* @return If it was handled and should stop.
*/
public boolean mouseReleased(double mouseX, double mouseY, int mouseButton) {
return false;
}
/**
* @param mouseX
* @param mouseY
* @param button
* @param deltaX
* @param deltaY
* @return If it was handled and should stop.
*/
public boolean mouseDragged(
double mouseX, double mouseY, int button, double deltaX, double deltaY) {
return false;
}
/**
* Called when the chat field gets set due to history (up arrows)
*
* @param hist History set from
*/
public void setChatFromHistory(String hist) {}
/**
* Called when the screen renders.
*
* @param matrixStack MatrixStack
* @param mouseX MouseX
* @param mouseY MouseY
* @param partialTicks Partial tick from the last tick
*/
public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\ConfigRegistryOption.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import fi.dy.masa.malilib.config.IConfigOptionListEntry;
import fi.dy.masa.malilib.config.options.ConfigBoolean;
import io.github.darkkronicle.advancedchatcore.config.SaveableConfig;
import java.util.Map;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
/**
* A {@link RegistryOption} that can be saved and loaded from a JSON file.
*
* @param <TYPE>
*/
@Environment(EnvType.CLIENT)
public interface ConfigRegistryOption<TYPE>
extends RegistryOption<TYPE>, IConfigOptionListEntry, IJsonApplier {
/**
* Get's a configurable boolean for whether or not the option is active.
*
* @return Configurable boolean
*/
SaveableConfig<ConfigBoolean> getActive();
/**
* Get's if the option is currently active.
*
* @return If the option is active
*/
@Override
default boolean isActive() {
return getActive().config.getBooleanValue();
}
/**
* Save's the config option and the object that it is wrapping.
*
* <p>By default it will only save if the option is active or not, but if the {@link TYPE}
* implements {@link IJsonApplier} it will also save/load that object.
*
* @return Serialized object
*/
@Override
default JsonObject save() {
JsonObject obj = new JsonObject();
obj.add(getActive().key, getActive().config.getAsJsonElement());
JsonObject extra = null;
if (getOption() instanceof IJsonApplier) {
extra = ((IJsonApplier) getOption()).save();
}
if (extra != null) {
for (Map.Entry<String, JsonElement> e : extra.entrySet()) {
obj.add(e.getKey(), e.getValue());
}
}
return obj;
}
/**
* Load's the config option and the object that it is wrapping.
*
* <p>By default it will only load if the option is active or not, but if the {@link TYPE}
* implements {@link IJsonApplier} it will also save/load that object.
*/
@Override
default void load(JsonElement element) {
if (element == null || !element.isJsonObject()) {
return;
}
JsonObject obj = element.getAsJsonObject();
getActive().config.setValueFromJsonElement(obj.get(getActive().key));
if (getOption() instanceof IJsonApplier) {
((IJsonApplier) getOption()).load(obj);
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\IChatMessageProcessor.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import io.github.darkkronicle.advancedchatcore.chat.ChatMessage;
/**
* A processor that will get updated whenever an event in {@link
* io.github.darkkronicle.advancedchatcore.chat.ChatHistory} happens. This gets triggered for
* specific {@link ChatMessage}.
*/
public interface IChatMessageProcessor {
/** Types of chat message events that can be referenced */
enum UpdateType {
/** A new message is sent. This still gets triggered even if the message is stacked. */
NEW,
/** A message is added to the history. This does not get called on stack. */
ADDED,
/** A previous message has been stacked. The stack number has changed. */
STACK,
/**
* A message is removed. This does not get called on clear, but only if a specific message
* was called to remove.
*/
REMOVE,
}
/**
* A method to handle a {@link ChatMessage} update.
*
* @param message Message that was updated
* @param type Type of the update
*/
void onMessageUpdate(ChatMessage message, UpdateType type);
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\IClosable.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import fi.dy.masa.malilib.gui.button.ButtonBase;
public interface IClosable {
void close(ButtonBase button);
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\IFinder.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import io.github.darkkronicle.advancedchatcore.util.StringMatch;
import net.minecraft.text.Text;
import java.util.List;
public interface IFinder {
boolean isMatch(String input, String toMatch);
default boolean isMatch(Text input, String toMatch) {
return isMatch(input.getString(), toMatch);
}
List<StringMatch> getMatches(String input, String toMatch);
default List<StringMatch> getMatches(Text input, String toMatch) {
return getMatches(input.getString(), toMatch);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\IJsonApplier.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/** An interface to serialize and deserialize classes into themselves. */
public interface IJsonApplier {
/**
* Serializes the object into a JsonObject.
*
* @return Constructed JsonObject
*/
JsonObject save();
/**
* Takes a JsonElement and loads it into the class.
*
* @param element Element to load
*/
void load(JsonElement element);
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\IJsonSave.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import com.google.gson.JsonObject;
/**
* Json serializer for other classes.
*
* @param <T> Class that this class serializes.
*/
public interface IJsonSave<T> {
/**
* Returns a new object from a JsonObject to deserialize from.
*
* @param obj Object containing serialized data
* @return Constructed object
*/
T load(JsonObject obj);
/**
* Takes an object (T) and serializes it.
*
* @param t Object to serialize
* @return Serialized {@link JsonObject}
*/
JsonObject save(T t);
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\IMatchProcessor.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import io.github.darkkronicle.advancedchatcore.util.SearchResult;
import net.minecraft.text.Text;
import org.jetbrains.annotations.Nullable;
/**
* An interface to receive text and matches to process.
*
* <p>Similar to {@link IMessageProcessor} but it takes matches and can return a {@link Result}
*/
public interface IMatchProcessor extends IMessageProcessor {
/** Different outcome's the processor can have */
enum Result {
FAIL(false, true, false),
PROCESSED(true, false, false),
FORCE_FORWARD(true, true, true),
FORCE_STOP(true, false, true);
public final boolean success;
public final boolean forward;
public final boolean force;
Result(boolean success, boolean forward, boolean force) {
this.success = success;
this.forward = forward;
this.force = force;
}
public static Result getFromBool(boolean success) {
if (!success) {
return FAIL;
}
return PROCESSED;
}
}
@Override
default boolean process(Text text, Text unfiltered) {
return processMatches(text, unfiltered, null).success;
}
/**
* Process specific matches and return how the rest of the processors should be handled
*
* @param text Final text
* @param unfiltered Unfiltered version of text. If not available null.
* @param search {@link SearchResult} matches
* @return The {@link Result} that the method performed
*/
Result processMatches(
Text text, @Nullable Text unfiltered, @Nullable SearchResult search);
/**
* Whether or not this processor should only trigger when matches are present. If false {@link
* SearchResult} can be null.
*
* @return If this processor should only trigger when matches are present
*/
default boolean matchesOnly() {
return true;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\IMessageFilter.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import net.minecraft.text.Text;
import java.util.Optional;
/** An interface to modify text. */
public interface IMessageFilter {
/**
* Modifies text
*
* @param text Text to modify
* @return Modified text. If empty, the text won't be changed.
*/
Optional<Text> filter(Text text);
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\IMessageProcessor.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import net.minecraft.client.gui.hud.MessageIndicator;
import net.minecraft.network.message.MessageSignatureData;
import net.minecraft.text.Text;
import java.util.Optional;
import org.jetbrains.annotations.Nullable;
/** An interface for taking text and processing it. */
public interface IMessageProcessor extends IMessageFilter {
/**
* Processes text without the unfiltered text.
*
* <p>Deprecated because it won't return anything. If unfiltered doesn't exist, insert null into
* process.
*
* @param text Text to modify
* @return Empty
*/
@Deprecated
@Override
default Optional<Text> filter(Text text) {
process(text, null);
return Optional.empty();
}
/**
* Consumes text.
*
* @param text Final text to process
* @param unfiltered Original text (if available)
* @return If the processing was a success
*/
boolean process(Text text, @Nullable Text unfiltered);
default boolean process(Text text, @Nullable Text unfilterered, @Nullable MessageSignatureData signature, @Nullable MessageIndicator indicator) {
return process(text, unfilterered);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\IScreenSupplier.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import java.util.function.Supplier;
import net.minecraft.client.gui.screen.Screen;
import org.jetbrains.annotations.Nullable;
/** An interface to supply a screen. */
public interface IScreenSupplier {
/**
* Get's a supplier of a screen based off of a parent.
*
* @param parent Parent screen (nullable)
* @return Supplier of a screen
*/
Supplier<Screen> getScreen(@Nullable Screen parent);
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\IStringFilter.java
|
/*
* Copyright (C) 2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import java.util.Optional;
/** An interface to modify raw string */
public interface IStringFilter {
Optional<String> filter(String input);
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\RegistryOption.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import io.github.darkkronicle.advancedchatcore.util.AbstractRegistry;
import java.util.List;
import java.util.function.Supplier;
import net.minecraft.client.gui.screen.Screen;
/**
* An interface to get a RegistryOption that can be saved/configured in game.
*
* @param <TYPE> Object type to be wrapped
*/
public interface RegistryOption<TYPE> {
/**
* Get's the object that this option is wrapping
*
* @return Object that is wrapped
*/
TYPE getOption();
/**
* Whether or not this option is currently active
*
* @return If it is active
*/
boolean isActive();
/**
* Get's the string that will be saved inside of the JSON.
*
* @return Save string
*/
String getSaveString();
/**
* Copies the registry option without a parent registry
*
* @return A copy of this object
*/
default RegistryOption<TYPE> copy() {
return copy(null);
}
/**
* If this value should be hidden in the menu
*
* @return If it should be hidden
*/
default boolean isHidden() {
return false;
}
/**
* Copies the registry option with a parent registry that it will be tied to.
*
* <p>Used for copying registries so that options can be modified easily.
*
* @param registry Registry that will be the parent
* @return Copied object
*/
RegistryOption<TYPE> copy(AbstractRegistry<TYPE, ?> registry);
/**
* Get's the configuration screen of this option. If this isn't null a button will be generated
* if in a GUI.
*
* @param parent Parent screen
* @return Supplier for the config screen. Null if it doesn't exist.
*/
default Supplier<Screen> getScreen(Screen parent) {
if (!(getOption() instanceof IScreenSupplier)) {
return null;
}
return ((IScreenSupplier) getOption()).getScreen(parent);
}
/**
* Hover lines to show when in the GUI and hovering.
*
* @return List of strings that contain the hover lines
*/
default List<String> getHoverLines() {
return null;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\interfaces\Translatable.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.interfaces;
import fi.dy.masa.malilib.util.StringUtils;
/** An interface for a translatable object */
public interface Translatable {
/**
* Translation key of the object
*
* @return Translation key
*/
String getTranslationKey();
/**
* Translates the object
*
* @return Translated string
*/
default String translate() {
return StringUtils.translate(getTranslationKey());
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\konstruct\AdvancedChatKonstruct.java
|
package io.github.darkkronicle.advancedchatcore.konstruct;
import io.github.darkkronicle.Konstruct.functions.Function;
import io.github.darkkronicle.Konstruct.functions.NamedFunction;
import io.github.darkkronicle.Konstruct.functions.Variable;
import io.github.darkkronicle.Konstruct.nodes.Node;
import io.github.darkkronicle.Konstruct.parser.*;
import io.github.darkkronicle.Konstruct.reader.builder.NodeBuilder;
import io.github.darkkronicle.Konstruct.type.IntegerObject;
import io.github.darkkronicle.Konstruct.type.StringObject;
import io.github.darkkronicle.addons.*;
import io.github.darkkronicle.advancedchatcore.AdvancedChatCore;
import io.github.darkkronicle.advancedchatcore.util.Color;
import io.github.darkkronicle.advancedchatcore.util.Colors;
import io.github.darkkronicle.advancedchatcore.util.TextUtil;
import lombok.Getter;
import net.minecraft.util.Util;
import java.util.List;
public class AdvancedChatKonstruct {
private static final AdvancedChatKonstruct INSTANCE = new AdvancedChatKonstruct();
public static AdvancedChatKonstruct getInstance() {
return INSTANCE;
}
@Getter
private NodeProcessor processor;
private AdvancedChatKonstruct() {
reset();
addFunction(new CalculatorFunction());
addFunction(new RandomFunction());
addFunction(new ReplaceFunction());
addFunction(new RoundFunction());
addFunction(new OwOFunction());
addFunction(new RomanNumeralFunction());
addFunction(new IsMatchFunction());
addFunction(new TimeFunction());
addVariable("server", () -> new StringObject(AdvancedChatCore.getServer()));
addFunction("randomString", new Function() {
@Override
public Result parse(ParseContext context, List<Node> input) {
return Result.success(AdvancedChatCore.getRandomString());
}
@Override
public IntRange getArgumentCount() {
return IntRange.none();
}
});
addFunction("getColor", new Function() {
@Override
public Result parse(ParseContext context, List<Node> input) {
Result res = Function.parseArgument(context, input, 0);
if (Function.shouldReturn(res)) return res;
Color color = Colors.getInstance().getColorOrWhite(res.getContent().getString());
return Result.success(color.getString());
}
@Override
public IntRange getArgumentCount() {
return IntRange.of(1);
}
});
addFunction("superscript", new Function() {
@Override
public Result parse(ParseContext context, List<Node> input) {
int number;
try {
Result res = Function.parseArgument(context, input, 0);
if (Function.shouldReturn(res)) return res;
number = Integer.parseInt(res.getContent().getString().strip());
} catch (NumberFormatException e) {
return Result.success("NaN");
}
return Result.success(TextUtil.toSuperscript(number));
}
@Override
public IntRange getArgumentCount() {
return IntRange.of(1);
}
});
addVariable("ms", () -> new IntegerObject((int) Util.getMeasuringTimeMs()));
}
public ParseResult parse(Node node) {
return processor.parse(node);
}
public Node getNode(String string) {
return new NodeBuilder(string).build();
}
public NodeProcessor copy() {
return processor.copy();
}
/** Not really recommended to call... */
public void reset() {
this.processor = new NodeProcessor();
}
public void addVariable(String key, Variable variable) {
processor.addVariable(key, variable);
}
public void addFunction(NamedFunction function) {
processor.addFunction(function);
}
public void addFunction(String key, Function function) {
processor.addFunction(key, function);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\konstruct\StringMatchObject.java
|
package io.github.darkkronicle.advancedchatcore.konstruct;
import io.github.darkkronicle.Konstruct.functions.ObjectFunction;
import io.github.darkkronicle.Konstruct.nodes.Node;
import io.github.darkkronicle.Konstruct.parser.IntRange;
import io.github.darkkronicle.Konstruct.parser.ParseContext;
import io.github.darkkronicle.Konstruct.parser.Result;
import io.github.darkkronicle.Konstruct.type.IntegerObject;
import io.github.darkkronicle.Konstruct.type.KonstructObject;
import io.github.darkkronicle.Konstruct.type.StringObject;
import io.github.darkkronicle.advancedchatcore.util.StringMatch;
import java.util.List;
public class StringMatchObject extends KonstructObject<StringMatchObject> {
private final StringMatch result;
private final static List<ObjectFunction<StringMatchObject>> FUNCTIONS = List.of(
new ObjectFunction<>() {
@Override
public Result parse(ParseContext context, StringMatchObject self, List<Node> input) {
return Result.success(new IntegerObject(self.result.start));
}
@Override
public String getName() {
return "getStart";
}
@Override
public IntRange getArgumentCount() {
return IntRange.of(0);
}
},
new ObjectFunction<>() {
@Override
public Result parse(ParseContext context, StringMatchObject self, List<Node> input) {
return Result.success(new IntegerObject(self.result.end));
}
@Override
public String getName() {
return "getEnd";
}
@Override
public IntRange getArgumentCount() {
return IntRange.of(0);
}
},
new ObjectFunction<>() {
@Override
public Result parse(ParseContext context, StringMatchObject self, List<Node> input) {
return Result.success(new StringObject(self.result.match));
}
@Override
public String getName() {
return "getMessage";
}
@Override
public IntRange getArgumentCount() {
return IntRange.of(0);
}
}
);
public StringMatchObject(StringMatch result) {
super(FUNCTIONS);
this.result = result;
}
@Override
public String getString() {
return result.toString();
}
@Override
public String getTypeName() {
return "string_match";
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\mixin\MixinChatHud.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.mixin;
import io.github.darkkronicle.advancedchatcore.chat.AdvancedChatScreen;
import io.github.darkkronicle.advancedchatcore.chat.MessageDispatcher;
import io.github.darkkronicle.advancedchatcore.config.ConfigStorage;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.hud.ChatHud;
import net.minecraft.client.gui.hud.MessageIndicator;
import net.minecraft.network.message.MessageSignatureData;
import net.minecraft.text.Text;
import org.jetbrains.annotations.Nullable;
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;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(value = ChatHud.class, priority = 1050)
public class MixinChatHud {
@Shadow @Final private MinecraftClient client;
@Inject(
method = "addMessage(Lnet/minecraft/text/Text;Lnet/minecraft/network/message/MessageSignatureData;Lnet/minecraft/client/gui/hud/MessageIndicator;)V",
at = @At("HEAD"),
cancellable = true)
private void addMessage(Text message, @Nullable MessageSignatureData signature, @Nullable MessageIndicator indicator, CallbackInfo ci) {
// Pass forward messages to dispatcher
MessageDispatcher.getInstance().handleText(message, signature, indicator);
ci.cancel();
}
@Inject(method = "clear", at = @At("HEAD"), cancellable = true)
private void clearMessages(boolean clearTextHistory, CallbackInfo ci) {
if (!clearTextHistory) {
// This only gets called if it is the keybind f3 + d
return;
}
if (!ConfigStorage.General.CLEAR_ON_DISCONNECT.config.getBooleanValue()) {
// Cancel clearing if it's turned off
ci.cancel();
}
}
@Inject(method = "isChatFocused", at = @At("HEAD"), cancellable = true)
private void isChatFocused(CallbackInfoReturnable<Boolean> ci) {
// If the chat is focused
ci.setReturnValue(AdvancedChatScreen.PERMANENT_FOCUS || client.currentScreen instanceof AdvancedChatScreen);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\mixin\MixinChatHudInvoker.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.mixin;
import net.minecraft.client.gui.hud.ChatHud;
import net.minecraft.client.gui.hud.MessageIndicator;
import net.minecraft.network.message.MessageSignatureData;
import net.minecraft.text.Text;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(ChatHud.class)
public interface MixinChatHudInvoker {
@Invoker
void invokeAddMessage(Text message, @Nullable MessageSignatureData signature, int ticks, @Nullable MessageIndicator indicator, boolean refresh);
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\mixin\MixinChatScreen.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.mixin;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.gui.screen.ChatScreen;
import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder;
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.callback.CallbackInfo;
@Environment(EnvType.CLIENT)
@Mixin(ChatScreen.class)
public class MixinChatScreen {
@Inject(method = "addScreenNarrations", at = @At("HEAD"), cancellable = true)
public void screenNarrations(NarrationMessageBuilder builder, CallbackInfo ci) {
// Don't cause random narrations to happen/crashes
ci.cancel();
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\mixin\MixinClientPlayerEntity.java
|
package io.github.darkkronicle.advancedchatcore.mixin;
import io.github.darkkronicle.advancedchatcore.chat.AdvancedChatScreen;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.world.World;
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;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ClientPlayerEntity.class)
public abstract class MixinClientPlayerEntity extends Entity {
@Shadow @Final protected MinecraftClient client;
@Shadow public float nextNauseaStrength;
public MixinClientPlayerEntity(EntityType<?> type, World world) {
super(type, world);
}
@Inject(
method="updateNausea",
at = @At(value="INVOKE", target="Lnet/minecraft/client/MinecraftClient;setScreen(Lnet/minecraft/client/gui/screen/Screen;)V"),
cancellable = true
)
public void updateNauseaHook(CallbackInfo ci) {
if (client.currentScreen instanceof AdvancedChatScreen) {
ci.cancel();
nextNauseaStrength += 0.0125f;
if (this.nextNauseaStrength >= 1.0f) {
this.nextNauseaStrength = 1.0f;
}
inNetherPortal = false;
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\mixin\MixinKeyboard.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.mixin;
import io.github.darkkronicle.advancedchatcore.chat.ChatHistory;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.Keyboard;
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.callback.CallbackInfoReturnable;
@Environment(EnvType.CLIENT)
@Mixin(Keyboard.class)
public class MixinKeyboard {
@Inject(
method = "processF3",
at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/hud/ChatHud;clear(Z)V"))
public void processF3Chat(int key, CallbackInfoReturnable<Boolean> ci) {
// Make it so that history can still be cleared
ChatHistory.getInstance().clearAll();
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\mixin\MixinMessageIndicator.java
|
package io.github.darkkronicle.advancedchatcore.mixin;
import io.github.darkkronicle.advancedchatcore.config.ConfigStorage;
import net.minecraft.client.gui.hud.MessageIndicator;
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.callback.CallbackInfoReturnable;
@Mixin(MessageIndicator.class)
public class MixinMessageIndicator {
@Inject(method = "indicatorColor", at = @At("HEAD"), cancellable = true)
private void getColor(CallbackInfoReturnable<Integer> ci) {
MessageIndicator indicator = ((MessageIndicator) (Object) this);
String name = indicator.loggedName();
ci.setReturnValue(switch (name) {
case "Modified" -> ConfigStorage.ChatScreen.MODIFIED.config.getColor().intValue;
case "Filtered" -> ConfigStorage.ChatScreen.FILTERED.config.getColor().intValue;
case "Not Secure" -> ConfigStorage.ChatScreen.NOT_SECURE.config.getColor().intValue;
default -> // And "System"
ConfigStorage.ChatScreen.SYSTEM.config.getColor().intValue;
});
}
@Inject(method = "icon", at = @At("HEAD"), cancellable = true)
private void getIcon(CallbackInfoReturnable<MessageIndicator.Icon> ci) {
if (!ConfigStorage.ChatScreen.SHOW_CHAT_ICONS.config.getBooleanValue()) {
ci.setReturnValue(null);
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\mixin\MixinMinecraftClient.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.mixin;
import io.github.darkkronicle.advancedchatcore.chat.AdvancedChatScreen;
import io.github.darkkronicle.advancedchatcore.chat.AdvancedSleepingChatScreen;
import io.github.darkkronicle.advancedchatcore.chat.ChatHistory;
import io.github.darkkronicle.advancedchatcore.config.ConfigStorage;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import org.jetbrains.annotations.Nullable;
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;
import org.spongepowered.asm.mixin.injection.ModifyArgs;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.invoke.arg.Args;
@Environment(EnvType.CLIENT)
@Mixin(MinecraftClient.class)
public class MixinMinecraftClient {
@Inject(method = "disconnect(Lnet/minecraft/client/gui/screen/Screen;)V", at = @At("RETURN"))
public void onDisconnect(Screen screen, CallbackInfo ci) {
// Clear data on disconnect
if (ConfigStorage.General.CLEAR_ON_DISCONNECT.config.getBooleanValue()) {
ChatHistory.getInstance().clearAll();
}
}
@Inject(method = "openChatScreen(Ljava/lang/String;)V",
at = @At(value = "HEAD"), cancellable = true)
public void openChatScreen(String text, CallbackInfo ci) {
MinecraftClient.getInstance().setScreen(new AdvancedChatScreen(text));
ci.cancel();
}
@ModifyArg(method = "tick()V",
at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/MinecraftClient;setScreen(Lnet/minecraft/client/gui/screen/Screen;)V", ordinal = 1))
public Screen openSleepingChatScreen(@Nullable Screen screen) {
return new AdvancedSleepingChatScreen();
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\mixin\MixinSleepingChatScreen.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.mixin;
import io.github.darkkronicle.advancedchatcore.chat.AdvancedChatScreen;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.gui.screen.ChatScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.SleepingChatScreen;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.ModifyArg;
@Environment(EnvType.CLIENT)
@Mixin(SleepingChatScreen.class)
public class MixinSleepingChatScreen extends ChatScreen {
public MixinSleepingChatScreen() {
super("");
}
@ModifyArg(method = "closeChatIfEmpty",
at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/MinecraftClient;setScreen(Lnet/minecraft/client/gui/screen/Screen;)V", ordinal = 1))
public Screen openSleepingChatScreen(@Nullable Screen screen) {
return new AdvancedChatScreen(this.chatField.getText());
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\AbstractRegistry.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import io.github.darkkronicle.advancedchatcore.interfaces.RegistryOption;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import lombok.Getter;
import lombok.NonNull;
/**
* Create a registry with options that can be added from anywhere.
*
* @param <TYPE> Class to be wrapped
* @param <OPTION> Wrapper option for the class
*/
public abstract class AbstractRegistry<TYPE, OPTION extends RegistryOption<TYPE>> {
private List<OPTION> options = new ArrayList<>();
public List<OPTION> getAll() {
return options;
}
@Getter private OPTION defaultOption;
/**
* Add's an option directly. Recommended to use register
*
* @param option Option to add
*/
protected void add(OPTION option) {
if (defaultOption == null) {
defaultOption = option;
}
options.add(option);
}
public void register(
Supplier<TYPE> replace, String saveString, String translation, String infoTranslation) {
register(replace, saveString, translation, infoTranslation, true, false);
}
public void register(
Supplier<TYPE> replace,
String saveString,
String translation,
String infoTranslation,
boolean active,
boolean setDefault) {
register(replace, saveString, translation, infoTranslation, active, setDefault, false);
}
public void register(
Supplier<TYPE> replace,
String saveString,
String translation,
String infoTranslation,
boolean active,
boolean setDefault,
boolean hidden) {
OPTION option =
constructOption(
replace,
saveString,
translation,
infoTranslation,
active,
setDefault,
hidden);
options.add(option);
if (setDefault || defaultOption == null) {
defaultOption = option;
}
}
public abstract AbstractRegistry<TYPE, OPTION> clone();
public abstract OPTION constructOption(
Supplier<TYPE> type,
String saveString,
String translation,
String infoTranslation,
boolean active,
boolean setDefault,
boolean hidden);
public void setDefaultOption(@NonNull OPTION newDefault) {
defaultOption = newDefault;
}
public OPTION fromString(String string) {
for (OPTION m : options) {
if (m.getSaveString().equals(string)) {
return m;
}
}
return defaultOption;
}
public OPTION getNext(OPTION option, boolean forward) {
if (options.size() == 0) {
return null;
}
int i = options.indexOf(option);
if (i < 0) {
return options.get(0);
}
if (forward) {
i = i + 1;
if (i >= options.size()) {
return options.get(0);
}
} else {
i = i - 1;
if (i < 0) {
return options.get(options.size() - 1);
}
}
return options.get(i);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\Color.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Value;
import lombok.With;
import lombok.experimental.Accessors;
@Value
@Accessors(fluent = true)
public class Color {
@Getter int red;
@Getter int green;
@Getter int blue;
@Getter
@With(AccessLevel.PUBLIC)
int alpha;
@Getter int color;
public Color(int color) {
this.color = color;
Color completeColor = ColorUtil.intToColor4f(color);
this.red = completeColor.red();
this.green = completeColor.green();
this.blue = completeColor.blue();
this.alpha = completeColor.alpha();
}
public Color(int red, int green, int blue, int alpha) {
if (red > 255) {
red = 255;
}
if (green > 255) {
green = 255;
}
if (blue > 255) {
blue = 255;
}
if (alpha > 255) {
alpha = 255;
}
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
this.color = ColorUtil.colorToInt4f(this);
}
/** Generated for use of Lombok's @With */
public Color(int red, int green, int blue, int alpha, int color) {
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
this.color = ColorUtil.colorToInt4f(this);
}
public String getString() {
return String.format("#%08X", color);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\Colors.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import com.electronwill.nightconfig.core.Config;
import com.electronwill.nightconfig.core.file.FileConfig;
import fi.dy.masa.malilib.util.FileUtils;
import io.github.darkkronicle.advancedchatcore.AdvancedChatCore;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.Getter;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import org.apache.logging.log4j.Level;
/** A class storing data of colors as defined in colors.toml */
@Environment(EnvType.CLIENT)
public class Colors {
private static final Colors INSTANCE = new Colors();
public static Colors getInstance() {
return INSTANCE;
}
@Getter private final Map<String, Color> colors = new HashMap<>();
@Getter private final Map<String, Palette> palettes = new HashMap<>();
private String defaultPalette = "";
private Colors() {}
/**
* Loads configuration from colors.toml
*
* <p>If the file doesn't exist in the configuration directory, it's copied from resources
*/
public void load() {
colors.clear();
palettes.clear();
// Get file or create if it doesn't exist
File file = FileUtils.getConfigDirectory()
.toPath()
.resolve("advancedchat")
.resolve("colors.toml")
.toFile();
if (!file.exists()) {
try {
org.apache.commons.io.FileUtils.copyInputStreamToFile(AdvancedChatCore.getResource("colors.toml"), file);
} catch (Exception e) {
// Rip
AdvancedChatCore.LOGGER.log(Level.ERROR, "Colors could not be loaded correctly!", e);
return;
}
}
// Use night-config toml parsing
FileConfig config = TomlUtil.loadFileWithDefaults(file, "colors.toml");
// Assign colors
Optional<Config> customColors = config.getOptional("color");
if (customColors.isPresent()) {
for (Config.Entry entry : customColors.get().entrySet()) {
this.colors.put(entry.getKey(), hexToSimple(entry.getValue()));
}
}
Optional<Config> palettes = config.getOptional("palettes");
if (palettes.isPresent()) {
// Nested configuration
for (Config.Entry entry : palettes.get().entrySet()) {
ArrayList<Color> colors = new ArrayList<>();
for (String c : (List<String>) entry.getValue()) {
if (this.colors.containsKey(c)) {
// Allow color reference
colors.add(this.colors.get(c));
} else {
colors.add(hexToSimple(c));
}
}
this.palettes.put(entry.getKey(), new Palette(colors));
}
}
// Set default
Optional<String> defaultPalette = config.getOptional("default_palette");
defaultPalette.ifPresent(s -> this.defaultPalette = s);
config.close();
}
/**
* Get's the default palette specified by the user.
*
* @return Palette user specified
*/
public Palette getDefault() {
if (this.palettes.containsKey(defaultPalette)) {
return this.palettes.get(defaultPalette);
}
AdvancedChatCore.LOGGER.log(
Level.WARN, "Default Palette " + defaultPalette + " does not exist!");
return this.palettes.values().toArray(new Palette[0])[0];
}
/**
* Get's a palette by name. If it doesn't exist, an empty optional is returned
*
* @param name Name of the palette from colors.toml
* @return Palette
*/
public Optional<Palette> get(String name) {
Palette palette = palettes.get(name);
if (palette != null) {
return Optional.of(palette);
}
return Optional.empty();
}
private static Color hexToSimple(String string) {
if (string.length() != 7 && string.length() != 9) {
// Not #ffffff (so invalid!)
AdvancedChatCore.LOGGER.log(
Level.WARN,
"Color " + string + " isn't formatted correctly! (#ffffff) (#ffffffff)");
return new Color(255, 255, 255, 255);
}
string = string.substring(1);
try {
int red = Integer.parseInt(string.substring(0, 2), 16);
int green = Integer.parseInt(string.substring(2, 4), 16);
int blue = Integer.parseInt(string.substring(4, 6), 16);
int alpha = 255;
if (string.length() == 8) {
alpha = Integer.parseInt(string.substring(6));
}
return new Color(red, green, blue, alpha);
} catch (Exception e) {
AdvancedChatCore.LOGGER.log(
Level.WARN, "Couldn't convert " + string + " into a color!", e);
}
return new Color(255, 255, 255, 255);
}
public Optional<Color> getColor(String key) {
if (colors.containsKey(key)) {
return Optional.of(colors.get(key));
}
return Optional.empty();
}
public Color getColorOrWhite(String key) {
return getColor(key).orElse(new Color(255, 255, 255, 255));
}
public static class Palette {
@Getter private final List<Color> colors;
public Palette(List<Color> colors) {
this.colors = colors;
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\ColorUtil.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import lombok.experimental.UtilityClass;
import net.minecraft.util.Formatting;
/**
* A static utility class that helps when dealing with colors that use bit shifting, like Minecraft.
* In here there is a color storage class that makes getting int and creating new colors simple.
*/
@UtilityClass
public class ColorUtil {
// Probably my best hope for color...
// https://github.com/parzivail/StarWarsMod/blob/master/src/main/java/com/parzivail/util/ui/GLPalette.java
// I don't like color ints :(
// intToColor and colorToInt from parzivail https://github.com/parzivail (slightly modified to
// account for Alpha)
/**
* Turns a packed RGB color into a Color
*
* @param rgb The color to unpack
* @return The new Color
*/
public Color intToColor4f(int rgb) {
int alpha = rgb >> 24 & 0xFF;
int red = rgb >> 16 & 0xFF;
int green = rgb >> 8 & 0xFF;
int blue = rgb & 0xFF;
return new Color(red, green, blue, alpha);
}
/**
* Turns a Color into a packed RGB int
*
* @param c The color to pack
* @return The packed int
*/
public int colorToInt4f(Color c) {
int rgb = c.alpha();
rgb = (rgb << 8) + c.red();
rgb = (rgb << 8) + c.green();
rgb = (rgb << 8) + c.blue();
return rgb;
}
public Color fade(Color color, float percent) {
float alpha = (float) color.alpha();
return color.withAlpha((int) Math.floor((alpha * percent)));
}
public Color colorFromFormatting(Formatting formatting) {
return new Color(formatting.getColorValue());
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\EasingMethod.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
/** A class to handle an easing method. Examples at https://easings.net/ */
public interface EasingMethod {
/**
* Applies the current percentage of the ease.
*
* @param x Double from 0-1 (will often clamp at those values)
* @return The easing value (often clamped at 0-1)
*/
double apply(double x);
/** Useful easing methods */
enum Method implements EasingMethod {
/** Implements the linear easing function. It returns the same value. x = x */
LINEAR(x -> x),
/**
* Implements the sine easing function.
*
* <p>https://easings.net/#easeInSine
*/
SINE(x -> 1 - Math.cos((x * Math.PI) / 2)),
/**
* Implements the quad easing function.
*
* <p>https://easings.net/#easeInQuad
*/
QUAD(x -> x * x),
/**
* Implements the quart easing function.
*
* <p>https://easings.net/#easeInQuart
*/
QUART(x -> x * x * x * x),
/**
* Implements the circ easing function.
*
* <p>https://easings.net/#easeInCirc
*/
CIRC(x -> 1 - Math.sqrt(1 - Math.pow(x, 2)));
private final EasingMethod method;
Method(EasingMethod method) {
this.method = method;
}
@Override
public double apply(double x) {
if (x < 0) {
return 0;
} else if (x > 1) {
return 1;
}
return method.apply(x);
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\FindPair.java
|
/*
* Copyright (C) 2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import lombok.AllArgsConstructor;
import lombok.Value;
@Value
@AllArgsConstructor
public class FindPair {
FindType type;
String string;
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\FindType.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import fi.dy.masa.malilib.config.IConfigOptionListEntry;
import fi.dy.masa.malilib.util.StringUtils;
import io.github.darkkronicle.advancedchatcore.finder.CustomFinder;
import io.github.darkkronicle.advancedchatcore.finder.LiteralFinder;
import io.github.darkkronicle.advancedchatcore.finder.RegexFinder;
import io.github.darkkronicle.advancedchatcore.finder.UpperLowerFinder;
import io.github.darkkronicle.advancedchatcore.interfaces.IFinder;
import java.util.function.Supplier;
/** Different methods of searching strings for matches. */
public enum FindType implements IConfigOptionListEntry {
/** An exact match found in the input */
LITERAL("literal", LiteralFinder::new),
/** A match found in the input that is case insensitive */
UPPERLOWER("upperlower", UpperLowerFinder::new),
/** A regex match found in the input */
REGEX("regex", RegexFinder::new),
/**
* Use custom ones that mods can create. Defined in {@link
* io.github.darkkronicle.advancedchatcore.finder.CustomFinder}
*/
CUSTOM("custom", CustomFinder::getInstance);
/** Serialized name of the {@link FindType} */
public final String configString;
private final Supplier<IFinder> finder;
private static String translate(String key) {
return StringUtils.translate("advancedchat.config.findtype." + key);
}
FindType(String configString, Supplier<IFinder> finder) {
this.configString = configString;
this.finder = finder;
}
/** Get's the finder associated with this */
public IFinder getFinder() {
return finder.get();
}
/**
* Get's the serialized name of the object.
*
* @return The config string
*/
@Override
public String getStringValue() {
return configString;
}
/**
* Get's the human readable form of the object.
*
* @return String that is for the display name.
*/
@Override
public String getDisplayName() {
return translate(configString);
}
/**
* Get's the next {@link FindType} from the previous one.
*
* @param forward Should cycle forward
* @return Next {@link FindType}
*/
@Override
public FindType cycle(boolean forward) {
int id = this.ordinal();
if (forward) {
id++;
} else {
id--;
}
if (id >= values().length) {
id = 0;
} else if (id < 0) {
id = values().length - 1;
}
return values()[id % values().length];
}
/**
* De-serializes a string to {@link FindType}
*
* @param value Serialized string
* @return The found {@link FindType}, null if none
*/
@Override
public FindType fromString(String value) {
return fromFindType(value);
}
public static FindType fromFindType(String findtype) {
for (FindType r : FindType.values()) {
if (r.configString.equals(findtype)) {
return r;
}
}
return FindType.LITERAL;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\LimitedInteger.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import lombok.Getter;
import lombok.Setter;
/** An object that will enforce limits on an integer value */
public class LimitedInteger {
@Getter private Integer value;
@Getter @Setter private Integer limit;
public LimitedInteger(int limit) {
this(limit, 0);
}
public LimitedInteger(int limit, int start) {
this.limit = limit;
this.value = start;
}
/**
* Increment only if the value is less than the limit.
*
* @param increment Integer to increment by
* @return If the increment was successful
*/
public boolean incrementIfLimited(int increment) {
if (value >= limit) {
return false;
}
value += increment;
return true;
}
/**
* Increment the value and then return if the value is over the limit
*
* @param increment Integer to increment by
* @return If the incremented value is greater than the limit
*/
public boolean incrementAndCheck(int increment) {
value += increment;
return value >= limit;
}
/**
* Increments the value if the value to increment by doesn't go over the limit.
*
* @param increment Integer to increment by
* @return Boolean if it sucecessfully incremented.
*/
public boolean incrementIfPossible(int increment) {
if ((value + increment) >= limit) {
return false;
}
value += increment;
return true;
}
/**
* A method to see if it is possible to increment. This does not change any values.
*
* @param increment Value to increment
* @return If it can increment
*/
public boolean isPossible(int increment) {
return !(value + increment >= limit);
}
/**
* Force set's the current value. Ignores limits.
*
* @param value Integer to set
*/
public void setValue(int value) {
this.value = value;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\ProfanityUtil.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import fi.dy.masa.malilib.util.FileUtils;
import io.github.darkkronicle.advancedchatcore.AdvancedChatCore;
import java.io.*;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.Getter;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.logging.log4j.Level;
/**
* https://gist.github.com/PimDeWitte/c04cc17bc5fa9d7e3aee6670d4105941
*
* @author PimDeWitte
*/
@Environment(EnvType.CLIENT)
public class ProfanityUtil {
@Getter private final Map<Float, List<String>> words = new HashMap<>();
@Getter private int largestWordLength = 0;
private static final ProfanityUtil INSTANCE = new ProfanityUtil();
public static ProfanityUtil getInstance() {
return INSTANCE;
}
private ProfanityUtil() {}
public void loadConfigs() {
try {
List<String> lines;
File file = FileUtils.getConfigDirectory()
.toPath()
.resolve("advancedchat")
.resolve("swear_words.csv")
.toFile();
Reader fileReader;
if (!file.exists()) {
// Use built in
fileReader = new InputStreamReader(AdvancedChatCore.getResource("swear_words.csv"), StandardCharsets.UTF_8);
} else {
fileReader = new FileReader(file);
}
CSVParser csv = new CSVParser(fileReader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase());
int counter = 0;
for (CSVRecord record : csv) {
counter++;
try {
String word = record.get("text");
float severity = Float.parseFloat(record.get("severity_rating"));
if (word.length() > largestWordLength) {
largestWordLength = word.length();
}
if (!words.containsKey(severity)) {
words.put(severity, new ArrayList<>());
}
words.get(severity).add(word);
} catch (Exception e) {
AdvancedChatCore.LOGGER.log(
Level.ERROR, "Error while initializing profanity words", e);
}
}
AdvancedChatCore.LOGGER.log(
Level.INFO, "Loaded " + counter + " words to profanity filter.");
} catch (URISyntaxException | IOException e) {
AdvancedChatCore.LOGGER.log(Level.ERROR, "Error loading swear_words.csv", e);
}
}
/**
* Iterates over a String input and checks whether a cuss word was found in a list, then checks
* if the word should be ignored (e.g. bass contains the word *ss).
*/
public List<StringMatch> getBadWords(String input, float severity, boolean onlyWordBoundaries) {
if (input == null) {
return new ArrayList<>();
}
List<StringMatch> badWords = new ArrayList<>();
input = input.toLowerCase();
List<Integer> wordBoundaries;
if (onlyWordBoundaries) {
wordBoundaries = SearchUtils.findMatches(input, "\\b", FindType.REGEX)
.map(matches -> matches.stream().map(m -> m.start).toList())
.orElseGet(ArrayList::new);
if (wordBoundaries.size() == 0) {
return new ArrayList<>();
}
} else {
wordBoundaries = new ArrayList<>();
}
List<String> wordsToFind = getAboveSeverity(severity);
// iterate over each letter in the word
int boundaryIndex = 0;
int index = onlyWordBoundaries ? wordBoundaries.get(0) : 0;
while (index < input.length()) {
// from each letter, keep going to find bad words until either the end of the sentence
// is reached, or the max word length is reached.
for (int offset = 1; offset < (input.length() + 1 - index) && offset < largestWordLength; offset++) {
String wordToCheck = input.substring(index, index + offset);
if (wordsToFind.contains(wordToCheck) && (!onlyWordBoundaries || (wordBoundaries.contains(index + offset)))) {
// for example, if you want to say the word bass, that should be possible.
badWords.add(new StringMatch(wordToCheck, index, index + offset));
}
}
if (onlyWordBoundaries) {
boundaryIndex++;
if (boundaryIndex >= wordBoundaries.size()) {
break;
}
index = wordBoundaries.get(boundaryIndex);
} else {
index++;
}
}
return badWords;
}
public List<String> getAboveSeverity(float severity) {
List<String> list = new ArrayList<>();
for (Map.Entry<Float, List<String>> entry : words.entrySet()) {
if (entry.getKey() >= severity) {
list.addAll(entry.getValue());
}
}
return list;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\RawText.java
|
package io.github.darkkronicle.advancedchatcore.util;
import net.minecraft.text.*;
import net.minecraft.util.Language;
import java.util.ArrayList;
import java.util.List;
public record RawText(String content, Style style) implements Text {
@Override
public Style getStyle() {
return style;
}
@Override
public TextContent getContent() {
return new LiteralTextContent(content);
}
@Override
public String getString() {
return content;
}
@Override
public List<Text> getSiblings() {
return new ArrayList<>();
}
@Override
public OrderedText asOrderedText() {
Language language = Language.getInstance();
return language.reorder(this);
}
public RawText withString(String string) {
return RawText.of(string, style);
}
public static RawText of(String string) {
return RawText.of(string, Style.EMPTY);
}
public static RawText of(String string, Style style) {
return new RawText(string, style);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\RowList.java
|
package io.github.darkkronicle.advancedchatcore.util;
import java.util.*;
public class RowList<T> {
private final Map<String, List<T>> list = new HashMap<>();
private final List<String> order = new ArrayList<>();
public RowList() {
}
private List<T> makeNewList() {
return new ArrayList<>();
}
public void createSection(String key, int y) {
List<T> newList = makeNewList();
order.add(y, key);
list.put(key, newList);
}
public void add(String key, T value) {
add(key, value, -1);
}
public void add(String key, T value, int index) {
if (!list.containsKey(key)) {
List<T> newList = makeNewList();
order.add(key);
newList.add(value);
list.put(key, newList);
return;
}
if (index < 0) {
list.get(key).add(value);
} else {
list.get(key).add(index, value);
}
}
public List<T> get(String key) {
return list.get(key);
}
public List<T> get(int y) {
String key;
if (y >= order.size()) {
key = order.get(order.size() - 1);
} else {
key = order.get(y);
}
return list.get(key);
}
public int rowSize() {
return list.size();
}
public void clear() {
order.clear();
list.clear();
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\SearchResult.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import io.github.darkkronicle.advancedchatcore.finder.RegexFinder;
import io.github.darkkronicle.advancedchatcore.interfaces.IFinder;
import lombok.Getter;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.text.Text;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** An object that holds information about a search. */
@Environment(EnvType.CLIENT)
public class SearchResult {
/** All the {@link StringMatch} that were found in the input */
@Getter private final List<StringMatch> matches;
/** The finder used to find matches */
@Getter private final IFinder finder;
/** The input string */
@Getter private final String input;
/** The condition search */
@Getter private final String search;
/**
* Constructs a search result based off of found information.
*
* @param input Input to search
* @param search Search value
* @param finder {@link IFinder} used to search
* @param matches {@link List} of {@link StringMatch} that were found
*/
public SearchResult(String input, String search, IFinder finder, List<StringMatch> matches) {
this.input = input;
this.search = search;
this.finder = finder;
this.matches = new ArrayList<>(matches);
Collections.sort(this.matches);
}
public int size() {
return matches.size();
}
/**
* Get's a group from the result. This only works if it's a {@link RegexFinder}, otherwise it
* returns the entire string.
*
* @param num Group number
* @return StringMatch from group. It references the original string.
*/
public StringMatch getGroup(StringMatch match, int num) {
if (!matches.contains(match)) {
return null;
}
if (!(finder instanceof RegexFinder)) {
return match;
}
try {
RegexFinder regex = (RegexFinder) finder;
Pattern p = regex.getPattern(input);
if (p == null) {
return null;
}
Matcher matcher = p.matcher(match.match);
String group = matcher.group(num);
int start = matcher.start(num);
int end = matcher.start(num);
return new StringMatch(group, start, end);
} catch (Exception e) {
return null;
}
}
/**
* Replaces the groups with a specified match
*
* @param string Contents to replace to
* @param matchIndex If it will replace/return only the first group. -1 will return the full
* string.
* @return The replaced values in context. If onlyFirst it will only do the context of the first
* group.
*/
public String getGroupReplacements(String string, int matchIndex) {
if (matchIndex >= 0) {
if (finder instanceof RegexFinder regex) {
try {
Pattern p = regex.getPattern(search);
if (p != null) {
return
p
.matcher(matches.get(matchIndex).match)
.replaceAll(string);
}
} catch (Exception e) {
// Didn't work
}
}
return SearchUtils.replaceGroups(Collections.singletonList(matches.get(0)), string);
}
if (finder instanceof RegexFinder regex) {
try {
Pattern p = regex.getPattern(search);
if (p != null) {
return p.matcher(input).replaceAll(string);
}
} catch (Exception e) {
// Did not work
}
}
return SearchUtils.replaceGroups(matches, string);
}
/**
* A method to construct a SearchResult based off of an input, condition, and {@link FindType}
*
* @param input Input string to match from
* @param match Search string
* @param type {@link FindType} way to search
* @return SearchResult with compiled searches
*/
public static SearchResult searchOf(String input, String match, FindType type) {
IFinder finder = type.getFinder();
List<StringMatch> matches = finder.getMatches(input, match);
return new SearchResult(input, match, finder, matches);
}
/**
* A method to construct a SearchResult based off of an input, condition, and {@link FindType}
*
* @param input Input string to match from
* @param match Search text
* @param type {@link FindType} way to search
* @return SearchResult with compiled searches
*/
public static SearchResult searchOf(Text input, String match, FindType type) {
IFinder finder = type.getFinder();
List<StringMatch> matches = finder.getMatches(input, match);
return new SearchResult(input.getString(), match, finder, matches);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\SearchUtils.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import io.github.darkkronicle.advancedchatcore.chat.MessageOwner;
import io.github.darkkronicle.advancedchatcore.config.ConfigStorage;
import io.github.darkkronicle.advancedchatcore.interfaces.IFinder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import lombok.experimental.UtilityClass;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.client.network.PlayerListEntry;
import net.minecraft.text.Text;
/**
* A class used for helping filters find matches and act on them. Helps with Regular Expressions and
* means that we don't need this in each class.
*/
@Environment(EnvType.CLIENT)
@UtilityClass
public class SearchUtils {
/**
* Method to see if there is a match somewhere with a string with an expression. Is similar to
* {@link #findMatches(String, String, FindType)} just less expensive since it doesn't need to
* find every match.
*
* @param input String to search.
* @param toMatch Expression to find.
* @param type How toMatch should be interpreted.
* @return If a match is found.
*/
public boolean isMatch(String input, String toMatch, FindType type) {
IFinder finder = type.getFinder();
if (finder == null) {
return false;
}
return finder.isMatch(input, toMatch);
}
/**
* Method to see if there is a match somewhere with a string with an expression. Is similar to
* {@link #findMatches(String, String, FindType)} just less expensive since it doesn't need to
* find every match.
*
* @param input String to search.
* @param toMatch Expression to find.
* @param type How toMatch should be interpreted.
* @return If a match is found.
*/
public boolean isMatch(Text input, String toMatch, FindType type) {
IFinder finder = type.getFinder();
if (finder == null) {
return false;
}
return finder.isMatch(input, toMatch);
}
/**
* Get's replacements for a string and matches following the format $\<number\>
*
* @param groups Matches that are found, will replace
* @param input Input with group replacements
* @return String with replaced groups
*/
public String replaceGroups(List<StringMatch> groups, String input) {
// Checks to make it so we don't always have to regex
if (input.length() < 2 || !input.contains("$")) {
return input;
}
Optional<List<StringMatch>> replace = findMatches(input, "\\$[0-9]", FindType.REGEX);
if (replace.isEmpty()) {
return input;
}
// Ensure sort
TreeSet<StringMatch> replaceMatches = new TreeSet<>(replace.get());
int last = 0;
StringBuilder edited = new StringBuilder();
for (StringMatch m : replaceMatches) {
int digit = Integer.parseInt(m.match.substring(1, 2));
if (digit == 0 || digit > groups.size()) {
continue;
}
edited.append(input, last, m.start).append(groups.get(digit));
last = m.end;
}
if (last != input.length()) {
edited.append(input.substring(last));
}
return edited.toString();
}
/**
* Method to find all matches within a string. Is similar to {@link #isMatch(String, String,
* FindType)}}. This method just finds every match and returns it.
*
* @param input String to search.
* @param toMatch Expression to find.
* @param type How toMatch should be interpreted.
* @return An Optional containing a list of {@link StringMatch}
*/
public Optional<List<StringMatch>> findMatches(String input, String toMatch, FindType type) {
IFinder finder = type.getFinder();
if (finder == null) {
return Optional.empty();
}
Set<StringMatch> matches = new TreeSet<>(finder.getMatches(input, toMatch));
if (matches.size() != 0) {
return Optional.of(new ArrayList<>(matches));
}
return Optional.empty();
}
/**
* Method to find all matches within a text. Is similar to {@link #isMatch(Text, String,
* FindType)}}. This method just finds every match and returns it.
*
* @param input Text to search.
* @param toMatch Expression to find.
* @param type How toMatch should be interpreted.
* @return An Optional containing a list of {@link StringMatch}
*/
public Optional<List<StringMatch>> findMatches(Text input, String toMatch, FindType type) {
IFinder finder = type.getFinder();
if (finder == null) {
return Optional.empty();
}
Set<StringMatch> matches = new TreeSet<>(finder.getMatches(input, toMatch));
if (matches.size() != 0) {
return Optional.of(new ArrayList<>(matches));
}
return Optional.empty();
}
/**
* Gets first match found based off of conditions
*
* @param input String to search
* @param toMatch Search content
* @param type {@link FindType} way to search
* @return Optional of a {@link StringMatch} if found
*/
public Optional<StringMatch> getMatch(String input, String toMatch, FindType type) {
IFinder finder = type.getFinder();
if (finder == null) {
return Optional.empty();
}
// Use treeset to sort the matches
Set<StringMatch> matches = new TreeSet<>(finder.getMatches(input, toMatch));
// Add and sort matches
if (matches.size() != 0) {
return Optional.of(matches.toArray(new StringMatch[0])[0]);
}
return Optional.empty();
}
/**
* Gets first match found based off of conditions
*
* @param input String to search
* @param toMatch Search content
* @param type {@link FindType} way to search
* @return Optional of a {@link StringMatch} if found
*/
public Optional<StringMatch> getMatch(Text input, String toMatch, FindType type) {
IFinder finder = type.getFinder();
if (finder == null) {
return Optional.empty();
}
// Use treeset to sort the matches
Set<StringMatch> matches = new TreeSet<>(finder.getMatches(input, toMatch));
// Add and sort matches
if (matches.size() != 0) {
return Optional.of(matches.toArray(new StringMatch[0])[0]);
}
return Optional.empty();
}
/**
* Get the author of a message using regex
*
* @param networkHandler Network handler to get player data
* @param text Text to search
* @return Owner of the message
*/
public MessageOwner getAuthor(ClientPlayNetworkHandler networkHandler, String text) {
if (networkHandler == null) {
return null;
}
Optional<List<StringMatch>> words =
SearchUtils.findMatches(
stripColorCodes(text),
ConfigStorage.General.MESSAGE_OWNER_REGEX.config.getStringValue(),
FindType.REGEX);
if (!words.isPresent()) {
return null;
}
// Start by just checking names and such
PlayerListEntry player = null;
StringMatch match = null;
for (StringMatch m : words.get()) {
if (player != null) {
break;
}
for (PlayerListEntry e : networkHandler.getPlayerList()) {
// Easy mode
if ((e.getDisplayName() != null
&& m.match.equals(stripColorCodes(e.getDisplayName().getString())))
|| m.match.equals(e.getProfile().getName())) {
player = e;
match = m;
break;
}
}
}
// Check for ***everything***
HashMap<PlayerListEntry, List<StringMatch>> entryMatches = new HashMap<>();
for (PlayerListEntry e : networkHandler.getPlayerList()) {
String name =
stripColorCodes(
e.getDisplayName() == null
? e.getProfile().getName()
: e.getDisplayName().getString());
Optional<List<StringMatch>> nameWords =
SearchUtils.findMatches(
name,
ConfigStorage.General.MESSAGE_OWNER_REGEX.config.getStringValue(),
FindType.REGEX);
if (!nameWords.isPresent()) {
continue;
}
entryMatches.put(e, nameWords.get());
}
for (StringMatch m : words.get()) {
for (Map.Entry<PlayerListEntry, List<StringMatch>> entry : entryMatches.entrySet()) {
for (StringMatch nm : entry.getValue()) {
if (nm.match.equals(m.match)) {
if (player != null && match.start <= m.start) {
return new MessageOwner(match.match, player);
}
return new MessageOwner(nm.match, entry.getKey());
}
}
}
}
return null;
}
/**
* Strip color codes from a String
*
* @param string String to strip
* @return String stripped of colorcodes
*/
public String stripColorCodes(String string) {
return string.replaceAll("§.", "");
}
private final TreeMap<Integer, String> map = new TreeMap<>();
static {
map.put(1000, "M");
map.put(900, "CM");
map.put(500, "D");
map.put(400, "CD");
map.put(100, "C");
map.put(90, "XC");
map.put(50, "L");
map.put(40, "XL");
map.put(10, "X");
map.put(9, "IX");
map.put(5, "V");
map.put(4, "IV");
map.put(1, "I");
}
/**
* Turns a number into a Roman Numeral.
*
* <p>Example: 4 -> IV
*
* <p>https://stackoverflow.com/questions/12967896/converting-integers-to-roman-numerals-java/12968022
*
* @param number Example to convert to
* @return String or Roman Numeral
*/
public String toRoman(int number) {
boolean neg = false;
if (number == 0) {
return "O";
}
if (number < 0) {
neg = true;
number = -1 * number;
}
int l = map.floorKey(number);
if (number == l) {
return map.get(number);
}
if (neg) {
return "-" + map.get(l) + toRoman(number - l);
} else {
return map.get(l) + toRoman(number - l);
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\StringInsert.java
|
package io.github.darkkronicle.advancedchatcore.util;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
/**
* An interface to provide a way to get the text that should be replaced based off of the
* current {@link Text} and the current {@link StringMatch}
*/
public interface StringInsert {
/**
* Return's the {@link MutableText} that should be inserted.
*
* @param current The current {@link Text}
* @param match The current {@link StringMatch}
* @return
*/
MutableText getText(Text current, StringMatch match);
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\StringMatch.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* A class to store data about a match.
*
* <p>This class is comparable based on where it starts.
*/
@EqualsAndHashCode
@ToString
@AllArgsConstructor
public class StringMatch implements Comparable<StringMatch> {
/** The content that was matched */
public String match;
/** The index of the start of the match */
public Integer start;
/** The index of the end of the match */
public Integer end;
@Override
public int compareTo(StringMatch o) {
return start.compareTo(o.start);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\StyleFormatter.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.util.ChatMessages;
import net.minecraft.text.*;
import net.minecraft.util.Formatting;
import net.minecraft.util.Unit;
/** Class to format text without losing data */
@Environment(EnvType.CLIENT)
public class StyleFormatter {
/**
* An interface to take multiple inputs from a string that has the Section Symbol formatting
* combined with standard {@link Text} formatting.
*/
public interface FormattingVisitable {
/**
* Accepts a character with information about current formatting
*
* @param c Current character
* @param currentIndex The current index of the raw string
* @param realIndex The current index without formatting symbols
* @param textStyle The style that the text currently has
* @param formattingStyle The style that combines text formatting and formatting symbols
* @return Whether to continue
*/
boolean accept(
char c, int currentIndex, int realIndex, Style textStyle, Style formattingStyle);
}
private int currentIndex;
private int realIndex;
private int skipBy = 0;
private Style currentStyle;
private Style lastTextStyle = null;
private final FormattingVisitable visitor;
private final int length;
/** Results of different parts of formatting */
private enum Result {
/** Go up a character */
INCREMENT,
/** Go to the next {@link StringVisitable} */
SKIP,
/** STOP */
TERMINATE,
}
/**
* Creates a StyleFormatter for a given length and a {@link FormattingVisitable}
*
* <p>This class is meant to be updated with a {@link StringVisitable.StyledVisitor}
*
* @param visitor {@link FormattingVisitable} to get updated with each visible character
* @param length Length of the string
*/
public StyleFormatter(FormattingVisitable visitor, int length) {
this.visitor = visitor;
this.currentIndex = 0;
this.realIndex = 0;
this.currentStyle = Style.EMPTY;
this.length = length;
}
/** Sends the current character with the current information to the visitor. */
private boolean sendToVisitor(char c, Style textStyle) {
return visitor.accept(c, currentIndex, realIndex, textStyle, currentStyle);
}
/** Handles how section symbols get processed */
private Result updateSection(Style textStyle, Character nextChar, String rest) {
if (nextChar == null) {
return Result.SKIP;
}
if (nextChar == '#') {
if (rest.length() > 6) {
String format = rest.substring(1, 7);
if (!SearchUtils.isMatch(format, "^[0-9a-fA-F]{6}", FindType.REGEX)) {
currentIndex++;
return Result.INCREMENT;
}
int red = Integer.parseInt(format.substring(0, 2), 16);
int green = Integer.parseInt(format.substring(2, 4), 16);
int blue = Integer.parseInt(format.substring(4, 6), 16);
TextColor color = TextColor.fromRgb(new Color(red, green, blue, 255).color());
if (currentStyle.equals(Style.EMPTY) || currentStyle.equals(textStyle)) {
// If it's empty or different rely on just the current text style
// Arbitrary color
currentStyle = textStyle.withExclusiveFormatting(Formatting.BLACK);
} else {
// Styles are different so we take what happened before. This allows us to chain
// formatting symbols.
// Arbitrary color to reset
currentStyle = currentStyle.withExclusiveFormatting(Formatting.BLACK);
}
currentStyle = currentStyle.withColor(color);
currentIndex += 7;
skipBy = 6;
}
return Result.INCREMENT;
}
Formatting formatting = Formatting.byCode(nextChar);
if (formatting != null) {
if (formatting == Formatting.RESET) {
// If it resets, just go to what the current text is.
currentStyle = textStyle;
} else {
if (currentStyle.equals(Style.EMPTY) || currentStyle.equals(textStyle)) {
// If it's empty or different rely on just the current text style
currentStyle = textStyle.withExclusiveFormatting(formatting);
} else {
// Styles are different so we take what happened before. This allows us to chain
// formatting symbols.
currentStyle = currentStyle.withExclusiveFormatting(formatting);
}
}
if (currentStyle.equals(Style.EMPTY)) {
currentStyle = textStyle;
}
}
currentIndex++;
return Result.INCREMENT;
}
/**
* Updates current visitable data as well as signifies whether to end.
*
* <p>Calling this method will result in each 'visible' character being sent to the {@link
* FormattingVisitable}
*
* @param textStyle Style of the current string
* @param string The current string
* @return Value to terminate. Follows {@link StringVisitable.StyledVisitor} return values.
*/
public Optional<Optional<Unit>> updateStyle(Style textStyle, String string) {
if (lastTextStyle == null) {
lastTextStyle = textStyle;
}
currentStyle = textStyle;
int stringLength = string.length();
for (int i = 0; i < stringLength; i++) {
char c = string.charAt(i);
Character nextChar = null;
if (i + 1 < stringLength) {
nextChar = string.charAt(i + 1);
}
if (c == '§') {
skipBy = 0;
switch (updateSection(textStyle, nextChar, string.substring(i + 1))) {
case SKIP:
return Optional.empty();
case TERMINATE:
return Optional.of(StringVisitable.TERMINATE_VISIT);
case INCREMENT:
i++;
}
i += skipBy;
} else if (sendToVisitor(c, textStyle)) {
realIndex++;
} else {
return Optional.of(StringVisitable.TERMINATE_VISIT);
}
currentIndex++;
}
lastTextStyle = textStyle;
return Optional.empty();
}
/**
* Formats text that contains styling data as well as formatting symbols
*
* <p>This method is used to remove section symbols while maintaining previous formatting as
* well as new formatting.
*
* @param text Text to reformat
* @return Formatted text
*/
public static MutableText formatText(Text text) {
MutableText t = Text.empty();
int length = text.getString().length();
StyleFormatter formatter =
new StyleFormatter(
(c, index, formattedIndex, style, formattedStyle) -> {
t.append(Text.literal(String.valueOf(c)).fillStyle(formattedStyle));
return true;
},
length);
text.visit(formatter::updateStyle, Style.EMPTY);
return flattenText(t);
}
public static MutableText flattenText(Text text) {
List<Text> newSiblings = new ArrayList<>();
Style last = text.getStyle();
StringBuilder content = new StringBuilder(TextUtil.getContent(text.getContent()));
for (Text t : text.getSiblings()) {
if (t.getStyle().equals(last)) {
content.append(TextUtil.getContent(t.getContent()));
continue;
}
newSiblings.add(Text.literal(content.toString()).fillStyle(last));
content = new StringBuilder(TextUtil.getContent(t.getContent()));
last = t.getStyle();
}
newSiblings.add(Text.literal(content.toString()).fillStyle(last));
MutableText newText = Text.empty();
for (Text sibling : newSiblings) {
newText.append(sibling);
}
return newText;
}
/**
* Wraps text into multiple lines
*
* @param textRenderer TextRenderer to handle text
* @param scaledWidth Maximum width before the line breaks
* @param text Text to break up
* @return List of MutableText of the new lines
*/
public static List<Text> wrapText(TextRenderer textRenderer, int scaledWidth, Text text) {
ArrayList<Text> lines = new ArrayList<>();
for (OrderedText breakRenderedChatMessageLine : ChatMessages.breakRenderedChatMessageLines(text, scaledWidth, textRenderer)) {
lines.add(new TextBuilder().append(breakRenderedChatMessageLine).build());
}
return lines;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\SyncTaskQueue.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import java.util.TreeSet;
import lombok.AllArgsConstructor;
import lombok.Value;
import org.jetbrains.annotations.NotNull;
// Referenced
// https://github.com/vacla/Watson/blob/fabric_1.16.2/src/main/java/eu/minemania/watson/scheduler/SyncTaskQueue.java
/** A queue to handle delayed tasks in ticks. */
public class SyncTaskQueue {
private static final SyncTaskQueue INSTANCE = new SyncTaskQueue();
public static SyncTaskQueue getInstance() {
return INSTANCE;
}
private int lastTick = 0;
/** A task that contains a time to trigger and a {@link Runnable} for when it should happen. */
@Value
@AllArgsConstructor
public static class QueuedTask implements Comparable<QueuedTask> {
/**
* Tick number when it should be triggered. This isn't delay, this is based off of the
* current tick value in {@link net.minecraft.client.gui.hud.InGameHud}
*/
int tick;
/** {@link Runnable} to run when the task is called. */
Runnable task;
@Override
public int compareTo(@NotNull SyncTaskQueue.QueuedTask o) {
// Compares when it should happen. Used to ensure that the first in the stack is what
// needs to
// happen.
return Integer.compare(tick, o.tick);
}
}
// Use TreeSet to automagically sort by when it needs to happen
private final TreeSet<QueuedTask> queue = new TreeSet<>();
/**
* Add's a new task to do after a certain amount of ticks
*
* @param after Delay in ticks
* @param runnable What to run when it should be called
*/
public void add(int after, Runnable runnable) {
queue.add(new QueuedTask(lastTick + after, runnable));
}
/**
* Updates the queue with the tick. This shouldn't be called outside of the core.
*
* @param tick Current time in ticks.
*/
public void update(int tick) {
lastTick = tick;
if (queue.size() == 0) {
return;
}
QueuedTask task = queue.first();
while (task != null && task.tick <= lastTick) {
task.task.run();
queue.pollFirst();
if (queue.size() == 0) {
break;
}
task = queue.first();
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\TextBuilder.java
|
package io.github.darkkronicle.advancedchatcore.util;
import net.minecraft.text.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
public class TextBuilder {
private List<RawText> siblings = new ArrayList<>();
public TextBuilder append(String string) {
siblings.add(RawText.of(string));
return this;
}
public TextBuilder append(String string, Style style) {
siblings.add(RawText.of(string, style));
return this;
}
public List<RawText> getTexts() {
return siblings;
}
public TextBuilder append(OrderedText text) {
AtomicReference<Style> last = new AtomicReference<>(null);
AtomicReference<StringBuilder> builder = new AtomicReference<>(new StringBuilder());
text.accept((index, style, codePoint) -> {
if (last.get() == null) {
last.set(style);
builder.get().append(Character.toChars(codePoint));
return true;
} else if (last.get().equals(style)) {
builder.get().append(Character.toChars(codePoint));
return true;
}
append(builder.get().toString(), last.get());
last.set(style);
builder.set(new StringBuilder().append(Character.toChars(codePoint)));
return true;
});
if (!builder.get().isEmpty()) {
append(builder.get().toString(), last.get());
}
return this;
}
public TextBuilder append(Text text) {
AtomicReference<Style> last = new AtomicReference<>(null);
AtomicReference<StringBuilder> builder = new AtomicReference<>(new StringBuilder());
text.visit((style, asString) -> {
if (last.get() == null) {
last.set(style);
builder.get().append(asString);
return Optional.empty();
} else if (last.get().equals(style)) {
builder.get().append(asString);
return Optional.empty();
}
append(builder.get().toString(), last.get());
last.set(style);
builder.set(new StringBuilder(asString));
return Optional.empty();
}, Style.EMPTY);
if (!builder.get().isEmpty()) {
append(builder.get().toString(), last.get());
}
return this;
}
public MutableText build() {
MutableText newText = Text.empty();
for (RawText sib : siblings) {
newText.append(Text.literal(sib.content()).fillStyle(sib.style()));
}
return newText;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\TextUtil.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import fi.dy.masa.malilib.util.StringUtils;
import java.util.*;
import java.util.function.BiFunction;
import lombok.experimental.UtilityClass;
import net.minecraft.text.MutableText;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.text.TextContent;
@UtilityClass
public class TextUtil {
private final char[] SUPERSCRIPTS =
new char[] {
'\u2070', '\u00B9', '\u00B2', '\u00B3', '\u2074', '\u2075', '\u2076', '\u2077',
'\u2078', '\u2079'
};
/**
* Calculates the similarity (a number within 0 and 1) between two strings.
*
* <p>https://stackoverflow.com/questions/955110/similarity-string-comparison-in-java
*/
public double similarity(String s1, String s2) {
String longer = s1, shorter = s2;
if (s1.length() < s2.length()) { // longer should always have greater length
longer = s2;
shorter = s1;
}
int longerLength = longer.length();
if (longerLength == 0) {
return 1.0; /* both strings are zero length */
}
/* // If you have Apache Commons Text, you can use it to calculate the edit distance:
LevenshteinDistance levenshteinDistance = new LevenshteinDistance();
return (longerLength - levenshteinDistance.apply(longer, shorter)) / (double) longerLength; */
return (longerLength - editDistance(longer, shorter)) / (double) longerLength;
}
// Example implementation of the Levenshtein Edit Distance
// See http://rosettacode.org/wiki/Levenshtein_distance#Java
/** https://stackoverflow.com/questions/955110/similarity-string-comparison-in-java */
public int editDistance(String s1, String s2) {
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
int[] costs = new int[s2.length() + 1];
for (int i = 0; i <= s1.length(); i++) {
int lastValue = i;
for (int j = 0; j <= s2.length(); j++) {
if (i == 0) costs[j] = j;
else {
if (j > 0) {
int newValue = costs[j - 1];
if (s1.charAt(i - 1) != s2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1;
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
}
if (i > 0) costs[s2.length()] = lastValue;
}
return costs[s2.length()];
}
/** Get's a superscript from a number */
public String toSuperscript(int num) {
StringBuilder sb = new StringBuilder();
do {
sb.append(SUPERSCRIPTS[num % 10]);
} while ((num /= 10) > 0);
return sb.reverse().toString();
}
/** Get's the maximum width of a list of translations */
public int getMaxLengthTranslation(Collection<String> translations) {
return getMaxLengthTranslation(translations.toArray(new String[0]));
}
/** Get's the maximum width of a list of translations */
public int getMaxLengthTranslation(String... translations) {
List<String> translated = new ArrayList<>();
for (String translation : translations) {
translated.add(StringUtils.translate(translation));
}
return getMaxLengthString(translated);
}
/** Get's the maximum width of a list of strings */
public int getMaxLengthString(Collection<String> strings) {
return getMaxLengthString(strings.toArray(new String[0]));
}
/** Get's the maximum width of a list of strings */
public int getMaxLengthString(String... strings) {
int max = 0;
for (String text : strings) {
int width = StringUtils.getStringWidth(text);
if (width > max) {
max = width;
}
}
return max;
}
private TreeMap<StringMatch, StringInsert> filterMatches(
Map<StringMatch, StringInsert> matches) {
// Filters through matches that don't make sense
TreeMap<StringMatch, StringInsert> map = new TreeMap<>(matches);
Iterator<StringMatch> search = new TreeMap<>(map).keySet().iterator();
int lastEnd = 0;
while (search.hasNext()) {
StringMatch m = search.next();
// Remove overlaps
if (m.start < lastEnd) {
map.remove(m);
} else {
lastEnd = m.end;
}
}
return map;
}
/**
* Complex method used to split up the split text in this class and replace matches to a string.
*
* @param matches Map containing a match and a FluidText provider
*/
public Text replaceStrings(Text input, Map<StringMatch, StringInsert> matches) {
// If there's no matches nothing should get replaced.
if (matches.size() == 0) {
return input;
}
// Sort the matches and then get a nice easy iterator for navigation
Iterator<Map.Entry<StringMatch, StringInsert>> sortedMatches =
filterMatches(matches).entrySet().iterator();
if (!sortedMatches.hasNext()) {
return input;
}
// List of new RawText to form a new FluidText.
TextBuilder newSiblings = new TextBuilder();
// What match this is currently on.
Map.Entry<StringMatch, StringInsert> match = sortedMatches.next();
// Total number of chars went through. Used to find where the match end and beginning is.
int totalchar = 0;
boolean inMatch = false;
for (RawText text : new TextBuilder().append(input).getTexts()) {
if (text.getString() == null || text.getString().length() <= 0) {
continue;
}
if (match == null) {
// No more replacing...
newSiblings.append(text);
continue;
}
int length = text.getString().length();
int last = 0;
while (true) {
if (length + totalchar <= match.getKey().start) {
newSiblings.append(text.getString().substring(last), text.getStyle());
break;
}
int start = match.getKey().start - totalchar;
int end = match.getKey().end - totalchar;
if (inMatch) {
if (end <= length) {
inMatch = false;
newSiblings.append(text.getString().substring(end), text.getStyle());
last = end;
if (!sortedMatches.hasNext()) {
match = null;
break;
}
match = sortedMatches.next();
} else {
break;
}
} else if (start < length) {
// End will go onto another string
if (start > 0) {
// Add previous string section
newSiblings.append(text.getString().substring(last, start), text.getStyle());
}
if (end >= length) {
newSiblings.append(match.getValue().getText(text, match.getKey()));
if (end == length) {
if (!sortedMatches.hasNext()) {
match = null;
break;
}
match = sortedMatches.next();
} else {
inMatch = true;
}
break;
}
newSiblings.append(match.getValue().getText(text, match.getKey()));
if (!sortedMatches.hasNext()) {
match = null;
} else {
match = sortedMatches.next();
}
last = end;
if (match == null || match.getKey().start - totalchar > length) {
newSiblings.append(text.getString().substring(end), text.getStyle());
break;
}
} else {
break;
}
if (match == null) {
break;
}
}
totalchar = totalchar + length;
}
return newSiblings.build();
}
/**
* Splits off the text that is held by a {@link StringMatch}
*
* @param match Match to grab text from
* @return MutableText of text
*/
public static MutableText truncate(Text input, StringMatch match) {
ArrayList<Text> newSiblings = new ArrayList<>();
boolean start = false;
// Total number of chars went through. Used to find where the match end and beginning is.
int totalchar = 0;
List<Text> siblings = input.getSiblings();
siblings.add(0, MutableText.of(input.getContent()).fillStyle(input.getStyle()));
for (Text text : siblings) {
if (text.getContent() == null || text.getString().length() <= 0) {
continue;
}
int length = text.getString().length();
// Checks to see if current text contains the match.start.
if (totalchar + length > match.start) {
if (totalchar + length >= match.end) {
if (!start) {
newSiblings.add(
Text.literal(
text.getString()
.substring(
match.start - totalchar,
match.end - totalchar)).fillStyle(text.getStyle()));
} else {
newSiblings.add(
Text.literal(
text.getString().substring(0, match.end - totalchar)).fillStyle(text.getStyle()));
}
MutableText newtext = Text.empty();
for (Text sibling : newSiblings) {
newtext.append(sibling);
}
return newtext;
} else {
if (!start) {
newSiblings.add(
Text.literal(
text.getString().substring(match.start - totalchar)).fillStyle(text.getStyle()));
start = true;
} else {
newSiblings.add(text);
}
}
}
totalchar = totalchar + length;
}
// At the end we take the siblings created in this method and return them.
MutableText newtext = Text.empty();
for (Text sibling : newSiblings) {
newtext.append(sibling);
}
return newtext;
}
/**
* See's if style changes for specified fluid text
* @param text Text to test
* @return If style changes
*/
public static boolean styleChanges(Text text) {
Style style = null;
if (text.getSiblings().size() == 1) {
return false;
}
for (Text raw : text.getSiblings()) {
if (style == null) {
style = raw.getStyle();
} else if (!style.equals(raw.getStyle())) {
return true;
}
}
return false;
}
/**
* See's if style changes for specified fluid text
* @param text Text to test
* @param predicate Predicate to see if style has changed enough. Previous, current, different
* @return If style changes
*/
public static boolean styleChanges(Text text, BiFunction<Style, Style, Boolean> predicate) {
Style previous = null;
if (text.getSiblings().size() == 1) {
return !predicate.apply(text.getSiblings().get(0).getStyle(), text.getSiblings().get(0).getStyle());
}
for (Text raw : text.getSiblings()) {
if (previous == null) {
previous = raw.getStyle();
} else if (!previous.equals(raw.getStyle())) {
if (!predicate.apply(previous, raw.getStyle())) {
return true;
}
previous = raw.getStyle();
}
}
return false;
}
public static String getContent(TextContent content) {
StringBuilder builder = new StringBuilder();
content.visit((s) -> {
builder.append(s);
return Optional.empty();
});
return builder.toString();
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\util\TomlUtil.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.util;
import com.electronwill.nightconfig.core.file.FileConfig;
import com.electronwill.nightconfig.core.io.ParsingMode;
import com.electronwill.nightconfig.toml.TomlFormat;
import com.electronwill.nightconfig.toml.TomlParser;
import io.github.darkkronicle.advancedchatcore.AdvancedChatCore;
import java.io.File;
import lombok.experimental.UtilityClass;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import org.apache.logging.log4j.Level;
@Environment(EnvType.CLIENT)
@UtilityClass
public class TomlUtil {
public FileConfig loadFile(File file) {
FileConfig config = FileConfig.of(file);
config.load();
return config;
}
public FileConfig loadFileWithDefaults(File file, String defaultName) {
TomlFormat tomlFormat = TomlFormat.instance();
TomlParser tomlParser = tomlFormat.createParser();
FileConfig config = loadFile(file);
try {
// Layer on top
tomlParser.parse(AdvancedChatCore.getResource(defaultName), config, ParsingMode.ADD);
} catch (Exception e) {
AdvancedChatCore.LOGGER.log(
Level.ERROR, "Could not load default settings into " + defaultName, e);
}
return config;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\gui\GuiConfig.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.config.gui;
import fi.dy.masa.malilib.config.IConfigBase;
import fi.dy.masa.malilib.gui.GuiBase;
import fi.dy.masa.malilib.gui.GuiConfigsBase;
import fi.dy.masa.malilib.gui.button.ButtonBase;
import fi.dy.masa.malilib.gui.button.ButtonGeneric;
import fi.dy.masa.malilib.gui.button.IButtonActionListener;
import fi.dy.masa.malilib.util.Color4f;
import io.github.darkkronicle.advancedchatcore.AdvancedChatCore;
import net.minecraft.client.gui.screen.Screen;
import java.util.List;
// Based off of
// https://github.com/maruohon/minihud/blob/fabric_1.16_snapshots_temp/src/main/java/fi/dy/masa/minihud/gui/GuiConfigs.java
// Released under GNU LGPL
public class GuiConfig extends GuiConfigsBase {
public static TabSupplier TAB = null;
@Deprecated
public GuiConfig(List<GuiConfigHandler.TabButton> tabButtons, List<IConfigBase> configs) {
this();
}
public GuiConfig() {
super(10, 50, AdvancedChatCore.MOD_ID, null, "advancedchat.screen.main");
}
@Override
public void initGui() {
if (TAB == null) {
// Should be general
for (int i = 0; i < GuiConfigHandler.getInstance().getTabs().size(); i++) {
TabSupplier tab = GuiConfigHandler.getInstance().getTabs().get(i);
if (tab.isSelectable()) {
TAB = tab;
break;
}
}
if (TAB == null) {
// sucks to suck lol
TAB = GuiConfigHandler.getInstance().getTabs().get(0);
}
}
boolean children = TAB.getChildren() != null && TAB.getChildren().size() != 0;
Screen child = getFullyNestedSupplier(TAB).getScreen(this);
if (child != null) {
GuiBase.openGui(child);
return;
}
clearElements();
int x = 10;
int y = 26;
int rows = addTabButtons(this, x, y);
y += rows * 22;
if (children) {
y += (addAllChildrenButtons(this, TAB, x, y) * 22);
}
setListPosition(getListX(), y + 10);
if (this.getListWidget() != null) {
this.getListWidget().setSize(this.getBrowserWidth(), this.getBrowserHeight());
this.getListWidget().initGui();
}
}
@Override
public List<ConfigOptionWrapper> getConfigs() {
return ConfigOptionWrapper.createFor(getFullyNestedSupplier(TAB).getOptions());
}
public static TabSupplier getFullyNestedSupplier(TabSupplier supplier) {
if (supplier.getChildren() == null || supplier.getChildren().size() == 0) {
return supplier;
}
return getFullyNestedSupplier(supplier.getNestedSelection());
}
public static int addAllChildrenButtons(GuiBase screen, TabSupplier supplier, int x, int y) {
int rows = 0;
if (supplier.getChildren() != null && supplier.getChildren().size() != 0) {
x += 2;
screen.addLabel(x, y, 10, 22, new Color4f(1, 1, 1, 1).intValue, ">");
x += 8;
addNestedTabButtons(screen, supplier, x, y);
y += 22;
rows++;
if (supplier.getNestedSelection() != null) {
rows += addAllChildrenButtons(screen, supplier.getNestedSelection(), x, y);
}
}
return rows;
}
/**
* Adds the category buttons to the selected screen
* @param screen Screen to apply to
* @return Amount of rows it created
*/
public static int addTabButtons(GuiBase screen, int x, int y) {
int rows = 1;
for (TabSupplier tab : GuiConfigHandler.getInstance().getTabs()) {
int width = screen.getStringWidth(tab.getDisplayName()) + 10;
if (x >= screen.width - width - 10)
{
x = 10;
y += 22;
++rows;
}
x += createTabButton(screen, x, y, width, tab);
}
return rows;
}
public static int addNestedTabButtons(GuiBase screen, TabSupplier supplier, int x, int y) {
int rows = 1;
for (TabSupplier tab : supplier.getChildren()) {
int width = screen.getStringWidth(tab.getDisplayName()) + 10;
if (x >= screen.width - width - 10)
{
x = 10;
y += 22;
++rows;
}
x += createTabButton(screen, x, y, width, tab, supplier);
}
return rows;
}
private static int createTabButton(GuiBase screen, int x, int y, int width, TabSupplier tab) {
return createTabButton(screen, x, y, width, tab, null);
}
private static int createTabButton(GuiBase screen, int x, int y, int width, TabSupplier tab, TabSupplier parent) {
ButtonGeneric button = new ButtonGeneric(x, y, width, 20, tab.getDisplayName());
if (parent == null) {
button.setEnabled(GuiConfig.TAB != tab);
} else {
button.setEnabled(parent.getNestedSelection() != tab);
}
screen.addButton(button, new ButtonListenerTab(tab, parent));
return button.getWidth() + 2;
}
public static class ButtonListenerTab implements IButtonActionListener {
private final TabSupplier tab;
private final TabSupplier parent;
public ButtonListenerTab(TabSupplier tab, TabSupplier parent) {
this.tab = tab;
this.parent = parent;
}
@Override
public void actionPerformedWithButton(ButtonBase button, int mouseButton) {
if (parent == null) {
GuiConfig.TAB = this.tab;
} else {
parent.setNestedSelection(this.tab);
}
GuiBase.openGui(new GuiConfig());
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\gui\GuiConfigHandler.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.config.gui;
import fi.dy.masa.malilib.config.IConfigBase;
import fi.dy.masa.malilib.gui.button.ButtonGeneric;
import fi.dy.masa.malilib.util.StringUtils;
import io.github.darkkronicle.advancedchatcore.config.SaveableConfig;
import io.github.darkkronicle.advancedchatcore.gui.buttons.ConfigTabsButtonListener;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Value;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
@Environment(EnvType.CLIENT)
public class GuiConfigHandler {
private static final GuiConfigHandler INSTANCE = new GuiConfigHandler();
@Deprecated
public String activeTab = "";
@Getter private final List<TabSupplier> tabs = new ArrayList<>();
private GuiConfigHandler() {}
@Deprecated
public boolean isTabActive(GuiConfigHandler.Tab button) {
return button.getName().equals(activeTab);
}
public static GuiConfigHandler getInstance() {
return INSTANCE;
}
@Deprecated
public void addGuiSection(Tab section) {
if (section instanceof GuiConfigSection gui) {
addTab(new TabSupplier(section.getName(), StringUtils.translate(section.getName())) {
@Override
public List<IConfigBase> getOptions() {
return gui.getOptions();
}
});
return;
}
tabs.add(new TabSupplier(section.getName(), section.getName()) {
@Override
public Screen getScreen(Screen parent) {
return section.getScreen(getButtons());
}
});
}
public void addTab(TabSupplier tab) {
tabs.add(tab);
}
public TabSupplier get(String name) {
for (TabSupplier child : tabs) {
if (child.getName().equals(name)) {
return child;
}
}
return null;
}
@Deprecated
public List<TabButton> getButtons() {
int x = 10;
int y = 26;
int rows = 1;
ArrayList<TabButton> buttons = new ArrayList<>();
MinecraftClient client = MinecraftClient.getInstance();
int windowWidth = client.getWindow().getScaledWidth();
for (TabSupplier tab : tabs) {
int width = client.textRenderer.getWidth(tab.getName()) + 10;
if (x >= windowWidth - width - 10) {
x = 10;
y += 22;
rows++;
}
ButtonGeneric button = this.createButton(x, y, width, tab);
x += button.getWidth() + 2;
buttons.add(new TabButton(tab, button));
}
return buttons;
}
private ButtonGeneric createButton(int x, int y, int width, TabSupplier tab) {
ButtonGeneric button = new ButtonGeneric(x, y, width, 20, tab.getName());
button.setEnabled(!GuiConfig.TAB.equals(tab));
return button;
}
public Tab getTab(String name) {
TabSupplier supplier = getTabSupplier(name);
return new Tab() {
@Override
public String getName() {
return supplier.getDisplayName();
}
@Override
public Screen getScreen(List<TabButton> buttons) {
return getDefaultScreen();
}
};
}
public TabSupplier getTabSupplier(String name) {
for (TabSupplier b : tabs) {
if (b.getName().equals(name)) {
return b;
}
}
return null;
}
public Screen getDefaultScreen() {
return new GuiConfig();
}
@Deprecated
public static GuiConfigSection createGuiConfigSection(String name, List<SaveableConfig<? extends IConfigBase>> configs) {
List<IConfigBase> configBases = new ArrayList<>();
for (SaveableConfig<? extends IConfigBase> saveable : configs) {
configBases.add(saveable.config);
}
return new GuiConfigSection() {
@Override
public List<IConfigBase> getOptions() {
return configBases;
}
@Override
public String getName() {
return StringUtils.translate(name);
}
};
}
@Deprecated
@AllArgsConstructor
@Value
public static class TabButton {
TabSupplier tabSupplier;
ButtonGeneric button;
@Deprecated
public Tab getTab() {
return new Tab() {
@Override
public String getName() {
return tabSupplier.getDisplayName();
}
@Override
public Screen getScreen(List<TabButton> buttons) {
return new GuiConfig();
}
};
}
public ConfigTabsButtonListener createListener() {
return new ConfigTabsButtonListener(this);
}
}
public static TabSupplier wrapSaveableOptions(String name, String translationKey, Supplier<List<SaveableConfig<? extends IConfigBase>>> supplier) {
Supplier<List<IConfigBase>> configSupplier = () -> {
List<IConfigBase> config = new ArrayList<>();
List<SaveableConfig<? extends IConfigBase>> options = supplier.get();
for (SaveableConfig<? extends IConfigBase> s : options) {
config.add(s.config);
}
return config;
};
return wrapOptions(name, translationKey, configSupplier);
}
public static TabSupplier wrapSaveableOptions(String name, String translationKey, List<SaveableConfig<? extends IConfigBase>> options) {
List<IConfigBase> config = new ArrayList<>();
for (SaveableConfig<? extends IConfigBase> s : options) {
config.add(s.config);
}
return wrapOptions(name, translationKey, config);
}
public static TabSupplier wrapOptions(String name, String translationKey, List<IConfigBase> configs) {
return wrapOptions(name, translationKey, () -> configs);
}
public static TabSupplier wrapOptions(String name, String translationKey, Supplier<List<IConfigBase>> options) {
return new TabSupplier(name, translationKey) {
@Override
public List<IConfigBase> getOptions() {
return options.get();
}
};
}
public static TabSupplier wrapScreen(String name, String translationKey, Function<Screen, Screen> screenSupplier) {
return new TabSupplier(name, translationKey) {
@Override
public Screen getScreen(Screen parent) {
return screenSupplier.apply(parent);
}
};
}
public static TabSupplier children(String name, String translationKey, TabSupplier... children) {
TabSupplier tab = new TabSupplier(name, translationKey) {
@Override
public String getName() {
return super.getName();
}
};
for (TabSupplier child : children) {
tab.addChild(child);
}
return tab;
}
@Deprecated
public interface Tab {
String getName();
Screen getScreen(List<TabButton> buttons);
}
@Deprecated
public interface GuiConfigSection extends Tab {
List<IConfigBase> getOptions();
String getName();
@Override
default Screen getScreen(List<TabButton> buttons) {
GuiConfigHandler.getInstance().activeTab = this.getName();
return new GuiConfig();
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\gui\ModMenuImpl.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.config.gui;
import com.terraformersmc.modmenu.api.ConfigScreenFactory;
import com.terraformersmc.modmenu.api.ModMenuApi;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
@Environment(EnvType.CLIENT)
public class ModMenuImpl implements ModMenuApi {
@Override
public ConfigScreenFactory<?> getModConfigScreenFactory() {
return parent -> GuiConfigHandler.getInstance().getDefaultScreen();
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\gui\OnOffListListener.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.config.gui;
import fi.dy.masa.malilib.gui.button.ButtonBase;
import fi.dy.masa.malilib.gui.button.ButtonGeneric;
import fi.dy.masa.malilib.gui.button.IButtonActionListener;
import io.github.darkkronicle.advancedchatcore.config.gui.widgets.WidgetToggle;
import io.github.darkkronicle.advancedchatcore.interfaces.Translatable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class OnOffListListener<T extends Translatable> implements IButtonActionListener {
private final ButtonGeneric button;
private final WidgetToggle toggle;
private T current;
private HashMap<T, Boolean> onOff;
private final List<T> order;
public OnOffListListener(ButtonGeneric button, WidgetToggle toggle, HashMap<T, Boolean> onOff) {
this.button = button;
this.toggle = toggle;
this.onOff = new HashMap<>(onOff);
this.order = new ArrayList<>(onOff.keySet());
next();
}
public IButtonActionListener getButtonListener() {
return (button1, mouseButton) -> {
onToggled();
};
}
private void onToggled() {
onOff.put(current, toggle.isCurrentlyOn());
}
private void next() {
int i = order.indexOf(current) + 1;
if (i >= order.size()) {
i = 0;
}
current = order.get(i);
button.setDisplayString(current.translate());
toggle.setOn(onOff.get(current));
}
public List<T> getOn() {
ArrayList<T> list = new ArrayList<>();
for (Map.Entry<T, Boolean> entry : onOff.entrySet()) {
if (entry.getValue()) {
list.add(entry.getKey());
}
}
return list;
}
public static <T extends Translatable> HashMap<T, Boolean> getOnOff(
List<T> all, List<T> active) {
HashMap<T, Boolean> map = new HashMap<>();
for (T a : all) {
map.put(a, active.contains(a));
}
return map;
}
@Override
public void actionPerformedWithButton(ButtonBase button, int mouseButton) {
next();
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\gui\TabSupplier.java
|
package io.github.darkkronicle.advancedchatcore.config.gui;
import fi.dy.masa.malilib.config.IConfigBase;
import fi.dy.masa.malilib.util.StringUtils;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.client.gui.screen.Screen;
import java.util.ArrayList;
import java.util.List;
public class TabSupplier {
@Getter
private final String name;
private final String translationKey;
@Getter
@Setter
private TabSupplier nestedSelection = null;
@Getter
private List<TabSupplier> children = new ArrayList<>();
public TabSupplier(String name, String translationKey) {
this.name = name;
this.translationKey = translationKey;
}
public String getDisplayName() {
return StringUtils.translate(translationKey);
}
public List<IConfigBase> getOptions() {
return null;
}
public Screen getScreen(Screen parent) {
return null;
}
public boolean isSelectable() {
return true;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TabSupplier)) {
return false;
}
return (((TabSupplier) obj).getName().equals(getName()));
}
public void addChild(TabSupplier supplier) {
if (nestedSelection == null) {
if (supplier.isSelectable()) {
nestedSelection = supplier;
}
}
this.children.add(supplier);
}
public TabSupplier get(String name) {
for (TabSupplier child : children) {
if (name.equals(child.getName())) {
return child;
}
}
return null;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\options\ConfigColor.java
|
/*
* Copyright (C) 2021-2022 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.config.options;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import fi.dy.masa.malilib.MaLiLib;
import fi.dy.masa.malilib.util.StringUtils;
import io.github.darkkronicle.advancedchatcore.util.Color;
import io.github.darkkronicle.advancedchatcore.util.Colors;
import java.util.Optional;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
@Environment(EnvType.CLIENT)
public class ConfigColor extends fi.dy.masa.malilib.config.options.ConfigColor {
private Color color;
private final String defaultReference;
private String reference = null;
public ConfigColor(String name, Color defaultValue, String comment) {
super(name, defaultValue.getString(), comment);
this.color = defaultValue;
this.defaultReference = null;
}
public ConfigColor(String name, String referenceDefault, String comment) {
super(name, Colors.getInstance().getColorOrWhite(referenceDefault).toString(), comment);
this.color = Colors.getInstance().getColorOrWhite(referenceDefault);
this.defaultReference = referenceDefault;
}
@Override
public void resetToDefault() {
if (defaultReference != null) {
this.setValueFromString(defaultReference);
} else {
this.setValueFromString(new Color(defaultValue).getString());
}
onValueChanged();
}
@Override
public String getDefaultStringValue() {
if (defaultReference == null) {
return super.getDefaultStringValue();
}
return defaultReference;
}
@Override
public void setValueFromString(String value) {
Optional<Color> color = Colors.getInstance().getColor(value);
if (color.isPresent()) {
this.setIntegerValue(color.get().color());
this.reference = value;
this.setColor();
return;
}
this.reference = null;
super.setValueFromString(value);
this.setColor();
}
@Override
public String getStringValue() {
if (reference != null) {
return this.reference;
}
return super.getStringValue();
}
private void setColor() {
this.color = new Color(getIntegerValue());
}
@Override
public void setValueFromJsonElement(JsonElement element) {
try {
if (element.isJsonPrimitive()) {
String value = element.getAsString();
Optional<Color> color = Colors.getInstance().getColor(value);
if (color.isPresent()) {
this.setIntegerValue(color.get().color());
this.reference = value;
this.setColor();
return;
}
this.value = this.getClampedValue(StringUtils.getColor(value, 0));
this.setIntegerValue(this.value);
this.setColor();
} else {
MaLiLib.logger.warn(
"Failed to set config value for '{}' from the JSON element '{}'",
this.getName(),
element);
}
} catch (Exception e) {
MaLiLib.logger.warn(
"Failed to set config value for '{}' from the JSON element '{}'",
this.getName(),
element,
e);
}
}
@Override
public JsonElement getAsJsonElement() {
return new JsonPrimitive(getStringValue());
}
public Color get() {
return color;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\gui\widgets\WidgetColor.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.config.gui.widgets;
import fi.dy.masa.malilib.gui.GuiTextFieldGeneric;
import fi.dy.masa.malilib.render.RenderUtils;
import fi.dy.masa.malilib.util.StringUtils;
import io.github.darkkronicle.advancedchatcore.util.Color;
import io.github.darkkronicle.advancedchatcore.util.Colors;
import java.util.Optional;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.util.math.MatrixStack;
public class WidgetColor extends GuiTextFieldGeneric {
private int colorX;
private Color currentColor;
public WidgetColor(
int x, int y, int width, int height, Color color, TextRenderer textRenderer) {
super(x, y, width - 22, height, textRenderer);
this.colorX = x + width - 20;
this.currentColor = color;
setText(String.format("#%08X", this.currentColor.color()));
}
@Override
public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
super.render(matrixStack, mouseX, mouseY, partialTicks);
int y = this.y;
RenderUtils.drawRect(this.colorX, y, 19, 19, 0xFFFFFFFF);
RenderUtils.drawRect(this.colorX + 1, y + 1, 17, 17, 0xFF000000);
RenderUtils.drawRect(this.colorX + 2, y + 2, 15, 15, this.currentColor.color());
}
@Override
public void write(String text) {
super.write(text);
getAndRefreshColor4f();
}
@Override
public int getWidth() {
return super.getWidth() + 22;
}
public Color getAndRefreshColor4f() {
Optional<Color> color = Colors.getInstance().getColor(getText());
if (color.isPresent()) {
this.currentColor = color.get();
return this.currentColor;
}
this.currentColor = new Color(StringUtils.getColor(getText(), 0));
return this.currentColor;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\gui\widgets\WidgetIntBox.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.config.gui.widgets;
import fi.dy.masa.malilib.gui.GuiTextFieldGeneric;
import io.github.darkkronicle.advancedchatcore.util.FindType;
import io.github.darkkronicle.advancedchatcore.util.SearchUtils;
import io.github.darkkronicle.advancedchatcore.util.StringMatch;
import java.util.List;
import java.util.Optional;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.client.font.TextRenderer;
public class WidgetIntBox extends GuiTextFieldGeneric {
@Setter @Getter private Runnable apply = null;
public WidgetIntBox(int x, int y, int width, int height, TextRenderer textRenderer) {
super(x, y, width, height, textRenderer);
this.setTextPredicate(
text -> {
if (text.equals("")) {
return true;
}
try {
// Only allow numbers!
Integer.valueOf(text);
} catch (NumberFormatException e) {
return false;
}
return true;
});
this.setDrawsBackground(true);
}
public Integer getInt() {
String text = this.getText();
if (text == null || text.length() == 0) {
return null;
}
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
// Extra catch
Optional<List<StringMatch>> omatches =
SearchUtils.findMatches(text, "[0-9]+", FindType.REGEX);
if (!omatches.isPresent()) {
return null;
}
for (StringMatch m : omatches.get()) {
try {
return Integer.parseInt(m.match);
} catch (NumberFormatException err) {
return null;
}
}
}
return null;
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\gui\widgets\WidgetLabelHoverable.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.config.gui.widgets;
import fi.dy.masa.malilib.gui.widgets.WidgetLabel;
import fi.dy.masa.malilib.render.RenderUtils;
import java.util.Arrays;
import java.util.List;
import net.minecraft.client.util.math.MatrixStack;
public class WidgetLabelHoverable extends WidgetLabel {
private List<String> hoverLines = null;
public WidgetLabelHoverable(
int x, int y, int width, int height, int textColor, List<String> lines) {
super(x, y, width, height, textColor, lines);
}
public WidgetLabelHoverable(
int x, int y, int width, int height, int textColor, String... text) {
super(x, y, width, height, textColor, text);
}
public void setHoverLines(String... hoverLines) {
this.hoverLines = Arrays.asList(hoverLines);
}
@Override
public void postRenderHovered(
int mouseX, int mouseY, boolean selected, MatrixStack matrixStack) {
super.postRenderHovered(mouseX, mouseY, selected, matrixStack);
if (hoverLines == null) {
return;
}
if (mouseX >= this.x
&& mouseX < this.x + this.width
&& mouseY >= this.y
&& mouseY <= this.y + this.height) {
RenderUtils.drawHoverText(mouseX, mouseY, this.hoverLines, matrixStack);
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\gui\widgets\WidgetListRegistryOption.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.config.gui.widgets;
import fi.dy.masa.malilib.gui.interfaces.ISelectionListener;
import fi.dy.masa.malilib.gui.widgets.WidgetListBase;
import io.github.darkkronicle.advancedchatcore.interfaces.ConfigRegistryOption;
import io.github.darkkronicle.advancedchatcore.util.AbstractRegistry;
import java.util.Collection;
import java.util.stream.Collectors;
import net.minecraft.client.gui.screen.Screen;
import org.jetbrains.annotations.Nullable;
public class WidgetListRegistryOption<T extends ConfigRegistryOption<?>>
extends WidgetListBase<T, WidgetRegistryOptionEntry<T>> {
private final AbstractRegistry<?, T> registry;
public WidgetListRegistryOption(
int x,
int y,
int width,
int height,
@Nullable ISelectionListener<T> selectionListener,
AbstractRegistry<?, T> registry,
Screen parent) {
super(x, y, width, height, selectionListener);
this.browserEntryHeight = 22;
this.setParent(parent);
this.registry = registry;
}
@Override
protected WidgetRegistryOptionEntry<T> createListEntryWidget(
int x, int y, int listIndex, boolean isOdd, T entry) {
return new WidgetRegistryOptionEntry<T>(
x,
y,
this.browserEntryWidth,
this.getBrowserEntryHeightFor(entry),
isOdd,
entry,
listIndex,
this);
}
@Override
protected Collection<T> getAllEntries() {
return registry.getAll().stream()
.filter(option -> !option.isHidden())
.collect(Collectors.toList());
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\gui\widgets\WidgetRegistryOptionEntry.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.config.gui.widgets;
import com.mojang.blaze3d.systems.RenderSystem;
import fi.dy.masa.malilib.gui.GuiBase;
import fi.dy.masa.malilib.gui.button.ButtonBase;
import fi.dy.masa.malilib.gui.button.ButtonGeneric;
import fi.dy.masa.malilib.gui.button.ButtonOnOff;
import fi.dy.masa.malilib.gui.button.IButtonActionListener;
import fi.dy.masa.malilib.gui.widgets.WidgetListEntryBase;
import fi.dy.masa.malilib.render.RenderUtils;
import fi.dy.masa.malilib.util.StringUtils;
import io.github.darkkronicle.advancedchatcore.interfaces.ConfigRegistryOption;
import io.github.darkkronicle.advancedchatcore.util.Colors;
import java.util.List;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.util.math.MatrixStack;
@Environment(EnvType.CLIENT)
public class WidgetRegistryOptionEntry<T extends ConfigRegistryOption<?>>
extends WidgetListEntryBase<T> {
private final WidgetListRegistryOption<T> parent;
private final boolean isOdd;
private final List<String> hoverLines;
private final int buttonStartX;
private final T option;
public WidgetRegistryOptionEntry(
int x,
int y,
int width,
int height,
boolean isOdd,
T registryOption,
int listIndex,
WidgetListRegistryOption<T> parent) {
super(x, y, width, height, registryOption, listIndex);
this.parent = parent;
this.isOdd = isOdd;
this.hoverLines = registryOption.getHoverLines();
this.option = registryOption;
y += 1;
int pos = x + width - 2;
pos -= addOnOffButton(pos, y, ButtonListener.Type.ACTIVE, option.isActive());
if (this.option.getScreen(parent) != null) {
pos -= addButton(pos, y, ButtonListener.Type.CONFIGURE);
}
buttonStartX = pos;
}
protected int addButton(int x, int y, ButtonListener.Type type) {
ButtonGeneric button = new ButtonGeneric(x, y, -1, true, type.getDisplayName());
this.addButton(button, new ButtonListener<>(type, this));
return button.getWidth() + 1;
}
private int addOnOffButton(int xRight, int y, ButtonListener.Type type, boolean isCurrentlyOn) {
ButtonOnOff button = new ButtonOnOff(xRight, y, -1, true, type.translate, isCurrentlyOn);
this.addButton(button, new ButtonListener<>(type, this));
return button.getWidth() + 1;
}
@Override
public void render(int mouseX, int mouseY, boolean selected, MatrixStack matrixStack) {
RenderUtils.color(1f, 1f, 1f, 1f);
// Draw a lighter background for the hovered and the selected entry
if (selected || this.isMouseOver(mouseX, mouseY)) {
RenderUtils.drawRect(
this.x,
this.y,
this.width,
this.height,
Colors.getInstance().getColorOrWhite("white").withAlpha(150).color());
} else if (this.isOdd) {
RenderUtils.drawRect(
this.x,
this.y,
this.width,
this.height,
Colors.getInstance().getColorOrWhite("white").withAlpha(70).color());
} else {
RenderUtils.drawRect(
this.x,
this.y,
this.width,
this.height,
Colors.getInstance().getColorOrWhite("white").withAlpha(50).color());
}
String name = this.option.getDisplayName();
this.drawString(
this.x + 4,
this.y + 7,
Colors.getInstance().getColorOrWhite("white").color(),
name,
matrixStack);
RenderUtils.color(1f, 1f, 1f, 1f);
RenderSystem.disableBlend();
super.render(mouseX, mouseY, selected, matrixStack);
RenderUtils.disableDiffuseLighting();
}
@Override
public void postRenderHovered(
int mouseX, int mouseY, boolean selected, MatrixStack matrixStack) {
super.postRenderHovered(mouseX, mouseY, selected, matrixStack);
if (hoverLines == null) {
return;
}
if (mouseX >= this.x
&& mouseX < this.buttonStartX
&& mouseY >= this.y
&& mouseY <= this.y + this.height) {
RenderUtils.drawHoverText(mouseX, mouseY, this.hoverLines, matrixStack);
}
}
private static class ButtonListener<T extends ConfigRegistryOption<?>>
implements IButtonActionListener {
private final Type type;
private final WidgetRegistryOptionEntry<T> parent;
public ButtonListener(Type type, WidgetRegistryOptionEntry<T> parent) {
this.parent = parent;
this.type = type;
}
@Override
public void actionPerformedWithButton(ButtonBase button, int mouseButton) {
if (type == Type.ACTIVE) {
this.parent
.option
.getActive()
.config
.setBooleanValue(!this.parent.option.isActive());
parent.parent.refreshEntries();
} else if (type == Type.CONFIGURE) {
Screen screen = parent.option.getScreen(parent.parent.getParent()).get();
if (screen != null) {
GuiBase.openGui(screen);
}
}
}
public enum Type {
CONFIGURE("configure"),
ACTIVE("active");
private final String translate;
Type(String name) {
this.translate = translate(name);
}
private static String translate(String key) {
return "advancedchat.config.button." + key;
}
public String getDisplayName() {
return StringUtils.translate(translate);
}
}
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\config\gui\widgets\WidgetToggle.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.config.gui.widgets;
import fi.dy.masa.malilib.gui.button.ButtonOnOff;
import lombok.Getter;
public class WidgetToggle extends ButtonOnOff {
@Getter private boolean currentlyOn;
public WidgetToggle(
int x,
int y,
int width,
boolean rightAlign,
String translationKey,
boolean isCurrentlyOn,
String... hoverStrings) {
super(x, y, width, rightAlign, translationKey, isCurrentlyOn, hoverStrings);
this.currentlyOn = isCurrentlyOn;
}
@Override
protected boolean onMouseClickedImpl(int mouseX, int mouseY, int mouseButton) {
this.currentlyOn = !this.currentlyOn;
this.updateDisplayString(this.currentlyOn);
return super.onMouseClickedImpl(mouseX, mouseY, mouseButton);
}
public void setOn(boolean on) {
this.currentlyOn = on;
this.updateDisplayString(on);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\finder\custom\ProfanityFinder.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.finder.custom;
import io.github.darkkronicle.advancedchatcore.config.ConfigStorage;
import io.github.darkkronicle.advancedchatcore.interfaces.IFinder;
import io.github.darkkronicle.advancedchatcore.util.ProfanityUtil;
import io.github.darkkronicle.advancedchatcore.util.StringMatch;
import java.util.List;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
@Environment(EnvType.CLIENT)
public class ProfanityFinder implements IFinder {
@Override
public boolean isMatch(String input, String toMatch) {
return getMatches(input, toMatch).size() != 0;
}
@Override
public List<StringMatch> getMatches(String input, String toMatch) {
return ProfanityUtil.getInstance().getBadWords(input, (float) ConfigStorage.General.PROFANITY_ABOVE.config.getDoubleValue(), ConfigStorage.General.PROFANITY_ON_WORD_BOUNDARIES.config.getBooleanValue());
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\gui\buttons\BackButtonListener.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.gui.buttons;
import fi.dy.masa.malilib.gui.button.ButtonBase;
import fi.dy.masa.malilib.gui.button.IButtonActionListener;
import io.github.darkkronicle.advancedchatcore.interfaces.IClosable;
public class BackButtonListener implements IButtonActionListener {
private final IClosable closable;
public BackButtonListener(IClosable closable) {
this.closable = closable;
}
@Override
public void actionPerformedWithButton(ButtonBase button, int mouseButton) {
this.closable.close(button);
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\gui\buttons\Buttons.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.gui.buttons;
import fi.dy.masa.malilib.util.StringUtils;
public enum Buttons {
BACK("advancedchat.gui.button.back");
private final String translationString;
Buttons(String translationString) {
this.translationString = translationString;
}
public NamedSimpleButton createButton(int x, int y) {
return new NamedSimpleButton(x, y, StringUtils.translate(translationString));
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\gui\buttons\ConfigTabsButtonListener.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.gui.buttons;
import fi.dy.masa.malilib.gui.GuiBase;
import fi.dy.masa.malilib.gui.button.ButtonBase;
import fi.dy.masa.malilib.gui.button.IButtonActionListener;
import io.github.darkkronicle.advancedchatcore.config.gui.GuiConfig;
import io.github.darkkronicle.advancedchatcore.config.gui.GuiConfigHandler;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
@Deprecated
@Environment(EnvType.CLIENT)
public class ConfigTabsButtonListener implements IButtonActionListener {
private final GuiConfigHandler.TabButton tabButton;
public ConfigTabsButtonListener(GuiConfigHandler.TabButton tabButton) {
this.tabButton = tabButton;
}
@Override
public void actionPerformedWithButton(ButtonBase button, int mouseButton) {
GuiConfig.TAB = tabButton.getTabSupplier();
GuiBase.openGui(new GuiConfig());
}
}
|
AdvancedChatCore
|
src\main\java\io\github\darkkronicle\advancedchatcore\gui\buttons\NamedSimpleButton.java
|
/*
* Copyright (C) 2021 DarkKronicle
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package io.github.darkkronicle.advancedchatcore.gui.buttons;
import fi.dy.masa.malilib.gui.button.ButtonGeneric;
import fi.dy.masa.malilib.util.StringUtils;
public class NamedSimpleButton extends ButtonGeneric {
public NamedSimpleButton(int x, int y, String text) {
this(x, y, text, true);
}
public NamedSimpleButton(int x, int y, String text, boolean alineLeft) {
super(x, y, 5, 20, text);
setWidth(StringUtils.getStringWidth(text) + 10);
if (!alineLeft) {
setX(this.x - this.width);
}
}
}
|
AdvancedChatCore
|
src\main\resources\assets\advancedchatcore\lang\en_us.json
|
{
"advancedchat.config.yes": "Correct!",
"advancedchat.gui.button.back": "Back",
"advancedchat.gui.button.settings": "Settings",
"advancedchat.gui.message.sucessful": "Success!",
"advancedchat.screen.main": "§3Advanced§5Chat§f Config",
"advancedchatcore.tab.general": "§7General",
"advancedchatcore.tab.chatscreen": "§bChat Screen",
"advancedchat.tab.advancedchatcore": "Core",
"advancedchatcore.message.togglepermanent": "Toggled Permanent",
"advancedchat.tab.hotkeys": "§cHotkeys",
"advancedchatcore.config.tab.hotkeysgeneral": "§bCore",
"advancedchat.config.hotkeys.opensettings": "Open Settings GUI",
"advancedchat.config.hotkeys.info.opensettings": "Opens the settings GUI",
"advancedchat.config.hotkeys.openchat": "Open Chat",
"advancedchat.config.hotkeys.info.openchat": "Opens chat (vanilla keybind still works)",
"advancedchat.config.hotkeys.togglepermanentfocus": "Toggle Permanent Focus",
"advancedchat.config.hotkeys.info.togglepermanentfocus": "Toggles an option to have chat viewed as permanently focused.\nThis makes it so that the HUD renders in focus with this active.",
"advancedchat.config.hotkeys.openchatwithlast": "Open Chat with Last Message",
"advancedchat.config.hotkeys.info.openchatwithlast": "Opens the chat screen with the previously sent message in the box.",
"advancedchat.config.hotkeys.openchatfreemovement": "Open Chat with Movement Enabled",
"advancedchat.config.hotkeys.info.openchatfreemovement": "Opens the chat screen with the keyboard unlocked. The character can move but cannot type messages.",
"advancedchat.config.general.timeformat": "Time Format",
"advancedchat.config.general.info.timeformat": "How time is displayed if §6Show Time§r is enabled for both the §9Chat HUD§r and the §aChat Log§r. \nSee the §6SimpleDateFormat§r class for the format ",
"advancedchat.config.general.timetextformat": "Complete Time Format",
"advancedchat.config.general.info.timetextformat": "How the §6text§r surrounding the §6time§r is formatted",
"advancedchat.config.general.showtime": "Show Time",
"advancedchat.config.general.info.showtime": "Whether or not the time is §6displayed alongside chat messages§r",
"advancedchat.config.general.timecolor": "Time Color",
"advancedchat.config.general.info.timecolor": "What color the §6time§r will display as",
"advancedchat.config.general.clearondisconnect": "Clear Chat Messages on Disconnect",
"advancedchat.config.general.info.clearondisconnect": "Whether or not chat messages are kept upon §6disconnecting from servers§r or §6quitting from a singleplayer world§r \nChat messages are §cnot kept§r upon §6quitting the game§r, regardless of this setting",
"advancedchat.config.general.chatstack": "Stack Duplicate Messages",
"advancedchat.config.general.chatstackupdate": "Resend Stacked Messages",
"advancedchat.config.general.info.chatstackupdate": "Whether or not stacked messages are §6shown again as new messages§r",
"advancedchat.config.general.info.chatstack": "How many previous lines are checked for §6stacking duplicate messages§r \nSet to §60§r to disable stacking duplicate messages",
"advancedchat.config.general.chatheads": "Display Chat Heads",
"advancedchat.config.general.info.chatheads": "Whether or not the §6head of the message sender§r displays beside their message",
"advancedchat.config.general.messageownerregex": "Message Owner Regex",
"advancedchat.config.general.info.messageownerregex": "The §6regular expression§r used to detect the head used for chat heads \n§cDon't mess with this unless you §c§oreally §cunderstand what you're working with!",
"advancedchat.config.general.filterprofanity": "Filter Profanity",
"advancedchat.config.general.info.filterprofanity": "Filter's out §9swear words§r and replaces them with *'s.\n\nTo use your own swear word list have each line be a swear word\nin a file in §7~minecraft/config/advancedchat/swear_words.txt",
"advancedchat.config.general.profanityabove": "Profanity Threshold",
"advancedchat.config.general.info.profanityabove": "The §6minimum level of severity§r before AdvancedChat filters a word. Ranges from §b0§r to §b3§r.\n1 includes common swear words, and progressively gets more explicit",
"advancedchat.config.general.profanitywordboundaries": "Disable Partial Matches",
"advancedchat.config.general.info.profanitywordboundaries": "Whether or not the profanity filter does not §6match words that contain swears§r, such as §6grass§r",
"advancedchat.config.chatscreen.persistenttext": "Persistent Text",
"advancedchat.config.chatscreen.info.persistenttext": "Whether or not messages that are §6typed but not sent§r are kept after closing the §9Chat Box",
"advancedchat.config.chatscreen.moretext": "Extended Text Limit",
"advancedchat.config.chatscreen.info.moretext": "Whether or not messages that are §6over the 256 character limit§r are broken into multiple chat messages",
"advancedchat.config.chatscreen.color": "Chat Color",
"advancedchat.config.chatscreen.info.color": "Changes color of the §6chat box§r and buttons nearby.",
"advancedchat.config.chatscreen.showchaticons": "Show Chat Icons",
"advancedchat.config.chatscreen.info.showchaticons": "Show chat icons that provide info on message signature type",
"advancedchat.config.chatscreen.modified": "Modified Color",
"advancedchat.config.chatscreen.info.modified": "The color that modified signed messages will be",
"advancedchat.config.chatscreen.filtered": "Filtered Color",
"advancedchat.config.chatscreen.info.filtered": "The color that filtered signed messages will be",
"advancedchat.config.chatscreen.system": "System Color",
"advancedchat.config.chatscreen.info.system": "The color that system signed messages will be",
"advancedchat.config.chatscreen.notsecure": "Not Secure Color",
"advancedchat.config.chatscreen.info.notsecure": "The color that not secure signed messages will be",
"advancedchat.config.button.configure": "§bConfigure",
"advancedchat.config.button.active": "%s",
"advancedchat.config.findtype.literal": "§6Literal",
"advancedchat.config.findtype.upperlower": "§eUpper-Lower",
"advancedchat.config.findtype.regex": "§bRegEx",
"advancedchat.config.findtype.custom": "§dCustom"
}
|
AdvancedChatCore
|
src\main\resources\assets\advancedchatcore\lang\zh_cn.json
|
{
"advancedchat.config.yes": "确认!",
"advancedchat.screen.main": "§3Advanced§5Chat§f 配置",
"advancedchat.screen.chatlog": "§3Advanced§5Chat§f 聊天记录",
"advancedchat.screen.sound": "声音设置",
"advancedchat.screen.suggestors": "补全设置",
"advancedchat.screen.shortcut": "快捷聊天设置",
"advancedchat.gui.button.save": "保存",
"advancedchat.gui.button.addtab": "创建新的聊天分页",
"advancedchat.gui.button.addfilter": "创建新的筛选器",
"advancedchat.gui.button.back": "返回",
"advancedchat.gui.button.import": "导入 筛选器/聊天分页",
"advancedchat.gui.button.export": "导出",
"advancedchat.gui.button.importfilter": "导入 筛选器",
"advancedchat.gui.button.importtab": "导入 聊天分页",
"advancedchat.gui.button.settings": "设定",
"advancedchat.gui.button.chatlog": "聊天记录",
"advancedchat.gui.button.addshortcut": "添加新的快捷方式",
"advancedchat.gui.menu.import": "导入/导出 筛选器和聊天分页",
"advancedchat.gui.message.successful": "导出成功!",
"advancedchat.gui.message.error": "导出不能",
"advancedchat.config.tab.general": "§7基础设定",
"advancedchat.config.tab.chatscreen": "§9聊天框",
"advancedchat.config.tab.chatlog": "§a聊天记录",
"advancedchat.config.tab.chatsuggestor": "§d聊天补全",
"advancedchat.config.tab.tabs": "§b聊天分页",
"advancedchat.config.tab.filters": "§c聊天筛选器",
"advancedchat.config.processoron": "%s",
"advancedchat.config.shortcutmenu.remove": "§c移除",
"advancedchat.config.general.timeformat": "时间格式",
"advancedchat.config.general.info.timeformat": "当 §6显示时间§r 在 §9聊天框§r 和 §a聊天记录§r 中开启时,时间的显示格式是怎样的? \n检阅 §6SimpleDateFormat§r 类来获取样式 ",
"advancedchat.config.general.timetextformat": "完整时间格式",
"advancedchat.config.general.info.timetextformat": "控制有关 §6时间§r 的 §6文本§r 如何格式化",
"advancedchat.config.general.timecolor": "时间颜色",
"advancedchat.config.general.info.timecolor": "控制 §6时间§r 用什么颜色来区分",
"advancedchat.config.general.clearondisconnect": "在断开连接时清空聊天框",
"advancedchat.config.general.info.clearondisconnect": "无论是否在§6从服务器断开连接时保留聊天消息§r或§6从单人世界退出时保留聊天消息§r\n在§6退出游戏时保留聊天消息§r,与此设置无关",
"advancedchat.config.general.chatstack": "堆叠重复信息",
"advancedchat.config.general.info.chatstack": "检查文本的多少字符用以检查§6堆叠重复消息§r\n设置为 §60§r 以禁用堆叠重复消息",
"advancedchat.config.general.chatheads": "显示聊天头颅",
"advancedchat.config.general.info.chatheads": "是否 §6显示玩家头颅§r 于玩家聊天信息前",
"advancedchat.config.general.messageownerregex": "消息所有者正则",
"advancedchat.config.general.info.messageownerregex": "用于检测聊天头的§6正则表达式\n不要搞砸这个,除非你真正理解你在使用什么!",
"advancedchat.config.chatscreen.width": "聊天框宽度",
"advancedchat.config.chatscreen.info.width": "§9聊天框的宽度\n这将覆盖原版的聊天宽度!",
"advancedchat.config.chatscreen.height": "聊天框高度",
"advancedchat.config.chatscreen.info.height": "§9聊天框的高度 \n这将覆写原版的聊天框高度!",
"advancedchat.config.chatscreen.showtabs": "显示聊天分页",
"advancedchat.config.chatscreen.info.showtabs": "控制是否在§9聊天框§r§6旁边§r显示§b聊天分页§r标签 ",
"advancedchat.config.chatscreen.leftpad": "左侧聊天填充",
"advancedchat.config.chatscreen.info.leftpad": "聊天框的§6左侧§r到§6文本开始处之间的空格量",
"advancedchat.config.chatscreen.rightpad": "右侧聊天填充",
"advancedchat.config.chatscreen.info.rightpad": "聊天框§6右侧§r到§6文本中断处之间的空格量",
"advancedchat.config.chatscreen.bottompad": "底部聊天填充",
"advancedchat.config.chatscreen.info.bottompad": "聊天框底部§r到§6最新消息之间的空间量",
"advancedchat.config.chatscreen.toppad": "顶部聊天填充",
"advancedchat.config.chatscreen.info.toppad": "聊天框的§6顶部§R到§6以前的空间量",
"advancedchat.config.chatscreen.tabsidechars": "最大缩写长度",
"advancedchat.config.chatscreen.info.tabsidechars": "用于§b聊天分页&r§6缩略语§r的最大字符长度\n影响位于§9聊天框§r旁边的§9聊天分页标签§r的显示",
"advancedchat.config.chatscreen.visibility": "聊天可见性",
"advancedchat.config.chatscreen.info.visibility": "控制§9聊天框§r§6可见性§r的行为\n§6原版 §r- §9聊天框§r像§6原版§r那样渲染 \n§a总是 §r- 渲染§9聊天框§6于任何时刻 \n§c聚焦 §r- 只在 §9聊天框 §6被打开 §r时进行渲染",
"advancedchat.config.visibility.vanilla": "§6原版",
"advancedchat.config.visibility.always": "§a总是",
"advancedchat.config.visibility.focus_only": "§c聚焦",
"advancedchat.config.chatscreen.linespace": "行间距",
"advancedchat.config.chatscreen.info.linespace": "聊天行之间的§6空间§r(以像素为单位)",
"advancedchat.config.chatscreen.x": "聊天 X 轴",
"advancedchat.config.chatscreen.info.x": "聊天框的§6 x-坐标轴§r,从屏幕的§6左下方§r开始计算",
"advancedchat.config.chatscreen.y": "聊天 Y 轴",
"advancedchat.config.chatscreen.info.y": "聊天框的§6 y-坐标轴§r,从屏幕§6左下方§r开始计算",
"advancedchat.config.chatscreen.messagespace": "消息之间的填充",
"advancedchat.config.chatscreen.info.messagespace": "§6单个消息之间应该有多大的空间",
"advancedchat.config.chatscreen.chatscale": "文本尺寸",
"advancedchat.config.chatscreen.info.chatscale": "控制位于§9聊天框中§r的文本大小。这不会影响§9聊天框§r的大小!",
"advancedchat.config.chatscreen.fadetime": "淡出速度",
"advancedchat.config.chatscreen.info.fadetime": "消息从出现到§6淡出§r的速度有多快",
"advancedchat.config.chatscreen.fadestart": "淡出时间",
"advancedchat.config.chatscreen.info.fadestart": "在新收到消息开始直到消失之前的§6tick数§r",
"advancedchat.config.chatscreen.fadetype": "淡出种类",
"advancedchat.config.chatscreen.info.fadetype": "用于淡入淡出动画的§6缓和函数§r\n原版使用§6线性§r淡出",
"advancedchat.config.easing.linear": "§c线性",
"advancedchat.config.easing.sine": "§6正弦的",
"advancedchat.config.easing.quad": "§e二次型",
"advancedchat.config.easing.quart": "§a四次",
"advancedchat.config.easing.circ": "§b循环",
"advancedchat.config.chatscreen.hudbackgroundcolor": "框体背景填充色",
"advancedchat.config.chatscreen.info.hudbackgroundcolor": "§9聊天框§6背景§r的颜色",
"advancedchat.config.chatscreen.emptytextcolor": "空文本颜色",
"advancedchat.config.chatscreen.info.emptytextcolor": "当文本§6没有特定标签§r时使用的文本颜色(一般指文本没有用&#等符号进行格式指定)",
"advancedchat.config.chatscreen.hudlinetype": "背景线条样式",
"advancedchat.config.chatscreen.info.hudlinetype": "控制§6未聚焦§9聊天框§6背景§r如何校对信息 \n§6完全 §r- 将背景与§9聊天框的§6宽度§r相匹配 \n§b紧凑型 §r- 将背景与每条§6线§r的长度相匹配",
"advancedchat.config.hudlinetype.full": "§6完全",
"advancedchat.config.hudlinetype.compact": "§b紧凑型",
"advancedchat.config.chatscreen.alternatelines": "下划线信息",
"advancedchat.config.chatscreen.info.alternatelines": "是否背景中的§6每条信息§r都要被异色标出§6下划线§r \n§7有助于区分消息",
"advancedchat.config.chatscreen.showtime": "显示时间",
"advancedchat.config.chatscreen.info.showtime": "是否在§9聊天框§r中显示§6时间§r \n格式能在 §7基础设定§r 中配置",
"advancedchat.config.chatscreen.storedlines": "存储行数",
"advancedchat.config.chatscreen.info.storedlines": "§9聊天框§r所能存储的§6最大§r行量§r\n§7过大的值可能会导致内存不足错误!",
"advancedchat.config.chatscreen.persistenttext": "文本保留",
"advancedchat.config.chatscreen.info.persistenttext": "§6输入但尚未发送的文本§r是否在关闭§9聊天框§r后保留",
"advancedchat.config.chatscreen.moretext": "扩展文本限制",
"advancedchat.config.chatscreen.info.moretext": "§6超过256字符限制§r的消息是否被分解为多条聊天消息",
"advancedchat.config.chatscreen.sendtocurrenttab": "始终将消息发送到聚焦分页",
"advancedchat.config.chatscreen.info.sendtocurrenttab": "无论§6聊天过滤器§r被如何配置,您发送的消息都将显示在当前聚焦分页中。",
"advancedchat.config.chatlog.storedlines": "存储行数",
"advancedchat.config.chatlog.info.storedlines": "§a聊天记录§r所能存储的§6最大§r行量§r\n§7过大的值可能会导致内存不足错误! ",
"advancedchat.config.chatlog.showtime": "显示时间",
"advancedchat.config.chatlog.info.showtime": "是否在§a聊天记录§r中显示§6时间§r \n格式能在 §7基础设定§r 中配置",
"advancedchat.config.chatsuggestor.button.config_suggestors": "配置补全器",
"advancedchat.config.chatsuggestor.players": "补全玩家",
"advancedchat.config.chatsuggestor.info.players": "§6玩家名称§r是否会在聊天中被补全\n这些都通过tab来显示",
"advancedchat.config.chatsuggestor.shortcuts": "快捷聊天方式补全",
"advancedchat.config.chatsuggestor.info.shortcuts": "§6快捷聊天方式§r是否会在您输入过程中补全\n快捷方式是一种将令人难记的短语绑定到文本字符串的方法,例如用于表情符号\n要使用快捷范式, §6冒号开头 (§f:§6)§r 并紧接快捷方式名称,并按下 §6tab键",
"advancedchat.config.chatsuggestor.calculator": "聊天即时计算器",
"advancedchat.config.chatsuggestor.info.calculator": "是否启用内置的§6聊天计算器§r\n要使用指定聊天计算器, 将 §6数学表达式§r 放在 §6[§f里面§6]§r\n表达式的格式遵循 §6mXParser",
"advancedchat.config.chatsuggestor.spellcheck": "拼写检查",
"advancedchat.config.chatsuggestor.info.spellcheck": "控制 §6拼写检查§r 是否启用",
"advancedchat.config.chatsuggestor.button.config_formatters": "配置格式",
"advancedchat.config.chatformatter.commandcolorer": "自定义命令高亮",
"advancedchat.config.chatformatter.info.commandcolorer": "自定义颜色是否被应用于§9聊天框§6命令§r部分",
"advancedchat.config.chatformatter.jsonformatter": "在命令中高亮 JSON",
"advancedchat.config.chatformatter.info.jsonformatter": "§6JSON§r 信息是否被解析并高亮于§9聊天框",
"advancedchat.config.chatsuggestor.highlightcolor": "高亮颜色",
"advancedchat.config.chatsuggestor.info.highlightcolor": "什么颜色会被用于 §6已选择的补全内容§r",
"advancedchat.config.chatsuggestor.unhighlightcolor": "非高亮文本颜色",
"advancedchat.config.chatsuggestor.info.unhighlightcolor": "什么颜色会被用于 §6未选中的补全结果§r",
"advancedchat.config.chatsuggestor.backgroundcolor": "背景颜色",
"advancedchat.config.chatsuggestor.info.backgroundcolor": "什么颜色会被用于§d补全选择§r的§6背景§r",
"advancedchat.config.chatsuggestor.suggestionsize": "补全待选数",
"advancedchat.config.chatsuggestor.info.suggestionsize": "§d补全选择§r中单次显示的§6最大待选数",
"advancedchat.config.chatsuggestor.removeidentifier": "移除命名空间",
"advancedchat.config.chatsuggestor.info.removeidentifier": "§6命名空间§r 是否应该从 §d补全选择§r中移除\n命名空间是ID冒号前的 §6前缀§r \n及冒号本身, 例如 minecraft:stone 中的 '§6minecraft:§r'",
"advancedchat.config.chatsuggestor.pruneplayersuggestions": "虚拟玩家补全",
"advancedchat.config.chatsuggestor.info.pruneplayersuggestions": "诸如BungeeTabListPlus中提供的假玩家等§6虚拟玩家§r是否应该从§d补全结果§中移除",
"advancedchat.config.chatsuggestor.availablesuggestioncolor": "可用补全颜色",
"advancedchat.config.chatsuggestor.info.availablesuggestioncolor": "什么颜色会被应用于 §6自定义聊天补全§r",
"advancedchat.config.tabmenu.configure": "§b配置",
"advancedchat.config.tabmenu.remove": "§c删除",
"advancedchat.config.tab.name": "分页名称",
"advancedchat.config.tab.info.name": "分页将以怎样的名称显示在 §6配置中 \n§7§o最好让您的分页命名有意义!",
"advancedchat.config.tab.startingmessage": "初始化信息",
"advancedchat.config.tab.info.startingmessage": "§6当分页被聚焦时§r显示的信息",
"advancedchat.config.tab.abbreviation": "分页框缩写",
"advancedchat.config.tab.info.abbreviation": "分页将以怎样的缩写名称显示在§9聊天框§6旁边§r。当然,前提是 §6显示聊天分页§r 必须在§9聊天框§r 设置中开启",
"advancedchat.config.tab.forward": "将消息转发到主分页",
"advancedchat.config.tab.info.forward": "在这个分页中收到的消息是否会显示在 §6主体聊天分页§r",
"advancedchat.config.tab.forwardtoggle": "%s",
"advancedchat.config.tab.findstring": "搜寻字符串",
"advancedchat.config.tab.info.findstring": "哪些字符串应该§6被搜寻§r并§6分类到这个聊天分页中§r",
"advancedchat.config.tab.findtype": "搜寻类型",
"advancedchat.config.tab.info.findtype": "匹配系统如何工作\n§6轻度 §r- 匹配§6完整的§r字符串\n§e忽略大小写 §r- 就像 §6轻量, §r但§6并不对大小写感冒\n§b正则表达式 §r - 解析字符串为 §6规则的表达式\n§d全部 §r- 传递 §6所有 §r文本到这个分页,不管要查找的字符串是什么",
"advancedchat.config.filterdescription": "§7名称§r: <name> \n§a搜寻字符串§r: <find>\n§e搜寻类型§r: <findtype>",
"advancedchat.config.filtermenu.configure": "§b配置",
"advancedchat.config.filtermenu.active": "%s",
"advancedchat.config.filtermenu.remove": "§c删除",
"advancedchat.config.filter.editor.config": "筛选器设定",
"advancedchat.config.filter.editor.children": "子筛选器设置",
"advancedchat.config.filter.name": "筛选器名称",
"advancedchat.config.filter.info.name": "筛选器以怎样的名称显示在 §6配置中§r\n §7§b最好让您的筛选器命名有意义!",
"advancedchat.config.filter.findstring": "要搜寻的字符串",
"advancedchat.config.filter.info.findstring": "哪些字符串应该§6被搜寻§r并§6过滤§r",
"advancedchat.config.filter.findtype": "筛选器类型",
"advancedchat.config.filter.info.findtype": "匹配系统如何工作\n§6轻度 §r- 匹配§6完整的§r字符串\n§e忽略大小写 §r- 就像 §6轻量, §r但§6并不对大小写感冒\n§b正则表达式 §r - 解析字符串为 §6规则的表达式\n§d全部 §r- 传递 §6所有 §r文本到这个分页,不管要查找的字符串是什么。此选项主要用于使用父筛选器名称对多个子筛选器进行分组",
"advancedchat.config.findtype.literal": "§6轻量",
"advancedchat.config.findtype.upperlower": "§e忽略大小写",
"advancedchat.config.findtype.regex": "§b正则表达式",
"advancedchat.config.findtype.all": "§d全部",
"advancedchat.config.filter.replaceto": "替换为",
"advancedchat.config.filter.info.replaceto": "字符串§6替换为§r替换类型的§6设定\n§b%MATCH% 总是被替换,无论是否被过滤器 §6标记§r",
"advancedchat.config.filter.replacetype": "替换类型",
"advancedchat.config.filter.info.replacetype": "筛选器如何替换被筛选信息 \n§e仅匹配 §r- 替换过滤器 §6标记 §r的信息片段 \n§6整条信息 §r- 整条信息 §6替换§r 字符串 \n§d传递给子集 §r- 传递 §6匹配字符串§r 给§6子筛选器§r来更改 \n§c啥也不干 §r - 什么都 §6不替换",
"advancedchat.config.replacetype.onlymatch": "§e仅匹配",
"advancedchat.config.replacetype.fullmessage": "§a整条信息",
"advancedchat.config.replacetype.children": "§d传递给子集",
"advancedchat.config.replacetype.owo": "§6OwO",
"advancedchat.config.replacetype.reverse": "§5颠倒顺序",
"advancedchat.config.replacetype.rainbow": "§9彩色处理",
"advancedchat.config.replacetype.romannumeral": "§b罗马数字",
"advancedchat.config.replacetype.none": "§c无",
"advancedchat.config.filter.editor.processors": "信息处理器设置",
"advancedchat.config.processor.chat": "§b聊天",
"advancedchat.config.processor.info.chat": "被筛选器捕捉到的信息是否是否应该送到 §a聊天框§r",
"advancedchat.config.processor.actionbar": "§eAction Bar",
"advancedchat.config.processor.info.actionbar": "被筛选器捕捉到的信息是否是否应该送到 §eAction Bar§r",
"advancedchat.config.processor.sound": "§d声音",
"advancedchat.config.processor.info.sound": "筛选器捕捉到信息时是否§6播放一种§d声音",
"advancedchat.config.filter.textcolor": "文本颜色",
"advancedchat.config.filter.info.textcolor": "当筛选器标记§6被替换文本§r的颜色 \n§7这个选项会被§6旧版格式化代码§7所覆盖!",
"advancedchat.config.filter.replacetextcolor": "是否替换文本颜色?",
"advancedchat.config.filter.info.replacetextcolor": "§6自定义文本颜色§r是否应该在被筛选器标记时使用",
"advancedchat.config.filter.textcoloractive": "%s",
"advancedchat.config.filter.backgroundcolor": "背景颜色",
"advancedchat.config.filter.info.backgroundcolor": "当筛选器标记时,§6背景颜色§r 应该被替换为什么 \n§7这个设置会被§6旧版格式化代码§7所覆盖!",
"advancedchat.config.filter.replacebackgroundcolor": "替换背景颜色?",
"advancedchat.config.filter.info.replacebackgroundcolor": "§6背景颜色§r是否应该在被筛选器标记时使用",
"advancedchat.config.filter.backgroundcoloractive": "%s",
"advancedchat.config.sound.soundvolume": "音量大小",
"advancedchat.config.sound.info.soundvolume": "提示音的音量。等价于使用命令 /playsound 时的§6音量§r参数",
"advancedchat.config.sound.soundpitch": "音频频率",
"advancedchat.config.sound.info.soundpitch": "提示音的频率。等价于使用命令 /playsound 时的 §6音频§r参数",
"advancedchat.config.sound.notifysound": "提示音",
"advancedchat.config.sound.info.notifysound": "§6当过滤器被触发时§r播放的声音",
"advancedchat.config.notifysound.none": "无",
"advancedchat.config.notifysound.arrow_hit_player": "弓箭射中玩家",
"advancedchat.config.notifysound.anvil_break": "铁砧破坏",
"advancedchat.config.notifysound.beacon_activate": "信标启动",
"advancedchat.config.notifysound.elder_guardian_curse": "远古守卫者的诅咒"
}
|
AdvancedKitsReloaded
|
src\main\java\hu\tryharddevs\advancedkits\AdvancedKitsMain.java
|
package hu.tryharddevs.advancedkits;
import co.aikar.commands.ACF;
import co.aikar.commands.CommandManager;
import co.aikar.commands.CommandReplacements;
import hu.tryharddevs.advancedkits.cinventory.CInventoryMain;
import hu.tryharddevs.advancedkits.commands.CreateCommand;
import hu.tryharddevs.advancedkits.commands.EditCommand;
import hu.tryharddevs.advancedkits.commands.MainCommand;
import hu.tryharddevs.advancedkits.commands.UseCommand;
import hu.tryharddevs.advancedkits.kits.Kit;
import hu.tryharddevs.advancedkits.kits.KitManager;
import hu.tryharddevs.advancedkits.kits.flags.DefaultFlags;
import hu.tryharddevs.advancedkits.kits.flags.Flag;
import hu.tryharddevs.advancedkits.listeners.PlayerListener;
import hu.tryharddevs.advancedkits.utils.localization.I18n;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.ChatColor;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.inventivetalent.reflection.minecraft.Minecraft;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
public final class AdvancedKitsMain extends JavaPlugin {
private static AdvancedKitsMain advancedKits;
public I18n i18n;
private Economy economy;
private KitManager kitManager;
private Boolean usePlaceholderAPI = false;
public static AdvancedKitsMain getPlugin() {
return advancedKits;
}
@Override
public void onEnable() {
this.log(ChatColor.GREEN + "Starting " + this.getDescription().getName() + " " + this.getDescription().getVersion());
advancedKits = this;
if (Minecraft.VERSION.olderThan(Minecraft.Version.v1_9_R1)) {
this.log(ChatColor.RED + "ERROR: Unsupported Minecraft version. (" + Minecraft.VERSION.toString() + ")");
this.setEnabled(false);
return;
}
// Hooking vault
this.log("Hooking to Vault.");
Boolean vaultFound = this.getServer().getPluginManager().getPlugin("Vault") != null;
if (!vaultFound) {
this.log(ChatColor.RED + "- Disabled due to no Vault dependency found!");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
RegisteredServiceProvider<Economy> rsp = this.getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null || rsp.getProvider() == null) {
this.log(ChatColor.RED + "- Disabled due to no Economy plugin found!");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
this.economy = rsp.getProvider();
// Checking for PlaceholderAPI
this.usePlaceholderAPI = this.getServer().getPluginManager().getPlugin("PlaceholderAPI") != null;
// Loading configuration
this.log("Loading configuration.");
this.saveDefaultConfig();
Config.loadConfigurationValues(this);
// Load KitManager and the kits
this.log("Loading KitManager.");
this.kitManager = new KitManager(this);
this.kitManager.loadKits();
// Register events
this.log("Registering events");
this.getServer().getPluginManager().registerEvents(new PlayerListener(this), this);
this.getServer().getPluginManager().registerEvents(new CInventoryMain(this), this);
// Register CommandManager and the Commands.
this.log("Registering commands.");
CommandManager commandManager = ACF.createManager(this);
commandManager.getCommandContexts().registerContext(Flag.class, Flag.getContextResolver());
commandManager.getCommandContexts().registerContext(Kit.class, Kit.getContextResolver());
commandManager.getCommandCompletions().registerCompletion("flags", (sender, config, input, c) -> (Arrays.stream(DefaultFlags.getFlags()).map(Flag::getName).sorted(String::compareToIgnoreCase).collect(Collectors.toCollection(ArrayList::new))));
commandManager.getCommandCompletions().registerCompletion("kits", (sender, config, input, c) -> (KitManager.getKits().stream().map(Kit::getName).sorted(String::compareToIgnoreCase).collect(Collectors.toCollection(ArrayList::new))));
CommandReplacements replacements = commandManager.getCommandReplacements();
replacements.addReplacements("rootcommand", "kit|akit|advancedkits|kits|akits");
commandManager.registerCommand(new CreateCommand(this));
commandManager.registerCommand(new EditCommand(this));
commandManager.registerCommand(new UseCommand(this));
commandManager.registerCommand(new MainCommand(this));
// Check for update
if (Config.AUTOUPDATE_ENABLED) {
this.log("Checking for updates.");
new Updater(this, 91129, this.getFile(), Updater.UpdateType.DEFAULT, true);
}
// Check if metrics is enabled
if (Config.METRICS_ENABLED) {
this.log("Enabling Plugin Metrics.");
new MetricsLite(this);
}
this.log(ChatColor.GREEN + "Finished loading " + this.getDescription().getName() + " " + this.getDescription().getVersion() + " by " + this.getDescription().getAuthors().stream().collect(Collectors.joining(",")));
}
@Override
public void onDisable() {
this.log(ChatColor.GOLD + "Stopping " + this.getDescription().getName() + " " + this.getDescription().getVersion());
if (this.i18n != null) {
this.i18n.onDisable();
}
}
public void log(String log) {
this.getServer().getConsoleSender().sendMessage(Config.COLORED_LOG ? Config.CHAT_PREFIX + ChatColor.RESET + " " + log : ChatColor.stripColor(Config.CHAT_PREFIX + ChatColor.RESET + " " + log));
}
public boolean isPlaceholderAPIEnabled() {
return this.usePlaceholderAPI;
}
public KitManager getKitManager() {
return this.kitManager;
}
public Economy getEconomy() {
return economy;
}
}
|
AdvancedKitsReloaded
|
src\main\java\hu\tryharddevs\advancedkits\Config.java
|
package hu.tryharddevs.advancedkits;
import hu.tryharddevs.advancedkits.utils.localization.I18n;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Config {
public static String CHAT_PREFIX = ChatColor.translateAlternateColorCodes('&', "&7[&6AdvancedKits&7]");
public static String LOCALE = "en";
public static Boolean COLORED_LOG = true;
public static Boolean METRICS_ENABLED = true;
public static Boolean AUTOUPDATE_ENABLED = true;
public static Boolean TITLES_ENABLED = true;
public static Boolean ACTIONBARS_ENABLED = true;
public static List<String> DISABLED_WORLDS = new ArrayList<>();
public static void loadConfigurationValues(AdvancedKitsMain instance) {
FileConfiguration config = instance.getConfig();
boolean oldConfig = false;
if (!config.contains("Chat.Prefix")) {
config.addDefault("Chat.Prefix", "&7[&6AdvancedKits&7]");
//config.addDefault("Chat.Prefix2", "&7[&6AdvancedKits&7]"); //Don't ask why. Idk
oldConfig = true;
}
if (!config.contains("Locale")) {
config.addDefault("Locale", "en");
oldConfig = true;
}
if (!config.contains("Log.ColoredLog")) {
config.addDefault("Log.ColoredLog", true);
//config.addDefault("Log.ColoredLog2", true); //Don't ask why. Idk
oldConfig = true;
}
if (!config.contains("MetricsEnabled")) {
config.addDefault("MetricsEnabled", true);
oldConfig = true;
}
if (!config.contains("AutoUpdateEnabled")) {
config.addDefault("AutoUpdateEnabled", true);
oldConfig = true;
}
if (!config.contains("Messages.TitlesEnabled")) {
config.addDefault("Messages.TitlesEnabled", true);
oldConfig = true;
}
if (!config.contains("Messages.ActionbarsEnabled")) {
config.addDefault("Messages.ActionbarsEnabled", true);
oldConfig = true;
}
if (!config.contains("DisabledInWorlds")) {
config.addDefault("DisabledInWorlds", new ArrayList<>());
oldConfig = true;
}
if (oldConfig) {
instance.log("Old configuration file found.. Updating config file.");
config.set("use-economy", null);
config.set("use-on-buy", null);
config.set("chat-prefix", null);
config.set("locale", null);
config.options().copyDefaults(true);
instance.saveConfig();
}
CHAT_PREFIX = ChatColor.translateAlternateColorCodes('&', config.getString("Chat.Prefix"));
LOCALE = config.getString("Locale");
COLORED_LOG = config.getBoolean("Log.ColoredLog");
METRICS_ENABLED = config.getBoolean("MetricsEnabled");
AUTOUPDATE_ENABLED = config.getBoolean("AutoUpdateEnabled");
TITLES_ENABLED = config.getBoolean("Messages.TitlesEnabled", true);
ACTIONBARS_ENABLED = config.getBoolean("Messages.ActionbarsEnabled", true);
DISABLED_WORLDS = config.getStringList("DisabledInWorlds");
// Copy translations.
String localeFile = "messages_" + LOCALE + ".properties";
if (Objects.isNull(instance.getResource(localeFile))) {
instance.log(ChatColor.RED + "Locale not found, revert back to the default. (en)");
LOCALE = "en";
localeFile = "messages_" + LOCALE + ".properties";
}
if (!new File(instance.getDataFolder() + File.separator + localeFile).exists()) {
instance.saveResource(localeFile, false);
}
// Update locales
instance.i18n = new I18n(instance);
instance.i18n.onEnable();
instance.i18n.updateLocale(LOCALE);
}
}
|
AdvancedKitsReloaded
|
src\main\java\hu\tryharddevs\advancedkits\MetricsLite.java
|
package hu.tryharddevs.advancedkits;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import javax.net.ssl.HttpsURLConnection;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
/**
* bStats collects some data for plugin authors.
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*/
public class MetricsLite {
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Should failed requests be logged?
private static boolean logFailedRequests;
// The uuid of the server
private static String serverUUID;
static {
// Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
final String defaultPackage = new String(new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'});
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
// We want to make sure nobody just copy & pastes the example and use the wrong package names
if (MetricsLite.class.getPackage().getName().equals(defaultPackage) || MetricsLite.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
// The plugin
private final JavaPlugin plugin;
/**
* Class constructor.
*
* @param plugin The plugin which stats should be submitted.
*/
public MetricsLite(JavaPlugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists
if (!config.isSet("serverUuid")) {
// Add default values
config.addDefault("enabled", true);
// Every server gets it's unique random id.
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
config.addDefault("logFailedRequests", false);
// Inform the server owners about bStats
config.options().header("bStats collects some data for plugin authors like how many servers are using their plugins.\n" + "To honor their work, you should not disable it.\n" + "This has nearly no effect on the server performance!\n" + "Check out https://bStats.org/ to learn more :)").copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) {
}
}
// Load the data
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
if (config.getBoolean("enabled", true)) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) {
}
}
// Register our service
Bukkit.getServicesManager().register(MetricsLite.class, this, plugin, ServicePriority.Normal);
if (!found) {
// We are the first!
startSubmitting();
}
}
}
/**
* Sends the data to the bStats server.
*
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(JSONObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
*
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes("UTF-8"));
gzip.close();
return outputStream.toByteArray();
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override public void run() {
submitData();
}
});
}
}, 1000 * 60 * 5, 1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JSONObject getPluginData() {
JSONObject data = new JSONObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.put("pluginName", pluginName); // Append the name of the plugin
data.put("pluginVersion", pluginVersion); // Append the version of the plugin
JSONArray customCharts = new JSONArray();
data.put("customCharts", customCharts);
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JSONObject getServerData() {
// Minecraft specific data
int playerAmount = Bukkit.getOnlinePlayers().size();
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1);
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
JSONObject data = new JSONObject();
data.put("serverUUID", serverUUID);
data.put("playerAmount", playerAmount);
data.put("onlineMode", onlineMode);
data.put("bukkitVersion", bukkitVersion);
data.put("javaVersion", javaVersion);
data.put("osName", osName);
data.put("osArch", osArch);
data.put("osVersion", osVersion);
data.put("coreCount", coreCount);
return data;
}
/**
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JSONObject data = getServerData();
JSONArray pluginData = new JSONArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
} catch (NoSuchFieldException ignored) {
continue; // Continue "searching"
}
// Found one!
try {
pluginData.add(service.getMethod("getPluginData").invoke(Bukkit.getServicesManager().load(service)));
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
}
}
data.put("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(new Runnable() {
@Override public void run() {
try {
// Send the data
sendData(data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}
}).start();
}
}
|
AdvancedKitsReloaded
|
src\main\java\hu\tryharddevs\advancedkits\Updater.java
|
package hu.tryharddevs.advancedkits;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Check for updates on BukkitDev for a given plugin, and download the updates if needed.
* <p>
* <b>VERY, VERY IMPORTANT</b>: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating.
* <br>
* It is a <b>BUKKIT POLICY</b> that you include a boolean value in your config that prevents the auto-updater from running <b>AT ALL</b>.
* <br>
* If you fail to include this option in your config, your plugin will be <b>REJECTED</b> when you attempt to submit it to dev.bukkit.org.
* </p>
* An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater.
* <br>
* If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l
*
* @author Gravity
* @version 2.4
*/
public class Updater {
/* Constants */
// Remote file's title
private static final String TITLE_VALUE = "name";
// Remote file's download link
private static final String LINK_VALUE = "downloadUrl";
// Remote file's release type
private static final String TYPE_VALUE = "releaseType";
// Remote file's build version
private static final String VERSION_VALUE = "gameVersion";
// Path to GET
private static final String QUERY = "/servermods/files?projectIds=";
// Slugs will be appended to this to get to the project's RSS feed
private static final String HOST = "https://api.curseforge.com";
// User-agent when querying Curse
private static final String USER_AGENT = "Updater (by Gravity)";
// Used for locating version numbers in file names
private static final String DELIMETER = "^v|[\\s_-]v";
// If the version number contains one of these, don't update.
private static final String[] NO_UPDATE_TAG = {"-DEV", "-PRE", "-SNAPSHOT"};
// Used for downloading files
private static final int BYTE_SIZE = 1024;
// Config key for api key
private static final String API_KEY_CONFIG_KEY = "api-key";
// Config key for disabling Updater
private static final String DISABLE_CONFIG_KEY = "disable";
// Default api key value in config
private static final String API_KEY_DEFAULT = "PUT_API_KEY_HERE";
// Default disable value in config
private static final boolean DISABLE_DEFAULT = false;
/* User-provided variables */
// Plugin running Updater
private final Plugin plugin;
// Type of update check to run
private final UpdateType type;
// Whether to announce file downloads
private final boolean announce;
// The plugin file (jar)
private final File file;
// The folder that downloads will be placed in
private final File updateFolder;
// The provided callback (if any)
private final UpdateCallback callback;
// Project's Curse ID
private int id = -1;
// BukkitDev ServerMods API key
private String apiKey = null;
/* Collected from Curse API */
private String versionName;
private String versionLink;
private String versionType;
private String versionGameVersion;
/* Update process variables */
// Connection to RSS
private URL url;
// Updater thread
private Thread thread;
// Used for determining the outcome of the update process
private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS;
/**
* Initialize the updater.
*
* @param plugin The plugin that is checking for an update.
* @param id The dev.bukkit.org id of the project.
* @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class.
* @param type Specify the type of update this will be. See {@link UpdateType}
* @param announce True if the program should announce the progress of new updates in console.
*/
public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) {
this(plugin, id, file, type, null, announce);
}
/**
* Initialize the updater with the provided callback.
*
* @param plugin The plugin that is checking for an update.
* @param id The dev.bukkit.org id of the project.
* @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class.
* @param type Specify the type of update this will be. See {@link UpdateType}
* @param callback The callback instance to notify when the Updater has finished
*/
public Updater(Plugin plugin, int id, File file, UpdateType type, UpdateCallback callback) {
this(plugin, id, file, type, callback, false);
}
/**
* Initialize the updater with the provided callback.
*
* @param plugin The plugin that is checking for an update.
* @param id The dev.bukkit.org id of the project.
* @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class.
* @param type Specify the type of update this will be. See {@link UpdateType}
* @param callback The callback instance to notify when the Updater has finished
* @param announce True if the program should announce the progress of new updates in console.
*/
public Updater(Plugin plugin, int id, File file, UpdateType type, UpdateCallback callback, boolean announce) {
this.plugin = plugin;
this.type = type;
this.announce = announce;
this.file = file;
this.id = id;
this.updateFolder = this.plugin.getServer().getUpdateFolderFile();
this.callback = callback;
final File pluginFile = this.plugin.getDataFolder().getParentFile();
final File updaterFile = new File(pluginFile, "Updater");
final File updaterConfigFile = new File(updaterFile, "config.yml");
YamlConfiguration config = new YamlConfiguration();
config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration.");
config.addDefault(API_KEY_CONFIG_KEY, API_KEY_DEFAULT);
config.addDefault(DISABLE_CONFIG_KEY, DISABLE_DEFAULT);
if (!updaterFile.exists()) {
this.fileIOOrError(updaterFile, updaterFile.mkdir(), true);
}
boolean createFile = !updaterConfigFile.exists();
try {
if (createFile) {
this.fileIOOrError(updaterConfigFile, updaterConfigFile.createNewFile(), true);
config.options().copyDefaults(true);
config.save(updaterConfigFile);
} else {
config.load(updaterConfigFile);
}
} catch (final Exception e) {
final String message;
if (createFile) {
message = "The updater could not create configuration at " + updaterFile.getAbsolutePath();
} else {
message = "The updater could not load configuration at " + updaterFile.getAbsolutePath();
}
this.plugin.getLogger().log(Level.SEVERE, message, e);
}
if (config.getBoolean(DISABLE_CONFIG_KEY)) {
this.result = UpdateResult.DISABLED;
return;
}
String key = config.getString(API_KEY_CONFIG_KEY);
if (API_KEY_DEFAULT.equalsIgnoreCase(key) || "".equals(key)) {
key = null;
}
this.apiKey = key;
try {
this.url = new URL(Updater.HOST + Updater.QUERY + this.id);
} catch (final MalformedURLException e) {
this.plugin.getLogger().log(Level.SEVERE, "The project ID provided for updating, " + this.id + " is invalid.", e);
this.result = UpdateResult.FAIL_BADID;
}
if (this.result != UpdateResult.FAIL_BADID) {
this.thread = new Thread(new UpdateRunnable());
this.thread.start();
} else {
runUpdater();
}
}
/**
* Get the result of the update process.
*
* @return result of the update process.
*
* @see UpdateResult
*/
public Updater.UpdateResult getResult() {
this.waitForThread();
return this.result;
}
/**
* Get the latest version's release type.
*
* @return latest version's release type.
*
* @see ReleaseType
*/
public ReleaseType getLatestType() {
this.waitForThread();
if (this.versionType != null) {
for (ReleaseType type : ReleaseType.values()) {
if (this.versionType.equalsIgnoreCase(type.name())) {
return type;
}
}
}
return null;
}
/**
* Get the latest version's game version (such as "CB 1.2.5-R1.0").
*
* @return latest version's game version.
*/
public String getLatestGameVersion() {
this.waitForThread();
return this.versionGameVersion;
}
/**
* Get the latest version's name (such as "Project v1.0").
*
* @return latest version's name.
*/
public String getLatestName() {
this.waitForThread();
return this.versionName;
}
/**
* Get the latest version's direct file link.
*
* @return latest version's file link.
*/
public String getLatestFileLink() {
this.waitForThread();
return this.versionLink;
}
/**
* As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish
* before allowing anyone to check the result.
*/
private void waitForThread() {
if ((this.thread != null) && this.thread.isAlive()) {
try {
this.thread.join();
} catch (final InterruptedException e) {
this.plugin.getLogger().log(Level.SEVERE, null, e);
}
}
}
/**
* Save an update from dev.bukkit.org into the server's update folder.
*
* @param file the name of the file to save it as.
*/
private void saveFile(String file) {
final File folder = this.updateFolder;
deleteOldFiles();
if (!folder.exists()) {
this.fileIOOrError(folder, folder.mkdir(), true);
}
downloadFile();
// Check to see if it's a zip file, if it is, unzip it.
final File dFile = new File(folder.getAbsolutePath(), file);
if (dFile.getName().endsWith(".zip")) {
// Unzip
this.unzip(dFile.getAbsolutePath());
}
if (this.announce) {
this.plugin.getLogger().info("Finished updating.");
}
}
/**
* Download a file and save it to the specified folder.
*/
private void downloadFile() {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
URL fileUrl = followRedirects(this.versionLink);
final int fileLength = fileUrl.openConnection().getContentLength();
in = new BufferedInputStream(fileUrl.openStream());
fout = new FileOutputStream(new File(this.updateFolder, file.getName()));
final byte[] data = new byte[Updater.BYTE_SIZE];
int count;
if (this.announce) {
this.plugin.getLogger().info("About to download a new update: " + this.versionName);
}
long downloaded = 0;
while ((count = in.read(data, 0, Updater.BYTE_SIZE)) != -1) {
downloaded += count;
fout.write(data, 0, count);
final int percent = (int) ((downloaded * 100) / fileLength);
if (this.announce && ((percent % 10) == 0)) {
this.plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes.");
}
}
} catch (Exception ex) {
this.plugin.getLogger().log(Level.WARNING, "The auto-updater tried to download a new update, but was unsuccessful.", ex);
this.result = Updater.UpdateResult.FAIL_DOWNLOAD;
} finally {
try {
if (in != null) {
in.close();
}
} catch (final IOException ex) {
this.plugin.getLogger().log(Level.SEVERE, null, ex);
}
try {
if (fout != null) {
fout.close();
}
} catch (final IOException ex) {
this.plugin.getLogger().log(Level.SEVERE, null, ex);
}
}
}
private URL followRedirects(String location) throws IOException {
URL resourceUrl, base, next;
HttpURLConnection conn;
String redLoc;
while (true) {
resourceUrl = new URL(location);
conn = (HttpURLConnection) resourceUrl.openConnection();
conn.setConnectTimeout(15000);
conn.setReadTimeout(15000);
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("User-Agent", "Mozilla/5.0...");
switch (conn.getResponseCode()) {
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
redLoc = conn.getHeaderField("Location");
base = new URL(location);
next = new URL(base, redLoc); // Deal with relative URLs
location = next.toExternalForm();
continue;
}
break;
}
return conn.getURL();
}
/**
* Remove possibly leftover files from the update folder.
*/
private void deleteOldFiles() {
//Just a quick check to make sure we didn't leave any files from last time...
File[] list = listFilesOrError(this.updateFolder);
for (final File xFile : list) {
if (xFile.getName().endsWith(".zip")) {
this.fileIOOrError(xFile, xFile.mkdir(), true);
}
}
}
/**
* Part of Zip-File-Extractor, modified by Gravity for use with Updater.
*
* @param file the location of the file to extract.
*/
private void unzip(String file) {
final File fSourceZip = new File(file);
try {
final String zipPath = file.substring(0, file.length() - 4);
ZipFile zipFile = new ZipFile(fSourceZip);
Enumeration<? extends ZipEntry> e = zipFile.entries();
while (e.hasMoreElements()) {
ZipEntry entry = e.nextElement();
File destinationFilePath = new File(zipPath, entry.getName());
this.fileIOOrError(destinationFilePath.getParentFile(), destinationFilePath.getParentFile().mkdirs(), true);
if (!entry.isDirectory()) {
final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
int b;
final byte[] buffer = new byte[Updater.BYTE_SIZE];
final FileOutputStream fos = new FileOutputStream(destinationFilePath);
final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE);
while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) {
bos.write(buffer, 0, b);
}
bos.flush();
bos.close();
bis.close();
final String name = destinationFilePath.getName();
if (name.endsWith(".jar") && this.pluginExists(name)) {
File output = new File(this.updateFolder, name);
this.fileIOOrError(output, destinationFilePath.renameTo(output), true);
}
}
}
zipFile.close();
// Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
moveNewZipFiles(zipPath);
} catch (final IOException e) {
this.plugin.getLogger().log(Level.SEVERE, "The auto-updater tried to unzip a new update file, but was unsuccessful.", e);
this.result = Updater.UpdateResult.FAIL_DOWNLOAD;
} finally {
this.fileIOOrError(fSourceZip, fSourceZip.delete(), false);
}
}
/**
* Find any new files extracted from an update into the plugin's data directory.
*
* @param zipPath path of extracted files.
*/
private void moveNewZipFiles(String zipPath) {
File[] list = listFilesOrError(new File(zipPath));
for (final File dFile : list) {
if (dFile.isDirectory() && this.pluginExists(dFile.getName())) {
// Current dir
final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName());
// List of existing files in the new dir
final File[] dList = listFilesOrError(dFile);
// List of existing files in the current dir
final File[] oList = listFilesOrError(oFile);
for (File cFile : dList) {
// Loop through all the files in the new dir
boolean found = false;
for (final File xFile : oList) {
// Loop through all the contents in the current dir to see if it exists
if (xFile.getName().equals(cFile.getName())) {
found = true;
break;
}
}
if (!found) {
// Move the new file into the current dir
File output = new File(oFile, cFile.getName());
this.fileIOOrError(output, cFile.renameTo(output), true);
} else {
// This file already exists, so we don't need it anymore.
this.fileIOOrError(cFile, cFile.delete(), false);
}
}
}
this.fileIOOrError(dFile, dFile.delete(), false);
}
File zip = new File(zipPath);
this.fileIOOrError(zip, zip.delete(), false);
}
/**
* Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip.
*
* @param name a name to check for inside the plugins folder.
* @return true if a file inside the plugins folder is named this.
*/
private boolean pluginExists(String name) {
File[] plugins = listFilesOrError(new File("plugins"));
for (final File file : plugins) {
if (file.getName().equals(name)) {
return true;
}
}
return false;
}
/**
* Check to see if the program should continue by evaluating whether the plugin is already updated, or shouldn't be updated.
*
* @return true if the version was located and is not the same as the remote's newest.
*/
private boolean versionCheck() {
final String title = this.versionName;
if (this.type != UpdateType.NO_VERSION_CHECK) {
final String localVersion = this.plugin.getDescription().getVersion();
if (title.split(DELIMETER).length >= 2) {
// Get the newest file's version number
final String remoteVersion = title.split(DELIMETER)[title.split(DELIMETER).length - 1].split(" ")[0];
if (this.hasTag(localVersion) || !this.shouldUpdate(localVersion, remoteVersion)) {
// We already have the latest version, or this build is tagged for no-update
this.result = Updater.UpdateResult.NO_UPDATE;
return false;
}
} else {
// The file's name did not contain the string 'vVersion'
final String authorInfo = this.plugin.getDescription().getAuthors().isEmpty() ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")";
this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system");
this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'");
this.plugin.getLogger().warning("Please notify the author of this error.");
this.result = Updater.UpdateResult.FAIL_NOVERSION;
return false;
}
}
return true;
}
/**
* <b>If you wish to run mathematical versioning checks, edit this method.</b>
* <p>
* With default behavior, Updater will NOT verify that a remote version available on BukkitDev
* which is not this version is indeed an "update".
* If a version is present on BukkitDev that is not the version that is currently running,
* Updater will assume that it is a newer version.
* This is because there is no standard versioning scheme, and creating a calculation that can
* determine whether a new update is actually an update is sometimes extremely complicated.
* </p>
* <p>
* Updater will call this method from {@link #versionCheck()} before deciding whether
* the remote version is actually an update.
* If you have a specific versioning scheme with which a mathematical determination can
* be reliably made to decide whether one version is higher than another, you may
* revise this method, using the local and remote version parameters, to execute the
* appropriate check.
* </p>
* <p>
* Returning a value of <b>false</b> will tell the update process that this is NOT a new version.
* Without revision, this method will always consider a remote version at all different from
* that of the local version a new update.
* </p>
*
* @param localVersion the current version
* @param remoteVersion the remote version
* @return true if Updater should consider the remote version an update, false if not.
*/
public boolean shouldUpdate(String localVersion, String remoteVersion) {
Integer iLocal = Integer.valueOf(localVersion.replace(".", ""));
Integer iRemote = Integer.valueOf(remoteVersion.replace(".", ""));
return (iRemote > iLocal);
//return !localVersion.equalsIgnoreCase(remoteVersion);
}
/**
* Evaluate whether the version number is marked showing that it should not be updated by this program.
*
* @param version a version number to check for tags in.
* @return true if updating should be disabled.
*/
private boolean hasTag(String version) {
for (final String string : Updater.NO_UPDATE_TAG) {
if (version.toUpperCase().contains(string)) {
return true;
}
}
return false;
}
/**
* Make a connection to the BukkitDev API and request the newest file's details.
*
* @return true if successful.
*/
private boolean read() {
try {
final URLConnection conn = this.url.openConnection();
conn.setConnectTimeout(5000);
if (this.apiKey != null) {
conn.addRequestProperty("X-API-Key", this.apiKey);
}
conn.addRequestProperty("User-Agent", Updater.USER_AGENT);
conn.setDoOutput(true);
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final String response = reader.readLine();
final JSONArray array = (JSONArray) JSONValue.parse(response);
if (array.isEmpty()) {
this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id);
this.result = UpdateResult.FAIL_BADID;
return false;
}
JSONObject latestUpdate = (JSONObject) array.get(array.size() - 1);
this.versionName = (String) latestUpdate.get(Updater.TITLE_VALUE);
this.versionLink = (String) latestUpdate.get(Updater.LINK_VALUE);
this.versionType = (String) latestUpdate.get(Updater.TYPE_VALUE);
this.versionGameVersion = (String) latestUpdate.get(Updater.VERSION_VALUE);
return true;
} catch (final IOException e) {
if (e.getMessage().contains("HTTP response code: 403")) {
this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct.");
this.result = UpdateResult.FAIL_APIKEY;
} else {
this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating.");
this.plugin.getLogger().severe("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
this.result = UpdateResult.FAIL_DBO;
}
this.plugin.getLogger().log(Level.SEVERE, null, e);
return false;
}
}
/**
* Perform a file operation and log any errors if it fails.
*
* @param file file operation is performed on.
* @param result result of file operation.
* @param create true if a file is being created, false if deleted.
*/
private void fileIOOrError(File file, boolean result, boolean create) {
if (!result) {
this.plugin.getLogger().severe("The updater could not " + (create ? "create" : "delete") + " file at: " + file.getAbsolutePath());
}
}
private File[] listFilesOrError(File folder) {
File[] contents = folder.listFiles();
if (contents == null) {
this.plugin.getLogger().severe("The updater could not access files at: " + this.updateFolder.getAbsolutePath());
return new File[0];
} else {
return contents;
}
}
private void runUpdater() {
if (this.url != null && (this.read() && this.versionCheck())) {
// Obtain the results of the project's file feed
if ((this.versionLink != null) && (this.type != UpdateType.NO_DOWNLOAD)) {
String name = this.file.getName();
// If it's a zip file, it shouldn't be downloaded as the plugin's name
if (this.versionLink.endsWith(".zip")) {
name = this.versionLink.substring(this.versionLink.lastIndexOf("/") + 1);
}
this.saveFile(name);
} else {
this.result = UpdateResult.UPDATE_AVAILABLE;
}
}
if (this.callback != null) {
new BukkitRunnable() {
@Override
public void run() {
runCallback();
}
}.runTask(this.plugin);
}
}
private void runCallback() {
this.callback.onFinish(this);
}
/**
* Gives the developer the result of the update process. Can be obtained by called {@link #getResult()}
*/
public enum UpdateResult {
/**
* The updater found an update, and has readied it to be loaded the next time the server restarts/reloads.
*/
SUCCESS,
/**
* The updater did not find an update, and nothing was downloaded.
*/
NO_UPDATE,
/**
* The server administrator has disabled the updating system.
*/
DISABLED,
/**
* The updater found an update, but was unable to download it.
*/
FAIL_DOWNLOAD,
/**
* For some reason, the updater was unable to contact dev.bukkit.org to download the file.
*/
FAIL_DBO,
/**
* When running the version check, the file on DBO did not contain a recognizable version.
*/
FAIL_NOVERSION,
/**
* The id provided by the plugin running the updater was invalid and doesn't exist on DBO.
*/
FAIL_BADID,
/**
* The server administrator has improperly configured their API key in the configuration.
*/
FAIL_APIKEY,
/**
* The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded.
*/
UPDATE_AVAILABLE
}
/**
* Allows the developer to specify the type of update that will be run.
*/
public enum UpdateType {
/**
* Run a version check, and then if the file is out of date, download the newest version.
*/
DEFAULT,
/**
* Don't run a version check, just find the latest update and download it.
*/
NO_VERSION_CHECK,
/**
* Get information about the version and the download size, but don't actually download anything.
*/
NO_DOWNLOAD
}
/**
* Represents the various release types of a file on BukkitDev.
*/
public enum ReleaseType {
/**
* An "alpha" file.
*/
ALPHA,
/**
* A "beta" file.
*/
BETA,
/**
* A "release" file.
*/
RELEASE
}
/**
* Called on main thread when the Updater has finished working, regardless
* of result.
*/
public interface UpdateCallback {
/**
* Called when the updater has finished working.
*
* @param updater The updater instance
*/
void onFinish(Updater updater);
}
private class UpdateRunnable implements Runnable {
@Override
public void run() {
runUpdater();
}
}
}
|
AdvancedKitsReloaded
|
src\main\java\hu\tryharddevs\advancedkits\cinventory\CInventory.java
|
package hu.tryharddevs.advancedkits.cinventory;
import hu.tryharddevs.advancedkits.cinventory.listeners.InventoryClickListener;
import hu.tryharddevs.advancedkits.cinventory.listeners.InventoryCloseListener;
import hu.tryharddevs.advancedkits.cinventory.listeners.InventoryDragListener;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public abstract class CInventory {
public InventoryClickListener inventoryClickListener;
public InventoryCloseListener inventoryCloseListener;
public InventoryDragListener inventoryDragListener;
public Inventory currentInventory;
private boolean modifiable = false;
private final Player player;
private final String inventoryName;
private boolean inventoryInUse;
protected CInventory(String inventoryName, Player player) {
this.player = player;
if (inventoryName == null) {
inventoryName = getClass().getSimpleName();
}
this.inventoryName = inventoryName;
}
protected abstract void onInventoryClick(InventoryClickEvent event);
public void closeInventory() {
closeInventory(true);
}
public void closeInventory(boolean forceClose) {
CInventoryMain.unregisterInventory(this);
inventoryInUse = false;
if (forceClose && getPlayer().getOpenInventory().getTopInventory().equals(currentInventory)) {
getPlayer().closeInventory();
}
}
protected void setItems(ItemStack[] items) {
currentInventory.setContents(items);
}
protected void openInv() {
getPlayer().openInventory(currentInventory);
CInventoryMain.registerInventory(this);
inventoryInUse = true;
}
public boolean isModifiable() {
return modifiable;
}
public Player getPlayer() {
return player;
}
public boolean isInventoryInUse() {
return inventoryInUse;
}
public void onInventoryClickEvent(InventoryClickListener inventoryClickListener) {
this.inventoryClickListener = inventoryClickListener;
}
public void onInventoryCloseEvent(InventoryCloseListener inventoryCloseListener) {
this.inventoryCloseListener = inventoryCloseListener;
}
public void onInventoryDragEvent(InventoryDragListener inventoryDragListener) {
this.inventoryDragListener = inventoryDragListener;
}
public void setModifiable(boolean modifiable) {
this.modifiable = modifiable;
}
protected String getInventoryName() {
return inventoryName;
}
public abstract ItemStack getItem(int slot);
}
|
AdvancedKitsReloaded
|
src\main\java\hu\tryharddevs\advancedkits\cinventory\CInventoryMain.java
|
package hu.tryharddevs.advancedkits.cinventory;
import hu.tryharddevs.advancedkits.AdvancedKitsMain;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.ArrayList;
import java.util.Objects;
public class CInventoryMain implements Listener {
private final AdvancedKitsMain instance;
private static final ArrayList<CInventory> cInventoryArrayList = new ArrayList<>();
public CInventoryMain(AdvancedKitsMain instance) {
this.instance = instance;
}
public static void registerInventory(CInventory cInventory) {
cInventoryArrayList.add(cInventory);
}
public static void unregisterInventory(CInventory cInventory) {
cInventoryArrayList.remove(cInventory);
}
@EventHandler
public void onClose(InventoryCloseEvent event) {
int found = 0;
for (CInventory cInv : new ArrayList<>(cInventoryArrayList)) {
if (cInv.getPlayer() == event.getPlayer()) {
if (Objects.nonNull(cInv.inventoryCloseListener)) {
cInv.inventoryCloseListener.interact(event);
}
if (cInv.isInventoryInUse()) {
cInv.closeInventory(false);
}
if (found++ == 1) break;
}
}
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
int found = 0;
for (CInventory cInv : new ArrayList<>(cInventoryArrayList)) {
if (cInv.getPlayer() == event.getWhoClicked()) {
if (!cInv.isModifiable()) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
}
if (Objects.nonNull(cInv.inventoryClickListener)) {
cInv.inventoryClickListener.interact(event);
}
cInv.onInventoryClick(event);
if (found++ == 1) break;
}
}
}
@EventHandler
public void onInventoryDrag(InventoryDragEvent event) {
int found = 0;
for (CInventory cInv : new ArrayList<>(cInventoryArrayList)) {
if (cInv.getPlayer() == event.getWhoClicked()) {
if (!cInv.isModifiable()) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
}
if (Objects.nonNull(cInv.inventoryDragListener)) {
cInv.inventoryDragListener.interact(event);
}
if (found++ == 1) break;
}
}
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
int found = 0;
for (CInventory cInv : new ArrayList<>(cInventoryArrayList)) {
if (cInv.getPlayer() == event.getPlayer()) {
if (cInv.isInventoryInUse()) {
cInv.closeInventory(false);
}
if (found++ == 1) break;
}
}
}
}
|
AdvancedKitsReloaded
|
src\main\java\hu\tryharddevs\advancedkits\commands\CreateCommand.java
|
package hu.tryharddevs.advancedkits.commands;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.annotation.CommandAlias;
import co.aikar.commands.annotation.CommandPermission;
import co.aikar.commands.annotation.Subcommand;
import co.aikar.commands.annotation.Syntax;
import hu.tryharddevs.advancedkits.AdvancedKitsMain;
import hu.tryharddevs.advancedkits.cinventory.inventories.CSimpleInventory;
import hu.tryharddevs.advancedkits.kits.Kit;
import hu.tryharddevs.advancedkits.kits.KitManager;
import hu.tryharddevs.advancedkits.kits.Session;
import hu.tryharddevs.advancedkits.utils.ItemBuilder;
import hu.tryharddevs.advancedkits.utils.ItemStackUtil;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.inventory.ItemStack;
import org.inventivetalent.reflection.minecraft.Minecraft;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static hu.tryharddevs.advancedkits.utils.MessagesApi.sendMessage;
import static hu.tryharddevs.advancedkits.utils.localization.I18n.getMessage;
@CommandAlias("%rootcommand")
public class CreateCommand extends BaseCommand {
private final AdvancedKitsMain instance;
public CreateCommand(AdvancedKitsMain instance) {
this.instance = instance;
}
@Subcommand("create")
@CommandPermission("advancedkits.create")
@Syntax("<kitname>")
public void onCreateCommand(Player player, String kitName) {
if (Objects.nonNull(KitManager.getKit(kitName, player.getWorld().getName()))) {
sendMessage(player, getMessage("kitAlreadyExists"));
return;
}
Session session = Session.getSession(player.getUniqueId());
CSimpleInventory cSimpleInventory = new CSimpleInventory("AdvancedKits - Create", player, 54);
cSimpleInventory.setModifiable(true);
cSimpleInventory.setItem(36, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorHelmet")).toItemStack());
cSimpleInventory.setItem(37, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorChestplate")).toItemStack());
cSimpleInventory.setItem(38, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorLeggings")).toItemStack());
cSimpleInventory.setItem(39, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorBoots")).toItemStack());
if (Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1)) {
cSimpleInventory.setItem(40, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorShield")).toItemStack());
}
cSimpleInventory.setItem(45, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 3).setName(getMessage("saveToSession")).toItemStack());
if (!session.getKitItems().isEmpty() || !session.getKitArmors().isEmpty()) {
cSimpleInventory.setItem(46, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 3).setName(getMessage("loadFromSession")).toItemStack());
}
cSimpleInventory.setItem(53, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 13).setName(getMessage("guiCreateKit", kitName)).toItemStack());
cSimpleInventory.openInventory();
cSimpleInventory.onInventoryDragEvent(event -> {
if (!Stream.of(
// Armor slots:
36, 37, 38, 39, 40,
// Other space slots:
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
// Create kit button slot
53).filter(event.getInventorySlots()::contains).collect(Collectors.toList()).isEmpty()) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
}
});
cSimpleInventory.onInventoryClickEvent(event -> {
if (Arrays.asList(
// Armor slots:
36, 37, 38, 39, 40,
// Other space slots:
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
// Create kit button slot
53).contains(event.getSlot())) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
}
int clickedSlot = event.getSlot();
ItemStack itemOnCursor = event.getCursor();
switch (clickedSlot) {
// Helmet
case 36: {
if (Objects.isNull(itemOnCursor) || itemOnCursor.getType() == Material.AIR) {
event.getInventory().setItem(clickedSlot, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorHelmet")).toItemStack());
} else if (ItemStackUtil.isHelmet(itemOnCursor)) {
event.getInventory().setItem(clickedSlot, itemOnCursor);
player.setItemOnCursor(null);
}
break;
}
// Chestplate
case 37: {
if (Objects.isNull(itemOnCursor) || itemOnCursor.getType() == Material.AIR) {
event.getInventory().setItem(clickedSlot, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorChestplate")).toItemStack());
} else if (ItemStackUtil.isChest(itemOnCursor)) {
event.getInventory().setItem(clickedSlot, itemOnCursor);
player.setItemOnCursor(null);
}
break;
}
// Leggings
case 38: {
if (Objects.isNull(itemOnCursor) || itemOnCursor.getType() == Material.AIR) {
event.getInventory().setItem(clickedSlot, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorLeggings")).toItemStack());
} else if (ItemStackUtil.isLegs(itemOnCursor)) {
event.getInventory().setItem(clickedSlot, itemOnCursor);
player.setItemOnCursor(null);
}
break;
}
// Boots
case 39: {
if (Objects.isNull(itemOnCursor) || itemOnCursor.getType() == Material.AIR) {
event.getInventory().setItem(clickedSlot, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorBoots")).toItemStack());
} else if (ItemStackUtil.isBoots(itemOnCursor)) {
event.getInventory().setItem(clickedSlot, itemOnCursor);
player.setItemOnCursor(null);
}
break;
}
// Shield
case 40: {
if (!Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1)) break;
if (Objects.isNull(itemOnCursor) || itemOnCursor.getType() == Material.AIR) {
event.getInventory().setItem(clickedSlot, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorShield")).toItemStack());
} else if (ItemStackUtil.isShield(itemOnCursor)) {
event.getInventory().setItem(clickedSlot, itemOnCursor);
player.setItemOnCursor(null);
}
break;
}
// Save session button.
case 45: {
session.getKitItems().clear();
session.getKitArmors().clear();
ItemStack itemStack;
for (int i = 0; i < 36; i++) {
itemStack = event.getInventory().getItem(i);
if (Objects.nonNull(itemStack)) session.addItems(itemStack);
}
for (int i = 36; i < 41; i++) {
itemStack = event.getInventory().getItem(i);
if (Objects.nonNull(itemStack) && itemStack.getType() != Material.ARMOR_STAND)
session.addArmor(itemStack);
}
sendMessage(player, getMessage("sessionSaved"));
player.closeInventory();
break;
}
// Load session button.
case 46: {
for (ItemStack itemStack : session.getKitItems()) {
event.getInventory().addItem(itemStack);
}
for (ItemStack armor : session.getKitArmors()) {
if (ItemStackUtil.isHelmet(armor)) event.getInventory().setItem(36, armor);
else if (ItemStackUtil.isChest(armor)) event.getInventory().setItem(37, armor);
else if (ItemStackUtil.isLegs(armor)) event.getInventory().setItem(38, armor);
else if (ItemStackUtil.isBoots(armor)) event.getInventory().setItem(39, armor);
else if (Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1) && ItemStackUtil.isShield(armor))
event.getInventory().setItem(40, armor);
}
sendMessage(player, getMessage("sessionLoaded"));
event.getInventory().setItem(46, null);
break;
}
// Create kit button.
case 53: {
Kit kit = new Kit(kitName);
ItemStack itemStack;
ArrayList<ItemStack> itemStacks = new ArrayList<>();
for (int i = 0; i < 36; i++) {
itemStack = event.getInventory().getItem(i);
if (Objects.nonNull(itemStack)) itemStacks.add(itemStack);
}
kit.setItems(itemStacks);
itemStacks = new ArrayList<>();
for (int i = 36; i < 41; i++) {
itemStack = event.getInventory().getItem(i);
if (Objects.nonNull(itemStack) && itemStack.getType() != Material.ARMOR_STAND)
itemStacks.add(itemStack);
}
kit.setArmors(itemStacks);
kit.save();
KitManager.getKits().add(kit);
sendMessage(player, getMessage("successfullyCreated", kitName));
player.closeInventory();
break;
}
default: {
}
}
});
}
}
|
AdvancedKitsReloaded
|
src\main\java\hu\tryharddevs\advancedkits\commands\EditCommand.java
|
package hu.tryharddevs.advancedkits.commands;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.annotation.*;
import hu.tryharddevs.advancedkits.AdvancedKitsMain;
import hu.tryharddevs.advancedkits.cinventory.inventories.CPageInventory;
import hu.tryharddevs.advancedkits.cinventory.inventories.CSimpleInventory;
import hu.tryharddevs.advancedkits.kits.Kit;
import hu.tryharddevs.advancedkits.kits.KitManager;
import hu.tryharddevs.advancedkits.kits.Session;
import hu.tryharddevs.advancedkits.utils.ItemBuilder;
import hu.tryharddevs.advancedkits.utils.ItemStackUtil;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.inventory.ItemStack;
import org.inventivetalent.reflection.minecraft.Minecraft;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static hu.tryharddevs.advancedkits.kits.flags.DefaultFlags.ICON;
import static hu.tryharddevs.advancedkits.kits.flags.DefaultFlags.VISIBLE;
import static hu.tryharddevs.advancedkits.utils.MessagesApi.sendMessage;
import static hu.tryharddevs.advancedkits.utils.localization.I18n.getMessage;
@CommandAlias("%rootcommand")
public class EditCommand extends BaseCommand {
private final AdvancedKitsMain instance;
public EditCommand(AdvancedKitsMain instance) {
this.instance = instance;
}
@Subcommand("edit")
@CommandPermission("advancedkits.edit")
@CommandCompletion("@kits @worlds")
@Syntax("[kitname]")
public void onEditCommand(Player player, @Optional Kit kit) {
String world = player.getWorld().getName();
if (Objects.isNull(kit)) {
CPageInventory cPageInventory = new CPageInventory("AdvancedKits - Edit Kit", player);
cPageInventory.setPages(KitManager.getKits().stream().filter(_kit -> _kit.getFlag(VISIBLE, world)).sorted(Comparator.comparing(Kit::getName)).map(_kit -> new ItemBuilder(_kit.getFlag(ICON, world).clone()).setName(ChatColor.WHITE + _kit.getDisplayName(world)).setLore(KitManager.getKitDescription(player, _kit, world)).hideAttributes().toItemStack()).collect(Collectors.toCollection(ArrayList::new)));
cPageInventory.openInventory();
cPageInventory.onInventoryClickEvent((_event) -> {
ItemStack clickedItem = _event.getCurrentItem();
if (Objects.isNull(clickedItem) || !clickedItem.hasItemMeta() || !clickedItem.getItemMeta().hasDisplayName())
return;
if (Arrays.asList(cPageInventory.getBackPage(), cPageInventory.getForwardsPage()).contains(clickedItem))
return;
Player _player = (Player) _event.getWhoClicked();
Kit clickedKit = KitManager.getKit(clickedItem.getItemMeta().getDisplayName(), _player.getWorld().getName());
if (Objects.isNull(clickedKit)) {
sendMessage(_player, getMessage("kitNotFound"));
return;
}
_player.closeInventory();
Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit edit " + clickedKit.getName());
});
return;
}
Session session = Session.getSession(player.getUniqueId());
CSimpleInventory cSimpleInventory = new CSimpleInventory("AdvancedKits - Edit", player, 54);
cSimpleInventory.setModifiable(true);
//Load kit items to the gui
cSimpleInventory.addItems(kit.getItems());
//Load kit armor to the gui
for (ItemStack armor : kit.getArmors()) {
if (ItemStackUtil.isHelmet(armor)) cSimpleInventory.setItem(36, armor);
else if (ItemStackUtil.isChest(armor)) cSimpleInventory.setItem(37, armor);
else if (ItemStackUtil.isLegs(armor)) cSimpleInventory.setItem(38, armor);
else if (ItemStackUtil.isBoots(armor)) cSimpleInventory.setItem(39, armor);
else if (Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1) && ItemStackUtil.isShield(armor))
cSimpleInventory.setItem(40, armor);
}
cSimpleInventory.setItem(45, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 3).setName(getMessage("saveToSession")).toItemStack());
if (!session.getKitItems().isEmpty() || !session.getKitArmors().isEmpty()) {
cSimpleInventory.setItem(46, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 3).setName(getMessage("loadFromSession")).setLore(getMessage("loadFromSessionWarning")).toItemStack());
}
cSimpleInventory.setItem(53, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 13).setName(getMessage("guiEditKit", kit.getName())).toItemStack());
cSimpleInventory.openInventory();
//Check if there's a missing armor piece from the gui. If so replace it with the holder
if (Objects.isNull(cSimpleInventory.getItem(36)))
cSimpleInventory.setItem(36, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorHelmet")).toItemStack());
if (Objects.isNull(cSimpleInventory.getItem(37)))
cSimpleInventory.setItem(37, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorChestplate")).toItemStack());
if (Objects.isNull(cSimpleInventory.getItem(38)))
cSimpleInventory.setItem(38, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorLeggings")).toItemStack());
if (Objects.isNull(cSimpleInventory.getItem(39)))
cSimpleInventory.setItem(39, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorBoots")).toItemStack());
if (Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1)) {
if (Objects.isNull(cSimpleInventory.getItem(40)))
cSimpleInventory.setItem(40, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorShield")).toItemStack());
}
cSimpleInventory.onInventoryDragEvent(event -> {
if (!Stream.of(
// Armor slots:
36, 37, 38, 39, 40,
// Other space slots:
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
// Edit kit button slot
53).filter(event.getInventorySlots()::contains).collect(Collectors.toList()).isEmpty()) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
}
});
cSimpleInventory.onInventoryClickEvent(event -> {
if (Arrays.asList(
// Armor slots:
36, 37, 38, 39, 40,
// Other space slots:
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
// Edit kit button slot
53).contains(event.getSlot())) {
event.setCancelled(true);
event.setResult(Event.Result.DENY);
}
int clickedSlot = event.getSlot();
ItemStack itemOnCursor = event.getCursor();
switch (clickedSlot) {
// Helmet
case 36: {
if (Objects.isNull(itemOnCursor) || itemOnCursor.getType() == Material.AIR) {
event.getInventory().setItem(clickedSlot, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorHelmet")).toItemStack());
} else if (ItemStackUtil.isHelmet(itemOnCursor)) {
event.getInventory().setItem(clickedSlot, itemOnCursor);
player.setItemOnCursor(null);
}
break;
}
// Chestplate
case 37: {
if (Objects.isNull(itemOnCursor) || itemOnCursor.getType() == Material.AIR) {
event.getInventory().setItem(clickedSlot, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorChestplate")).toItemStack());
} else if (ItemStackUtil.isChest(itemOnCursor)) {
event.getInventory().setItem(clickedSlot, itemOnCursor);
player.setItemOnCursor(null);
}
break;
}
// Leggings
case 38: {
if (Objects.isNull(itemOnCursor) || itemOnCursor.getType() == Material.AIR) {
event.getInventory().setItem(clickedSlot, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorLeggings")).toItemStack());
} else if (ItemStackUtil.isLegs(itemOnCursor)) {
event.getInventory().setItem(clickedSlot, itemOnCursor);
player.setItemOnCursor(null);
}
break;
}
// Boots
case 39: {
if (Objects.isNull(itemOnCursor) || itemOnCursor.getType() == Material.AIR) {
event.getInventory().setItem(clickedSlot, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorBoots")).toItemStack());
} else if (ItemStackUtil.isBoots(itemOnCursor)) {
event.getInventory().setItem(clickedSlot, itemOnCursor);
player.setItemOnCursor(null);
}
break;
}
// Shield
case 40: {
if (!Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1)) break;
if (Objects.isNull(itemOnCursor) || itemOnCursor.getType() == Material.AIR) {
event.getInventory().setItem(clickedSlot, new ItemBuilder(Material.ARMOR_STAND).setName(getMessage("armorPieceHere")).setLore(getMessage("armorType") + " " + getMessage("armorShield")).toItemStack());
} else if (ItemStackUtil.isShield(itemOnCursor)) {
event.getInventory().setItem(clickedSlot, itemOnCursor);
player.setItemOnCursor(null);
}
break;
}
// Save session button.
case 45: {
session.getKitItems().clear();
session.getKitArmors().clear();
ItemStack itemStack;
for (int i = 0; i < 36; i++) {
itemStack = event.getInventory().getItem(i);
if (Objects.nonNull(itemStack)) session.addItems(itemStack);
}
for (int i = 36; i < 41; i++) {
itemStack = event.getInventory().getItem(i);
if (Objects.nonNull(itemStack) && itemStack.getType() != Material.ARMOR_STAND)
session.addArmor(itemStack);
}
sendMessage(player, getMessage("sessionSaved"));
player.closeInventory();
break;
}
// Load session button.
case 46: {
// Clearing current items
for (int i = 0; i < 41; i++) {
event.getInventory().setItem(i, null);
}
for (ItemStack itemStack : session.getKitItems()) {
event.getInventory().addItem(itemStack);
}
for (ItemStack armor : session.getKitArmors()) {
if (ItemStackUtil.isHelmet(armor)) event.getInventory().setItem(36, armor);
else if (ItemStackUtil.isChest(armor)) event.getInventory().setItem(37, armor);
else if (ItemStackUtil.isLegs(armor)) event.getInventory().setItem(38, armor);
else if (ItemStackUtil.isBoots(armor)) event.getInventory().setItem(39, armor);
else if (Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1) && ItemStackUtil.isShield(armor))
event.getInventory().setItem(40, armor);
}
sendMessage(player, getMessage("sessionLoaded"));
event.getInventory().setItem(46, null);
break;
}
// Edit kit button.
case 53: {
ItemStack itemStack;
ArrayList<ItemStack> itemStacks = new ArrayList<>();
for (int i = 0; i < 36; i++) {
itemStack = event.getInventory().getItem(i);
if (Objects.nonNull(itemStack)) itemStacks.add(itemStack);
}
kit.setItems(itemStacks);
itemStacks = new ArrayList<>();
for (int i = 36; i < 41; i++) {
itemStack = event.getInventory().getItem(i);
if (Objects.nonNull(itemStack) && itemStack.getType() != Material.ARMOR_STAND)
itemStacks.add(itemStack);
}
kit.setArmors(itemStacks);
kit.save();
sendMessage(player, getMessage("successfullyEdited", kit.getDisplayName(world)));
player.closeInventory();
break;
}
default: {
}
}
});
}
}
|
AdvancedKitsReloaded
|
src\main\java\hu\tryharddevs\advancedkits\commands\MainCommand.java
|
package hu.tryharddevs.advancedkits.commands;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.annotation.*;
import co.aikar.commands.contexts.OnlinePlayer;
import hu.tryharddevs.advancedkits.AdvancedKitsMain;
import hu.tryharddevs.advancedkits.Config;
import hu.tryharddevs.advancedkits.cinventory.inventories.CPageInventory;
import hu.tryharddevs.advancedkits.cinventory.inventories.CSimpleInventory;
import hu.tryharddevs.advancedkits.kits.Kit;
import hu.tryharddevs.advancedkits.kits.KitManager;
import hu.tryharddevs.advancedkits.kits.User;
import hu.tryharddevs.advancedkits.kits.flags.Flag;
import hu.tryharddevs.advancedkits.kits.flags.InvalidFlagValueException;
import hu.tryharddevs.advancedkits.utils.ItemBuilder;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
import java.util.stream.Collectors;
import static hu.tryharddevs.advancedkits.kits.flags.DefaultFlags.*;
import static hu.tryharddevs.advancedkits.utils.MessagesApi.sendMessage;
import static hu.tryharddevs.advancedkits.utils.localization.I18n.getMessage;
@SuppressWarnings("ConstantConditions")
@CommandAlias("%rootcommand")
public class MainCommand extends BaseCommand {
private final AdvancedKitsMain instance;
public MainCommand(AdvancedKitsMain instance) {
this.instance = instance;
}
@Default
public void onDefault(CommandSender sender) {
Player player = sender instanceof Player ? (Player) sender : null;
if (Objects.isNull(player)) onHelp(sender);
else Bukkit.dispatchCommand(player, "kit view");
}
@Subcommand("reload")
@CommandPermission("advancedkits.reload")
public void onReloadCommand(CommandSender sender) {
sendMessage(sender, "Starting to reload configuration.");
Config.loadConfigurationValues(instance);
sendMessage(sender, "Done reloading the configuration.");
sendMessage(sender, "Loading KitManager.");
instance.getKitManager().loadKits();
sendMessage(sender, "Done loading KitManager.");
}
@Subcommand("help")
public void onHelp(CommandSender sender) {
ArrayList<String> helpList = new ArrayList<>();
sender.sendMessage(ChatColor.YELLOW + "--------- " + ChatColor.WHITE + Config.CHAT_PREFIX + " Help " + ChatColor.YELLOW + " ---------------------");
helpList.add(ChatColor.GOLD + "/kit" + " " + "use <kitname>" + ": " + ChatColor.WHITE + "Uses the free or bought kit.");
helpList.add(ChatColor.GOLD + "/kit" + " " + "view <kitname>" + ": " + ChatColor.WHITE + "Views the kit items and armor.");
helpList.add(ChatColor.GOLD + "/kit" + " " + "create <kitname>" + ": " + ChatColor.WHITE + "Creates the kit with the items and armor in your inventory");
helpList.add(ChatColor.GOLD + "/kit" + " " + "delete <kitname>" + ": " + ChatColor.WHITE + "Deletes the kit");
helpList.add(ChatColor.GOLD + "/kit" + " " + "edit <kitname>" + ": " + ChatColor.WHITE + "Edits the kit.");
helpList.add(ChatColor.GOLD + "/kit" + " " + "flag <kitname> <flag> <value> [world]" + ": " + ChatColor.WHITE + "Sets a flag.");
helpList.add(ChatColor.GOLD + "/kit" + " " + "give <kitname> <player> [forceuse]" + ": " + ChatColor.WHITE + "Gives the kit to the player.");
helpList.add(ChatColor.GOLD + "/kit" + " " + "reload" + ": " + ChatColor.WHITE + "Reloads the kits and the configuration");
sender.sendMessage(helpList.toArray(new String[helpList.size()]));
}
@Subcommand("delete")
@CommandPermission("advancedkits.delete")
@Syntax("<kitname>")
@CommandCompletion("@kits")
public void onDeleteCommand(CommandSender sender, @Optional Kit kit) {
Player player = sender instanceof Player ? (Player) sender : null;
if (Objects.isNull(kit) && Objects.nonNull(player)) {
String world = player.getWorld().getName();
CPageInventory cPageInventory = new CPageInventory("AdvancedKits - View Kit", (Player) sender);
cPageInventory.setPages(KitManager.getKits().stream().filter(_kit -> _kit.getFlag(VISIBLE, world)).sorted(Comparator.comparing(Kit::getName)).map(_kit -> new ItemBuilder(_kit.getFlag(ICON, world).clone()).setName(ChatColor.WHITE + _kit.getDisplayName(world)).setLore(KitManager.getKitDescription(player, _kit, world)).hideAttributes().toItemStack()).collect(Collectors.toCollection(ArrayList::new)));
cPageInventory.openInventory();
cPageInventory.onInventoryClickEvent((_event) -> {
ItemStack clickedItem = _event.getCurrentItem();
if (Objects.isNull(clickedItem) || !clickedItem.hasItemMeta() || !clickedItem.getItemMeta().hasDisplayName())
return;
if (Arrays.asList(cPageInventory.getBackPage(), cPageInventory.getForwardsPage()).contains(clickedItem))
return;
Player _player = (Player) _event.getWhoClicked();
Kit clickedKit = KitManager.getKit(clickedItem.getItemMeta().getDisplayName(), _player.getWorld().getName());
if (Objects.isNull(clickedKit)) {
sendMessage(_player, getMessage("kitNotFound"));
return;
}
_player.closeInventory();
Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit delete " + clickedKit.getName());
});
return;
} else if (Objects.isNull(kit) && Objects.isNull(player)) {
sendMessage(sender, "Syntax: /kit delete <kitname>");
return;
}
String name = kit.getName();
if (Objects.nonNull(player)) {
CSimpleInventory cSimpleInventory = new CSimpleInventory("AdvancedKits - Delete Kit", player);
cSimpleInventory.setItem(2, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 13).setName(getMessage("guiConfirm")).toItemStack());
cSimpleInventory.setItem(6, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 14).setName(getMessage("guiCancel")).toItemStack());
cSimpleInventory.openInventory();
cSimpleInventory.onInventoryClickEvent((_event) -> {
if (_event.getCurrentItem() == null) return;
ItemStack item = _event.getCurrentItem();
if (item.getDurability() == (short) 14) //Cancel
{
_event.getWhoClicked().closeInventory();
} else if (item.getDurability() == (short) 13) //Delete
{
_event.getWhoClicked().closeInventory();
instance.getKitManager().deleteKit(kit);
sendMessage(player, getMessage("successfullyDeleted", name));
}
});
} else {
instance.getKitManager().deleteKit(kit);
sendMessage(sender, getMessage("successfullyDeleted", name));
}
}
@Subcommand("buy")
@CommandPermission("advancedkits.buy")
@CommandCompletion("@kits")
@Syntax("[kitname]")
public void onBuyCommand(Player player, @Optional Kit kit) {
User user = User.getUser(player.getUniqueId());
String world = player.getWorld().getName();
if (Config.DISABLED_WORLDS.contains(world)) {
sendMessage(player, getMessage("kitUseDisabledInWorld"));
return;
}
if (Objects.isNull(kit)) {
CPageInventory cPageInventory = new CPageInventory("AdvancedKits - Buy Kit", player);
cPageInventory.setPages(KitManager.getKits().stream().filter(_kit -> _kit.getFlag(VISIBLE, world) && (!_kit.getFlag(FREE, world) && !user.isUnlocked(_kit))).sorted(Comparator.comparing(Kit::getName)).map(_kit -> new ItemBuilder(_kit.getFlag(ICON, world).clone()).setName(ChatColor.WHITE + _kit.getDisplayName(world)).setLore(KitManager.getKitDescription(player, _kit, world)).hideAttributes().toItemStack()).collect(Collectors.toCollection(ArrayList::new)));
cPageInventory.openInventory();
cPageInventory.onInventoryClickEvent((_event) -> {
ItemStack clickedItem = _event.getCurrentItem();
if (Objects.isNull(clickedItem) || !clickedItem.hasItemMeta() || !clickedItem.getItemMeta().hasDisplayName()) {
return;
}
if (Arrays.asList(cPageInventory.getBackPage(), cPageInventory.getForwardsPage()).contains(clickedItem))
return;
Player _player = (Player) _event.getWhoClicked();
Kit clickedKit = KitManager.getKit(clickedItem.getItemMeta().getDisplayName(), _player.getWorld().getName());
if (Objects.isNull(clickedKit)) {
sendMessage(_player, getMessage("kitNotFound"));
return;
}
_player.closeInventory();
Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit buy " + clickedKit.getName());
});
return;
}
if (!player.hasPermission(kit.getPermission())) {
sendMessage(player, getMessage("noKitPermission"));
return;
}
if (user.isUnlocked(kit)) {
sendMessage(player, getMessage("alreadyUnlocked", kit.getName()));
return;
}
EconomyResponse r = instance.getEconomy().withdrawPlayer(player, kit.getFlag(COST, world));
if (r.transactionSuccess()) {
sendMessage(player, getMessage("successfullyBought", kit.getDisplayName(world)));
user.addToUnlocked(kit);
user.save();
if (kit.getFlag(USEONBUY, world))
Bukkit.dispatchCommand(player, "advancedkitsreloaded:kit use " + kit.getName());
} else {
sendMessage(player, getMessage("notEnoughMoney", r.amount));
}
}
@Subcommand("give")
@CommandPermission("advancedkits.give")
@CommandCompletion("@kits @players true|false true|false")
@Syntax("<kitname> <player> [forceuse, default=false] [unlock, default=false]")
public void onGiveCommand(CommandSender sender, Kit kit, OnlinePlayer player, @Default("false") Boolean forceUse, @Default("false") Boolean unlockKit) {
if (Objects.isNull(player)) {
sendMessage(sender, getMessage("playerNotFound"));
return;
}
if (player.getPlayer().isDead()) {
sendMessage(sender, getMessage("playerIsDead"));
return;
}
User user = User.getUser(player.getPlayer().getUniqueId());
sender.sendMessage(forceUse + " " + unlockKit);
// /kit give kit name true
if (forceUse) {
if (!user.isUnlocked(kit) && unlockKit) { // /kit give kit name true true
user.addToUnlocked(kit);
user.save();
}
UseCommand.giveKitToPlayer(player.getPlayer(), kit);
sendMessage(sender, getMessage("successfullyGiven", kit.getName(), player.getPlayer().getName()));
} else if (!user.isUnlocked(kit) && unlockKit) { // /kit give kit name false true
user.addToUnlocked(kit);
user.save();
sendMessage(sender, getMessage("successfullyGiven", kit.getName(), player.getPlayer().getName()));
} else {
sendMessage(sender, getMessage("giveAlreadyUnlocked", kit.getName()));
}
}
@Subcommand("view")
@CommandPermission("advancedkits.view")
@CommandCompletion("@kits")
@Syntax("[kitname]")
public void onViewCommand(Player player, @Optional Kit kit) {
User user = User.getUser(player.getUniqueId());
String world = player.getWorld().getName();
if (Config.DISABLED_WORLDS.contains(world)) {
sendMessage(player, getMessage("kitUseDisabledInWorld"));
return;
}
if (Objects.isNull(kit)) {
CPageInventory cPageInventory = new CPageInventory("AdvancedKits - View Kit", player);
cPageInventory.setPages(KitManager.getKits().stream().filter(_kit -> _kit.getFlag(VISIBLE, world)).sorted(Comparator.comparing(Kit::getName)).map(_kit -> new ItemBuilder(_kit.getFlag(ICON, world).clone()).setName(ChatColor.WHITE + _kit.getDisplayName(world)).setLore(KitManager.getKitDescription(player, _kit, world)).hideAttributes().toItemStack()).collect(Collectors.toCollection(ArrayList::new)));
cPageInventory.openInventory();
cPageInventory.onInventoryClickEvent((_event) -> {
ItemStack clickedItem = _event.getCurrentItem();
if (Objects.isNull(clickedItem) || !clickedItem.hasItemMeta() || !clickedItem.getItemMeta().hasDisplayName())
return;
if (Arrays.asList(cPageInventory.getBackPage(), cPageInventory.getForwardsPage()).contains(clickedItem))
return;
Player _player = (Player) _event.getWhoClicked();
Kit clickedKit = KitManager.getKit(clickedItem.getItemMeta().getDisplayName(), _player.getWorld().getName());
if (Objects.isNull(clickedKit)) {
return;
}
_player.closeInventory();
Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit view " + clickedKit.getName());
});
return;
}
CSimpleInventory cSimpleInventory = new CSimpleInventory("AdvancedKits - View Kit", player, 54);
cSimpleInventory.addItems(kit.getItems());
int i = 36;
for (ItemStack armor : kit.getArmors()) {
cSimpleInventory.setItem(i, armor);
i++;
}
cSimpleInventory.setItem(49, new ItemBuilder(Material.PAPER).setName(getMessage("informations")).setLore(KitManager.getKitDescription(player, kit, world)).toItemStack());
if (user.isUnlocked(kit) || kit.getFlag(FREE, world)) {
cSimpleInventory.setItem(53, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 13).setName(ChatColor.GREEN + getMessage("guiUse")).hideAttributes().toItemStack());
} else if (kit.getFlag(COST, world) > 0) {
cSimpleInventory.setItem(53, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 14).setName(ChatColor.GREEN + getMessage("guiBuy")).hideAttributes().toItemStack());
}
cSimpleInventory.setItem(45, new ItemBuilder(Material.STAINED_GLASS_PANE).setDurability((short) 0).setName(ChatColor.GREEN + getMessage("guiBackToMenu")).hideAttributes().toItemStack());
cSimpleInventory.openInventory();
cSimpleInventory.onInventoryClickEvent((_event) -> {
ItemStack clickedItem = _event.getCurrentItem();
if (Objects.isNull(clickedItem) || !clickedItem.hasItemMeta() || !clickedItem.getItemMeta().hasDisplayName())
return;
Player _player = (Player) _event.getWhoClicked();
if (clickedItem.getType() == Material.STAINED_GLASS_PANE) {
if (clickedItem.getDurability() == (short) 13) {
Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit use " + kit.getName());
} else if (clickedItem.getDurability() == (short) 14) {
Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit buy " + kit.getName());
} else if (clickedItem.getDurability() == (short) 0) {
Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit view");
}
}
});
sendMessage(player, getMessage("kitView", kit.getDisplayName(world)));
}
@Subcommand("flag")
@CommandPermission("advancedkits.flag")
@CommandCompletion("@kits @flags")
@Syntax("<kitname> <flag> <value> [world]")
public void onFlagCommand(CommandSender sender, Kit kit, Flag flag, String value, @Optional String world) {
String tempValue = String.join(" ", value, Objects.isNull(world) ? "" : world);
String[] splittedValue = tempValue.split(" ");
if (Objects.nonNull(Bukkit.getWorld(splittedValue[splittedValue.length - 1]))) {
world = splittedValue[splittedValue.length - 1];
value = String.join(" ", Arrays.copyOf(splittedValue, splittedValue.length - 1));
} else {
world = "global";
value = String.join(" ", splittedValue);
}
if (value.equalsIgnoreCase("hand")) {
Player player = sender instanceof Player ? (Player) sender : null;
if (Objects.isNull(player)) {
sendMessage(sender, getMessage("playerOnly"));
return;
}
if (flag.getName().equalsIgnoreCase("firework")) {
if (Objects.isNull(player.getInventory().getItemInMainHand()) || !player.getInventory().getItemInMainHand().getType().equals(Material.FIREWORK)) {
sendMessage(player, getMessage("notFirework"));
return;
}
try {
kit.setFlag(flag, world, flag.parseItem(player));
} catch (InvalidFlagValueException e) {
player.sendMessage(e.getMessages());
return;
}
sendMessage(player, getMessage("flagSet", flag.getName(), value, kit.getDisplayName(world), world));
return;
} else if (flag.getName().equalsIgnoreCase("icon")) {
if (Objects.isNull(player.getInventory().getItemInMainHand()) || player.getInventory().getItemInMainHand().getType().equals(Material.AIR)) {
sendMessage(player, getMessage("notValidIcon"));
return;
}
try {
kit.setFlag(flag, world, flag.parseItem(player));
} catch (InvalidFlagValueException e) {
player.sendMessage(e.getMessages());
return;
}
sendMessage(player, getMessage("flagSet", flag.getName(), value, kit.getDisplayName(world), world));
return;
}
}
if (flag.getName().equalsIgnoreCase("firework") || flag.getName().equalsIgnoreCase("icon")) {
sendMessage(sender, ChatColor.GRAY + "Usage: /kit flag <kitname> <flag> hand");
return;
}
try {
kit.setFlag(flag, world, flag.parseInput(value));
} catch (InvalidFlagValueException e) {
sender.sendMessage(e.getMessages());
return;
}
sendMessage(sender, getMessage("flagSet", flag.getName(), value, kit.getDisplayName(world), world));
}
}
|
AdvancedKitsReloaded
|
src\main\java\hu\tryharddevs\advancedkits\commands\UseCommand.java
|
package hu.tryharddevs.advancedkits.commands;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.annotation.*;
import co.aikar.commands.annotation.Optional;
import hu.tryharddevs.advancedkits.AdvancedKitsMain;
import hu.tryharddevs.advancedkits.Config;
import hu.tryharddevs.advancedkits.cinventory.inventories.CPageInventory;
import hu.tryharddevs.advancedkits.kits.Kit;
import hu.tryharddevs.advancedkits.kits.KitManager;
import hu.tryharddevs.advancedkits.kits.User;
import hu.tryharddevs.advancedkits.utils.ItemBuilder;
import hu.tryharddevs.advancedkits.utils.ItemStackUtil;
import hu.tryharddevs.advancedkits.utils.MessagesApi;
import me.clip.placeholderapi.PlaceholderAPI;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.potion.PotionEffect;
import org.inventivetalent.particle.ParticleEffect;
import org.inventivetalent.reflection.minecraft.Minecraft;
import java.util.*;
import java.util.stream.Collectors;
import static hu.tryharddevs.advancedkits.kits.flags.DefaultFlags.*;
import static hu.tryharddevs.advancedkits.utils.MessagesApi.sendMessage;
import static hu.tryharddevs.advancedkits.utils.localization.I18n.getMessage;
@CommandAlias("%rootcommand")
public class UseCommand extends BaseCommand {
private static AdvancedKitsMain instance;
public UseCommand(AdvancedKitsMain instance) {
UseCommand.instance = instance;
}
@Subcommand("use")
@CommandPermission("advancedkits.use")
@CommandCompletion("@kits")
@Syntax("[kitname]")
public void onUseCommand(Player player, @Optional Kit kit) {
User user = User.getUser(player.getUniqueId());
String world = player.getWorld().getName();
if (Config.DISABLED_WORLDS.contains(world)) {
sendMessage(player, getMessage("kitUseDisabledInWorld"));
return;
}
if (Objects.isNull(kit)) {
CPageInventory cPageInventory = new CPageInventory("AdvancedKits - Use Kit", player);
cPageInventory.setPages(KitManager.getKits().stream().filter(_kit -> _kit.getFlag(VISIBLE, world) && (_kit.getFlag(FREE, world) && player.hasPermission(_kit.getPermission()) || user.isUnlocked(_kit))).sorted(Comparator.comparing(Kit::getName)).map(_kit -> new ItemBuilder(_kit.getFlag(ICON, world).clone()).setName(ChatColor.WHITE + _kit.getDisplayName(world)).setLore(KitManager.getKitDescription(player, _kit, world)).hideAttributes().toItemStack()).collect(Collectors.toCollection(ArrayList::new)));
cPageInventory.openInventory();
cPageInventory.onInventoryClickEvent((_event) -> {
ItemStack clickedItem = _event.getCurrentItem();
if (Objects.isNull(clickedItem) || !clickedItem.hasItemMeta() || !clickedItem.getItemMeta().hasDisplayName())
return;
if (Arrays.asList(cPageInventory.getBackPage(), cPageInventory.getForwardsPage()).contains(clickedItem))
return;
Player _player = (Player) _event.getWhoClicked();
Kit clickedKit = KitManager.getKit(clickedItem.getItemMeta().getDisplayName(), _player.getWorld().getName());
if (Objects.isNull(clickedKit)) {
sendMessage(_player, getMessage("kitNotFound"));
return;
}
_player.closeInventory();
Bukkit.dispatchCommand(_player, "advancedkitsreloaded:kit use " + clickedKit.getName());
});
return;
}
if (!player.hasPermission(kit.getPermission())) {
sendMessage(player, getMessage("noKitPermission", kit.getPermission()));
return;
}
if (kit.getFlag(DISABLEDWORLDS, world).contains(player.getWorld().getName())) {
sendMessage(player, getMessage("cantUseWorld"));
return;
}
if (kit.getFlag(MAXUSES, world) != 0) {
if (user.getTimesUsed(kit, world) >= kit.getFlag(MAXUSES, world)) {
sendMessage(player, getMessage("cantUseNoMore"));
return;
}
}
if (kit.getFlag(DELAY, world) > 0 && !player.hasPermission(kit.getDelayPermission())) {
if (!user.checkDelay(kit, world)) {
sendMessage(player, getMessage("cantUseDelay", user.getDelay(kit, world)));
return;
}
}
if (kit.getFlag(PERUSECOST, world) != 0) {
EconomyResponse r = instance.getEconomy().withdrawPlayer(player, kit.getFlag(PERUSECOST, world));
if (r.transactionSuccess()) {
sendMessage(player, getMessage("moneyLowered", instance.getEconomy().format(r.balance), instance.getEconomy().format(r.amount), "PerUseCost"));
} else {
sendMessage(player, getMessage("notEnoughMoney", instance.getEconomy().format(r.amount)));
return;
}
}
if (giveKitToPlayer(player, kit)) {
if (kit.getFlag(DELAY, world) > 0 && !player.hasPermission(kit.getDelayPermission())) {
user.setDelay(kit, world, kit.getFlag(DELAY, world));
}
if (kit.getFlag(MAXUSES, world) > 0) user.addUse(kit, world);
}
sendMessage(player, getMessage("successfullyUsed", kit.getName()));
}
private static boolean hasInventorySpace(Player player, ItemStack item) {
int free = 0;
for (ItemStack itemStack : player.getInventory().getStorageContents()) {
if (itemStack == null || itemStack.getType() == Material.AIR) {
free += item.getMaxStackSize();
} else if (itemStack.isSimilar(item)) {
free += item.getMaxStackSize() - itemStack.getAmount();
}
}
return free >= item.getAmount();
}
private static int getEmptySpaces(Player player) {
return (int) Arrays.stream(player.getInventory().getStorageContents()).filter(item -> Objects.isNull(item) || item.getType() == Material.AIR).count();
}
public static boolean giveKitToPlayer(Player player, Kit kit) {
String world = player.getWorld().getName();
if (kit.getFlag(ITEMSINCONTAINER, world)) {
ItemStack chestItem = new ItemBuilder(Material.CHEST).setName(kit.getDisplayName(world)).setLore("Place it down to get your items.").toItemStack();
player.getInventory().addItem(chestItem);
} else {
PlayerInventory playerInventory = player.getInventory();
int freeSpace = getEmptySpaces(player);
int spaceneed = kit.getItems().size();
if (kit.getFlag(AUTOEQUIPARMOR, world)) {
spaceneed += player.getInventory().getArmorContents().length;
}
if (!kit.getFlag(SPEWITEMS, world) && spaceneed > freeSpace) {
sendMessage(player, getMessage("notEnoughSpace", spaceneed));
return false;
}
ItemStack[] equipment = playerInventory.getArmorContents();
if (kit.getFlag(CLEARINVENTORY, world)) {
player.getInventory().clear();
player.getEquipment().clear();
}
kit.getItems().forEach(itemStack -> {
if (hasInventorySpace(player, itemStack)) {
player.getInventory().addItem(itemStack);
} else if (kit.getFlag(SPEWITEMS, world)) {
player.getWorld().dropItemNaturally(player.getLocation(), itemStack);
}
});
// AutoEquip
if (kit.getFlag(AUTOEQUIPARMOR, world)) {
for (ItemStack armor : equipment) { //If player had prev armor on
if (Objects.isNull(armor)) continue;
if (hasInventorySpace(player, armor)) {
playerInventory.addItem(armor); // add it to his inventory
} else if (kit.getFlag(SPEWITEMS, world)) {
player.getWorld().dropItemNaturally(player.getLocation(), armor); // Or drop it
}
}
//Equip armor
kit.getArmors().forEach(itemStack -> {
if (ItemStackUtil.isHelmet(itemStack)) {
playerInventory.setHelmet(itemStack);
} else if (ItemStackUtil.isChest(itemStack)) {
playerInventory.setChestplate(itemStack);
} else if (ItemStackUtil.isLegs(itemStack)) {
playerInventory.setLeggings(itemStack);
} else if (ItemStackUtil.isBoots(itemStack)) {
playerInventory.setBoots(itemStack);
}
if (Minecraft.VERSION.newerThan(Minecraft.Version.v1_9_R1) && ItemStackUtil.isShield(itemStack)) {
playerInventory.setItemInOffHand(itemStack);
}
});
} else {
for (ItemStack armor : kit.getArmors()) { //Add items to the player's inventory.
if (hasInventorySpace(player, armor)) {
playerInventory.addItem(armor);
} else if (kit.getFlag(SPEWITEMS, world)) {
player.getWorld().dropItemNaturally(player.getLocation(), armor);
}
}
}
}
String temp;
for (String command : kit.getFlag(COMMANDS, world)) {
temp = (instance.isPlaceholderAPIEnabled() ? PlaceholderAPI.setPlaceholders(player, command) : command.replace("%player_name%", player.getName()));
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), temp);
}
for (String message : kit.getFlag(MESSAGES, world)) {
temp = (instance.isPlaceholderAPIEnabled() ? PlaceholderAPI.setPlaceholders(player, message) : message.replace("%player_name%", player.getName()));
if (temp.contains("subtitle:") && Config.TITLES_ENABLED) {
MessagesApi.sendTitle(player, "", temp.replace("subtitle:", ""));
} else if (temp.contains("title:") && Config.TITLES_ENABLED) {
MessagesApi.sendTitle(player, temp.replace("title:", ""), "");
} else if (temp.contains("actionbar:") && Config.ACTIONBARS_ENABLED) {
MessagesApi.sendActionBar(player, ChatColor.translateAlternateColorCodes('&', temp.replace("actionbar:", "")));
} else {
player.sendMessage(ChatColor.translateAlternateColorCodes('&', temp));
}
}
for (PotionEffect potionEffect : kit.getFlag(POTIONEFFECTS, world)) {
player.addPotionEffect(potionEffect);
}
for (ParticleEffect particleEffect : kit.getFlag(PARTICLEEFFECTS, world)) {
particleEffect.send(Collections.singletonList(player), player.getLocation().clone(), 0, 0, 0, 0, 1);
}
for (Sound sound : kit.getFlag(SOUNDEFFECTS, world)) {
player.playSound(player.getLocation().clone(), sound, 1.0F, 1.0F);
}
if (kit.getFlag(FIREWORK, world) != null) {
ItemStack firework = kit.getFlag(FIREWORK, world);
Firework fireworkEntity = player.getWorld().spawn(player.getLocation().clone(), Firework.class);
FireworkMeta data = (FireworkMeta) firework.getItemMeta();
if (data != null) fireworkEntity.setFireworkMeta(data);
}
return true;
}
}
|
AdvancedKitsReloaded
|
src\main\java\hu\tryharddevs\advancedkits\kits\Kit.java
|
package hu.tryharddevs.advancedkits.kits;
import co.aikar.commands.InvalidCommandArgument;
import co.aikar.commands.contexts.ContextResolver;
import hu.tryharddevs.advancedkits.AdvancedKitsMain;
import hu.tryharddevs.advancedkits.kits.flags.DefaultFlags;
import hu.tryharddevs.advancedkits.kits.flags.Flag;
import hu.tryharddevs.advancedkits.utils.ItemStackUtil;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static hu.tryharddevs.advancedkits.kits.flags.DefaultFlags.DISPLAYNAME;
import static hu.tryharddevs.advancedkits.utils.localization.I18n.getMessage;
public class Kit {
private final String name;
private final AdvancedKitsMain instance = AdvancedKitsMain.getPlugin();
private HashMap<String, ConcurrentHashMap<Flag<?>, Object>> flags = new HashMap<>();
private ArrayList<ItemStack> itemsArrayList = new ArrayList<>();
private ArrayList<ItemStack> armorsArrayList = new ArrayList<>();
private YamlConfiguration kitConfig;
public Kit(String name) {
this.name = name;
this.kitConfig = YamlConfiguration.loadConfiguration(getSaveFile());
}
public static ContextResolver<Kit> getContextResolver() {
return (c) -> {
Player senderPlayer = c.getSender() instanceof Player ? (Player) c.getSender() : null;
String world = "global";
String kitName = c.popFirstArg();
if (Objects.nonNull(senderPlayer)) {
world = senderPlayer.getWorld().getName();
}
Kit kit = KitManager.getKit(kitName, world);
if (Objects.isNull(kit)) {
throw new InvalidCommandArgument(getMessage("kitNotFound"));
}
return kit;
};
}
public final String getName() {
return this.name;
}
public HashMap<String, ConcurrentHashMap<Flag<?>, Object>> getFlags() {
return this.flags;
}
public String getDisplayName(String world) {
if (!this.flags.containsKey(world)) world = "global";
if (Objects.isNull(getFlag(DISPLAYNAME, world))) setFlag(DISPLAYNAME, world, this.name);
return ChatColor.translateAlternateColorCodes('&', getFlag(DISPLAYNAME, world));
}
public String getPermission() {
return "advancedkits.use." + this.name;
}
public String getDelayPermission() {
return "advancedkits.skipdelay." + this.name;
}
public void save() {
// Serialize items in the ArrayLists. This way we don't lose any custom data, including books.
this.kitConfig.set("Items", this.itemsArrayList.stream().map(ItemStackUtil::itemToString).collect(Collectors.toCollection(ArrayList::new)));
this.kitConfig.set("Armors", this.armorsArrayList.stream().map(ItemStackUtil::itemToString).collect(Collectors.toCollection(ArrayList::new)));
if (this.flags.isEmpty()) {
ConcurrentHashMap<Flag<?>, Object> flagObjects = new ConcurrentHashMap<>();
for (Flag<?> flag : DefaultFlags.getDefaultFlags()) {
if (Objects.nonNull(flag.getDefault())) flagObjects.put(flag, flag.getDefault());
if (flag.getName().equalsIgnoreCase("displayname")) flagObjects.put(flag, this.name);
}
this.flags.put("global", flagObjects);
}
for (String world : flags.keySet()) {
this.kitConfig.set("Flags." + world, this.instance.getKitManager().marshal(this.flags.get(world)));
}
try {
this.kitConfig.save(getSaveFile());
} catch (IOException e) {
e.printStackTrace();
}
this.instance.log("Saved " + this.name);
}
public File getSaveFile() {
File file = new File(this.instance.getDataFolder() + File.separator + "kits", this.name + ".yml");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
this.instance.log(ChatColor.GOLD + "Please send this to the author of this plugin:");
this.instance.log(" -- StackTrace --");
e.printStackTrace();
this.instance.log(" -- End of StackTrace --");
}
}
return file;
}
YamlConfiguration getConfig() {
return this.kitConfig;
}
public ArrayList<ItemStack> getItems() {
return this.itemsArrayList;
}
public void setItems(ArrayList<ItemStack> itemsArrayList) {
this.itemsArrayList = itemsArrayList;
}
public ArrayList<ItemStack> getArmors() {
return this.armorsArrayList;
}
public void setArmors(ArrayList<ItemStack> armorsArrayList) {
this.armorsArrayList = armorsArrayList;
}
@SuppressWarnings("unchecked")
@Nullable
public <T extends Flag<V>, V> V getFlag(T flag, String world) {
checkNotNull(flag);
if (!this.flags.containsKey(world)) world = "global";
if (!this.flags.get(world).containsKey(flag)) world = "global";
Object obj = this.flags.get(world).get(flag);
V val;
if (obj != null) {
val = (V) obj;
} else {
return flag.getDefault();
}
return val;
}
public boolean hasFlag(Flag flag, String world) {
if (this.flags.containsKey(world)) {
if (this.flags.get(world).containsKey(flag)) {
return true;
}
}
return false;
}
public <T extends Flag<V>, V> void setFlag(T flag, String world, @Nullable V val) {
checkNotNull(flag);
if (!this.flags.containsKey(world)) this.flags.put(world, new ConcurrentHashMap<>());
if (val == null) {
this.flags.get(world).remove(flag);
} else {
this.flags.get(world).put(flag, val);
}
save();
}
public void setFlags(String world, Map<Flag<?>, Object> flags) {
checkNotNull(flags);
this.flags.put(world, new ConcurrentHashMap<>(flags));
}
}
|
AdvancedKitsReloaded
|
src\main\java\hu\tryharddevs\advancedkits\kits\KitManager.java
|
package hu.tryharddevs.advancedkits.kits;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.gson.JsonSyntaxException;
import hu.tryharddevs.advancedkits.AdvancedKitsMain;
import hu.tryharddevs.advancedkits.kits.flags.DefaultFlags;
import hu.tryharddevs.advancedkits.kits.flags.Flag;
import hu.tryharddevs.advancedkits.utils.ItemStackUtil;
import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkNotNull;
import static hu.tryharddevs.advancedkits.kits.flags.DefaultFlags.*;
import static hu.tryharddevs.advancedkits.utils.localization.I18n.getMessage;
@SuppressWarnings("ALL")
public class KitManager {
private static final Pattern FILE_PATTERN = Pattern.compile("[^A-Za-z0-9_]+", Pattern.CASE_INSENSITIVE);
private static ArrayList<Kit> kitArrayList = new ArrayList<>();
private static AdvancedKitsMain instance;
public KitManager(AdvancedKitsMain instance) {
this.instance = instance;
}
public static ArrayList<Kit> getKits() {
return kitArrayList;
}
public static Kit getKit(String name, String world) {
return kitArrayList.stream().filter(kit -> kit.getName().equalsIgnoreCase(name) || ChatColor.stripColor(kit.getDisplayName(world)).equalsIgnoreCase(ChatColor.stripColor(name))).findFirst().orElse(null);
}
public void deleteKit(Kit kit) {
File config = kit.getSaveFile();
if (config.delete()) instance.log(ChatColor.GREEN + kit.getName() + " has been deleted.");
else instance.log(ChatColor.RED + kit.getName() + " could not be deleted.");
kitArrayList.remove(kit);
}
public static ArrayList<String> getKitDescription(Player player, Kit kit, String world) {
ArrayList<String> descriptions = new ArrayList<>();
User user = User.getUser(player.getUniqueId());
if (!kit.getFlag(CUSTOMDESCRIPTION, world).isEmpty()) {
kit.getFlag(CUSTOMDESCRIPTION, world).forEach(message -> descriptions.add(ChatColor.translateAlternateColorCodes('&', (AdvancedKitsMain.getPlugin().isPlaceholderAPIEnabled() ? PlaceholderAPI.setPlaceholders(player, message) : message.replace("%player_name%", player.getName())))));
descriptions.add(" ");
}
if (kit.getFlag(DELAY, world) > 0) {
if (!user.checkDelay(kit, world) && !player.hasPermission(kit.getDelayPermission())) {
descriptions.add(" ");
descriptions.add(getMessage("cantUseDelay", user.getDelay(kit, world)));
descriptions.add(" ");
} else if (player.hasPermission(kit.getDelayPermission())) {
descriptions.add(" ");
descriptions.add(getMessage("delayImmunity"));
descriptions.add(" ");
}
descriptions.add(getMessage("flagDelay", getDelayInString((int) (double) kit.getFlag(DELAY, world))));
}
if (kit.getFlag(COST, world) > 0) {
descriptions.add(getMessage("flagCost", instance.getEconomy().format(kit.getFlag(COST, world))));
} else if (kit.getFlag(FREE, world)) {
descriptions.add(getMessage("flagFree"));
}
if (kit.getFlag(MAXUSES, world) != 0) {
if (user.getTimesUsed(kit, world) >= kit.getFlag(MAXUSES, world)) {
descriptions.add(getMessage("cantUseNoMore"));
} else {
descriptions.add(getMessage("flagAmountOfUses", (kit.getFlag(MAXUSES, world) - user.getTimesUsed(kit, world))));
}
descriptions.add(getMessage("flagMaxUses", kit.getFlag(MAXUSES, world)));
}
if (kit.getFlag(PERUSECOST, world) != 0) {
descriptions.add(getMessage("flagPerUseCost", instance.getEconomy().format(kit.getFlag(PERUSECOST, world))));
}
if (!kit.getFlag(DISABLEDWORLDS, world).isEmpty()) {
descriptions.add(getMessage("flagDisabledWorlds"));
kit.getFlag(DISABLEDWORLDS, world).forEach(s -> descriptions.add(ChatColor.WHITE + "- " + s));
}
return descriptions;
}
static String getDifferenceText(Date startDate, Date endDate) {
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
StringBuilder sb = new StringBuilder();
if (elapsedDays >= 1) {
sb.append(elapsedDays).append(" ").append(getMessage("timeUnitDays")).append(" ");
}
if (elapsedHours >= 1) {
sb.append(elapsedHours).append(" ").append(getMessage("timeUnitHours")).append(" ");
}
if (elapsedMinutes >= 1) {
sb.append(elapsedMinutes).append(" ").append(getMessage("timeUnitMinutes")).append(" ");
}
if (elapsedSeconds >= 1) {
sb.append(elapsedSeconds).append(" ").append(getMessage("timeUnitSeconds")).append(" ");
}
return sb.toString();
}
private static String getDelayInString(int delay) {
int numberOfDays;
int numberOfHours;
int numberOfMinutes;
int numberOfSeconds;
numberOfDays = delay / 86400;
numberOfHours = (delay % 86400) / 3600;
numberOfMinutes = ((delay % 86400) % 3600) / 60;
numberOfSeconds = ((delay % 86400) % 3600) % 60;
StringBuilder sb = new StringBuilder();
if (numberOfDays >= 1) {
sb.append(numberOfDays).append(" ").append(getMessage("timeUnitDays")).append(" ");
}
if (numberOfHours >= 1) {
sb.append(numberOfHours).append(" ").append(getMessage("timeUnitHours")).append(" ");
}
if (numberOfMinutes >= 1) {
sb.append(numberOfMinutes).append(" ").append(getMessage("timeUnitMinutes")).append(" ");
}
if (numberOfSeconds >= 1) {
sb.append(numberOfSeconds).append(" ").append(getMessage("timeUnitSeconds")).append(" ");
}
return sb.toString();
}
public void loadKits() {
final File folder = new File(instance.getDataFolder(), "kits");
if (!folder.isDirectory()) {
instance.log(ChatColor.GOLD + "- kits folder not found. Creating...");
folder.mkdirs();
return;
}
kitArrayList = new ArrayList<>();
Kit kit;
YamlConfiguration kitConfig;
String fileName;
File[] directoryListing = folder.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
if (!child.isFile()) continue;
if (!Files.getFileExtension(child.getName()).equalsIgnoreCase("yml")) continue;
fileName = Files.getNameWithoutExtension(child.getName());
if (FILE_PATTERN.matcher(fileName).find()) {
instance.log(ChatColor.RED + "Error when trying to load " + fileName);
instance.log(ChatColor.RED + "- The name contains special characters.");
continue;
}
kit = new Kit(fileName);
kitConfig = kit.getConfig();
if (kitConfig.contains("Items")) {
List<?> itemsList = kitConfig.getList("Items");
if (!itemsList.isEmpty()) {
try {
kit.setItems(itemsList.stream().map(item -> ItemStackUtil.itemFromString(String.valueOf(item))).collect(Collectors.toCollection(ArrayList::new)));
} catch (NullPointerException | JsonSyntaxException e) {
instance.log(ChatColor.RED + "Failed to parse items.");
instance.log(ChatColor.RED + "Trying to load items using the old methods.");
kit.setItems(itemsList.stream().map(object -> ItemStack.deserialize((Map<String, Object>) object)).collect(Collectors.toCollection(ArrayList::new)));
}
}
}
if (kitConfig.contains("Armors")) {
List<?> armorsList = kitConfig.getList("Armors");
if (!armorsList.isEmpty()) {
kit.setArmors(armorsList.stream().map(armor -> ItemStackUtil.itemFromString(String.valueOf(armor))).collect(Collectors.toCollection(ArrayList::new)));
}
} else if (kitConfig.contains("Armor")) {
List<?> armorsList = kitConfig.getList("Armor");
if (!armorsList.isEmpty()) {
instance.log(ChatColor.GOLD + "Failed to parse armors.");
instance.log(ChatColor.GOLD + "Trying to load items using the old methods.");
kit.setArmors(armorsList.stream().map(object -> ItemStack.deserialize((Map<String, Object>) object)).collect(Collectors.toCollection(ArrayList::new)));
}
kitConfig.set("Armor", null);
kit.save();
}
Map<String, Object> temp = null;
if (kitConfig.contains("Flags")) {
for (String world : kitConfig.getConfigurationSection("Flags").getKeys(false)) {
try {
kit.setFlags(world, unmarshalFlags(kitConfig.getConfigurationSection("Flags." + world).getValues(false)));
} catch (NullPointerException | JsonSyntaxException e) {
if (temp == null) {
temp = kitConfig.getConfigurationSection("Flags").getValues(false);
kit.setFlags("global", unmarshalFlags(temp));
}
kitConfig.set("Flags." + world, null);
}
}
if (temp != null) {
kit.save();
}
}
kitArrayList.add(kit);
}
}
instance.log(ChatColor.GREEN + "Loaded " + kitArrayList.size() + " kit(s).");
}
private Map<Flag<?>, Object> unmarshalFlags(Map<String, Object> rawValues) {
checkNotNull(rawValues, "rawValues");
ConcurrentMap<Flag<?>, Object> values = Maps.newConcurrentMap();
for (Map.Entry<String, Object> entry : rawValues.entrySet()) {
Flag<?> flag = DefaultFlags.fuzzyMatchFlag(entry.getKey());
if (flag != null) {
try {
values.put(flag, flag.unmarshal(entry.getValue()));
} catch (Exception e) {
instance.log(ChatColor.RED + "Error: " + e.getMessage());
instance.log(ChatColor.RED + "Failed to unmarshal flag value for " + flag);
}
}
}
return values;
}
public Map<String, Object> marshal(Map<Flag<?>, Object> values) {
checkNotNull(values, "values");
Map<String, Object> rawValues = Maps.newHashMap();
for (Map.Entry<Flag<?>, Object> entry : values.entrySet()) {
try {
rawValues.put(entry.getKey().getName(), marshal(entry.getKey(), entry.getValue()));
} catch (Exception e) {
instance.log(ChatColor.RED + "Error: " + e.getMessage());
instance.log(ChatColor.RED + "Failed to marshal flag value for " + entry.getKey() + "; value is " + entry.getValue());
}
}
return rawValues;
}
@SuppressWarnings("unchecked") private <T> Object marshal(Flag<T> flag, Object value) {
return flag.marshal((T) value);
}
}
|
AdvancedKitsReloaded
|
src\main\java\hu\tryharddevs\advancedkits\kits\Session.java
|
package hu.tryharddevs.advancedkits.kits;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.UUID;
public class Session {
private static HashMap<UUID, Session> sessions = new HashMap<>();
private UUID uuid;
private ArrayList<ItemStack> kitItems = new ArrayList<>();
private ArrayList<ItemStack> kitArmors = new ArrayList<>();
private Session(UUID uuid) {
this.uuid = uuid;
}
public static Session getSession(UUID uuid) {
if (!sessions.containsKey(uuid)) {
Session sett = new Session(uuid);
sessions.put(uuid, sett);
return sett;
}
Session sett = sessions.get(uuid);
sett.setUUID(uuid);
return sett;
}
private void setUUID(UUID uuid) {
this.uuid = uuid;
}
public ArrayList<ItemStack> getKitItems() {
return kitItems;
}
public void addItems(ItemStack... itemStacks) {
Collections.addAll(kitItems, itemStacks);
}
public void addArmor(ItemStack... itemStacks) {
Collections.addAll(kitArmors, itemStacks);
}
public ArrayList<ItemStack> getKitArmors() {
return kitArmors;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.