Java Code Examples for org.bukkit.ChatColor#getLastColors()

The following examples show how to use org.bukkit.ChatColor#getLastColors() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CustomScoreBoard.java    From CombatLogX with GNU General Public License v3.0 6 votes vote down vote up
private void setLine(int line, String value) {
    CustomLine custom = getLine(line);
    Validate.notNull(custom, "Could not find scoreboard line with index '" + line + "'.");

    this.objective.getScore(custom.getColor().toString()).setScore(line);

    int maxLength = getMaxLineLength();
    int valueLength = value.length();
    if(valueLength > maxLength) {
        String part1 = value.substring(0, maxLength);
        String part2 = value.substring(maxLength);
        String colorCodes = ChatColor.getLastColors(part1);
        part2 = colorCodes + part2;
        if(part2.length() > maxLength) {
            part2 = part2.substring(0, maxLength);
        }

        custom.getTeam().setPrefix(part1);
        custom.getTeam().setSuffix(part2);
    } else custom.getTeam().setPrefix(value);
}
 
Example 2
Source File: AbstractScoreboardTeam.java    From ProtocolSupport with GNU Affero General Public License v3.0 6 votes vote down vote up
protected String formatLegacyClampedPrefix() {
	String prefix = this.prefix.toLegacyText(clientCache.getLocale());

	if ((format != ChatColor.RESET) && !prefix.isEmpty() && !isStringFormatOverride(prefix, format)) {
		prefix = format + prefix;
	}

	String prefixLastFormatString = ChatColor.getLastColors(prefix);
	String formatString = format.toString();
	if (
		(prefixLastFormatString.isEmpty() && (format != ChatColor.RESET)) ||
		!formatString.equals(prefixLastFormatString)
	) {
		if (format.isColor()) {
			return LegacyChat.clampLegacyText(prefix, NFIX_LIMIT_1F) + formatString;
		} else {
			return LegacyChat.clampLegacyText(prefix, NFIX_LIMIT_2F) + ChatColor.RESET + formatString;
		}
	}
	return LegacyChat.clampLegacyText(prefix, NFIX_LIMIT);
}
 
Example 3
Source File: AbstractScoreboardTeam.java    From ProtocolSupport with GNU Affero General Public License v3.0 6 votes vote down vote up
protected Any<String, String> formatDisplayLinePrefixSuffix() {
	String prefix = this.prefix.toLegacyText(clientCache.getLocale());

	if ((format != ChatColor.RESET) && !isStringFormatOverride(prefix, format)) {
		prefix = format + prefix;
	}

	if (prefix.length() <= NFIX_LIMIT) {
		return new Any<>(prefix, "");
	}

	int limit = prefix.charAt(NFIX_LIMIT_FCUT) == ChatColor.COLOR_CHAR ? NFIX_LIMIT_FCUT : NFIX_LIMIT;

	String sPrefix = prefix.substring(0, limit);

	String sSuffix = ChatColor.getLastColors(sPrefix) + prefix.substring(limit);
	if (!isStringFormatOverride(sSuffix, ChatColor.RESET)) {
		sSuffix = ChatColor.RESET + sSuffix;
	}
	sSuffix = LegacyChat.clampLegacyText(sSuffix, NFIX_LIMIT);

	return new Any<>(sPrefix, sSuffix);
}
 
Example 4
Source File: SidebarMatchModule.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
private void setRow(int maxScore, int row, @Nullable String text) {
  if (row < 0 || row >= MAX_ROWS) return;

  int score = text == null ? -1 : maxScore - row - 1;
  if (this.scores[row] != score) {
    this.scores[row] = score;

    if (score == -1) {
      this.scoreboard.resetScores(this.players[row]);
    } else {
      this.objective.getScore(this.players[row]).setScore(score);
    }
  }

  if (!Objects.equals(this.rows[row], text)) {
    this.rows[row] = text;

    if (text != null) {
      /*
       Split the row text into prefix and suffix, limited to 16 chars each. Because the player name
       is a color code, we have to restore the color at the split in the suffix. We also have to be
       careful not to split in the middle of a color code.
      */
      int split = MAX_PREFIX - 1; // Start by assuming there is a color code right on the split
      if (text.length() < MAX_PREFIX || text.charAt(split) != ChatColor.COLOR_CHAR) {
        // If there isn't, we can fit one more char in the prefix
        split++;
      }

      // Split and truncate the text, and restore the color in the suffix
      String prefix = StringUtils.substring(text, 0, split);
      String lastColors = ChatColor.getLastColors(prefix);
      String suffix =
          lastColors
              + StringUtils.substring(text, split, split + MAX_SUFFIX - lastColors.length());
      this.teams[row].setPrefix(prefix);
      this.teams[row].setSuffix(suffix);
    }
  }
}
 
