Search in sources :

Example 1 with LanternTexts

use of org.lanternpowered.server.text.LanternTexts in project LanternServer by LanternPowered.

the class ItemStackStore method deserializeValues.

@Override
public void deserializeValues(LanternItemStack object, SimpleValueContainer valueContainer, DataView dataView) {
    final ItemTypeObjectSerializer serializer = this.itemTypeSerializers.get(object.getType());
    if (serializer != null) {
        serializer.deserializeValues(object, valueContainer, dataView);
    }
    final Optional<DataView> optDisplayView = dataView.getView(DISPLAY);
    if (optDisplayView.isPresent()) {
        final DataView displayView = optDisplayView.get();
        if (!valueContainer.get(Keys.DISPLAY_NAME).isPresent()) {
            Optional<String> name = displayView.getString(NAME);
            if (name.isPresent()) {
                valueContainer.set(Keys.DISPLAY_NAME, LanternTexts.fromLegacy(name.get()));
            } else if ((name = displayView.getString(LOCALIZED_NAME)).isPresent()) {
                valueContainer.set(Keys.DISPLAY_NAME, t(name.get()));
            }
        }
        dataView.getStringList(LORE).ifPresent(lore -> {
            if (!lore.isEmpty()) {
                valueContainer.set(Keys.ITEM_LORE, lore.stream().map(LanternTexts::fromLegacy).collect(Collectors.toList()));
            }
        });
    }
    dataView.getStringList(CAN_DESTROY).ifPresent(types -> {
        if (!types.isEmpty()) {
            final Set<BlockType> blockTypes = new HashSet<>();
            types.forEach(type -> BlockRegistryModule.get().getById(type).ifPresent(blockTypes::add));
            valueContainer.set(Keys.BREAKABLE_BLOCK_TYPES, blockTypes);
        }
    });
    deserializeEnchantments(dataView, ENCHANTMENTS, Keys.ITEM_ENCHANTMENTS, valueContainer);
    deserializeEnchantments(dataView, STORED_ENCHANTMENTS, Keys.STORED_ENCHANTMENTS, valueContainer);
    super.deserializeValues(object, valueContainer, dataView);
}
Also used : DataView(org.spongepowered.api.data.DataView) BlockType(org.spongepowered.api.block.BlockType) LanternTexts(org.lanternpowered.server.text.LanternTexts) HashSet(java.util.HashSet)

Example 2 with LanternTexts

use of org.lanternpowered.server.text.LanternTexts in project LanternServer by LanternPowered.

the class ScoreboardIO method read.

