net.kyori.text.format.TextDecoration Java Examples

The following examples show how to use net.kyori.text.format.TextDecoration. 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: PlayerComponent.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
static TextComponent.Builder formatTab(Player player, @Nullable Player viewer) {
  TextComponent.Builder prefix = getPrefixComponent(player);
  TextComponent.Builder colorName = formatColor(player);

  if (isDead(player)) {
    colorName.color(TextColor.DARK_GRAY);
  }

  if (isVanished(player)) {
    colorName = formatVanished(colorName);
  }

  if (viewer != null && player.equals(viewer)) {
    colorName.decoration(TextDecoration.BOLD, true);
  }

  return prefix.append(colorName);
}
 
Example #2
Source File: MapInfoImpl.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Component getStyledName(MapNameStyle style) {
  TextComponent.Builder name = TextComponent.builder(getName());

  if (style.isColor) name.color(TextColor.GOLD);
  if (style.isHighlight) name.decoration(TextDecoration.UNDERLINED, true);
  if (style.showAuthors) {
    return TranslatableComponent.of(
        "misc.authorship",
        TextColor.DARK_PURPLE,
        name.build(),
        TextFormatter.list(
            getAuthors().stream()
                .map(c -> c.getName(NameStyle.PLAIN).color(TextColor.RED))
                .collect(Collectors.toList()),
            TextColor.DARK_PURPLE));
  }

  return name.build();
}
 
Example #3
Source File: MapPoll.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
private Component getMapBookComponent(MatchPlayer viewer, MapInfo map) {
  boolean voted = votes.get(map).contains(viewer.getId());

  return TextComponent.builder()
      .append(
          voted ? SYMBOL_VOTED : SYMBOL_IGNORE, voted ? TextColor.DARK_GREEN : TextColor.DARK_RED)
      .append(
          TextComponent.of(" ").decoration(TextDecoration.BOLD, !voted)) // Fix 1px symbol diff
      .append(map.getName() + "\n", TextColor.GOLD, TextDecoration.BOLD)
      .hoverEvent(
          HoverEvent.showText(
              TextComponent.of(
                  map.getTags().stream().map(MapTag::toString).collect(Collectors.joining(" ")),
                  TextColor.YELLOW)))
      .clickEvent(ClickEvent.runCommand("/votenext -o " + map.getName()))
      .build();
}
 
Example #4
Source File: DeathMessageMatchModule.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void handleDeathBroadcast(MatchPlayerDeathEvent event) {
  if (!event.getMatch().isRunning()) return;

  DeathMessageBuilder builder = new DeathMessageBuilder(event, logger);
  Component message = builder.getMessage().color(TextColor.GRAY);

  for (MatchPlayer viewer : event.getMatch().getPlayers()) {
    switch (viewer.getSettings().getValue(SettingKey.DEATH)) {
      case DEATH_OWN:
        if (event.isInvolved(viewer)) {
          viewer.sendMessage(message);
        } else if (event.isTeamKill() && viewer.getBukkit().hasPermission(Permissions.STAFF)) {
          viewer.sendMessage(message.decoration(TextDecoration.ITALIC, true));
        }
        break;
      case DEATH_ALL:
        if (event.isInvolved(viewer)) {
          viewer.sendMessage(message.decoration(TextDecoration.BOLD, true));
        } else {
          viewer.sendMessage(message);
        }
        break;
    }
  }
}
 
Example #5
Source File: Carried.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
protected Component getMessage() {
  Component message;
  if (this.deniedByNet == null) {
    if (this.flag.getDefinition().getCarryMessage() != null) {
      message = this.flag.getDefinition().getCarryMessage();
    } else {
      message = TranslatableComponent.of("flag.carrying", this.flag.getComponentName());
    }

    return message.color(TextColor.AQUA).decoration(TextDecoration.BOLD, true);
  } else {
    if (this.deniedByNet.getDenyMessage() != null) {
      message = this.deniedByNet.getDenyMessage();
    } else if (this.deniedByFlag != null) {
      message =
          TranslatableComponent.of(
              "flag.captureDenied.byFlag",
              this.flag.getComponentName(),
              this.deniedByFlag.getComponentName());
    } else {
      message = TranslatableComponent.of("flag.captureDenied", this.flag.getComponentName());
    }

    return message.color(TextColor.RED).decoration(TextDecoration.BOLD, true);
  }
}
 
