Search in sources :

Example 6 with TextStyle

use of org.spongepowered.api.text.format.TextStyle in project Nucleus by NucleusPowered.

the class TextParsingUtils method createTextTemplateFragmentWithLinks.

public Tuples.NullableTuple<List<TextRepresentable>, Map<String, Function<CommandSource, Text>>> createTextTemplateFragmentWithLinks(String message) {
    Preconditions.checkNotNull(message, "message");
    if (message.isEmpty()) {
        return new Tuples.NullableTuple<>(Lists.newArrayList(Text.EMPTY), null);
    }
    Matcher m = enhancedUrlParser.matcher(message);
    if (!m.find()) {
        return new Tuples.NullableTuple<>(Lists.newArrayList(oldLegacy(message)), null);
    }
    Map<String, Function<CommandSource, Text>> args = Maps.newHashMap();
    List<TextRepresentable> texts = Lists.newArrayList();
    String remaining = message;
    StyleTuple st = TextParsingUtils.EMPTY;
    do {
        // We found a URL. We split on the URL that we have.
        String[] textArray = remaining.split(enhancedUrlParser.pattern(), 2);
        TextRepresentable first = Text.builder().color(st.colour).style(st.style).append(oldLegacy(textArray[0])).build();
        // Add this text to the list regardless.
        texts.add(first);
        // If we have more to do, shove it into the "remaining" variable.
        if (textArray.length == 2) {
            remaining = textArray[1];
        } else {
            remaining = null;
        }
        // Get the last colour & styles
        String colourMatch = m.group("colour");
        if (colourMatch != null && !colourMatch.isEmpty()) {
            // If there is a reset, explicitly do it.
            TextStyle reset = TextStyles.NONE;
            if (m.group("reset") != null) {
                reset = TextStyles.RESET;
            }
            first = Text.of(reset, oldLegacy(m.group("colour")));
        }
        st = getLastColourAndStyle(first, st);
        // Build the URL
        String whiteSpace = m.group("first");
        if (m.group("url") != null) {
            String url = m.group("url");
            texts.add(getTextForUrl(url, url, whiteSpace, st, m.group("options")));
        } else if (m.group("specialUrl") != null) {
            String url = m.group("sUrl");
            String msg = m.group("msg");
            texts.add(getTextForUrl(url, msg, whiteSpace, st, m.group("optionssurl")));
        } else {
            // Must be commands.
            String cmd = m.group("sCmd");
            String msg = m.group("sMsg");
            String optionList = m.group("optionsscmd");
            if (cmd.contains("{{subject}}")) {
                String arg = UUID.randomUUID().toString();
                args.put(arg, cs -> {
                    String command = cmd.replace("{{subject}}", cs.getName());
                    return getCmd(msg, command, optionList, whiteSpace);
                });
                texts.add(TextTemplate.arg(arg).color(st.colour).style(st.style).build());
            } else {
                texts.add(Text.of(st.colour, st.style, getCmd(msg, cmd, optionList, whiteSpace)));
            }
        }
    } while (remaining != null && m.find());
    // Add the last bit.
    if (remaining != null) {
        Text.Builder tb = Text.builder().color(st.colour).style(st.style).append(TextSerializers.FORMATTING_CODE.deserialize(remaining));
        if (remaining.matches("^\\s+&r.*")) {
            tb.style(TextStyles.RESET);
        }
        texts.add(tb.build());
    }
    // Return the list.
    return new Tuples.NullableTuple<>(texts, args);
}
Also used : TextRepresentable(org.spongepowered.api.text.TextRepresentable) TextStyle(org.spongepowered.api.text.format.TextStyle) Arrays(java.util.Arrays) TextRepresentable(org.spongepowered.api.text.TextRepresentable) NucleusPlugin(io.github.nucleuspowered.nucleus.NucleusPlugin) URL(java.net.URL) TextTemplate(org.spongepowered.api.text.TextTemplate) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) Function(java.util.function.Function) CoreModule(io.github.nucleuspowered.nucleus.modules.core.CoreModule) CoreConfigAdapter(io.github.nucleuspowered.nucleus.modules.core.config.CoreConfigAdapter) Lists(com.google.common.collect.Lists) Matcher(java.util.regex.Matcher) Text(org.spongepowered.api.text.Text) TextColor(org.spongepowered.api.text.format.TextColor) Map(java.util.Map) HoverAction(org.spongepowered.api.text.action.HoverAction) TextColors(org.spongepowered.api.text.format.TextColors) Nullable(javax.annotation.Nullable) TextActions(org.spongepowered.api.text.action.TextActions) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) User(org.spongepowered.api.entity.living.player.User) Iterator(java.util.Iterator) CommandSource(org.spongepowered.api.command.CommandSource) MalformedURLException(java.net.MalformedURLException) TextStyles(org.spongepowered.api.text.format.TextStyles) UUID(java.util.UUID) Maps(com.google.common.collect.Maps) Consumer(java.util.function.Consumer) TextSerializers(org.spongepowered.api.text.serializer.TextSerializers) List(java.util.List) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) Tuples(io.github.nucleuspowered.nucleus.util.Tuples) Player(org.spongepowered.api.entity.living.player.Player) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Text(org.spongepowered.api.text.Text) Function(java.util.function.Function) TextStyle(org.spongepowered.api.text.format.TextStyle)