public static Scoreboard read(Path worldFolder) throws IOException {
    DataView dataView = IOHelper.<DataView>read(worldFolder.resolve(SCOREBOARD_DATA), file -> {
        try {
            return NbtStreamUtils.read(Files.newInputStream(file), true);
        } catch (IOException e) {
            throw new IOException("Unable to access " + file.getFileName() + "!", e);
        }
    }).orElse(null);
    final Scoreboard.Builder scoreboardBuilder = Scoreboard.builder();
    if (dataView == null) {
        return scoreboardBuilder.build();
    }
    final Map<String, Objective> objectives = new HashMap<>();
    dataView = dataView.getView(DATA).orElseThrow(() -> new IllegalStateException("Unable to find the data compound."));
    dataView.getViewList(OBJECTIVES).ifPresent(list -> list.forEach(entry -> {
        final String name = entry.getString(NAME).get();
        final Text displayName = LanternTexts.fromLegacy(entry.getString(DISPLAY_NAME).get());
        final Criterion criterion = Sponge.getRegistry().getType(Criterion.class, entry.getString(CRITERION_NAME).get()).orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a criterion with id: {}, default to dummy.", entry.getString(CRITERION_NAME).get());
            return Criteria.DUMMY;
        });
        final ObjectiveDisplayMode objectiveDisplayMode = Sponge.getRegistry().getType(ObjectiveDisplayMode.class, entry.getString(DISPLAY_MODE).get()).orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a display mode with id: {}, default to integer.", entry.getString(CRITERION_NAME).get());
            return ObjectiveDisplayModes.INTEGER;
        });
        objectives.put(name, Objective.builder().name(name).displayName(displayName).criterion(criterion).objectiveDisplayMode(objectiveDisplayMode).build());
    }));
    dataView.getViewList(SCORES).ifPresent(list -> list.forEach(entry -> {
        // We have to keep all the entries to remain compatible with vanilla mc.
        if (entry.getInt(INVALID).orElse(0) > 0) {
            return;
        }
        final Text name = LanternTexts.fromLegacy(entry.getString(NAME).get());
        final int value = entry.getInt(SCORE).get();
        // TODO
        final boolean locked = entry.getInt(LOCKED).orElse(0) > 0;
        final String objectiveName = entry.getString(OBJECTIVE).get();
        Score score = null;
        Objective objective = objectives.get(objectiveName);
        if (objective != null) {
            score = addToObjective(objective, null, name, value);
        }
        final List<String> extraObjectives = entry.getStringList(EXTRA_OBJECTIVES).orElse(null);
        if (extraObjectives != null) {
            for (String extraObjective : extraObjectives) {
                objective = objectives.get(extraObjective);
                if (objective != null) {
                    score = addToObjective(objective, score, name, value);
                }
            }
        }
    }));
    final List<Team> teams = new ArrayList<>();
    dataView.getViewList(TEAMS).ifPresent(list -> list.forEach(entry -> {
        final Team.Builder builder = Team.builder().allowFriendlyFire(entry.getInt(ALLOW_FRIENDLY_FIRE).orElse(0) > 0).canSeeFriendlyInvisibles(entry.getInt(CAN_SEE_FRIENDLY_INVISIBLES).orElse(0) > 0).name(entry.getString(NAME).get()).displayName(LanternTexts.fromLegacy(entry.getString(DISPLAY_NAME).get())).prefix(LanternTexts.fromLegacy(entry.getString(PREFIX).get())).suffix(LanternTexts.fromLegacy(entry.getString(SUFFIX).get())).members(entry.getStringList(MEMBERS).get().stream().map(LanternTexts::fromLegacy).collect(Collectors.toSet()));
        entry.getString(NAME_TAG_VISIBILITY).ifPresent(value -> builder.nameTagVisibility(Sponge.getRegistry().getAllOf(Visibility.class).stream().filter(visibility -> visibility.getName().equals(value)).findFirst().orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a name tag visibility with id: {}, default to always.", value);
            return Visibilities.ALWAYS;
        })));
        entry.getString(DEATH_MESSAGE_VISIBILITY).ifPresent(value -> builder.deathTextVisibility(Sponge.getRegistry().getAllOf(Visibility.class).stream().filter(visibility -> visibility.getName().equals(value)).findFirst().orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a death message visibility with id: {}, default to always.", value);
            return Visibilities.ALWAYS;
        })));
        entry.getString(COLLISION_RULE).ifPresent(value -> builder.collisionRule(Sponge.getRegistry().getAllOf(CollisionRule.class).stream().filter(visibility -> visibility.getName().equals(value)).findFirst().orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a collision rule with id: {}, default to never.", value);
            return CollisionRules.NEVER;
        })));
        entry.getString(TEAM_COLOR).ifPresent(color -> {
            TextColor textColor = Sponge.getRegistry().getType(TextColor.class, color).orElseGet(() -> {
                Lantern.getLogger().warn("Unable to find a team color with id: {}, default to none.", color);
                return TextColors.NONE;
            });
            if (textColor != TextColors.NONE && textColor != TextColors.RESET) {
                builder.color(textColor);
            }
        });
        teams.add(builder.build());
    }));
    final Scoreboard scoreboard = scoreboardBuilder.objectives(new ArrayList<>(objectives.values())).teams(teams).build();
    dataView.getView(DISPLAY_SLOTS).ifPresent(displaySlots -> {
        for (DataQuery key : displaySlots.getKeys(false)) {
            final Matcher matcher = DISPLAY_SLOT_PATTERN.matcher(key.getParts().get(0));
            if (matcher.matches()) {
                final int internalId = Integer.parseInt(matcher.group(1));
                Lantern.getRegistry().getRegistryModule(DisplaySlotRegistryModule.class).get().getByInternalId(internalId).ifPresent(slot -> {
                    final Objective objective = objectives.get(displaySlots.getString(key).get());
                    if (objective != null) {
                        scoreboard.updateDisplaySlot(objective, slot);
                    }
                });
            }
        }
    });
    return scoreboard;
}
Also used : CollisionRule(org.spongepowered.api.scoreboard.CollisionRule) Visibility(org.spongepowered.api.scoreboard.Visibility) HashMap(java.util.HashMap) LanternTexts(org.lanternpowered.server.text.LanternTexts) DataQuery(org.spongepowered.api.data.DataQuery) LanternObjective(org.lanternpowered.server.scoreboard.LanternObjective) ArrayList(java.util.ArrayList) ObjectiveDisplayMode(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayMode) NbtStreamUtils(org.lanternpowered.server.data.persistence.nbt.NbtStreamUtils) Matcher(java.util.regex.Matcher) Text(org.spongepowered.api.text.Text) TextColor(org.spongepowered.api.text.format.TextColor) Map(java.util.Map) Objective(org.spongepowered.api.scoreboard.objective.Objective) TextColors(org.spongepowered.api.text.format.TextColors) Path(java.nio.file.Path) Nullable(javax.annotation.Nullable) DisplaySlotRegistryModule(org.lanternpowered.server.game.registry.type.scoreboard.DisplaySlotRegistryModule) Iterator(java.util.Iterator) Files(java.nio.file.Files) Criterion(org.spongepowered.api.scoreboard.critieria.Criterion) Sponge(org.spongepowered.api.Sponge) DataContainer(org.spongepowered.api.data.DataContainer) Visibilities(org.spongepowered.api.scoreboard.Visibilities) Set(java.util.Set) LanternDisplaySlot(org.lanternpowered.server.scoreboard.LanternDisplaySlot) Scoreboard(org.spongepowered.api.scoreboard.Scoreboard) Team(org.spongepowered.api.scoreboard.Team) IOException(java.io.IOException) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) Collectors(java.util.stream.Collectors) Score(org.spongepowered.api.scoreboard.Score) Criteria(org.spongepowered.api.scoreboard.critieria.Criteria) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) List(java.util.List) DataView(org.spongepowered.api.data.DataView) CollisionRules(org.spongepowered.api.scoreboard.CollisionRules) Lantern(org.lanternpowered.server.game.Lantern) ObjectiveDisplayModes(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayModes) Pattern(java.util.regex.Pattern) LanternScoreboard(org.lanternpowered.server.scoreboard.LanternScoreboard) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) Scoreboard(org.spongepowered.api.scoreboard.Scoreboard) LanternScoreboard(org.lanternpowered.server.scoreboard.LanternScoreboard) Criterion(org.spongepowered.api.scoreboard.critieria.Criterion) ArrayList(java.util.ArrayList) List(java.util.List) Team(org.spongepowered.api.scoreboard.Team) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) DataQuery(org.spongepowered.api.data.DataQuery) TextColor(org.spongepowered.api.text.format.TextColor) ObjectiveDisplayMode(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayMode) CollisionRule(org.spongepowered.api.scoreboard.CollisionRule) Text(org.spongepowered.api.text.Text) IOException(java.io.IOException) DataView(org.spongepowered.api.data.DataView) LanternObjective(org.lanternpowered.server.scoreboard.LanternObjective) Objective(org.spongepowered.api.scoreboard.objective.Objective) Score(org.spongepowered.api.scoreboard.Score) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) DisplaySlotRegistryModule(org.lanternpowered.server.game.registry.type.scoreboard.DisplaySlotRegistryModule) Visibility(org.spongepowered.api.scoreboard.Visibility)