Example #6
Source File: MapPoll.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public void announceWinner(MatchPlayer viewer, MapInfo winner) {
  for (MapInfo pgmMap : votes.keySet())
    viewer.sendMessage(getMapChatComponent(viewer, pgmMap, pgmMap.equals(winner)));

  // Check if the winning map name's length suitable for the top title, otherwise subtitle
  boolean top = winner.getName().length() < TITLE_LENGTH_CUTOFF;
  Component mapName =
      winner.getStyledName(MapNameStyle.COLOR).decoration(TextDecoration.BOLD, true);

  viewer.showTitle(
      top ? mapName : TextComponent.empty(), top ? TextComponent.empty() : mapName, 5, 60, 5);
}
 
Example #7
Source File: FreeForAllTabEntry.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public BaseComponent getContent(TabView view) {
  Component content =
      TextComponent.builder()
          .append(String.valueOf(match.getParticipants().size()), TextColor.WHITE)
          .append("/", TextColor.DARK_GRAY)
          .append(String.valueOf(match.getMaxPlayers()), TextColor.GRAY)
          .append(" ")
          .append(
              TranslatableComponent.of(
                  "match.info.players", TextColor.YELLOW, TextDecoration.BOLD))
          .build();
  return TextTranslations.toBaseComponent(content, view.getViewer());
}
 
Example #8
Source File: TeamTabEntry.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public BaseComponent getContent(TabView view) {
  Component content =
      TextComponent.builder()
          .append(String.valueOf(team.getPlayers().size()), TextColor.WHITE)
          .append("/", TextColor.DARK_GRAY)
          .append(String.valueOf(team.getMaxPlayers()), TextColor.GRAY)
          .append(" ")
          .append(
              team.getShortName(), TextFormatter.convert(team.getColor()), TextDecoration.BOLD)
          .build();

  return TextTranslations.toBaseComponent(content, view.getViewer());
}
 
Example #9
Source File: Broadcast.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public Component format(Component message) {
  return TextComponent.builder()
      .append("[")
      .append(prefix)
      .append("] ")
      .append(
          message
              .color(TextColor.AQUA)
              .decoration(TextDecoration.BOLD, false)
              .decoration(TextDecoration.ITALIC, true))
      .colorIfAbsent(TextColor.GRAY)
      .decoration(TextDecoration.BOLD, true)
      .build();
}
 
Example #10
Source File: VanishManagerImpl.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
private void sendHotbarVanish(MatchPlayer player, boolean flashColor) {
  Component warning =
      TextComponent.of(" \u26a0 ", flashColor ? TextColor.YELLOW : TextColor.GOLD);
  Component vanish =
      TranslatableComponent.of("vanish.hotbar", TextColor.RED, TextDecoration.BOLD);
  Component message =
      TextComponent.builder().append(warning).append(vanish).append(warning).build();
  player.showHotbar(message);
}
 
Example #11
Source File: ReportCommand.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
private Component getUsername(UUID uuid, Match match) {
  MatchPlayer player = match.getPlayer(uuid);
  Component name =
      TranslatableComponent.of("misc.unknown", TextColor.AQUA, TextDecoration.ITALIC);
  if (match.getPlayer(uuid) != null) {
    name = player.getName(NameStyle.FANCY);
  } else {
    name =
        TextComponent.of(
            uuid.equals(targetUUID) ? getOfflineTargetName() : getOfflineSenderName(),
            TextColor.DARK_AQUA,
            TextDecoration.ITALIC);
  }
  return name;
}
 
Example #12
Source File: ModesPaginatedResult.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String format(ModeChangeCountdown countdown, int index) {
  String materialName = countdown.getMode().getPreformattedMaterialName();
  Duration timeFromStart = countdown.getMode().getAfter();

  StringBuilder builder = new StringBuilder();

  builder.append(ChatColor.GOLD).append(index + 1).append(". ");
  builder.append(ChatColor.LIGHT_PURPLE).append(materialName).append(" - ");
  builder.append(ChatColor.AQUA).append(TimeUtils.formatDuration(timeFromStart));

  if (countdown.getMatch().isRunning()) {
    builder
        .append(ChatColor.DARK_AQUA)
        .append(" (")
        .append(this.formatSingleCountdown(countdown))
        .append(')');
  }

  if (this.isExpired(countdown)) {
    return TextTranslations.translateLegacy(
        TextComponent.of(builder.toString()).decoration(TextDecoration.STRIKETHROUGH, true),
        null);
  } else {
    return builder.toString();
  }
}
 