Example 7 with TextStyle

use of org.spongepowered.api.text.format.TextStyle in project Nucleus by NucleusPowered.

the class TextParsingUtils method getLastColourAndStyle.

public static StyleTuple getLastColourAndStyle(TextRepresentable text, @Nullable StyleTuple current) {
    List<Text> texts = flatten(text.toText());
    if (texts.isEmpty()) {
        return current == null ? new StyleTuple(TextColors.NONE, TextStyles.NONE) : current;
    }
    TextColor tc = TextColors.NONE;
    TextStyle ts = texts.get(texts.size() - 1).getStyle();
    for (int i = texts.size() - 1; i > -1; i--) {
        // If we have both a Text Colour and a Text Style, then break out.
        if (tc == TextColors.NONE) {
            tc = texts.get(i).getColor();
            break;
        }
    }
    if (current == null) {
        return new StyleTuple(tc, ts);
    }
    return new StyleTuple(tc != TextColors.NONE ? tc : current.colour, ts);
}
Also used : TextStyle(org.spongepowered.api.text.format.TextStyle) Text(org.spongepowered.api.text.Text) TextColor(org.spongepowered.api.text.format.TextColor)

Example 8 with TextStyle

use of org.spongepowered.api.text.format.TextStyle in project SpongeAPI by SpongePowered.

the class Text method of.

/**
 * Builds a {@link Text} from a given array of objects.
 *
 * <p>For instance, you can use this like
 * <code>Text.of(TextColors.DARK_AQUA, "Hi", TextColors.AQUA, "Bye")</code>
 * </p>
 *
 * <p>This will create the correct {@link Text} instance if the input object
 * is the input for one of the {@link Text} types or convert the object to a
 * string otherwise.</p>
 *
 * <p>For instances of type {@link TextRepresentable} (e.g. {@link Text},
 * {@link Builder}, ...) the formatting of appended text has priority over
 * the current formatting in the method, e.g. the following results in a
 * green, then yellow and at the end green again {@link Text}:</p>
 *
 * <code>Text.of(TextColors.GREEN, "Hello ", Text.of(TextColors.YELLOW,
 * "Spongie"), '!');</code>
 *
 * @param objects The object array
 * @return The built text object
 */
