Skip to content

Commit

Permalink
Hex pr 1820 (#1822)
Browse files Browse the repository at this point in the history
  • Loading branch information
tastybento authored Aug 19, 2021
1 parent e0d6e4d commit b906f55
Show file tree
Hide file tree
Showing 17 changed files with 105 additions and 34 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
import java.util.SortedMap;
import java.util.TreeMap;

import org.bukkit.ChatColor;
import org.bukkit.World;

import world.bentobox.bentobox.api.panels.Panel;
import world.bentobox.bentobox.api.panels.PanelItem;
import world.bentobox.bentobox.api.panels.PanelListener;
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.util.Util;


/**
* Builds panels
Expand All @@ -26,7 +27,7 @@ public class PanelBuilder {
private World world;

public PanelBuilder name(String name) {
this.name = ChatColor.translateAlternateColorCodes('&', name);
this.name = Util.translateColorCodes(name);
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
import java.util.Collections;
import java.util.List;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.eclipse.jdt.annotation.Nullable;

import world.bentobox.bentobox.api.panels.PanelItem;
import world.bentobox.bentobox.api.panels.PanelItem.ClickHandler;
import world.bentobox.bentobox.util.Util;


public class PanelItemBuilder {
private ItemStack icon = new ItemStack(Material.AIR);
Expand Down Expand Up @@ -59,7 +60,7 @@ public PanelItemBuilder icon(String playerName) {
}

public PanelItemBuilder name(@Nullable String name) {
this.name = name != null ? ChatColor.translateAlternateColorCodes('&', name) : null;
this.name = name != null ? Util.translateColorCodes(name) : null;
return this;
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/world/bentobox/bentobox/api/user/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ private String translate(String addonPrefix, String reference, String[] variable
translation = plugin.getPlaceholdersManager().replacePlaceholders(player, translation);
}

return Util.stripSpaceAfterColorCodes(ChatColor.translateAlternateColorCodes('&', translation));
return Util.translateColorCodes(translation);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import java.util.concurrent.CompletableFuture;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
Expand Down Expand Up @@ -414,7 +413,7 @@ private void writeSign(final Block block, final List<String> lines) {
// Get the addon that is operating in this world
String addonName = plugin.getIWM().getAddon(island.getWorld()).map(addon -> addon.getDescription().getName().toLowerCase(Locale.ENGLISH)).orElse("");
for (int i = 0; i < 4; i++) {
s.setLine(i, ChatColor.translateAlternateColorCodes('&', plugin.getLocalesManager().getOrDefault(User.getInstance(island.getOwner()),
s.setLine(i, Util.translateColorCodes(plugin.getLocalesManager().getOrDefault(User.getInstance(island.getOwner()),
addonName + ".sign.line" + i,"").replace(TextVariables.NAME, name)));
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import java.util.ArrayList;
import java.util.List;

import org.bukkit.ChatColor;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.Prompt;
import org.bukkit.conversations.StringPrompt;
Expand All @@ -13,6 +12,8 @@
import world.bentobox.bentobox.api.localization.TextVariables;
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.blueprints.dataobjects.BlueprintBundle;
import world.bentobox.bentobox.util.Util;


/**
* Collects a description
Expand Down Expand Up @@ -57,7 +58,7 @@ public Prompt acceptInput(ConversationContext context, String input) {
if (context.getSessionData(DESCRIPTION) != null) {
desc = ((List<String>) context.getSessionData(DESCRIPTION));
}
desc.add(ChatColor.translateAlternateColorCodes('&', input));
desc.add(Util.translateColorCodes(input));
context.setSessionData(DESCRIPTION, desc);
return this;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import world.bentobox.bentobox.blueprints.Blueprint;
import world.bentobox.bentobox.blueprints.dataobjects.BlueprintBundle;
import world.bentobox.bentobox.managers.BlueprintsManager;
import world.bentobox.bentobox.util.Util;


public class NamePrompt extends StringPrompt {

Expand Down Expand Up @@ -45,7 +47,7 @@ public String getPromptText(ConversationContext context) {
public Prompt acceptInput(ConversationContext context, String input) {
User user = User.getInstance((Player)context.getForWhom());
// Convert color codes
input = ChatColor.translateAlternateColorCodes('&', input);
input = Util.translateColorCodes(input);
if (ChatColor.stripColor(input).length() > 32) {
context.getForWhom().sendRawMessage("Too long");
return this;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
Expand Down Expand Up @@ -242,7 +241,7 @@ private PanelItem getSlotIcon(GameModeAddon addon, BlueprintBundle bb) {
protected PanelItem getBundleIcon(BlueprintBundle bb) {
return new PanelItemBuilder()
.name(t("edit-description"))
.description(bb.getDescription().stream().map(l -> ChatColor.translateAlternateColorCodes('&', l)).collect(Collectors.toList()))
.description(bb.getDescription().stream().map(Util::translateColorCodes).collect(Collectors.toList()))
.icon(bb.getIcon())
.clickHandler((panel, u, clickType, slot) -> {
u.closeInventory();
Expand Down Expand Up @@ -340,7 +339,7 @@ private PanelItem getNoPermissionIcon() {
protected PanelItem getBlueprintItem(GameModeAddon addon, int pos, BlueprintBundle bb, Blueprint blueprint) {
// Create description
List<String> desc = blueprint.getDescription() == null ? new ArrayList<>() : blueprint.getDescription();
desc = desc.stream().map(l -> ChatColor.translateAlternateColorCodes('&', l)).collect(Collectors.toList());
desc = desc.stream().map(Util::translateColorCodes).collect(Collectors.toList());
if ((!blueprint.equals(endBlueprint) && !blueprint.equals(normalBlueprint) && !blueprint.equals(netherBlueprint))) {
if ((pos > MIN_WORLD_SLOT && pos < MAX_WORLD_SLOT)) {
desc.add(t("remove"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import java.util.List;
import java.util.stream.Collectors;

import org.bukkit.ChatColor;
import org.eclipse.jdt.annotation.NonNull;

import world.bentobox.bentobox.BentoBox;
Expand All @@ -16,6 +15,8 @@
import world.bentobox.bentobox.api.user.User;
import world.bentobox.bentobox.blueprints.dataobjects.BlueprintBundle;
import world.bentobox.bentobox.managers.BlueprintsManager;
import world.bentobox.bentobox.util.Util;


/**
* Displays the available BlueprintBundles to pick up as the island.
Expand Down Expand Up @@ -49,7 +50,7 @@ public static void openPanel(@NonNull CompositeCommand command, @NonNull User us
// Add an item
PanelItem item = new PanelItemBuilder()
.name(bb.getDisplayName())
.description(bb.getDescription().stream().map(l -> ChatColor.translateAlternateColorCodes('&', l)).collect(Collectors.toList()))
.description(bb.getDescription().stream().map(Util::translateColorCodes).collect(Collectors.toList()))
.icon(bb.getIcon()).clickHandler((panel, user1, clickType, slot1) -> {
user1.closeInventory();
command.execute(user1, label, Collections.singletonList(bb.getUniqueId()));
Expand Down
45 changes: 44 additions & 1 deletion src/main/java/world/bentobox/bentobox/util/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import java.util.concurrent.CompletableFuture;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.commons.lang.Validate;
Expand Down Expand Up @@ -55,7 +57,10 @@
* @author Poslovitch
*/
public class Util {

/**
* Use standard color code definition: &<hex>.
*/
private static final Pattern HEX_PATTERN = Pattern.compile("&#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})");
private static final String NETHER = "_nether";
private static final String THE_END = "_the_end";
private static String serverVersion = null;
Expand Down Expand Up @@ -523,6 +528,44 @@ private static boolean isJUnitTest() {
return false;
}


/**
* This method translates color codes in given string and strips whitespace after them.
* This code parses both: hex and old color codes.
* @param textToColor Text which color codes must be parsed.
* @return String text with parsed colors and stripped whitespaces after them.
*/
@NonNull
public static String translateColorCodes(@NonNull String textToColor) {
// Use matcher to find hex patterns in given text.
Matcher matcher = HEX_PATTERN.matcher(textToColor);
// Increase buffer size by 32 like it is in bungee cord api. Use buffer because it is sync.
StringBuffer buffer = new StringBuffer(textToColor.length() + 32);

while (matcher.find()) {
String group = matcher.group(1);

if (group.length() == 6) {
// Parses #ffffff to a color text.
matcher.appendReplacement(buffer, ChatColor.COLOR_CHAR + "x"
+ ChatColor.COLOR_CHAR + group.charAt(0) + ChatColor.COLOR_CHAR + group.charAt(1)
+ ChatColor.COLOR_CHAR + group.charAt(2) + ChatColor.COLOR_CHAR + group.charAt(3)
+ ChatColor.COLOR_CHAR + group.charAt(4) + ChatColor.COLOR_CHAR + group.charAt(5));
} else {
// Parses #fff to a color text.
matcher.appendReplacement(buffer, ChatColor.COLOR_CHAR + "x"
+ ChatColor.COLOR_CHAR + group.charAt(0) + ChatColor.COLOR_CHAR + group.charAt(0)
+ ChatColor.COLOR_CHAR + group.charAt(1) + ChatColor.COLOR_CHAR + group.charAt(1)
+ ChatColor.COLOR_CHAR + group.charAt(2) + ChatColor.COLOR_CHAR + group.charAt(2));
}
}

// transform normal codes and strip spaces after color code.
return Util.stripSpaceAfterColorCodes(
ChatColor.translateAlternateColorCodes('&', matcher.appendTail(buffer).toString()));
}


/**
* Strips spaces immediately after color codes. Used by {@link User#getTranslation(String, String...)}.
* @param textToStrip - text to strip
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ public void setUp() throws Exception {

// Locales
LocalesManager lm = mock(LocalesManager.class);
when(lm.get(Mockito.any(), Mockito.any())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(1, String.class));
when(lm.get(any(), any())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(1, String.class));
when(plugin.getLocalesManager()).thenReturn(lm);
// Return the same string
PlaceholdersManager phm = mock(PlaceholdersManager.class);
Expand All @@ -172,8 +172,8 @@ public void setUp() throws Exception {
// Notifier
when(plugin.getNotifier()).thenReturn(notifier);

// Util strip spaces
when(Util.stripSpaceAfterColorCodes(anyString())).thenCallRealMethod();
// Util translate color codes (used in user translate methods)
when(Util.translateColorCodes(anyString())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(0, String.class));

// Command
igc = new IslandGoCommand(ic);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,10 +194,10 @@ public void setUp() throws Exception {
// Util
PowerMockito.mockStatic(Util.class);
when(Util.getWorld(any())).thenReturn(world);
when(Util.stripSpaceAfterColorCodes(anyString())).thenCallRealMethod();
// Util translate color codes (used in user translate methods)
when(Util.translateColorCodes(anyString())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(0, String.class));

// user text

LocalesManager lm = mock(LocalesManager.class);
when(plugin.getLocalesManager()).thenReturn(lm);
when(lm.get(any(), anyString())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(1, String.class));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,8 @@ public void setUp() throws Exception {
// Block
when(block.getLocation()).thenReturn(location);

// Util strip spaces
when(Util.stripSpaceAfterColorCodes(anyString())).thenCallRealMethod();
// Util translate color codes (used in user translate methods)
when(Util.translateColorCodes(anyString())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(0, String.class));

// Set up class
ssp = new StandardSpawnProtectionListener(plugin);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,8 @@ public void setUp() throws Exception {

PowerMockito.mockStatic(Util.class);
when(Util.getWorld(any())).thenReturn(mock(World.class));
// Util strip spaces
when(Util.stripSpaceAfterColorCodes(anyString())).thenCallRealMethod();

// Util translate color codes (used in user translate methods)
when(Util.translateColorCodes(anyString())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(0, String.class));

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,8 @@ public void setUp() throws Exception {
// Addon
when(iwm.getAddon(any())).thenReturn(Optional.empty());

// Util strip spaces
when(Util.stripSpaceAfterColorCodes(anyString())).thenCallRealMethod();
// Util translate color codes (used in user translate methods)
when(Util.translateColorCodes(anyString())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(0, String.class));

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,8 @@ public void setUp() throws Exception {
// Flags
Flags.ENTER_EXIT_MESSAGES.setSetting(world, true);

// Util strip spaces
when(Util.stripSpaceAfterColorCodes(anyString())).thenCallRealMethod();
// Util translate color codes (used in user translate methods)
when(Util.translateColorCodes(anyString())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(0, String.class));
}

@After
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
Expand Down Expand Up @@ -127,6 +128,8 @@ public void setUp() throws Exception {
PowerMockito.mockStatic(Util.class);
when(Util.getWorld(any())).thenReturn(mock(World.class));
when(Util.prettifyText(anyString())).thenCallRealMethod();
// Util translate color codes (used in user translate methods)
when(Util.translateColorCodes(anyString())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(0, String.class));
FlagsManager fm = mock(FlagsManager.class);
Flag flag = mock(Flag.class);
when(flag.isSetForWorld(any())).thenReturn(false);
Expand Down
30 changes: 26 additions & 4 deletions src/test/java/world/bentobox/bentobox/util/UtilTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public void setUp() throws Exception {
when(phm.replacePlaceholders(any(), any())).thenAnswer((Answer<String>) invocation -> invocation.getArgument(1, String.class));

when(plugin.getLocalesManager()).thenReturn(lm);

}

@After
Expand Down Expand Up @@ -458,7 +458,7 @@ public void testRunCommandsConsoleCommandFail() {
Bukkit.dispatchCommand(sender, "replace tastybento");
verify(plugin).logError("Could not execute test command as console: replace tastybento");
}

/**
* Test for {@link Util#broadcast(String, String...)}
*/
Expand All @@ -468,14 +468,36 @@ public void testBroadcastStringStringNoPlayers() {
int result = Util.broadcast("test.key", TextVariables.DESCRIPTION, "hello");
assertEquals(0, result);
}

/**
* Test for {@link Util#broadcast(String, String...)}
*/
@Test
public void testBroadcastStringStringHasPerm() {
int result = Util.broadcast("test.key", TextVariables.DESCRIPTION, "hello");
assertEquals(11, result);


}

/**
* Test for {@link Util#translateColorCodes(String)}
*/
@Test
public void testTranslateColorCodesAmpersand() {
assertEquals("", Util.translateColorCodes(""));
assertEquals("abcdef ABCDEF", Util.translateColorCodes("abcdef ABCDEF"));
assertEquals("white space after ", Util.translateColorCodes("white space after "));
assertEquals("§ared color", Util.translateColorCodes("&a red color"));
assertEquals("§a big space", Util.translateColorCodes("&a big space"));
assertEquals("§ared color", Util.translateColorCodes("&ared color"));
assertEquals("§ared §bcolor §cgreen §fheheh", Util.translateColorCodes("&ared &bcolor &c green &f heheh"));
}

/**
* Test for {@link Util#translateColorCodes(String)}
*/
@Test
public void testTranslateColorCodesHex() {
assertEquals("§ared color", Util.translateColorCodes("&#ff0000 red color"));
}
}

0 comments on commit b906f55

Please sign in to comment.