Skip to content

Commit

Permalink
Merge pull request #29 from CyR1en/console-delegate
Browse files Browse the repository at this point in the history
Console delegate
  • Loading branch information
CyR1en authored Nov 7, 2023
2 parents b8405f0 + 963d7e3 commit 3828d52
Show file tree
Hide file tree
Showing 23 changed files with 674 additions and 309 deletions.
8 changes: 7 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ $RECYCLE.BIN/
*.iml
out
gen### Java template

# Vscode
.vscode

# Compiled class file
*.class

Expand All @@ -95,4 +99,6 @@ gen### Java template
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
hs_err_pid*

bin/
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ compileTestJava.options.encoding = "UTF-8"

java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
languageVersion = JavaLanguageVersion.of(16)
}
}

PluginManifest pluginManifest = [
name : 'CommandPrompter',
version : new Version(major: 2, minor: 4, patch: 1, fix: 0, classifier: 'SNAPSHOT'),
version : new Version(major: 2, minor: 5, patch: 0, fix: 0, classifier: 'SNAPSHOT'),
author : 'CyR1en',
description: 'Perfect companion plugin for inventory UI menu.',
entry : 'com.cyr1en.commandprompter.CommandPrompter'
Expand Down
54 changes: 42 additions & 12 deletions src/main/java/com/cyr1en/commandprompter/CommandPrompter.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

import com.cyr1en.commandprompter.command.CommodoreRegistry;
import com.cyr1en.commandprompter.commands.Cancel;
import com.cyr1en.commandprompter.commands.ConsoleDelegate;
import com.cyr1en.commandprompter.commands.Reload;
import com.cyr1en.commandprompter.config.CommandPrompterConfig;
import com.cyr1en.commandprompter.config.ConfigurationManager;
Expand All @@ -43,6 +44,7 @@
import com.cyr1en.commandprompter.unsafe.ModifiedCommandMap;
import com.cyr1en.commandprompter.unsafe.PvtFieldMutator;
import com.cyr1en.commandprompter.util.Util;
import com.cyr1en.commandprompter.util.Util.ServerType;
import com.cyr1en.kiso.mc.I18N;
import com.cyr1en.kiso.mc.UpdateChecker;
import com.cyr1en.kiso.mc.command.CommandManager;
Expand Down Expand Up @@ -79,12 +81,20 @@ public void onEnable() {
new Metrics(this, 5359);
setupConfig();
logger = new PluginLogger(this, "CommandPrompter");
loadDeps();
var serverType = ServerType.resolve();
logger.debug("Server Name: " + serverType.name());
logger.debug("Server Version: " + serverType.version());
var result = loadDeps();
if (!result)
return;

i18n = new I18N(this, "CommandPrompter");
messenger = new PluginMessenger(config.promptPrefix());

setupUpdater();
setupCommands();
initPromptSystem();
messenger = new PluginMessenger(config.promptPrefix());
setupCommands();

instance = this;
Bukkit.getPluginManager().registerEvents(new CommandSendListener(this), this);

Expand All @@ -97,8 +107,13 @@ public void onEnable() {

@Override
public void onDisable() {
promptManager.clearPromptRegistry();
getPluginLogger().ansiUninstall();
if (promptManager != null)
promptManager.clearPromptRegistry();

PluginLogger logger;
if ((logger = getPluginLogger()) != null)
logger.ansiUninstall();

if (Objects.nonNull(updateChecker) && !updateChecker.isDisabled())
HandlerList.unregisterAll(updateChecker);
}
Expand All @@ -109,21 +124,34 @@ private void initPromptSystem() {
Bukkit.getPluginManager().registerEvents(headCache = new HeadCache(this), this);
}

private void loadDeps() {
private boolean loadDeps() {
if (Util.isBundledVersion(this)) {
getPluginLogger().info("This is a bundled version! Skipping dependency loading");
return;
return true;
}

getPluginLogger().info("Loading dependencies...");

var depLoader = new DependencyLoader(this);
if (depLoader.isRelocatorAvailable()) {
if (!depLoader.isClassLoaderAccessSupported())
return depErrAndDisable("No access to URLClassloader, cannot load depedencies!", depLoader);

if (!depLoader.loadCoreDeps())
return depErrAndDisable("Unable to load dependencies!", depLoader);

if (depLoader.relocatorAvailable()) {
depLoader.loadDependency();
return;
return true;
}

getPluginLogger().err("Unable to load dependencies!");
return depErrAndDisable("Unable to load dependencies!", depLoader);
}

private boolean depErrAndDisable(String message, DependencyLoader depLoader) {
getPluginLogger().err(message);
depLoader.sendBundledMessage();
Bukkit.getPluginManager().disablePlugin(this);
return false;
}

/**
Expand Down Expand Up @@ -174,6 +202,8 @@ private void setupCommands() {
commandManager.registerCommand(Reload.class);
commandManager.registerCommand(Cancel.class);
PluginCommand command = getCommand("commandprompter");
PluginCommand delegate = getCommand("consoledelegate");
delegate.setExecutor(new ConsoleDelegate(this));
Objects.requireNonNull(command).setExecutor(commandManager);
CommodoreRegistry.register(this, command);
}
Expand All @@ -198,7 +228,8 @@ private void setupCommandManager() {

private void setupUpdater() {
updateChecker = new UpdateChecker(this, 47772);
if (updateChecker.isDisabled()) return;
if (updateChecker.isDisabled())
return;
Bukkit.getServer().getScheduler().runTaskAsynchronously(this, () -> {
if (updateChecker.newVersionAvailable())
logger.info(SRegex.ANSI_GREEN + "A new update is available! (" +
Expand Down Expand Up @@ -270,4 +301,3 @@ public UpdateChecker getUpdateChecker() {
return updateChecker;
}
}

9 changes: 3 additions & 6 deletions src/main/java/com/cyr1en/commandprompter/PluginLogger.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,15 @@
public class PluginLogger {

private String prefix;
private String plainPrefix;
private String debugPrefix;

private final ColorGradient normalGrad;
private final ColorGradient debugGrad;

private boolean debugMode = false;
private boolean isFancy = true;
private CommandPrompter plugin;

public PluginLogger(CommandPrompter plugin, String prefix) {
this.plugin = plugin;
this.isFancy = plugin.getConfiguration().fancyLogger();
this.debugMode = plugin.getConfiguration().debugMode();
AnsiConsole.systemInstall();
Expand All @@ -42,7 +39,6 @@ public void ansiUninstall() {
}

public void setPrefix(String prefix) {
this.plainPrefix = prefix;
var sep = isFancy ? new Ansi().fgRgb(153, 214, 90).a(">>").reset().toString() : ">>";
var normal = isFancy ? makeGradient(prefix, normalGrad) : prefix;
var debug = isFancy ? makeGradient(prefix + "-" + "Debug", debugGrad) : prefix + "-" + "Debug";
Expand Down Expand Up @@ -93,8 +89,9 @@ public void debug(String msg, Object... args) {
lastDebugClass = caller;

if (debugMode) {
msg = callerAvailable ? String.format("[%s] - %s", caller.getSimpleName(), msg) :
Objects.isNull(lastDebugClass) ? msg : String.format("[%s?] - %s", lastDebugClass.getSimpleName(), msg);
msg = callerAvailable ? String.format("[%s] - %s", caller.getSimpleName(), msg)
: Objects.isNull(lastDebugClass) ? msg
: String.format("[%s?] - %s", lastDebugClass.getSimpleName(), msg);
var str = new Ansi().fgRgb(255, 195, 113).a(msg).reset().toString();
log(debugPrefix, Level.INFO, str, args);
}
Expand Down
32 changes: 15 additions & 17 deletions src/main/java/com/cyr1en/commandprompter/api/Dispatcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@
/**
* Player command dispatcher for Support with CommandPrompter.
*
* <p>Because CommandPrompter cannot catch commands that were dispatched from
* <p>
* Because CommandPrompter cannot catch commands that were dispatched from
* {@link org.bukkit.Bukkit#dispatchCommand(CommandSender, String)}, plugins
* need a special way to execute player commands.</p>
* need a special way to execute player commands.
* </p>
*/
public class Dispatcher {

Expand All @@ -58,34 +60,32 @@ public void run() {
}.runTask(plugin);
}

public static void dispatchNative(CommandSender sender, String command) {
final String checked = command.codePointAt(0) == 0x2F ?
command.replace("/", "") : command;
Bukkit.dispatchCommand(sender, checked);
}

/**
* Dispatch the command as Console.
*
* @param command command that would be dispatched.
*/
public static void dispatchOP(String command) {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
public static void dispatchConsole(final String command) {
final String checked = command.codePointAt(0) == 0x2F ? command.replace("/", "") : command;
new BukkitRunnable() {
public void run() {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), checked);
}
}.runTask(CommandPrompter.getInstance());
}


/**
* Dispatch a command for a player with a PermissionAttachment that contains
* all the whitelisted commands.
*
* @param plugin Instance of plugin.
* @param sender command sender (in menu's, then the item clicker)
* @param command command that would be dispatched.
* @param ticks Number of ticks before the attachment expires
* @param perms Permissions to set to the PermissionAttachment
* @param ticks Number of ticks before the attachment expires
* @param perms Permissions to set to the PermissionAttachment
*/
public static void dispatchWithAttachment
(Plugin plugin, Player sender, String command, int ticks, @NotNull String[] perms) {
public static void dispatchWithAttachment(Plugin plugin, Player sender, String command, int ticks,
@NotNull String[] perms) {
var commandPrompter = (CommandPrompter) plugin;
var logger = commandPrompter.getPluginLogger();

Expand All @@ -102,6 +102,4 @@ public static void dispatchOP(String command) {
dispatchCommand(plugin, (Player) attachment.getPermissible(), command);
}



}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package com.cyr1en.commandprompter.commands;

import java.util.Arrays;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import com.cyr1en.commandprompter.CommandPrompter;
import com.cyr1en.commandprompter.PluginLogger;
import com.cyr1en.commandprompter.PluginMessenger;
import com.cyr1en.commandprompter.prompt.ContextProcessor;
import com.cyr1en.commandprompter.prompt.PromptContext;
import com.cyr1en.kiso.mc.I18N;

public class ConsoleDelegate extends ContextProcessor implements CommandExecutor {

private final CommandPrompter commandPrompter;
private final PluginLogger logger;
private final PluginMessenger messenger;
private final I18N i18n;
private final String usage;

public ConsoleDelegate(JavaPlugin plugin) {
super((CommandPrompter) plugin, ((CommandPrompter) plugin).getPromptManager());
this.commandPrompter = (CommandPrompter) plugin;
this.logger = commandPrompter.getPluginLogger();
this.messenger = commandPrompter.getMessenger();
this.i18n = commandPrompter.getI18N();
this.usage = "consoledelegate <target player> <command...>";
}

private void doCommand(Player targetPlayer, String command) {
var context = new PromptContext(null, targetPlayer, command);
context.setIsConsoleDelegate(true);
this.process(context);
}

@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
logger.debug("Command: " + command);
logger.debug("Label: " + label);
logger.debug("Args: " + Arrays.toString(args));

if (!(sender instanceof ConsoleCommandSender)) {
messenger.sendMessage(sender, i18n.getProperty("DelegateConsoleOnly"));
return true;
}

if (args.length < 2) {
messenger.sendMessage(sender, i18n.getProperty("DelegateInvalidArgs"));
messenger.sendMessage(sender, i18n.getFormattedProperty("DelegateUsage", this.usage));
return true;
}

var arg0 = args[0];
var targetPlayer = commandPrompter.getServer().getPlayer(arg0);

if (targetPlayer == null) {
messenger.sendMessage(sender, i18n.getFormattedProperty("DelegateInvalidPlayer", arg0));
return true;
}

var delegatedCommand = String.join(" ", Arrays.copyOfRange(args, 1, args.length));

if (delegatedCommand.isEmpty()) {
messenger.sendMessage(sender, i18n.getProperty("DelegateInvalidCommand"));
return true;
}

if (delegatedCommand.contains("%target_player%"))
delegatedCommand = delegatedCommand.replace("%target_player%", targetPlayer.getName());

doCommand(targetPlayer, delegatedCommand);
return true;
}

}
Loading

0 comments on commit 3828d52

Please sign in to comment.