Search in sources :

Example 1 with ClickEvent

use of com.sk89q.worldedit.util.formatting.text.event.ClickEvent in project FastAsyncWorldEdit by IntellectualSites.

the class RichPatternParser method parseFromInput.

@Override
public Pattern parseFromInput(String input, ParserContext context) throws InputParseException {
    if (input.isEmpty()) {
        throw new SuggestInputParseException("No input provided", "", () -> Stream.concat(Stream.of("#", ",", "&"), BlockTypes.getNameSpaces().stream().map(n -> n + ":")).collect(Collectors.toList()));
    }
    List<Double> chances = new ArrayList<>();
    List<Pattern> patterns = new ArrayList<>();
    final CommandLocals locals = new CommandLocals();
    Actor actor = context != null ? context.getActor() : null;
    if (actor != null) {
        locals.put(Actor.class, actor);
    }
    try {
        for (Map.Entry<ParseEntry, List<String>> entry : parse(input)) {
            ParseEntry pe = entry.getKey();
            final String command = pe.getInput();
            String full = pe.getFull();
            Pattern pattern = null;
            double chance = 1;
            if (command.isEmpty()) {
                pattern = parseFromInput(StringMan.join(entry.getValue(), ','), context);
            } else if (!worldEdit.getPatternFactory().containsAlias(command)) {
                // Legacy patterns
                char char0 = command.charAt(0);
                boolean charPattern = input.length() > 1 && input.charAt(1) != '[';
                if (charPattern && input.charAt(0) == '=') {
                    pattern = parseFromInput(char0 + "[" + input.substring(1) + "]", context);
                }
                if (char0 == '#' && command.length() > 1 && command.charAt(1) != '#') {
                    throw new SuggestInputParseException(new NoMatchException(Caption.of("fawe.error.parse.unknown-pattern", full, TextComponent.of("https://intellectualsites.github.io/fastasyncworldedit-documentation/patterns/patterns").clickEvent(ClickEvent.openUrl("https://intellectualsites.github.io/fastasyncworldedit-documentation/patterns/patterns")))), full, () -> {
                        if (full.length() == 1) {
                            return new ArrayList<>(worldEdit.getPatternFactory().getSuggestions(""));
                        }
                        return new ArrayList<>(worldEdit.getPatternFactory().getSuggestions(command.toLowerCase(Locale.ROOT)));
                    });
                }
                if (charPattern) {
                    if (char0 == '$' || char0 == '^' || char0 == '*' || (char0 == '#' && input.charAt(1) == '#')) {
                        pattern = worldEdit.getPatternFactory().parseWithoutRich(full, context);
                    }
                }
                if (pattern == null) {
                    if (command.startsWith("[")) {
                        int end = command.lastIndexOf(']');
                        pattern = parseFromInput(command.substring(1, end == -1 ? command.length() : end), context);
                    } else {
                        int percentIndex = command.indexOf('%');
                        if (percentIndex != -1 && percentPatternRegex.matcher(command).matches()) {
                            // Legacy percent pattern
                            chance = Expression.compile(command.substring(0, percentIndex)).evaluate();
                            String value = command.substring(percentIndex + 1);
                            if (!entry.getValue().isEmpty()) {
                                boolean addBrackets = !value.isEmpty();
                                if (addBrackets) {
                                    value += "[";
                                }
                                value += StringMan.join(entry.getValue(), " ");
                                if (addBrackets) {
                                    value += "]";
                                }
                            }
                            pattern = parseFromInput(value, context);
                        } else {
                            // legacy block pattern
                            try {
                                pattern = worldEdit.getBlockFactory().parseFromInput(pe.getFull(), context);
                            } catch (NoMatchException e) {
                                throw new NoMatchException(Caption.of("fawe.error.parse.unknown-pattern", full, TextComponent.of("https://intellectualsites.github.io/fastasyncworldedit-documentation/patterns/patterns").clickEvent(com.sk89q.worldedit.util.formatting.text.event.ClickEvent.openUrl("https://intellectualsites.github.io/fastasyncworldedit-documentation/patterns/patterns"))));
                            }
                        }
                    }
                }
            } else {
                List<String> args = entry.getValue();
                try {
                    pattern = worldEdit.getPatternFactory().parseWithoutRich(full, context);
                } catch (InputParseException rethrow) {
                    throw rethrow;
                } catch (Throwable e) {
                    throw SuggestInputParseException.of(e, full, () -> {
                        try {
                            String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " "));
                            List<Substring> split = CommandArgParser.forArgString(cmdArgs).parseArgs().toList();
                            List<String> argStrings = split.stream().map(Substring::getSubstring).collect(Collectors.toList());
                            MemoizingValueAccess access = getPlatform().initializeInjectedValues(() -> cmdArgs, actor, null, true);
                            List<String> suggestions = getPlatform().getCommandManager().getSuggestions(access, argStrings).stream().map(Suggestion::getSuggestion).collect(Collectors.toUnmodifiableList());
                            List<String> result = new ArrayList<>();
                            if (suggestions.size() <= 2) {
                                for (int i = 0; i < suggestions.size(); i++) {
                                    String suggestion = suggestions.get(i);
                                    if (suggestion.indexOf(' ') != 0) {
                                        String[] splitSuggestion = suggestion.split(" ");
                                        suggestion = "[" + StringMan.join(splitSuggestion, "][") + "]";
                                        result.set(i, suggestion);
                                    }
                                }
                            }
                            return result;
                        } catch (Throwable e2) {
                            e2.printStackTrace();
                            throw new InputParseException(TextComponent.of(e2.getMessage()));
                        }
                    });
                }
            }
            if (pattern != null) {
                patterns.add(pattern);
                chances.add(chance);
            }
        }
    } catch (InputParseException rethrow) {
        throw rethrow;
    } catch (Throwable e) {
        e.printStackTrace();
        throw new InputParseException(TextComponent.of(e.getMessage()), e);
    }
    if (patterns.isEmpty()) {
        return null;
    }
    if (patterns.size() == 1) {
        return patterns.get(0);
    }
    RandomPattern random = new RandomPattern(new TrueRandom());
    for (int i = 0; i < patterns.size(); i++) {
        random.add(patterns.get(i), chances.get(i));
    }
    return random;
}
Also used : SuggestInputParseException(com.fastasyncworldedit.core.command.SuggestInputParseException) BlockTypes(com.sk89q.worldedit.world.block.BlockTypes) Suggestion(org.enginehub.piston.suggestion.Suggestion) Caption(com.fastasyncworldedit.core.configuration.Caption) MemoizingValueAccess(org.enginehub.piston.inject.MemoizingValueAccess) ParserContext(com.sk89q.worldedit.extension.input.ParserContext) FaweParser(com.fastasyncworldedit.core.extension.factory.parser.FaweParser) TrueRandom(com.fastasyncworldedit.core.math.random.TrueRandom) StringMan(com.fastasyncworldedit.core.util.StringMan) ArrayList(java.util.ArrayList) CommandLocals(com.sk89q.minecraft.util.commands.CommandLocals) Substring(com.sk89q.worldedit.internal.util.Substring) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) Locale(java.util.Locale) ClickEvent(com.sk89q.worldedit.util.formatting.text.event.ClickEvent) Map(java.util.Map) WorldEdit(com.sk89q.worldedit.WorldEdit) NoMatchException(com.sk89q.worldedit.extension.input.NoMatchException) CommandArgParser(com.sk89q.worldedit.internal.command.CommandArgParser) TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent) Expression(com.sk89q.worldedit.internal.expression.Expression) RandomPattern(com.sk89q.worldedit.function.pattern.RandomPattern) Collectors(java.util.stream.Collectors) Actor(com.sk89q.worldedit.extension.platform.Actor) List(java.util.List) Stream(java.util.stream.Stream) Pattern(com.sk89q.worldedit.function.pattern.Pattern) Collections(java.util.Collections) ArrayList(java.util.ArrayList) SuggestInputParseException(com.fastasyncworldedit.core.command.SuggestInputParseException) InputParseException(com.sk89q.worldedit.extension.input.InputParseException) Actor(com.sk89q.worldedit.extension.platform.Actor) TrueRandom(com.fastasyncworldedit.core.math.random.TrueRandom) ArrayList(java.util.ArrayList) List(java.util.List) Substring(com.sk89q.worldedit.internal.util.Substring) RandomPattern(com.sk89q.worldedit.function.pattern.RandomPattern) Pattern(com.sk89q.worldedit.function.pattern.Pattern) MemoizingValueAccess(org.enginehub.piston.inject.MemoizingValueAccess) SuggestInputParseException(com.fastasyncworldedit.core.command.SuggestInputParseException) CommandLocals(com.sk89q.minecraft.util.commands.CommandLocals) RandomPattern(com.sk89q.worldedit.function.pattern.RandomPattern) NoMatchException(com.sk89q.worldedit.extension.input.NoMatchException) Map(java.util.Map)