public static Text of(Object... objects) {
    // Shortcut for lonely TextRepresentables
    if (objects.length == 1 && objects[0] instanceof TextRepresentable) {
        return ((TextRepresentable) objects[0]).toText();
    }
    final Text.Builder builder = builder();
    TextFormat format = TextFormat.NONE;
    HoverAction<?> hoverAction = null;
    ClickAction<?> clickAction = null;
    ShiftClickAction<?> shiftClickAction = null;
    boolean changedFormat = false;
    for (Object obj : objects) {
        // Text formatting + actions
        if (obj instanceof TextFormat) {
            changedFormat = true;
            format = (TextFormat) obj;
        } else if (obj instanceof TextColor) {
            changedFormat = true;
            format = format.color((TextColor) obj);
        } else if (obj instanceof TextStyle) {
            changedFormat = true;
            format = format.style(obj.equals(TextStyles.RESET) ? TextStyles.NONE : format.getStyle().and((TextStyle) obj));
        } else if (obj instanceof TextAction) {
            changedFormat = true;
            if (obj instanceof HoverAction) {
                hoverAction = (HoverAction<?>) obj;
            } else if (obj instanceof ClickAction) {
                clickAction = (ClickAction<?>) obj;
            } else if (obj instanceof ShiftClickAction) {
                shiftClickAction = (ShiftClickAction<?>) obj;
            } else {
            // Unsupported TextAction
            }
        } else if (obj instanceof TextRepresentable) {
            // Special content
            changedFormat = false;
            Text.Builder childBuilder = ((TextRepresentable) obj).toText().toBuilder();
            // Merge format (existing format has priority)
            childBuilder.format(format.merge(childBuilder.format));
            // Overwrite text actions if *NOT* present
            if (childBuilder.clickAction == null) {
                childBuilder.clickAction = clickAction;
            }
            if (childBuilder.hoverAction == null) {
                childBuilder.hoverAction = hoverAction;
            }
            if (childBuilder.shiftClickAction == null) {
                childBuilder.shiftClickAction = shiftClickAction;
            }
            builder.append(childBuilder.build());
        } else {
            // Simple content
            changedFormat = false;
            Text.Builder childBuilder;
            if (obj instanceof String) {
                childBuilder = builder((String) obj);
            } else if (obj instanceof Translation) {
                childBuilder = builder((Translation) obj);
            } else if (obj instanceof Translatable) {
                childBuilder = builder(((Translatable) obj).getTranslation());
            } else if (obj instanceof Selector) {
                childBuilder = builder((Selector) obj);
            } else if (obj instanceof Score) {
                childBuilder = builder((Score) obj);
            } else {
                childBuilder = builder(String.valueOf(obj));
            }
            if (hoverAction != null) {
                childBuilder.onHover(hoverAction);
            }
            if (clickAction != null) {
                childBuilder.onClick(clickAction);
            }
            if (shiftClickAction != null) {
                childBuilder.onShiftClick(shiftClickAction);
            }
            builder.append(childBuilder.format(format).build());
        }
    }
    if (changedFormat) {
        // Did the formatting change without being applied to something?
        // Then just append an empty text with that formatting
        final Text.Builder childBuilder = builder();
        if (hoverAction != null) {
            childBuilder.onHover(hoverAction);
        }
        if (clickAction != null) {
            childBuilder.onClick(clickAction);
        }
        if (shiftClickAction != null) {
            childBuilder.onShiftClick(shiftClickAction);
        }
        builder.append(childBuilder.format(format).build());
    }
    if (builder.children.size() == 1) {
        // Single content, reduce Text depth
        return builder.children.get(0);
    }
    return builder.build();
}
Also used : Translation(org.spongepowered.api.text.translation.Translation) Translatable(org.spongepowered.api.text.translation.Translatable) TextAction(org.spongepowered.api.text.action.TextAction) Score(org.spongepowered.api.scoreboard.Score) HoverAction(org.spongepowered.api.text.action.HoverAction) TextStyle(org.spongepowered.api.text.format.TextStyle) ClickAction(org.spongepowered.api.text.action.ClickAction) ShiftClickAction(org.spongepowered.api.text.action.ShiftClickAction) ShiftClickAction(org.spongepowered.api.text.action.ShiftClickAction) TextFormat(org.spongepowered.api.text.format.TextFormat) TextColor(org.spongepowered.api.text.format.TextColor) Selector(org.spongepowered.api.text.selector.Selector)

Example 9 with TextStyle

use of org.spongepowered.api.text.format.TextStyle in project LanternServer by LanternPowered.

the class LegacyTexts method toLegacy.