Example #13
Source File: LangFormatter.java    From VoxelGamesLibv2 with MIT License 5 votes vote down vote up
@Nonnull
private static Optional<TextDecoration> resolveDecoration(@Nonnull String token) {
    try {
        return Optional.of(TextDecoration.valueOf(token.toUpperCase()));
    } catch (IllegalArgumentException ex) {
        return Optional.empty();
    }
}
 
Example #14
Source File: MapPoll.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
private Component getMapChatComponent(MatchPlayer viewer, MapInfo map, boolean winner) {
  boolean voted = votes.get(map).contains(viewer.getId());

  return TextComponent.builder()
      .append("[")
      .append(voted ? SYMBOL_VOTED : SYMBOL_IGNORE, voted ? TextColor.GREEN : TextColor.DARK_RED)
      .append(
          TextComponent.of(" ").decoration(TextDecoration.BOLD, !voted)) // Fix 1px symbol diff
      .append("" + countVotes(votes.get(map)), TextColor.YELLOW)
      .append("] ")
      .append(
          map.getStyledName(
              winner ? MapNameStyle.HIGHLIGHT_WITH_AUTHORS : MapNameStyle.COLOR_WITH_AUTHORS))
      .build();
}
 
Example #15
Source File: ClassCommand.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
@Command(
    aliases = {"class", "selectclass", "c", "cl"},
    desc = "Select your class")
public void classSelect(Match match, MatchPlayer player, @Nullable @Text String query) {
  final ClassMatchModule classes = getClasses(match);
  final PlayerClass currentClass = classes.getSelectedClass(player.getId());

  if (query == null) {
    player.sendMessage(
        TranslatableComponent.of("match.class.current", TextColor.GREEN)
            .append(TextComponent.space())
            .append(
                TextComponent.of(currentClass.getName(), TextColor.GOLD, TextDecoration.BOLD)));
    player.sendMessage(TranslatableComponent.of("match.class.view", TextColor.GOLD));
  } else {
    final PlayerClass newClass = StringUtils.bestFuzzyMatch(query, classes.getClasses(), 0.9);

    if (newClass == null) {
      throw TextException.of("match.class.notFound");
    }

    try {
      classes.setPlayerClass(player.getId(), newClass);
    } catch (IllegalStateException e) {
      throw TextException.of("match.class.sticky");
    }

    player.sendMessage(
        TranslatableComponent.of(
            "match.class.ok",
            TextColor.GREEN,
            TextComponent.of(newClass.getName(), TextColor.GOLD, TextDecoration.UNDERLINED)));
    if (player.isParticipating()) {
      player.sendMessage(TranslatableComponent.of("match.class.queue", TextColor.GREEN));
    }
  }
}
 
Example #16
Source File: MapCommand.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
private @Nullable Component formatContribution(Contributor contributor) {
  Component componentName = contributor.getName(NameStyle.FANCY);
  if (contributor.getContribution() == null) return componentName;
  return TextComponent.builder()
      .append(componentName)
      .append(" - ", TextColor.GRAY)
      .append(contributor.getContribution(), TextColor.GRAY, TextDecoration.ITALIC)
      .build();
}
 
Example #17
Source File: ObserverToolsMatchModule.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
private ItemStack createToolItem(MatchPlayer player) {
  ItemStack tool = new ItemStack(TOOL_MATERIAL);
  ItemMeta meta = tool.getItemMeta();
  Component displayName =
      TranslatableComponent.of("setting.displayName", TextColor.AQUA, TextDecoration.BOLD);
  Component lore = TranslatableComponent.of("setting.lore", TextColor.GRAY);
  meta.setDisplayName(TextTranslations.translateLegacy(displayName, player.getBukkit()));
  meta.setLore(Lists.newArrayList(TextTranslations.translateLegacy(lore, player.getBukkit())));
  meta.addItemFlags(ItemFlag.values());
  tool.setItemMeta(meta);
  return tool;
}
 