Example 5
Source File: AssembleBoardEntry.java    From Assemble with GNU General Public License v3.0 5 votes vote down vote up
public void send(int position) {
	if (this.text.length() > 16) {
		String prefix = this.text.substring(0, 16);
		String suffix;

		if (prefix.charAt(15) == ChatColor.COLOR_CHAR) {
			prefix = prefix.substring(0, 15);
			suffix = this.text.substring(15, this.text.length());
		} else if (prefix.charAt(14) == ChatColor.COLOR_CHAR) {
			prefix = prefix.substring(0, 14);
			suffix = this.text.substring(14, this.text.length());
		} else {
			if (ChatColor.getLastColors(prefix).equalsIgnoreCase(ChatColor.getLastColors(this.identifier))) {
				suffix = this.text.substring(16, this.text.length());
			} else {
				suffix = ChatColor.getLastColors(prefix) + this.text.substring(16, this.text.length());
			}
		}

		if (suffix.length() > 16) {
			suffix = suffix.substring(0, 16);
		}

		this.team.setPrefix(prefix);
		this.team.setSuffix(suffix);
	} else {
		this.team.setPrefix(this.text);
		this.team.setSuffix("");
	}

	Score score = this.board.getObjective().getScore(this.identifier);
	score.setScore(position);
}
 
Example 6
Source File: SpigotUtils.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
private static String insertLastColorCodes(String s){
    String[] words = s.split(" ");

    StringBuilder sb = new StringBuilder();

    String lastColor = "";
    for (String word : words){
        word = lastColor + word;
        sb.append(word);
        sb.append(" ");
        lastColor = ChatColor.getLastColors(word);
    }

    return sb.toString();
}
 
Example 7
Source File: BukkitStringScoreboardLine.java    From VoxelGamesLibv2 with MIT License 5 votes vote down vote up
@Override
// thanks to this random gist https://gist.github.com/mkotb/d99eccdcc78a43ffb707
public void setValue(@Nonnull String value) {
    super.setValue(value);

    Iterator<String> iterator = Splitter.fixedLength(16).split(value).iterator();
    String prefix = iterator.next();

    team.setPrefix(prefix);

    if (!team.hasEntry(entry)) {
        team.addEntry(entry);
    }

    if (value.length() > 16) {
        String prefixColor = ChatColor.getLastColors(prefix);
        String suffix = iterator.next();

        if (prefix.endsWith(String.valueOf(ChatColor.COLOR_CHAR))) {
            prefix = prefix.substring(0, prefix.length() - 1);
            team.setPrefix(prefix);
            prefixColor = ChatColor.getByChar(suffix.charAt(0)).toString();
            suffix = suffix.substring(1);
        }

        if (prefixColor == null) {
            prefixColor = "";
        }

        if (suffix.length() > 15) {
            suffix = suffix.substring(0, (16 - Math.max(prefixColor.length(), ChatColor.RESET.toString()
                    .length()))); // cut off suffix, done if text is over 30 characters
        }

        team.setSuffix((prefixColor.equals("") ? ChatColor.RESET : prefixColor) + suffix);
    }
}
 