Example 2 with ClickEvent

use of com.sk89q.worldedit.util.formatting.text.event.ClickEvent in project WorldGuard by EngineHub.

the class DefaultDomain method toPlayersComponent.

private Component toPlayersComponent(ProfileCache cache) {
    List<String> uuids = Lists.newArrayList();
    Map<String, UUID> profileMap = Maps.newHashMap();
    for (String name : playerDomain.getPlayers()) {
        profileMap.put(name, null);
    }
    if (cache != null) {
        ImmutableMap<UUID, Profile> results = cache.getAllPresent(playerDomain.getUniqueIds());
        for (UUID uuid : playerDomain.getUniqueIds()) {
            Profile profile = results.get(uuid);
            if (profile != null) {
                profileMap.put(profile.getName(), uuid);
            } else {
                uuids.add(uuid.toString());
            }
        }
    } else {
        for (UUID uuid : playerDomain.getUniqueIds()) {
            uuids.add(uuid.toString());
        }
    }
    final TextComponent.Builder builder = TextComponent.builder("");
    final Iterator<TextComponent> profiles = profileMap.keySet().stream().sorted().map(name -> {
        final UUID uuid = profileMap.get(name);
        final TextComponent component = TextComponent.of(name, TextColor.YELLOW).hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, uuid == null ? TextComponent.of("Name only", TextColor.GRAY) : TextComponent.of("Last known name of uuid: ", TextColor.GRAY).append(TextComponent.of(uuid.toString(), TextColor.WHITE))));
        if (uuid == null) {
            return component;
        }
        return component.clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, uuid.toString()));
    }).iterator();
    while (profiles.hasNext()) {
        builder.append(profiles.next());
        if (profiles.hasNext() || !uuids.isEmpty()) {
            builder.append(TextComponent.of(", "));
        }
    }
    if (!uuids.isEmpty()) {
        builder.append(TextComponent.of(uuids.size() + " unknown uuid" + (uuids.size() == 1 ? "" : "s"), TextColor.GRAY).hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of(String.join("\n", uuids)).append(TextComponent.newline().append(TextComponent.of("Click to select"))))).clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, String.join(",", uuids))));
    }
    return builder.build();
}
Also used : TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent) Iterator(java.util.Iterator) ImmutableMap(com.google.common.collect.ImmutableMap) TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Set(java.util.Set) LocalPlayer(com.sk89q.worldguard.LocalPlayer) UUID(java.util.UUID) HoverEvent(com.sk89q.worldedit.util.formatting.text.event.HoverEvent) Maps(com.google.common.collect.Maps) Component(com.sk89q.worldedit.util.formatting.text.Component) ArrayList(java.util.ArrayList) List(java.util.List) Lists(com.google.common.collect.Lists) TextColor(com.sk89q.worldedit.util.formatting.text.format.TextColor) ClickEvent(com.sk89q.worldedit.util.formatting.text.event.ClickEvent) Map(java.util.Map) Profile(com.sk89q.worldguard.util.profile.Profile) ChangeTracked(com.sk89q.worldguard.util.ChangeTracked) ProfileCache(com.sk89q.worldguard.util.profile.cache.ProfileCache) Nullable(javax.annotation.Nullable) UUID(java.util.UUID) Profile(com.sk89q.worldguard.util.profile.Profile)