Example 3 with LanternTexts

use of org.lanternpowered.server.text.LanternTexts in project LanternServer by LanternPowered.

the class ScoreboardIO method write.

public static void write(Path folder, Scoreboard scoreboard) throws IOException {
    final List<DataView> objectives = scoreboard.getObjectives().stream().map(objective -> DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED).set(NAME, objective.getName()).set(DISPLAY_NAME, ((LanternObjective) objective).getLegacyDisplayName()).set(CRITERION_NAME, objective.getCriterion().getId()).set(DISPLAY_MODE, objective.getDisplayMode().getId())).collect(Collectors.toList());
    final List<DataView> scores = new ArrayList<>();
    for (Score score : scoreboard.getScores()) {
        final Iterator<Objective> it = score.getObjectives().iterator();
        final DataView baseView = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED).set(NAME, ((LanternScore) score).getLegacyName()).set(SCORE, score.getScore());
        // TODO: Locked state
        final DataView mainView = baseView.copy().set(OBJECTIVE, it.next().getName());
        final List<String> extraObjectives = new ArrayList<>();
        while (it.hasNext()) {
            final String extraObjectiveName = it.next().getName();
            scores.add(baseView.copy().set(OBJECTIVE, extraObjectiveName).set(INVALID, (byte) 1));
            extraObjectives.add(extraObjectiveName);
        }
        if (!extraObjectives.isEmpty()) {
            mainView.set(EXTRA_OBJECTIVES, extraObjectives);
        }
    }
    final List<DataView> teams = new ArrayList<>();
    for (Team team : scoreboard.getTeams()) {
        final DataView container = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED).set(ALLOW_FRIENDLY_FIRE, (byte) (team.allowFriendlyFire() ? 1 : 0)).set(CAN_SEE_FRIENDLY_INVISIBLES, (byte) (team.canSeeFriendlyInvisibles() ? 1 : 0)).set(NAME_TAG_VISIBILITY, team.getNameTagVisibility().getName()).set(NAME, team.getName()).set(DISPLAY_NAME, ((LanternTeam) team).getLegacyDisplayName()).set(DEATH_MESSAGE_VISIBILITY, team.getDeathMessageVisibility().getName()).set(COLLISION_RULE, team.getCollisionRule().getName()).set(PREFIX, ((LanternTeam) team).getLegacyPrefix()).set(SUFFIX, ((LanternTeam) team).getLegacySuffix());
        final TextColor teamColor = team.getColor();
        if (teamColor != TextColors.NONE) {
            container.set(TEAM_COLOR, teamColor.getId());
        }
        final Set<Text> members = team.getMembers();
        container.set(MEMBERS, members.stream().map(LanternTexts::toLegacy).collect(Collectors.toList()));
        teams.add(container);
    }
    final DataContainer rootDataContainer = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
    final DataView dataView = rootDataContainer.createView(DATA).set(OBJECTIVES, objectives).set(SCORES, scores).set(TEAMS, teams);
    final DataView displaySlots = dataView.createView(DISPLAY_SLOTS);
    ((LanternScoreboard) scoreboard).getObjectivesInSlot().entrySet().forEach(entry -> displaySlots.set(DataQuery.of("slot_" + ((LanternDisplaySlot) entry.getKey()).getInternalId()), entry.getValue().getName()));
    IOHelper.write(folder.resolve(SCOREBOARD_DATA), file -> {
        NbtStreamUtils.write(rootDataContainer, Files.newOutputStream(file), true);
        return true;
    });
}
Also used : CollisionRule(org.spongepowered.api.scoreboard.CollisionRule) Visibility(org.spongepowered.api.scoreboard.Visibility) HashMap(java.util.HashMap) LanternTexts(org.lanternpowered.server.text.LanternTexts) DataQuery(org.spongepowered.api.data.DataQuery) LanternObjective(org.lanternpowered.server.scoreboard.LanternObjective) ArrayList(java.util.ArrayList) ObjectiveDisplayMode(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayMode) NbtStreamUtils(org.lanternpowered.server.data.persistence.nbt.NbtStreamUtils) Matcher(java.util.regex.Matcher) Text(org.spongepowered.api.text.Text) TextColor(org.spongepowered.api.text.format.TextColor) Map(java.util.Map) Objective(org.spongepowered.api.scoreboard.objective.Objective) TextColors(org.spongepowered.api.text.format.TextColors) Path(java.nio.file.Path) Nullable(javax.annotation.Nullable) DisplaySlotRegistryModule(org.lanternpowered.server.game.registry.type.scoreboard.DisplaySlotRegistryModule) Iterator(java.util.Iterator) Files(java.nio.file.Files) Criterion(org.spongepowered.api.scoreboard.critieria.Criterion) Sponge(org.spongepowered.api.Sponge) DataContainer(org.spongepowered.api.data.DataContainer) Visibilities(org.spongepowered.api.scoreboard.Visibilities) Set(java.util.Set) LanternDisplaySlot(org.lanternpowered.server.scoreboard.LanternDisplaySlot) Scoreboard(org.spongepowered.api.scoreboard.Scoreboard) Team(org.spongepowered.api.scoreboard.Team) IOException(java.io.IOException) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) Collectors(java.util.stream.Collectors) Score(org.spongepowered.api.scoreboard.Score) Criteria(org.spongepowered.api.scoreboard.critieria.Criteria) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) List(java.util.List) DataView(org.spongepowered.api.data.DataView) CollisionRules(org.spongepowered.api.scoreboard.CollisionRules) Lantern(org.lanternpowered.server.game.Lantern) ObjectiveDisplayModes(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayModes) Pattern(java.util.regex.Pattern) LanternScoreboard(org.lanternpowered.server.scoreboard.LanternScoreboard) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) ArrayList(java.util.ArrayList) Text(org.spongepowered.api.text.Text) DataView(org.spongepowered.api.data.DataView) LanternObjective(org.lanternpowered.server.scoreboard.LanternObjective) Objective(org.spongepowered.api.scoreboard.objective.Objective) Score(org.spongepowered.api.scoreboard.Score) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) DataContainer(org.spongepowered.api.data.DataContainer) LanternDisplaySlot(org.lanternpowered.server.scoreboard.LanternDisplaySlot) LanternTexts(org.lanternpowered.server.text.LanternTexts) LanternScoreboard(org.lanternpowered.server.scoreboard.LanternScoreboard) Team(org.spongepowered.api.scoreboard.Team) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) TextColor(org.spongepowered.api.text.format.TextColor) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam)