Example 8
Source File: UpdateScoreboardThread.java    From UhcCore with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
	if (!uhcPlayer.isOnline()){
		return;
	}

	if (!scoreboardType.equals(getScoreboardType())){
		scoreboardType = getScoreboardType();
		resetObjective();
		scoreboardManager.updatePlayerTab(uhcPlayer);
	}

	int i = 0;
	for (String line : scoreboardLayout.getLines(scoreboardType)){

		String first = "";
		String second = "";

		if (!line.isEmpty()) {

			String translatedLine = scoreboardManager.translatePlaceholders(line, uhcPlayer, bukkitPlayer, scoreboardType);

			if (translatedLine.length() <= 16){
				first = translatedLine;
			}else {

				int split = 16;

				first = translatedLine.substring(0, split);
				boolean copyColor = true;

				if (first.endsWith(COLOR_CHAR)){
					copyColor = false;
					split = 15;
					first = translatedLine.substring(0, split);

					if (first.substring(0, 14).endsWith(COLOR_CHAR)){
						split = 13;
						first = translatedLine.substring(0, split);
					}
				}

				if (copyColor) {
					second = ChatColor.getLastColors(first);
				}

				second += translatedLine.substring(split);

				if (second.length() > 16){
					Bukkit.getLogger().warning("[UhcCore] Scoreboard line is too long: '" + translatedLine + "'!");
					second = "";
				}
			}
		}

		Team lineTeam = scoreboard.getTeam(scoreboardManager.getScoreboardLine(i));

		if (!lineTeam.getPrefix().equals(first)){
			lineTeam.setPrefix(first);
		}
		if (!lineTeam.getSuffix().equals(second)){
			lineTeam.setSuffix(second);
		}

		i++;
	}

	Bukkit.getScheduler().scheduleSyncDelayedTask(UhcCore.getPlugin(),task, UPDATE_DELAY);
}
 
Example 9
Source File: PacketWrapper.java    From NametagEdit with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public PacketWrapper(String name, String prefix, String suffix, int param, Collection<?> players) {
    setupDefaults(name, param);
    if (param == 0 || param == 2) {
        try {            	            	
            if (PacketAccessor.isLegacyVersion()) {
                PacketAccessor.DISPLAY_NAME.set(packet, name);
                PacketAccessor.PREFIX.set(packet, prefix);
                PacketAccessor.SUFFIX.set(packet, suffix);
            } else {					
                String color = ChatColor.getLastColors(prefix);
                String colorCode = null;

                if (!color.isEmpty()) {						
                    colorCode = color.substring(color.length() - 1);
                    String chatColor = ChatColor.getByChar(colorCode).name();

                    if (chatColor.equalsIgnoreCase("MAGIC"))
                        chatColor = "OBFUSCATED";

                    Enum<?> colorEnum = Enum.valueOf(typeEnumChatFormat, chatColor);
                    PacketAccessor.TEAM_COLOR.set(packet, colorEnum);
                }

                PacketAccessor.DISPLAY_NAME.set(packet, ChatComponentText.newInstance(name));
                PacketAccessor.PREFIX.set(packet, ChatComponentText.newInstance(prefix));

                if (colorCode != null)
                    suffix = ChatColor.getByChar(colorCode) + suffix;

                PacketAccessor.SUFFIX.set(packet, ChatComponentText.newInstance(suffix));
            }

            PacketAccessor.PACK_OPTION.set(packet, 1);

            if (PacketAccessor.VISIBILITY != null) {
                PacketAccessor.VISIBILITY.set(packet, "always");
            }

            if (param == 0) {
                ((Collection) PacketAccessor.MEMBERS.get(packet)).addAll(players);
            }
        } catch (Exception e) {
            error = e.getMessage();
        }
    }
}
 