Example 3 with ClickEvent

use of com.sk89q.worldedit.util.formatting.text.event.ClickEvent in project WorldGuard by EngineHub.

the class WorldGuardCommands method profile.

@Command(aliases = { "profile" }, usage = "[-p] [-i <interval>] [-t <thread filter>] [<minutes>]", desc = "Profile the CPU usage of the server", min = 0, max = 1, flags = "t:i:p")
@CommandPermissions("worldguard.profile")
public void profile(final CommandContext args, final Actor sender) throws CommandException, AuthorizationException {
    Predicate<ThreadInfo> threadFilter;
    String threadName = args.getFlag('t');
    final boolean pastebin;
    if (args.hasFlag('p')) {
        sender.checkPermission("worldguard.report.pastebin");
        pastebin = true;
    } else {
        pastebin = false;
    }
    if (threadName == null) {
        threadFilter = new ThreadIdFilter(Thread.currentThread().getId());
    } else if (threadName.equals("*")) {
        threadFilter = thread -> true;
    } else {
        threadFilter = new ThreadNameFilter(threadName);
    }
    int minutes;
    if (args.argsLength() == 0) {
        minutes = 5;
    } else {
        minutes = args.getInteger(0);
        if (minutes < 1) {
            throw new CommandException("You must run the profile for at least 1 minute.");
        } else if (minutes > 10) {
            throw new CommandException("You can profile for, at maximum, 10 minutes.");
        }
    }
    int interval = 20;
    if (args.hasFlag('i')) {
        interval = args.getFlagInteger('i');
        if (interval < 1 || interval > 100) {
            throw new CommandException("Interval must be between 1 and 100 (in milliseconds)");
        }
        if (interval < 10) {
            sender.printDebug("Note: A low interval may cause additional slowdown during profiling.");
        }
    }
    Sampler sampler;
    synchronized (this) {
        if (activeSampler != null) {
            throw new CommandException("A profile is currently in progress! Please use /wg stopprofile to cancel the current profile.");
        }
        SamplerBuilder builder = new SamplerBuilder();
        builder.setThreadFilter(threadFilter);
        builder.setRunTime(minutes, TimeUnit.MINUTES);
        builder.setInterval(interval);
        sampler = activeSampler = builder.start();
    }
    sender.print(TextComponent.of("Starting CPU profiling. Results will be available in " + minutes + " minutes.", TextColor.LIGHT_PURPLE).append(TextComponent.newline()).append(TextComponent.of("Use ", TextColor.GRAY)).append(TextComponent.of("/wg stopprofile", TextColor.AQUA).clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, "/wg stopprofile"))).append(TextComponent.of(" at any time to cancel CPU profiling.", TextColor.GRAY)));
    worldGuard.getSupervisor().monitor(FutureForwardingTask.create(sampler.getFuture(), "CPU profiling for " + minutes + " minutes", sender));
    sampler.getFuture().addListener(() -> {
        synchronized (WorldGuardCommands.this) {
            activeSampler = null;
        }
    }, MoreExecutors.directExecutor());
    Futures.addCallback(sampler.getFuture(), new FutureCallback<>() {

        @Override
        public void onSuccess(Sampler result) {
            String output = result.toString();
            try {
                File dest = new File(worldGuard.getPlatform().getConfigDir().toFile(), "profile.txt");
                Files.write(output, dest, StandardCharsets.UTF_8);
                sender.print("CPU profiling data written to " + dest.getAbsolutePath());
            } catch (IOException e) {
                sender.printError("Failed to write CPU profiling data: " + e.getMessage());
            }
            if (pastebin) {
                ActorCallbackPaste.pastebin(worldGuard.getSupervisor(), sender, output, "Profile result: %s.profile");
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
        }
    }, MoreExecutors.directExecutor());
}
Also used : Sampler(com.sk89q.worldguard.util.profiler.SamplerBuilder.Sampler) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) CommandPermissions(com.sk89q.minecraft.util.commands.CommandPermissions) FutureForwardingTask(com.sk89q.worldedit.util.task.FutureForwardingTask) SystemInfoReport(com.sk89q.worldedit.util.report.SystemInfoReport) World(com.sk89q.worldedit.world.World) ActorCallbackPaste(com.sk89q.worldedit.util.paste.ActorCallbackPaste) SamplerBuilder(com.sk89q.worldguard.util.profiler.SamplerBuilder) Level(java.util.logging.Level) CommandException(com.sk89q.minecraft.util.commands.CommandException) Task(com.sk89q.worldedit.util.task.Task) ApplicableRegionsReport(com.sk89q.worldguard.util.report.ApplicableRegionsReport) ThreadInfo(java.lang.management.ThreadInfo) AuthorizationException(com.sk89q.worldedit.util.auth.AuthorizationException) Files(com.google.common.io.Files) TextColor(com.sk89q.worldedit.util.formatting.text.format.TextColor) ClickEvent(com.sk89q.worldedit.util.formatting.text.event.ClickEvent) WorldGuard(com.sk89q.worldguard.WorldGuard) NestedCommand(com.sk89q.minecraft.util.commands.NestedCommand) ConfigReport(com.sk89q.worldguard.util.report.ConfigReport) WorldEdit(com.sk89q.worldedit.WorldEdit) ReportList(com.sk89q.worldedit.util.report.ReportList) Nullable(javax.annotation.Nullable) TaskStateComparator(com.sk89q.worldedit.util.task.TaskStateComparator) ThreadNameFilter(com.sk89q.worldguard.util.profiler.ThreadNameFilter) TextComponent(com.sk89q.worldedit.util.formatting.text.TextComponent) Predicate(java.util.function.Predicate) LoggerToChatHandler(com.sk89q.worldguard.util.logging.LoggerToChatHandler) ThreadIdFilter(com.sk89q.worldguard.util.profiler.ThreadIdFilter) LocalPlayer(com.sk89q.worldguard.LocalPlayer) IOException(java.io.IOException) MessageBox(com.sk89q.worldedit.util.formatting.component.MessageBox) Logger(java.util.logging.Logger) FutureCallback(com.google.common.util.concurrent.FutureCallback) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) Actor(com.sk89q.worldedit.extension.platform.Actor) TimeUnit(java.util.concurrent.TimeUnit) TextComponentProducer(com.sk89q.worldedit.util.formatting.component.TextComponentProducer) Futures(com.google.common.util.concurrent.Futures) List(java.util.List) ConfigurationManager(com.sk89q.worldguard.config.ConfigurationManager) Capability(com.sk89q.worldedit.extension.platform.Capability) CommandContext(com.sk89q.minecraft.util.commands.CommandContext) Command(com.sk89q.minecraft.util.commands.Command) ThreadNameFilter(com.sk89q.worldguard.util.profiler.ThreadNameFilter) ThreadIdFilter(com.sk89q.worldguard.util.profiler.ThreadIdFilter) CommandException(com.sk89q.minecraft.util.commands.CommandException) IOException(java.io.IOException) SamplerBuilder(com.sk89q.worldguard.util.profiler.SamplerBuilder) ThreadInfo(java.lang.management.ThreadInfo) Sampler(com.sk89q.worldguard.util.profiler.SamplerBuilder.Sampler) File(java.io.File) NestedCommand(com.sk89q.minecraft.util.commands.NestedCommand) Command(com.sk89q.minecraft.util.commands.Command) CommandPermissions(com.sk89q.minecraft.util.commands.CommandPermissions)

Aggregations

TextComponent (com.sk89q.worldedit.util.formatting.text.TextComponent)3 ClickEvent (com.sk89q.worldedit.util.formatting.text.event.ClickEvent)3 List (java.util.List)3 WorldEdit (com.sk89q.worldedit.WorldEdit)2 Actor (com.sk89q.worldedit.extension.platform.Actor)2 TextColor (com.sk89q.worldedit.util.formatting.text.format.TextColor)2 LocalPlayer (com.sk89q.worldguard.LocalPlayer)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 SuggestInputParseException (com.fastasyncworldedit.core.command.SuggestInputParseException)1 Caption (com.fastasyncworldedit.core.configuration.Caption)1 FaweParser (com.fastasyncworldedit.core.extension.factory.parser.FaweParser)1 TrueRandom (com.fastasyncworldedit.core.math.random.TrueRandom)1 StringMan (com.fastasyncworldedit.core.util.StringMan)1 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 Lists (com.google.common.collect.Lists)1 Maps (com.google.common.collect.Maps)1 Files (com.google.common.io.Files)1 FutureCallback (com.google.common.util.concurrent.FutureCallback)1