plugins/DuneMenus/src/main/java/com/dunerealms/menus/DuneMenusPlugin.java

199 lines
9.9 KiB
Java

package com.dunerealms.menus;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
public final class DuneMenusPlugin extends JavaPlugin implements TabExecutor {
static final List<String> IDS = List.of("hub", "travel", "exchange", "clan", "company", "missions",
"spice", "war", "mentat", "lore", "politics", "house", "equipment", "bank", "atm", "withdraw");
private static final String PACK_CONTROL = "dunerealms:pack_control";
private Backend backend;
private NativePresentationRoutes nativePresentationRoutes;
private final Map<Player, String> loadedPacks = new HashMap<>();
private final Map<UUID, Menu> openMenus = new HashMap<>();
void opened(Player player, Menu menu) {
Menu previous = openMenus.put(player.getUniqueId(), menu);
if (previous != null && previous != menu) previous.closed();
}
void closed(Player player, Menu menu) {
openMenus.remove(player.getUniqueId(), menu);
}
boolean hasOpenMenu(Player player, Menu menu) {
return openMenus.get(player.getUniqueId()) == menu;
}
void dismiss(Player player) {
Menu menu = openMenus.remove(player.getUniqueId());
if (menu != null) menu.closed();
}
@Override
public void onEnable() {
saveDefaultConfig();
backend = JarvisBackend.create(this);
var messenger = getServer().getMessenger();
messenger.registerOutgoingPluginChannel(this, PACK_CONTROL);
messenger.registerIncomingPluginChannel(this, PACK_CONTROL, (channel, player, bytes) -> {
if (bytes.length > 52) return;
String message = new String(bytes, java.nio.charset.StandardCharsets.US_ASCII);
if (message.equals("common-sha1 -")) loadedPacks.remove(player);
else if (message.matches("common-sha1 [a-f0-9]{40}")) loadedPacks.put(player, message.substring(12));
});
getLogger().info("Backend: " + backend.getClass().getSimpleName());
getServer().getPluginManager().registerEvents(new MenuListener(this), this);
getServer().getPluginManager().registerEvents(new ChatPrompt(this), this);
if (getConfig().getBoolean("fullscreen.enabled", true)) {
getServer().getServicesManager().register(FullscreenProvider.class, new CanvasProvider(this), this, org.bukkit.plugin.ServicePriority.Normal);
}
getCommand("dm").setExecutor(this);
getCommand("dm").setTabCompleter(this);
nativePresentationRoutes=new NativePresentationRoutes(this);
}
@Override public void onDisable() {
if(nativePresentationRoutes!=null)nativePresentationRoutes.close();
for (Menu menu : List.copyOf(openMenus.values())) menu.closed();
openMenus.clear();
getServer().getServicesManager().unregisterAll(this);
getServer().getMessenger().unregisterIncomingPluginChannel(this);
getServer().getMessenger().unregisterOutgoingPluginChannel(this);
}
Backend backend() { return backend; }
public void openMenu(Player player, String menu) {
if (player.hasPermission("dunemenus.use")) create(menu, player, null).open();
}
public void presentService(Player player, String section, String title, String description,
org.bukkit.inventory.Inventory inventory, Map<Integer, Runnable> actions) {
if (player.hasPermission("dunemenus.use"))
new ServiceMenu(this, player, section, title, description, inventory, actions).open();
}
void organisationServices(Player player,String kind,String id) {
var services=getServer().getPluginManager().getPlugin("DunerealmsGUI");
if(services==null||!services.isEnabled())return;
try {services.getClass().getMethod("openOrganisationServices",Player.class,String.class,String.class).invoke(services,player,kind,id);}
catch(ReflectiveOperationException failure){player.sendMessage("Organisation services are temporarily unavailable.");}
}
public void warObjective(Player player, com.google.gson.JsonObject target, Runnable capture) {
if (!getServer().isPrimaryThread() || !player.isOnline() || !player.hasPermission("dunemenus.use")) return;
new WarObjectiveMenu(this, player, target.deepCopy(), capture).open();
}
public void openSharedMenu(Player player, String title, org.bukkit.inventory.Inventory model, Map<Integer,Runnable> actions) {
if (!getServer().isPrimaryThread() || !player.isOnline() || !player.hasPermission("dunemenus.use")) return;
String lower=title.toLowerCase(java.util.Locale.ROOT);
String section=lower.contains("travel")||lower.contains("guild")?"travel":lower.contains("exchange")?"exchange":lower.contains("spice")?"spice":lower.contains("quest")?"missions":"hub";
new ServiceMenu(this,player,section,title,"",model,actions).open();
}
void requestPackStatus(Player player) {
if (player.isOnline()) player.sendPluginMessage(this, PACK_CONTROL,
"common-status".getBytes(java.nio.charset.StandardCharsets.US_ASCII));
}
void forgetPack(Player player) { loadedPacks.remove(player); }
boolean itemCardPackLoaded(Player player) {
if(Bedrock.is(player))return false;
var services=getServer().getPluginManager().getPlugin("DunerealmsGUI");
if(services==null||!services.isEnabled())return false;
try{return Boolean.TRUE.equals(services.getClass().getMethod("menuAssetsLoaded",Player.class).invoke(services,player));}
catch(ReflectiveOperationException failure){return false;}
}
boolean hasOpenMenu(Player player) { return openMenus.containsKey(player.getUniqueId()); }
FullscreenProvider fullscreen() { return getServer().getServicesManager().load(FullscreenProvider.class); }
Menu.Mode modeFor(Player p) {
if (getConfig().getBoolean("bedrock.forms", true) && Bedrock.is(p)) return Menu.Mode.BEDROCK;
return Menu.Mode.FULLSCREEN;
}
/** Coloured title, optionally led by the DuneRealms logo glyph from the resource pack. */
Component titleFor(Menu m) {
Component text = Component.text(m.title(), m.skin().color()).decoration(TextDecoration.BOLD, true).decoration(TextDecoration.ITALIC, false);
if (getConfig().getBoolean("resource-pack.logo-in-title", false)) {
return Component.text("", NamedTextColor.WHITE).font(Key.key(getConfig().getString("resource-pack.font", "dunerealms:menu")))
.append(Component.text(" ")).append(text);
}
return Component.text("◆ ", m.skin().color()).append(text);
}
Menu create(String id, Player p, Menu parent) {
return switch (id.toLowerCase()) {
case "travel" -> new TravelMenu(this, p, parent);
case "exchange" -> new ExchangeMenu(this, p, parent);
case "clan" -> new OrganisationChoiceMenu(this, p, parent, "clan");
case "company" -> new OrganisationChoiceMenu(this, p, parent, "company");
case "missions" -> new MissionsMenu(this, p, parent);
case "spice" -> new SpiceMenu(this, p, parent);
case "war" -> new WarMenu(this, p, parent);
case "politics" -> new PoliticsMenu(this, p, parent);
case "lore" -> new LoreArchiveMenu(this, p, parent);
case "mentat" -> new MentatMenu(this, p, parent);
case "house" -> new HouseMenu(this, p, parent);
case "equipment" -> new EquipmentMenu(this, p, parent);
case "bank" -> new BankMenu(this, p, parent);
case "atm" -> new AtmMenu(this, p, parent, AtmMenu.Tab.DEPOSIT);
case "withdraw" -> new AtmMenu(this, p, parent, AtmMenu.Tab.WITHDRAW);
default -> new HubMenu(this, p);
};
}
@Override
public boolean onCommand(CommandSender s, Command c, String l, String[] a) {
if (!c.getName().equals("dm")) return false;
if (a.length > 0 && a[0].equalsIgnoreCase("reload")) {
if (!s.hasPermission("dunemenus.admin")) { s.sendMessage("No permission."); return true; }
reloadConfig();
s.sendMessage("DuneMenus config reloaded. (Backend changes need a restart.)");
return true;
}
if (!(s instanceof Player p)) { s.sendMessage("Players only."); return true; }
if (!p.hasPermission("dunemenus.use")) { p.sendMessage("No permission."); return true; }
if (a.length == 1 && a[0].equalsIgnoreCase("item")) {
p.sendMessage(backend().claimCodex(p).message());
return true;
}
if (a.length > 0 && a[0].equalsIgnoreCase("previewitem")) {
try {
if (a.length != 3) throw new IllegalArgumentException();
var id = java.util.UUID.fromString(a[1]);
int revision = Integer.parseInt(a[2]);
if (revision < 1 || revision > 999999) throw new IllegalArgumentException();
new SavedItemMenu(this, p, id, revision).open();
} catch (IllegalArgumentException invalid) {
p.sendMessage("Use /dm previewitem <saved-design-id> <revision>.");
}
return true;
}
create(a.length == 0 ? "hub" : a[0], p, null).open();
return true;
}
@Override
public List<String> onTabComplete(CommandSender s, Command c, String l, String[] a) {
if (a.length != 1) return List.of();
return java.util.stream.Stream.concat(IDS.stream(), java.util.stream.Stream.of("reload"))
.filter(x -> x.startsWith(a[0].toLowerCase())).toList();
}
}