Example 4 with LanternTexts

use of org.lanternpowered.server.text.LanternTexts in project LanternServer by LanternPowered.

the class ItemStackStore method serializeValues.

@Override
public void serializeValues(LanternItemStack object, SimpleValueContainer valueContainer, DataView dataView) {
    final ItemTypeObjectSerializer serializer = this.itemTypeSerializers.get(object.getType());
    if (serializer != null) {
        serializer.serializeValues(object, valueContainer, dataView);
    }
    DataView displayView = null;
    final Optional<Text> optDisplayName = valueContainer.remove(Keys.DISPLAY_NAME);
    if (optDisplayName.isPresent()) {
        displayView = getOrCreateView(dataView, DISPLAY);
        final Text displayName = optDisplayName.get();
        if (displayName instanceof TranslatableText) {
            final TranslatableText name1 = (TranslatableText) displayName;
            // We can only do this for translatable text without any formatting
            if (name1.getArguments().isEmpty() && name1.getChildren().isEmpty() && name1.getStyle().isEmpty() && name1.getColor() == TextColors.NONE) {
                displayView.set(LOCALIZED_NAME, name1.getTranslation().getId());
            } else {
                displayView.set(NAME, LanternTexts.toLegacy(displayName));
            }
        } else {
            displayView.set(NAME, LanternTexts.toLegacy(displayName));
        }
    }
    final Optional<List<Text>> optLore = valueContainer.remove(Keys.ITEM_LORE);
    if (optLore.isPresent() && !optLore.get().isEmpty()) {
        if (displayView == null) {
            displayView = getOrCreateView(dataView, DISPLAY);
        }
        displayView.set(LORE, optLore.get().stream().map(LanternTexts::toLegacy).collect(Collectors.toList()));
    }
    if (valueContainer.remove(Keys.UNBREAKABLE).orElse(false)) {
        dataView.set(UNBREAKABLE, (byte) 1);
    }
    final Optional<Set<BlockType>> optBlockTypes = valueContainer.remove(Keys.BREAKABLE_BLOCK_TYPES);
    if (optBlockTypes.isPresent() && !optBlockTypes.get().isEmpty()) {
        dataView.set(CAN_DESTROY, optBlockTypes.get().stream().map(CatalogType::getId).collect(Collectors.toSet()));
    }
    valueContainer.remove(Keys.ITEM_ENCHANTMENTS).ifPresent(list -> serializeEnchantments(dataView, ENCHANTMENTS, list));
    valueContainer.remove(Keys.STORED_ENCHANTMENTS).ifPresent(list -> serializeEnchantments(dataView, STORED_ENCHANTMENTS, list));
    super.serializeValues(object, valueContainer, dataView);
}
Also used : TranslatableText(org.spongepowered.api.text.TranslatableText) DataView(org.spongepowered.api.data.DataView) CatalogType(org.spongepowered.api.CatalogType) Set(java.util.Set) HashSet(java.util.HashSet) LanternTexts(org.lanternpowered.server.text.LanternTexts) TranslatableText(org.spongepowered.api.text.TranslatableText) Text(org.spongepowered.api.text.Text) List(java.util.List) ArrayList(java.util.ArrayList)