Example 10
Source File: ExcInfo.java    From FunnyGuilds with Apache License 2.0 4 votes vote down vote up
@Override
public void execute(CommandSender sender, String[] args) {
    MessageConfiguration messages = FunnyGuilds.getInstance().getMessageConfiguration();
    PluginConfiguration config = FunnyGuilds.getInstance().getPluginConfiguration();
    String tag = null;

    if (args.length > 0) {
        tag = args[0];
    } else if (sender instanceof Player) {
        User user = User.get((Player) sender);

        if (user.hasGuild()) {
            tag = user.getGuild().getTag();
        }
    }

    if (tag == null || tag.isEmpty()) {
        sender.sendMessage(messages.infoTag);
        return;
    }

    if (!GuildUtils.tagExists(tag)) {
        sender.sendMessage(messages.infoExists);
        return;
    }

    Guild guild = GuildUtils.getByTag(tag);

    if (guild == null) {
        sender.sendMessage(messages.infoExists);
        return;
    }

    String validity = config.dateFormat.format(new Date(guild.getValidity()));
    
    long now = System.currentTimeMillis();
    long protectionEndTime = guild.getProtectionEndTime();
    long additionalProtectionEndTime = guild.getAdditionalProtectionEndTime();

    for (String messageLine : messages.infoList) {
        messageLine = StringUtils.replace(messageLine, "{GUILD}", guild.getName());
        messageLine = StringUtils.replace(messageLine, "{TAG}", guild.getTag());
        messageLine = StringUtils.replace(messageLine, "{OWNER}", guild.getOwner().getName());
        messageLine = StringUtils.replace(messageLine, "{MEMBERS-ONLINE}", String.valueOf(guild.getOnlineMembers().size()));
        messageLine = StringUtils.replace(messageLine, "{MEMBERS-ALL}", String.valueOf(guild.getMembers().size()));
        messageLine = StringUtils.replace(messageLine, "{MEMBERS}", ChatUtils.toString(UserUtils.getOnlineNames(guild.getMembers()), true));
        messageLine = StringUtils.replace(messageLine, "{DEPUTIES}", guild.getDeputies().isEmpty() ? "Brak" : ChatUtils.toString(UserUtils.getNames(guild.getDeputies()), true));
        messageLine = StringUtils.replace(messageLine, "{REGION-SIZE}", config.regionsEnabled ? String.valueOf(guild.getRegion().getSize()) : messages.gRegionSizeNoValue);
        messageLine = StringUtils.replace(messageLine, "{GUILD-PROTECTION}", protectionEndTime < now ? "Brak" : TimeUtils.getDurationBreakdown(protectionEndTime - now));
        messageLine = StringUtils.replace(messageLine, "{GUILD-ADDITIONAL-PROTECTION}", additionalProtectionEndTime < now ? "Brak" : TimeUtils.getDurationBreakdown(additionalProtectionEndTime - now));

        Rank rank = guild.getRank();
        messageLine = StringUtils.replace(messageLine, "{POINTS-FORMAT}", IntegerRange.inRange(rank.getPoints(), config.pointsFormat, "POINTS"));
        messageLine = StringUtils.replace(messageLine, "{POINTS}", Integer.toString(rank.getPoints()));
        messageLine = StringUtils.replace(messageLine, "{KILLS}", Integer.toString(rank.getKills()));
        messageLine = StringUtils.replace(messageLine, "{DEATHS}", Integer.toString(rank.getDeaths()));
        messageLine = StringUtils.replace(messageLine, "{KDR}", String.format(Locale.US, "%.2f", rank.getKDR()));
        messageLine = StringUtils.replace(messageLine, "{VALIDITY}", validity);
        messageLine = StringUtils.replace(messageLine, "{LIVES}", Integer.toString(guild.getLives()));
        
        if (guild.getMembers().size() >= config.minMembersToInclude) {
            messageLine = StringUtils.replace(messageLine, "{RANK}", String.valueOf(rank.getPosition()));
        } else {
            messageLine = StringUtils.replace(messageLine, "{RANK}", messages.minMembersToIncludeNoValue);
        }
        
        if (!guild.getAllies().isEmpty()) {
            messageLine = StringUtils.replace(messageLine, "{ALLIES}", ChatUtils.toString(GuildUtils.getNames(guild.getAllies()), true));
            messageLine = StringUtils.replace(messageLine, "{ALLIES-TAGS}", ChatUtils.toString(GuildUtils.getTags(guild.getAllies()), true));
        } else {
            messageLine = StringUtils.replace(messageLine, "{ALLIES}", messages.alliesNoValue);
            messageLine = StringUtils.replace(messageLine, "{ALLIES-TAGS}", messages.alliesNoValue);
        }
        
        if (messageLine.contains("<online>")) {
            String color = ChatColor.getLastColors(messageLine.split("<online>")[0]);
            messageLine = StringUtils.replace(messageLine, "<online>", ChatColor.GREEN + "");
            messageLine = StringUtils.replace(messageLine, "</online>", color);
        }
        
        sender.sendMessage(messageLine);
    }
}