Example #18
Source File: SparkPlatform.java    From spark with GNU General Public License v3.0 5 votes vote down vote up
private void sendUsage(CommandResponseHandler sender) {
    sender.replyPrefixed(TextComponent.builder("")
            .append(TextComponent.of("spark", TextColor.WHITE))
            .append(TextComponent.space())
            .append(TextComponent.of("v" + getPlugin().getVersion(), TextColor.GRAY))
            .build()
    );
    for (Command command : this.commands) {
        String usage = "/" + getPlugin().getCommandName() + " " + command.aliases().get(0);
        ClickEvent clickEvent = ClickEvent.suggestCommand(usage);
        sender.reply(TextComponent.builder("")
                .append(TextComponent.builder(">").color(TextColor.GOLD).decoration(TextDecoration.BOLD, true).build())
                .append(TextComponent.space())
                .append(TextComponent.builder(usage).color(TextColor.GRAY).clickEvent(clickEvent).build())
                .build()
        );
        for (Command.ArgumentInfo arg : command.arguments()) {
            if (arg.requiresParameter()) {
                sender.reply(TextComponent.builder("       ")
                        .append(TextComponent.of("[", TextColor.DARK_GRAY))
                        .append(TextComponent.of("--" + arg.argumentName(), TextColor.GRAY))
                        .append(TextComponent.space())
                        .append(TextComponent.of("<" + arg.parameterDescription() + ">", TextColor.DARK_GRAY))
                        .append(TextComponent.of("]", TextColor.DARK_GRAY))
                        .build()
                );
            } else {
                sender.reply(TextComponent.builder("       ")
                        .append(TextComponent.of("[", TextColor.DARK_GRAY))
                        .append(TextComponent.of("--" + arg.argumentName(), TextColor.GRAY))
                        .append(TextComponent.of("]", TextColor.DARK_GRAY))
                        .build()
                );
            }
        }
    }
}
 
Example #19
Source File: ActivityLogModule.java    From spark with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Collection<Component> renderRow(Activity activity, int index) {
    List<Component> reply = new ArrayList<>(5);
    reply.add(TextComponent.builder("")
            .append(TextComponent.builder(">").color(TextColor.DARK_GRAY).decoration(TextDecoration.BOLD, true).build())
            .append(TextComponent.space())
            .append(TextComponent.of("#" + (index + 1), TextColor.WHITE))
            .append(TextComponent.of(" - ", TextColor.DARK_GRAY))
            .append(TextComponent.of(activity.getType(), TextColor.YELLOW))
            .append(TextComponent.of(" - ", TextColor.DARK_GRAY))
            .append(TextComponent.of(formatDateDiff(activity.getTime()), TextColor.GRAY))
            .build()
    );
    reply.add(TextComponent.builder("  ")
            .append(TextComponent.of("Created by: ", TextColor.GRAY))
            .append(TextComponent.of(activity.getUser().getName(), TextColor.WHITE))
            .build()
    );

    TextComponent.Builder valueComponent = TextComponent.builder(activity.getDataValue(), TextColor.WHITE);
    if (activity.getDataType().equals("url")) {
        valueComponent.clickEvent(ClickEvent.openUrl(activity.getDataValue()));
    }

    reply.add(TextComponent.builder("  ")
            .append(TextComponent.of(Character.toUpperCase(activity.getDataType().charAt(0)) + activity.getDataType().substring(1) + ": ", TextColor.GRAY))
            .append(valueComponent)
            .build()
    );
    reply.add(TextComponent.space());
    return reply;
}
 
Example #20
Source File: VelocityCommand.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void execute(CommandSource source, String @NonNull [] args) {
  if (args.length != 0) {
    source.sendMessage(TextComponent.of("/velocity version", TextColor.RED));
    return;
  }

  ProxyVersion version = server.getVersion();

  TextComponent velocity = TextComponent.builder(version.getName() + " ")
      .decoration(TextDecoration.BOLD, true)
      .color(TextColor.DARK_AQUA)
      .append(TextComponent.of(version.getVersion()).decoration(TextDecoration.BOLD, false))
      .build();
  TextComponent copyright = TextComponent
      .of("Copyright 2018-2020 " + version.getVendor() + ". " + version.getName()
          + " is freely licensed under the terms of the MIT License.");
  source.sendMessage(velocity);
  source.sendMessage(copyright);

  if (version.getName().equals("Velocity")) {
    TextComponent velocityWebsite = TextComponent.builder()
        .content("Visit the ")
        .append(TextComponent.builder("Velocity website")
            .color(TextColor.GREEN)
            .clickEvent(
                ClickEvent.openUrl("https://www.velocitypowered.com"))
            .build())
        .append(TextComponent.of(" or the "))
        .append(TextComponent.builder("Velocity GitHub")
            .color(TextColor.GREEN)
            .clickEvent(ClickEvent.openUrl(
                "https://github.com/VelocityPowered/Velocity"))
            .build())
        .build();
    source.sendMessage(velocityWebsite);
  }
}
 