Example 5 with LanternTexts

use of org.lanternpowered.server.text.LanternTexts in project LanternServer by LanternPowered.

the class CommandScoreboard method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.arguments(GenericArguments.flags().valueFlag(GenericArguments.world(CommandHelper.WORLD_KEY), "-world", "w").buildWith(GenericArguments.none())).child(CommandSpec.builder().child(CommandSpec.builder().executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        final Set<Objective> objectives = scoreboard.getObjectives();
        if (objectives.isEmpty()) {
            throw new CommandException(t("commands.scoreboard.objectives.list.empty"));
        }
        src.sendMessage(tb("commands.scoreboard.objectives.list.count", objectives.size()).color(TextColors.DARK_GREEN).build());
        objectives.forEach(objective -> src.sendMessage(t("commands.scoreboard.objectives.list.entry", objective.getName(), objective.getDisplayName(), objective.getCriterion().getName())));
        return CommandResult.success();
    }).build(), "list").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("name")), GenericArguments.catalogedElement(Text.of("criterion"), Criterion.class), GenericArguments.flags().valueFlag(GenericArguments.catalogedElement(Text.of("display-mode"), ObjectiveDisplayMode.class), "-display-mode", "-dm", "d").buildWith(GenericArguments.none()), GenericArguments2.remainingString(Text.of("display-name"))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        final String name = args.<String>getOne("name").get();
        final Criterion criterion = args.<Criterion>getOne("criterion").get();
        if (scoreboard.getObjective(name).isPresent()) {
            throw new CommandException(t("commands.scoreboard.objectives.add.alreadyExists", name));
        }
        if (name.length() > 16) {
            throw new CommandException(t("commands.scoreboard.objectives.add.tooLong", name, 16));
        }
        String displayName = args.<String>getOne("display-name").orElse(null);
        if (displayName != null && displayName.length() > 32) {
            throw new CommandException(t("commands.scoreboard.objectives.add.displayTooLong", displayName, 32));
        }
        Objective.Builder builder = Objective.builder().name(name).criterion(criterion);
        if (displayName != null && !displayName.isEmpty()) {
            builder.displayName(Text.of(displayName));
        }
        args.<ObjectiveDisplayMode>getOne("display-mode").ifPresent(builder::objectiveDisplayMode);
        scoreboard.addObjective(builder.build());
        src.sendMessage(t("commands.scoreboard.objectives.add.success", name));
        return CommandResult.success();
    }).build(), "add").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("name"))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        final String name = args.<String>getOne("name").get();
        scoreboard.removeObjective(scoreboard.getObjective(name).orElseThrow(() -> new CommandException(t("commands.scoreboard.objectiveNotFound", name))));
        src.sendMessage(t("commands.scoreboard.objectives.remove.success", name));
        return CommandResult.success();
    }).build(), "remove").child(CommandSpec.builder().arguments(GenericArguments.catalogedElement(Text.of("display-slot"), DisplaySlot.class), GenericArguments.optional(GenericArguments.string(Text.of("name")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        final Optional<String> optName = args.<String>getOne("name");
        DisplaySlot displaySlot = args.<DisplaySlot>getOne("display-slot").get();
        Objective objective = null;
        if (optName.isPresent()) {
            final String name = optName.get();
            objective = scoreboard.getObjective(name).orElseThrow(() -> new CommandException(t("commands.scoreboard.objectiveNotFound", name)));
            src.sendMessage(t("commands.scoreboard.objectives.setdisplay.successSet", displaySlot.getName(), name));
        } else {
            src.sendMessage(t("commands.scoreboard.objectives.setdisplay.successCleared", displaySlot.getName()));
        }
        scoreboard.updateDisplaySlot(objective, displaySlot);
        return CommandResult.success();
    }).build(), "setdisplay").build(), "objectives").child(CommandSpec.builder().child(CommandSpec.builder().arguments(GenericArguments.optional(GenericArguments.string(Text.of("target")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        int result;
        if (args.hasAny("target")) {
            String entity = args.<String>getOne("target").get();
            Set<Score> scores = scoreboard.getScores(Text.of(entity));
            if (scores.isEmpty()) {
                throw new CommandException(t("commands.scoreboard.players.list.player.empty"));
            }
            result = scores.size();
            src.sendMessage(tb("commands.scoreboard.players.list.player.count", result, entity).color(TextColors.DARK_GREEN).build());
            scores.forEach(score -> score.getObjectives().forEach(objective -> src.sendMessage(t("commands.scoreboard.players.list.player.entry", score.getScore(), objective.getDisplayName(), objective.getName()))));
        } else {
            Set<Text> names = scoreboard.getScores().stream().map(Score::getName).collect(Collectors.toSet());
            if (names.isEmpty()) {
                throw new CommandException(t("commands.scoreboard.players.list.empty"));
            }
            result = names.size();
            src.sendMessage(tb("commands.scoreboard.players.list.count", result).color(TextColors.DARK_GREEN).build());
            src.sendMessage(Text.joinWith(Text.of(", "), names));
        }
        return CommandResult.builder().successCount(1).queryResult(result).build();
    }).build(), "list").child(createPlayerScoreSpec(Score::setScore), "set").child(createPlayerScoreSpec((score, value) -> score.setScore(score.getScore() + value)), "add").child(createPlayerScoreSpec((score, value) -> score.setScore(score.getScore() - value)), "remove").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("target")), GenericArguments.optional(GenericArguments.string(Text.of("objective")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        String target = args.<String>getOne("target").get();
        if (args.hasAny("objective")) {
            String objectiveName = args.<String>getOne("objective").get();
            Objective objective = scoreboard.getObjective(objectiveName).orElseThrow(() -> new CommandException(t("commands.scoreboard.objectiveNotFound", objectiveName)));
            objective.removeScore(Text.of(target));
            src.sendMessage(t("commands.scoreboard.players.resetscore.success", objectiveName, target));
        } else {
            scoreboard.removeScores(Text.of(target));
            src.sendMessage(t("commands.scoreboard.players.reset.success", target));
        }
        return CommandResult.success();
    }).build(), "reset").build(), "players").child(CommandSpec.builder().child(CommandSpec.builder().arguments(GenericArguments.optional(GenericArguments.string(Text.of("name")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        int result;
        if (args.hasAny("name")) {
            String teamName = args.<String>getOne("name").get();
            Team team = scoreboard.getTeam(teamName).orElseThrow(() -> new CommandException(t("commands.scoreboard.teamNotFound", teamName)));
            Set<Text> members = team.getMembers();
            if (members.isEmpty()) {
                throw new CommandException(t("commands.scoreboard.teams.list.player.empty", teamName));
            }
            result = members.size();
            src.sendMessage(tb("commands.scoreboard.teams.list.player.count", result, teamName).color(TextColors.DARK_GREEN).build());
            src.sendMessage(Text.joinWith(Text.of(", "), members));
        } else {
            Set<Team> teams = scoreboard.getTeams();
            if (teams.isEmpty()) {
                throw new CommandException(t("commands.scoreboard.teams.list.empty"));
            }
            result = teams.size();
            src.sendMessage(tb("commands.scoreboard.teams.list.count", result).color(TextColors.DARK_GREEN).build());
            teams.forEach(team -> src.sendMessage(t("commands.scoreboard.teams.list.entry", team.getName(), team.getDisplayName(), team.getMembers().size())));
        }
        return CommandResult.builder().successCount(1).queryResult(result).build();
    }).build(), "list").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("name")), GenericArguments.optional(GenericArguments2.remainingString(Text.of("display-name")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        final String teamName = args.<String>getOne("name").get();
        if (scoreboard.getTeam(teamName).isPresent()) {
            throw new CommandException(t("commands.scoreboard.teams.add.alreadyExists", teamName));
        }
        if (teamName.length() > 16) {
            throw new CommandException(t("commands.scoreboard.teams.add.tooLong", teamName, 16));
        }
        String displayName = args.<String>getOne("display-name").orElse(null);
        if (displayName != null && displayName.length() > 32) {
            throw new CommandException(t("commands.scoreboard.teams.add.displayTooLong", displayName, 32));
        }
        Team.Builder teamBuilder = Team.builder().name(teamName);
        if (displayName != null && !displayName.isEmpty()) {
            teamBuilder.displayName(Text.of(displayName));
        }
        scoreboard.registerTeam(teamBuilder.build());
        src.sendMessage(t("commands.scoreboard.teams.add.success", teamName));
        return CommandResult.success();
    }).build(), "add").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("name"))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        String teamName = args.<String>getOne("name").get();
        final Team team = scoreboard.getTeam(teamName).orElseThrow(() -> new CommandException(t("commands.scoreboard.teamNotFound", teamName)));
        team.unregister();
        src.sendMessage(t("commands.scoreboard.teams.remove.success", teamName));
        return CommandResult.success();
    }).build(), "remove").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("name"))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        String teamName = args.<String>getOne("name").get();
        final Team team = scoreboard.getTeam(teamName).orElseThrow(() -> new CommandException(t("commands.scoreboard.teamNotFound", teamName)));
        Set<Text> members = team.getMembers();
        if (members.isEmpty()) {
            throw new CommandException(t("commands.scoreboard.teams.empty.alreadyEmpty", teamName));
        }
        int result = members.size();
        ((LanternTeam) team).removeMembers(members);
        src.sendMessage(t("commands.scoreboard.teams.empty.success", result, teamName));
        return CommandResult.builder().successCount(1).queryResult(result).build();
    }).build(), "empty").child(CommandSpec.builder().arguments(GenericArguments.optional(GenericArguments.string(Text.of("name"))), GenericArguments.optional(GenericArguments2.remainingStringArray(Text.of("players")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        String teamName = args.<String>getOne("name").orElse(null);
        final Team team = teamName == null ? null : scoreboard.getTeam(teamName).orElse(null);
        Set<Text> members = args.<String[]>getOne("players").map(array -> Arrays.stream(array).map(LanternTexts::fromLegacy).collect(Collectors.toSet())).orElse(new HashSet<>());
        // that wants to leave a team
        if (teamName != null && team == null) {
            members.add(LanternTexts.fromLegacy(teamName));
        }
        // If there are no members found, use the source if possible
        if (members.isEmpty() && src instanceof Player) {
            members.add(((Player) src).getTeamRepresentation());
        }
        // If there is a team specified, remove the members from a specific team
        Collection<Team> teams = team == null ? scoreboard.getTeams() : Collections.singleton(team);
        List<Text> failedMembers = null;
        for (Team team0 : teams) {
            List<Text> failedMembers0 = ((LanternTeam) team0).removeMembers(members);
            if (failedMembers == null) {
                failedMembers = failedMembers0;
            } else {
                failedMembers.retainAll(failedMembers0);
            }
        }
        if (failedMembers != null) {
            members.removeAll(failedMembers);
        }
        int result = members.size();
        if (result > 0) {
            src.sendMessage(t("commands.scoreboard.teams.leave.success", result, Text.joinWith(Text.of(", "), members)));
        }
        if (failedMembers != null && failedMembers.size() > 0) {
            src.sendMessage(error(t("commands.scoreboard.teams.leave.failure", failedMembers.size(), Text.joinWith(Text.of(", "), failedMembers))));
        }
        return CommandResult.builder().successCount(1).queryResult(result).build();
    }).build(), "leave").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("name")), GenericArguments.optional(GenericArguments2.remainingStringArray(Text.of("players")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        String teamName = args.<String>getOne("name").get();
        final Team team = scoreboard.getTeam(teamName).orElseThrow(() -> new CommandException(t("commands.scoreboard.teamNotFound", teamName)));
        Set<Text> members = args.<String[]>getOne("players").map(array -> Arrays.stream(array).map(LanternTexts::fromLegacy).collect(Collectors.toSet())).orElse(new HashSet<>());
        // If there are no members found, use the source if possible
        if (members.isEmpty() && src instanceof Player) {
            members.add(((Player) src).getTeamRepresentation());
        }
        List<Text> failedMembers = ((LanternTeam) team).addMembers(members);
        int result = members.size();
        if (result > 0) {
            src.sendMessage(t("commands.scoreboard.teams.join.success", result, teamName, Text.joinWith(Text.of(", "), members)));
        }
        if (failedMembers.size() > 0) {
            src.sendMessage(error(t("commands.scoreboard.teams.join.failure", failedMembers.size(), teamName, Text.joinWith(Text.of(", "), failedMembers))));
        }
        return CommandResult.builder().successCount(1).queryResult(result).build();
    }).build(), "join").build(), "teams");
}
Also used : Arrays(java.util.Arrays) LanternTexts(org.lanternpowered.server.text.LanternTexts) GenericArguments(org.spongepowered.api.command.args.GenericArguments) HashSet(java.util.HashSet) ObjectiveDisplayMode(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayMode) TranslationHelper.tb(org.lanternpowered.server.text.translation.TranslationHelper.tb) Text(org.spongepowered.api.text.Text) GenericArguments2(org.lanternpowered.server.command.element.GenericArguments2) BiConsumer(java.util.function.BiConsumer) Objective(org.spongepowered.api.scoreboard.objective.Objective) PluginContainer(org.spongepowered.api.plugin.PluginContainer) TextColors(org.spongepowered.api.text.format.TextColors) CommandResult(org.spongepowered.api.command.CommandResult) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) Criterion(org.spongepowered.api.scoreboard.critieria.Criterion) Collection(java.util.Collection) Set(java.util.Set) Scoreboard(org.spongepowered.api.scoreboard.Scoreboard) Team(org.spongepowered.api.scoreboard.Team) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) Collectors(java.util.stream.Collectors) DisplaySlot(org.spongepowered.api.scoreboard.displayslot.DisplaySlot) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) Score(org.spongepowered.api.scoreboard.Score) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) List(java.util.List) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) Collections(java.util.Collections) CommandMessageFormatting.error(org.spongepowered.api.command.CommandMessageFormatting.error) HashSet(java.util.HashSet) Set(java.util.Set) Scoreboard(org.spongepowered.api.scoreboard.Scoreboard) Criterion(org.spongepowered.api.scoreboard.critieria.Criterion) DisplaySlot(org.spongepowered.api.scoreboard.displayslot.DisplaySlot) Team(org.spongepowered.api.scoreboard.Team) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) List(java.util.List) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) HashSet(java.util.HashSet) Player(org.spongepowered.api.entity.living.player.Player) Text(org.spongepowered.api.text.Text) CommandException(org.spongepowered.api.command.CommandException) Objective(org.spongepowered.api.scoreboard.objective.Objective) Score(org.spongepowered.api.scoreboard.Score) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) LanternTexts(org.lanternpowered.server.text.LanternTexts) Collection(java.util.Collection)

Aggregations

LanternTexts (org.lanternpowered.server.text.LanternTexts)5 List (java.util.List)4 Set (java.util.Set)4 DataView (org.spongepowered.api.data.DataView)4 Text (org.spongepowered.api.text.Text)4 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 Collectors (java.util.stream.Collectors)3 LanternScore (org.lanternpowered.server.scoreboard.LanternScore)3 LanternTeam (org.lanternpowered.server.scoreboard.LanternTeam)3 Score (org.spongepowered.api.scoreboard.Score)3 Scoreboard (org.spongepowered.api.scoreboard.Scoreboard)3 Team (org.spongepowered.api.scoreboard.Team)3 Criterion (org.spongepowered.api.scoreboard.critieria.Criterion)3 Objective (org.spongepowered.api.scoreboard.objective.Objective)3 ObjectiveDisplayMode (org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayMode)3 TextColors (org.spongepowered.api.text.format.TextColors)3 IOException (java.io.IOException)2 Files (java.nio.file.Files)2 Path (java.nio.file.Path)2