private static StringBuilder toLegacy(StringBuilder builder, Locale locale, Text text, char legacyChar, Style base, Style applied) {
    if (legacyChar != 0) {
        final TextFormat format = text.getFormat();
        final TextColor color = format.getColor();
        final TextStyle style = format.getStyle();
        // Create a new style object
        final Style newStyle = base.copyTo(new Style());
        base = newStyle;
        if (color != TextColors.NONE) {
            newStyle.color = color == TextColors.RESET ? null : color;
        }
        style.isBold().ifPresent(value -> newStyle.bold = value);
        style.isItalic().ifPresent(value -> newStyle.italic = value);
        style.isObfuscated().ifPresent(value -> newStyle.obfuscated = value);
        style.hasUnderline().ifPresent(value -> newStyle.underlined = value);
        style.hasStrikethrough().ifPresent(value -> newStyle.strikethrough = value);
        if ((applied.color != null && newStyle.color == null) || (applied.bold && !newStyle.bold) || (applied.italic && !newStyle.italic) || (applied.obfuscated && !newStyle.obfuscated) || (applied.underlined && !newStyle.underlined) || (applied.strikethrough && !newStyle.strikethrough)) {
            builder.append(legacyChar).append(TextConstants.RESET);
            if (newStyle.color != null) {
                builder.append(legacyChar).append(((FormattingCodeHolder) newStyle.color).getCode());
            }
            if (newStyle.bold) {
                builder.append(legacyChar).append(TextConstants.BOLD);
            }
            if (newStyle.italic) {
                builder.append(legacyChar).append(TextConstants.ITALIC);
            }
            if (newStyle.obfuscated) {
                builder.append(legacyChar).append(TextConstants.OBFUSCATED);
            }
            if (newStyle.underlined) {
                builder.append(legacyChar).append(TextConstants.UNDERLINE);
            }
            if (newStyle.strikethrough) {
                builder.append(legacyChar).append(TextConstants.STRIKETHROUGH);
            }
        } else {
            if (applied.color != newStyle.color) {
                builder.append(legacyChar).append(((FormattingCodeHolder) newStyle.color).getCode());
            }
            if (applied.bold != newStyle.bold) {
                builder.append(legacyChar).append(TextConstants.BOLD);
            }
            if (applied.italic != newStyle.italic) {
                builder.append(legacyChar).append(TextConstants.ITALIC);
            }
            if (applied.obfuscated != newStyle.obfuscated) {
                builder.append(legacyChar).append(TextConstants.OBFUSCATED);
            }
            if (applied.underlined != newStyle.underlined) {
                builder.append(legacyChar).append(TextConstants.UNDERLINE);
            }
            if (applied.strikethrough != newStyle.strikethrough) {
                builder.append(legacyChar).append(TextConstants.STRIKETHROUGH);
            }
        }
        newStyle.copyTo(applied);
    }
    if (text instanceof LiteralText) {
        builder.append(((LiteralText) text).getContent());
    } else if (text instanceof SelectorText) {
        builder.append(((SelectorText) text).getSelector().toPlain());
    } else if (text instanceof TranslatableText) {
        final TranslatableText text0 = (TranslatableText) text;
        final Translation translation = text0.getTranslation();
        final ImmutableList<Object> args = text0.getArguments();
        final Object[] args0 = new Object[args.size()];
        for (int i = 0; i < args0.length; i++) {
            Object object = args.get(i);
            if (object instanceof Text || object instanceof Text.Builder || object instanceof TextRepresentable) {
                if (object instanceof Text) {
                // Ignore
                } else if (object instanceof Text.Builder) {
                    object = ((Text.Builder) object).build();
                } else {
                    object = ((TextRepresentable) object).toText();
                }
                args0[i] = toLegacy(new StringBuilder(), locale, (Text) object, legacyChar, base, applied).toString();
            } else {
                args0[i] = object;
            }
        }
        builder.append(translation.get(locale, args0));
    } else if (text instanceof ScoreText) {
        final ScoreText text0 = (ScoreText) text;
        final Optional<String> override = text0.getOverride();
        if (override.isPresent()) {
            builder.append(override.get());
        } else {
            builder.append(text0.getScore().getScore());
        }
    }
    for (Text child : text.getChildren()) {
        toLegacy(builder, locale, child, legacyChar, base, applied);
    }
    return builder;
}
Also used : TranslatableText(org.spongepowered.api.text.TranslatableText) TextRepresentable(org.spongepowered.api.text.TextRepresentable) SelectorText(org.spongepowered.api.text.SelectorText) Translation(org.spongepowered.api.text.translation.Translation) Optional(java.util.Optional) ScoreText(org.spongepowered.api.text.ScoreText) LiteralText(org.spongepowered.api.text.LiteralText) ScoreText(org.spongepowered.api.text.ScoreText) SelectorText(org.spongepowered.api.text.SelectorText) Text(org.spongepowered.api.text.Text) TranslatableText(org.spongepowered.api.text.TranslatableText) TextStyle(org.spongepowered.api.text.format.TextStyle) TextFormat(org.spongepowered.api.text.format.TextFormat) TextStyle(org.spongepowered.api.text.format.TextStyle) TextColor(org.spongepowered.api.text.format.TextColor) LiteralText(org.spongepowered.api.text.LiteralText)