Example #21
Source File: ChatCaptureUtil.java    From GriefDefender with MIT License 5 votes vote down vote up
public Consumer<CommandSender> createChatSettingsConsumer(Player player, GDClaim claim, String command, Component returnComponent) {
    return settings -> {
        PaginationList.Builder paginationBuilder = PaginationList.builder()
                .title(TextComponent.of("RECORD-CHAT").color(TextColor.AQUA)).padding(TextComponent.of(" ").decoration(TextDecoration.STRIKETHROUGH, true)).contents(generateChatSettings(player, claim, command, returnComponent));
        paginationBuilder.sendTo(player);
    };
}
 
Example #22
Source File: CommandClaimInfo.java    From GriefDefender with MIT License 5 votes vote down vote up
public static Consumer<CommandSender> createSettingsConsumer(CommandSender src, Claim claim, List<Component> textList, ClaimType type) {
    return settings -> {
        Component name = type == ClaimTypes.TOWN ? MessageCache.getInstance().CLAIMINFO_UI_TOWN_SETTINGS : MessageCache.getInstance().CLAIMINFO_UI_ADMIN_SETTINGS;
        PaginationList.Builder paginationBuilder = PaginationList.builder()
                .title(name.color(TextColor.AQUA)).padding(TextComponent.of(" ").decoration(TextDecoration.STRIKETHROUGH, true)).contents(textList);
        paginationBuilder.sendTo(src);
    };
}
 
Example #23
Source File: CommandHelp.java    From GriefDefender with MIT License 5 votes vote down vote up
@HelpCommand
@Description("Displays GriefDefender command help.")
public void execute(CommandSender src) {
    PaginationList.Builder paginationBuilder =
            PaginationList.builder().title(TextComponent.of("Showing GriefDefender Help", TextColor.AQUA)).padding(TextComponent.of(" ").decoration(TextDecoration.STRIKETHROUGH, true)).contents(GriefDefenderPlugin.helpComponents);
    paginationBuilder.sendTo(src);
}
 
Example #24
Source File: ChatCaptureUtil.java    From GriefDefender with MIT License 5 votes vote down vote up
public Consumer<CommandSource> createChatSettingsConsumer(Player player, GDClaim claim, String command, Component returnComponent) {
    return settings -> {
        PaginationList.Builder paginationBuilder = PaginationList.builder()
                .title(TextComponent.of("RECORD-CHAT").color(TextColor.AQUA)).padding(TextComponent.of(" ").decoration(TextDecoration.STRIKETHROUGH, true)).contents(generateChatSettings(player, claim, command, returnComponent));
        paginationBuilder.sendTo(player);
    };
}
 
Example #25
Source File: MapTabEntry.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public BaseComponent getContent(TabView view) {
  final Component text =
      TranslatableComponent.of(
          "misc.authorship",
          TextColor.GRAY,
          TextComponent.of(map.getName(), TextColor.AQUA, TextDecoration.BOLD),
          TextFormatter.nameList(map.getAuthors(), NameStyle.FANCY, TextColor.GRAY));

  return TextTranslations.toBaseComponent(text, view.getViewer());
}
 
Example #26
Source File: CommandClaimInfo.java    From GriefDefender with MIT License 5 votes vote down vote up
public static Consumer<CommandSource> createSettingsConsumer(CommandSource src, Claim claim, List<Component> textList, ClaimType type) {
    return settings -> {
        Component name = type == ClaimTypes.TOWN ? MessageCache.getInstance().CLAIMINFO_UI_TOWN_SETTINGS : MessageCache.getInstance().CLAIMINFO_UI_ADMIN_SETTINGS;
        PaginationList.Builder paginationBuilder = PaginationList.builder()
                .title(name.color(TextColor.AQUA)).padding(TextComponent.of(" ").decoration(TextDecoration.STRIKETHROUGH, true)).contents(textList);
        paginationBuilder.sendTo(src);
    };
}
 
