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;
}
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();
}
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());
}
Aggregations