Example 10 with TextStyle

use of org.spongepowered.api.text.format.TextStyle in project Nucleus by NucleusPowered.

the class NameUtil method getName.

/**
 * Gets the display name from a {@link User} as Sponge sees it.
 *
 * @param player The {@link User} to get the data from.
 * @return The {@link Text}
 */
public Text getName(User player) {
    Preconditions.checkNotNull(player);
    TextColor tc = getNameColour(player);
    TextStyle ts = getNameStyle(player);
    Optional<Text> dname = player.getPlayer().map(x -> x.get(Keys.DISPLAY_NAME).orElse(null));
    Text.Builder tb = null;
    if (plugin != null && plugin.isModuleLoaded(NicknameModule.ID)) {
        Optional<ModularUserService> userService = plugin.getUserDataManager().get(player);
        if (userService.isPresent()) {
            Optional<Text> n = userService.get().get(NicknameUserDataModule.class).getNicknameWithPrefix();
            if (n.isPresent()) {
                tb = n.get().toBuilder();
            }
        }
    } else if (dname.isPresent()) {
        tb = dname.get().toBuilder();
    }
    if (tb == null) {
        tb = Text.builder(player.getName());
    }
    tb.onHover(TextActions.showText(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("name.hover.ign", player.getName()))).build();
    if (tc != TextColors.NONE && tb.getColor() == TextColors.NONE) {
        List<Text> lt = tb.getChildren();
        if (lt.isEmpty() || lt.get(0).getColor().equals(TextColors.NONE)) {
            tb.color(tc);
        }
    }
    if (!ts.isEmpty()) {
        tb.style(ts);
    }
    return tb.build();
}
Also used : TextStyle(org.spongepowered.api.text.format.TextStyle) Text(org.spongepowered.api.text.Text) TextColor(org.spongepowered.api.text.format.TextColor) ModularUserService(io.github.nucleuspowered.nucleus.dataservices.modular.ModularUserService) NicknameUserDataModule(io.github.nucleuspowered.nucleus.modules.nickname.datamodules.NicknameUserDataModule)

Aggregations

TextStyle (org.spongepowered.api.text.format.TextStyle)10 TextColor (org.spongepowered.api.text.format.TextColor)8 Text (org.spongepowered.api.text.Text)6 JsonObject (com.google.gson.JsonObject)2 Optional (java.util.Optional)2 Matcher (java.util.regex.Matcher)2 ConfigurationNode (ninja.leaping.configurate.ConfigurationNode)2 TextRepresentable (org.spongepowered.api.text.TextRepresentable)2 HoverAction (org.spongepowered.api.text.action.HoverAction)2 ShiftClickAction (org.spongepowered.api.text.action.ShiftClickAction)2 TextFormat (org.spongepowered.api.text.format.TextFormat)2 Translation (org.spongepowered.api.text.translation.Translation)2 Preconditions (com.google.common.base.Preconditions)1 Lists (com.google.common.collect.Lists)1 Maps (com.google.common.collect.Maps)1 JsonElement (com.google.gson.JsonElement)1 JsonPrimitive (com.google.gson.JsonPrimitive)1 Nucleus (io.github.nucleuspowered.nucleus.Nucleus)1 NucleusPlugin (io.github.nucleuspowered.nucleus.NucleusPlugin)1 ModularUserService (io.github.nucleuspowered.nucleus.dataservices.modular.ModularUserService)1