Example #27
Source File: CommandHelp.java    From GriefDefender with MIT License 5 votes vote down vote up
@HelpCommand
@Description("Displays GriefDefender command help.")
public void execute(CommandSource src) {
    PaginationList.Builder paginationBuilder =
            PaginationList.builder().title(TextComponent.of("Showing GriefDefender Help", TextColor.AQUA)).padding(TextComponent.of(" ").decoration(TextDecoration.STRIKETHROUGH, true)).contents(GriefDefenderPlugin.helpComponents);
    paginationBuilder.sendTo(src);
}
 
Example #28
Source File: TextFormatter.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Formats the provided text with a header that spans the chat window.
 *
 * @param sender Who is viewing the list
 * @param text The text to format
 * @param lineColor Color of the line
 * @param width length of the line
 * @return A formatted header
 */
public static Component horizontalLineHeading(
    CommandSender sender, Component text, TextColor lineColor, int width) {
  text = TextComponent.builder().append(" ").append(text).append(" ").build();
  int textWidth = LegacyFormatUtils.pixelWidth(TextTranslations.translateLegacy(text, sender));
  int spaceCount =
      Math.max(0, ((width - textWidth) / 2 + 1) / (LegacyFormatUtils.SPACE_PIXEL_WIDTH + 1));
  String line = Strings.repeat(" ", spaceCount);
  return TextComponent.builder()
      .append(line, lineColor, TextDecoration.STRIKETHROUGH)
      .append(text)
      .append(line, lineColor, TextDecoration.STRIKETHROUGH)
      .build();
}
 
Example #29
Source File: LangFormatter.java    From VoxelGamesLibv2 with MIT License 4 votes vote down vote up
@Nonnull
public static TextComponent parseFormat(@Nonnull String string) {
    //%replace%System.out.println("parse format " + string);
    TextComponent.Builder builder = TextComponent.builder("");
    TextComponent.Builder current = TextComponent.builder("");

    List<String> tokens = tokenize(string);
    //%replace%System.out.println(tokens);

    Stack<ClickEvent> clickEvents = new Stack<>();
    Stack<HoverEvent> hoverEvents = new Stack<>();
    Stack<TextColor> colors = new Stack<>();
    Stack<TextDecoration> decorations = new Stack<>();

    //%replace%System.out.println("enable parsing");
    for (String token : tokens) {
        // click
        if (token.startsWith("click")) {
            //%replace%System.out.println("add click " + token);
            clickEvents.push(handleClick(token));
        } else if (token.equals("/click")) {
            //%replace%System.out.println("end click");
            clickEvents.pop();
        }
        // hover
        else if (token.startsWith("hover")) {
            //%replace%System.out.println("add hover " + token);
            hoverEvents.push(handleHover(token));
        } else if (token.equals("/hover")) {
            //%replace%System.out.println("end hover");
            hoverEvents.pop();
        }
        // color
        else if (resolveColor(token).isPresent()) {
            //%replace%System.out.println("add color " + token);
            colors.push(handleColor(token));
        } else if (token.startsWith("/") && resolveColor(token.replace("/", "")).isPresent()) {
            //%replace%System.out.println("end color");
            colors.pop();
        }
        // decoration
        else if (resolveDecoration(token).isPresent()) {
            //%replace%System.out.println("add deco " + token);
            decorations.push(handleDecoration(token));
        } else if (token.startsWith("/") && resolveDecoration(token.replace("/", "")).isPresent()) {
            //%replace%System.out.println("end deco");
            decorations.pop();
        }
        // normal text
        else {
            if (token.equals("")) continue;

            // set everything that is not closed yet
            if (clickEvents.size() > 0) {
                //%replace%System.out.println("add extra click");
                current.clickEvent(clickEvents.peek());
            }
            if (hoverEvents.size() > 0) {
                //%replace%System.out.println("add extra hover");
                current.hoverEvent(hoverEvents.peek());
            }
            if (colors.size() > 0) {
                //%replace%System.out.println("add extra color");
                current.color(colors.peek());
            }
            if (decorations.size() > 0) {
                //%replace%System.out.println("add extra deco");
                current.decoration(decorations.peek(), true);
            }

            //%replace%System.out.println("add text " + token);
            // add to main builder and enable new component
            builder.append(current.content(token).build());
            current = TextComponent.builder();
        }
    }
    try {
        builder.append(current.build());
    } catch (IllegalStateException e) {
        builder.append(current.content("").build());
    }
    return builder.build();
}
 
Example #30
Source File: CommandClaimPermissionGroup.java    From GriefDefender with MIT License 4 votes vote down vote up
@CommandCompletion("@gdgroups @gddummy")
@CommandAlias("cpg")
@Description("Sets a permission on a group with a claim context.")
@Syntax("<group> [<permission> <value>]")
@Subcommand("permission group")
public void execute(Player player, String group, @Optional String[] args) throws CommandException, InvalidCommandArgument {
    String permission = null;
    String value = null;
    final GDPlayerData playerData = GriefDefenderPlugin.getInstance().dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId());
    if (args.length > 0) {
        if (args.length < 2) {
            throw new InvalidCommandArgument();
        }
        permission = args[0];
        if (!playerData.ignoreClaims && permission != null && !player.hasPermission(permission)) {
            GriefDefenderPlugin.sendMessage(player, MessageCache.getInstance().PERMISSION_ASSIGN_WITHOUT_HAVING);
            return;
        }

        value = args[1];
    }

    if (!PermissionUtil.getInstance().hasGroupSubject(group)) {
        GriefDefenderPlugin.sendMessage(player, GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.COMMAND_INVALID_GROUP));
        return;
    }

    final GDPermissionHolder subj = PermissionHolderCache.getInstance().getOrCreateHolder(group);
    GDClaim claim = GriefDefenderPlugin.getInstance().dataStore.getClaimAtPlayer(playerData, player.getLocation());
    final Component message = GriefDefenderPlugin.getInstance().messageData.getMessage(MessageStorage.PERMISSION_CLAIM_MANAGE,
            ImmutableMap.of(
            "type", claim.getType().getName()));
    if (claim.isWilderness() && !playerData.canManageWilderness) {
        GriefDefenderPlugin.sendMessage(player, message);
        return;
    } else if (claim.isAdminClaim() && !playerData.canManageAdminClaims) {
        GriefDefenderPlugin.sendMessage(player, message);
        return;
    }

    Set<Context> contexts = new HashSet<>();
    contexts.add(claim.getContext());
    if (permission == null || value == null) {
        List<Component> permList = Lists.newArrayList();
        Map<String, Boolean> permissions = PermissionUtil.getInstance().getPermissions(subj, contexts);
        for (Map.Entry<String, Boolean> permissionEntry : permissions.entrySet()) {
            Boolean permValue = permissionEntry.getValue();
            Component permText = TextComponent.builder("")
                    .append(permissionEntry.getKey(), TextColor.GREEN)
                    .append("  ")
                    .append(permValue.toString(), TextColor.GOLD).build();
            permList.add(permText);
        }

        List<Component> finalTexts = UIHelper.stripeText(permList);

        PaginationList.Builder paginationBuilder = PaginationList.builder()
                .title(TextComponent.of(subj.getFriendlyName() + " Permissions", TextColor.AQUA)).padding(TextComponent.of(" ").decoration(TextDecoration.STRIKETHROUGH, true)).contents(finalTexts);
        paginationBuilder.sendTo(player);
        return;
    }

    Tristate tristateValue = PermissionUtil.getInstance().getTristateFromString(value);
    if (tristateValue == null) {
        TextAdapter.sendComponent(player, TextComponent.of("Invalid value entered. '" + value + "' is not a valid value. Valid values are : true, false, undefined, 1, -1, or 0.", TextColor.RED));
        return;
    }

    PermissionUtil.getInstance().setPermissionValue(subj, permission, tristateValue, contexts);
    TextAdapter.sendComponent(player, TextComponent.builder("")
            .append("Set permission ")
            .append(permission, TextColor.AQUA)
            .append(" to ")
            .append(value, TextColor.GREEN)
            .append(" on group ")
            .append(subj.getFriendlyName(), TextColor.GOLD)
            .append(".").build());
}