Import the supplied DuneMenus plugin and connect its first JARVIS actions

This commit is contained in:
unimatrixgit 2026-11-28 15:31:21 +01:00
commit 41ef8f4329
35 changed files with 1782 additions and 0 deletions

View file

@ -56,6 +56,16 @@ jobs:
path: plugin-artifacts/
if-no-files-found: error
- name: Test and build the replacement DuneMenus plugin
if: github.repository == 'dev/MC'
run: gradle --no-daemon -p DuneMenus test jar
- uses: actions/upload-artifact@v3
if: github.repository == 'dev/MC'
with:
name: DuneMenus-Development
path: DuneMenus/build/libs/DuneMenus.jar
if-no-files-found: error
- uses: actions/setup-java@v4
with:
distribution: temurin

5
DuneMenus/README.md Normal file
View file

@ -0,0 +1,5 @@
# DuneMenus
Custom Dune-themed menus for DuneRealms. No ChestCommands. One menu definition, rendered as a chest inventory (Java), a Floodgate form (Bedrock), or a full-screen provider (optional `FullscreenProvider` service).
Build JarvisConnector first, then run `gradle test jar` in this module (Java 21, Paper 1.21.8). Commands use `/dm [menu|reload]`. The plugin requires JarvisTranslator. The optional fullscreen service is a contract in the supplied module and requires a compatible implementation.
Exchange, House and mission actions use the existing J.A.R.V.I.S. service. Methods without an authoritative adapter remain unavailable. See docs/BACKEND.md for the original backend contract.

View file

@ -0,0 +1,23 @@
plugins { java }
group = "com.dunerealms"
version = "2.0.0"
repositories {
mavenCentral()
maven("https://repo.papermc.io/repository/maven-public/")
maven("https://repo.opencollab.dev/main/")
}
dependencies {
compileOnly(files("../JarvisConnector/build/libs/jarvistranslator.jar"))
testImplementation(files("../JarvisConnector/build/libs/jarvistranslator.jar"))
testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
compileOnly("org.geysermc.floodgate:api:2.2.5-SNAPSHOT") // same coordinates as DunerealmsGUI
}
java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) }
tasks.withType<JavaCompile> { options.encoding = "UTF-8" }
tasks.jar { archiveFileName.set("DuneMenus.jar") }
tasks.processResources { filesMatching("plugin.yml") { expand("version" to project.version) } }
tasks.test { useJUnitPlatform() }

17
DuneMenus/docs/BACKEND.md Normal file
View file

@ -0,0 +1,17 @@
# Backend contract (for the coder)
The GUI is design only. Everything it needs from the game lives in `Backend.java`; wire `JarvisBackend.java` by overriding methods one at a time. Un-overridden methods make the menu say "not connected yet". The development plugin loads the J.A.R.V.I.S. adapter.
Rules: money is minor units (1.00 DM = 100). Futures may complete on any thread. There are no confirm screens, so every mutating call must be safe against a double click (idempotent). Return `Result.no("reason")` for refusals; the text is shown to the player as is.
## ATM (one GUI, three tabs)
- Deposit cash: `atmCreateRia(player, amountMinor)` takes the cash (bills and coins amounts are chosen in the GUI, denominations in config.yml `atm.bills` / `atm.coins`), creates a NEW RIA ID worth that amount, returns `Issued(ok, message, riaId)`.
- Redeem: `atmLookup(player, riaId)` returns `Voucher(riaId, amountMinor, fromName)` or null if unknown/used. `atmRedeem(player, riaId, toBank)` pays out as cash (toBank=false) or credits the player's bank account (toBank=true). Must mark the ID used atomically.
- Withdraw cash: `bankWithdraw(player, amountMinor)` debits the bank account and gives cash.
The RIA ID is typed by the player in chat (next chat line is captured, "cancel" aborts) so it works on Java and Bedrock.
## Bank (Rihla Money Transfer)
`bankAccount`, `bankTransfers`, `bankSend(player, toUuid, amountMinor)` (creates a pending transfer, reserves amount + tax), `bankCancel(player, id)` (releases the reservation), `bankCollect(player, id)` (-1 = all). Tax: 1% of the amount up to and including 3,000 DM, 5% above, rounded up to the cent; the recipient receives the full amount. `Rihla.tax()` / `Rihla.total()` implement this for the previews; the backend stays the source of truth.
## Everything else
See the javadoc in `Backend.java`: balance, worlds/book (travel), listings/buy/sell/withdraw/collectPurchases (exchange), org/members/orgAction (clan, company), missions, spice, war, decisions, houses, refit.

View file

@ -0,0 +1 @@
rootProject.name = "DuneMenus"

View file

@ -0,0 +1,115 @@
package com.dunerealms.menus;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.entity.Player;
/**
* ONE ATM, three tabs, 5 rows, no PIN, no confirmations.
* Deposit : tap bills and coins, one click -> a new RIA ID is created and shown in the ID box.
* Redeem : type an RIA ID, then one click pays it out as Cash or To bank.
* Withdraw : tap bills and coins, one click takes the cash out of your own account.
*/
final class AtmMenu extends Menu {
enum Tab { DEPOSIT, REDEEM, WITHDRAW }
private static final int[] BILLS = {10, 11, 12, 19, 20};
private static final int[] COINS = {14, 15, 16};
private static final Material[] COIN_ICON = {Material.GOLD_NUGGET, Material.IRON_NUGGET, Material.COPPER_INGOT};
private Tab tab;
private long minor = 0;
private String issued; // RIA ID created by the last deposit
private String entered; // RIA ID typed on the Redeem tab
AtmMenu(DuneMenusPlugin plugin, Player p, Menu parent, Tab tab) { super(plugin, p, parent); this.tab = tab; }
String id() { return tab == Tab.WITHDRAW ? "withdraw" : "atm"; }
Skin skin() { return tab == Tab.REDEEM ? Skin.GOLD : Skin.TRAVEL; }
String title() { return "Rihla ATM"; }
String subtitle() { return switch (tab) {
case DEPOSIT -> "Put in cash. You get an RIA ID to keep or give away.";
case REDEEM -> "Got an RIA ID? Type it in and take the money as cash or to your bank.";
case WITHDRAW -> "Take cash out of your own bank account."; }; }
int rows() { return 5; }
private void tabButton(int slot, Material m, String label, Tab t) {
var item = Ui.item(m, (tab == t ? "<green><b>" : "<gray>") + label);
put(slot, tab == t ? Ui.glow(item) : item, c -> { tab = t; minor = 0; redraw(); });
}
private void add(int slot, Material m, String name, long dm) {
put(slot, Ui.item(m, name, "<gray>Click to add"), c -> { if (minor + dm * 100 <= 9_999_999_900L) minor += dm * 100; redraw(); });
}
void draw() {
backdrop(Material.BLACK_STAINED_GLASS_PANE);
for (int s : new int[]{3, 5, 6, 7, 8}) put(s, Ui.pane(Material.CYAN_STAINED_GLASS_PANE));
tabButton(0, Material.EMERALD, "Deposit cash", Tab.DEPOSIT);
tabButton(1, Material.NAME_TAG, "Redeem RIA ID", Tab.REDEEM);
tabButton(2, Material.GOLD_INGOT, "Withdraw cash", Tab.WITHDRAW);
back(36);
if (tab == Tab.REDEEM) drawRedeem(); else drawCash();
}
private void drawCash() {
boolean dep = tab == Tab.DEPOSIT;
String verb = dep ? "Deposit" : "Withdraw";
put(4, Ui.glow(Ui.item(Material.LIGHTNING_ROD, "<aqua><b>" + (minor == 0 ? "Choose bills and coins" : verb + " " + Ui.dm(minor)),
minor == 0 ? "<gray>Tap the bills and coins below" : "<gray>Ready")));
put(9, Ui.item(Material.GREEN_STAINED_GLASS_PANE, "<green><b>Bills"));
put(13, Ui.item(Material.YELLOW_STAINED_GLASS_PANE, "<gold><b>Coins"));
List<Integer> bills = plugin.getConfig().getIntegerList("atm.bills");
List<Integer> coins = plugin.getConfig().getIntegerList("atm.coins");
for (int i = 0; i < Math.min(BILLS.length, bills.size()); i++) add(BILLS[i], Material.PAPER, "<green>" + bills.get(i) + " DM note", bills.get(i));
for (int i = 0; i < Math.min(COINS.length, coins.size()); i++) add(COINS[i], COIN_ICON[i], "<gold>" + coins.get(i) + " DM coin", coins.get(i));
put(21, Ui.item(Material.RED_STAINED_GLASS_PANE, "<red><b>Clear"), c -> { minor = 0; redraw(); });
put(24, minor == 0 ? Ui.item(Material.GRAY_DYE, "<gray>" + verb, "<dark_gray>Choose bills and coins first")
: Ui.glow(Ui.item(dep ? Material.EMERALD : Material.GOLD_INGOT, "<green><b>" + verb + " " + Ui.dm(minor),
dep ? "<gray>Creates a new RIA ID" : "<gray>From your bank account")),
c -> {
if (minor <= 0) return;
long amt = minor; minor = 0;
if (dep) load(backend().atmCreateRia(player, amt), r -> {
player.sendMessage(Ui.text((r.ok() ? "<green>" : "<red>") + r.message()));
if (r.ok()) issued = r.riaId();
redraw();
});
else act(backend().bankWithdraw(player, amt));
});
// framed ID box
for (int s : new int[]{28, 30}) put(s, Ui.pane(Material.YELLOW_STAINED_GLASS_PANE));
if (dep) {
put(29, issued == null ? Ui.item(Material.NAME_TAG, "<gold><b>Your new RIA ID", "<dark_gray>Appears here after you deposit")
: Ui.glow(Ui.item(Material.NAME_TAG, "<gold><b>Your new RIA ID", "<white>" + issued, "<gray>Give it to anyone to collect the money",
"<yellow>Click to show in chat")),
c -> { if (issued != null) player.sendMessage(Ui.text("<gold>RIA ID: <click:copy_to_clipboard:'" + issued + "'><white><u>" + issued + "</u></click>")); });
} else {
put(29, Ui.item(Material.NAME_TAG, "<gold><b>Your account", "<gray>Loading…"));
load(backend().bankAccount(player), a -> put(29, Ui.item(Material.NAME_TAG, "<gold><b>Your account",
"<white>" + a.accountNo(), "<gray>Balance: <white>" + Ui.dm(a.balanceMinor()))));
}
}
private void drawRedeem() {
put(4, Ui.glow(Ui.item(Material.LIGHTNING_ROD, "<aqua><b>Redeem an RIA ID", "<gray>1. Type the ID", "<gray>2. Pick Cash or To bank")));
put(13, Ui.item(Material.WRITABLE_BOOK, entered == null ? "<yellow><b>Type RIA ID" : "<yellow><b>Change RIA ID",
"<gray>Click, then type it in chat"), c -> {
end();
ChatPrompt.ask(player, "<gold>Type the RIA ID in chat:", text -> { if (text != null) entered = text; open(); });
});
for (int s : new int[]{28, 30}) put(s, Ui.pane(Material.YELLOW_STAINED_GLASS_PANE));
put(29, Ui.item(Material.NAME_TAG, "<gold><b>RIA ID", entered == null ? "<dark_gray>Nothing entered yet" : "<white>" + entered));
put(24, Ui.item(Material.GRAY_DYE, "<gray>Take as cash", "<dark_gray>Enter an RIA ID first"));
put(26, Ui.item(Material.GRAY_DYE, "<gray>Send to my bank", "<dark_gray>Enter an RIA ID first"));
if (entered == null) return;
final String id = entered;
load(backend().atmLookup(player, id), v -> {
if (v == null) { put(22, Ui.item(Material.BARRIER, "<red>RIA ID not found")); return; }
put(22, Ui.glow(Ui.item(Material.GOLD_BLOCK, "<gold><b>" + Ui.dm(v.amountMinor()), "<gray>From: <white>" + v.fromName())));
put(24, Ui.glow(Ui.item(Material.GOLD_INGOT, "<green><b>Take as cash", "<gray>Bills and coins in your inventory")),
c -> load(backend().atmRedeem(player, id, false), r -> { say(r); if (r.ok()) entered = null; redraw(); }));
put(26, Ui.glow(Ui.item(Material.ENDER_CHEST, "<aqua><b>Send to my bank", "<gray>Credited to your account")),
c -> load(backend().atmRedeem(player, id, true), r -> { say(r); if (r.ok()) entered = null; redraw(); }));
});
}
}

View file

@ -0,0 +1,104 @@
package com.dunerealms.menus;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
* Everything the menus need from the game backend (Jarvis). Menus never talk to Jarvis directly.
* <p>Every method defaults to "not connected", so a backend only overrides what it supports and the
* menu tells the player politely instead of faking data or touching money.
* <p>Rules for implementers (full detail in docs/BACKEND.md):
* money is minor units (1.00 DM = 100); futures may complete on any thread; there are NO confirm screens,
* so each mutating call must be idempotent and safe against a double click.
*/
public interface Backend {
/** Complete a future exceptionally with this to mean "this feature is not wired yet". */
final class Unavailable extends RuntimeException { public Unavailable() { super("not wired", null, false, false); } }
record Result(boolean ok, String message) {
public static Result yes(String m) { return new Result(true, m); }
public static Result no(String m) { return new Result(false, m); }
}
/** fareMinor: -1 unknown (no fare line shown), 0 free, >0 price. */
record World(String id, String name, String tagline, Material icon, int online, boolean up, long fareMinor) {}
record Listing(String id, String title, Material icon, String seller, long priceMinor, int quantity, Integer kitVersion, boolean purchasable) {}
record Page(List<Listing> items, boolean hasNext) {}
record Org(String name, String role, int members, long vaultMinor) {}
record Member(UUID id, String name, String role) {}
/** state is one of ACTIVE, AVAILABLE, DONE. */
record Mission(String id, String title, Material icon, String state, int percent, boolean claimable, String summary, Long revision) {}
record Spice(int carried, long guildQuote, long smugglerQuote, long pendingMinor) {}
/** roster has 8 entries; blank = empty slot. */
record War(String title, List<String> roster, List<String> status, boolean canLaunch) {}
record Decision(String id, String title, Material icon, String cost, String effect, boolean allowed) {}
record House(String id, String name, String motto, Material banner, int version) {}
/** Rihla account. reservedMinor = amount+tax locked by pending outgoing transfers. collectableMinor = incoming transfers waiting to be collected. */
record Account(String accountNo, long balanceMinor, long reservedMinor, long collectableMinor) {}
/** direction is "OUT" (you sent it, still pending, cancellable) or "IN" (waiting for you to collect). taxMinor is only set for OUT. */
record Transfer(long id, String direction, String counterparty, long amountMinor, long taxMinor, String when) {}
record Refit(boolean possible, String itemName, Material icon, List<String> costs, String note) {}
private static <T> CompletableFuture<T> na() { return CompletableFuture.failedFuture(new Unavailable()); }
// ---- wallet / travel ----
default CompletableFuture<Long> balance(Player p) { return na(); }
default CompletableFuture<List<World>> worlds(Player p) { return na(); }
default CompletableFuture<Result> book(Player p, String worldId) { return na(); }
// ---- exchange (tab is "buy" | "kits" | "mine") ----
default CompletableFuture<Page> listings(Player p, String tab, int page) { return na(); }
default CompletableFuture<Result> buy(Player p, Listing offer, int qty) { return na(); }
default CompletableFuture<Result> withdraw(Player p, Listing offer) { return na(); }
/** Lists the item in the player's main hand at the given unit price. */
default CompletableFuture<Result> sell(Player p, ItemStack expected, int slot, long priceMinor) { return na(); }
default CompletableFuture<Result> collectPurchases(Player p) { return na(); }
// ---- organisations (kind is "clan" | "company") ----
default CompletableFuture<Org> org(Player p, String kind) { return na(); }
default CompletableFuture<List<Member>> members(Player p, String kind) { return na(); }
/** action ids used by the menus: home, claims, vault, allies, wars, invite, transactions, roles, war-transport */
default CompletableFuture<Result> orgAction(Player p, String kind, String action) { return na(); }
// ---- missions ----
default CompletableFuture<List<Mission>> missions(Player p) { return na(); }
default CompletableFuture<Result> missionAction(Player p, Mission mission, boolean claim) { return na(); }
// ---- spice (channel is "guild" | "smuggler") ----
default CompletableFuture<Spice> spice(Player p) { return na(); }
default CompletableFuture<Result> sellSpice(Player p, String channel) { return na(); }
default CompletableFuture<Result> collectSpice(Player p) { return na(); }
// ---- war muster ----
default CompletableFuture<War> war(Player p) { return na(); }
default CompletableFuture<List<Member>> warCandidates(Player p) { return na(); }
default CompletableFuture<Result> warAssign(Player p, int slot, UUID candidateOrNull) { return na(); }
default CompletableFuture<Result> warSave(Player p) { return na(); }
default CompletableFuture<Result> warLaunch(Player p) { return na(); }
// ---- politics / house / equipment ----
default CompletableFuture<List<Decision>> decisions(Player p) { return na(); }
default CompletableFuture<Result> enact(Player p, String id) { return na(); }
default CompletableFuture<List<House>> houses(Player p) { return na(); }
default CompletableFuture<Result> chooseHouse(Player p, House house) { return na(); }
default CompletableFuture<Refit> refitQuote(Player p) { return na(); }
default CompletableFuture<Result> refit(Player p) { return na(); }
// ---- Rihla money transfer (Corrino Group). Used by the Bank screen and the ATM. ----
// Rules (docs/BACKEND.md): private account per user; sending creates a pending transfer that reserves
// amount + tax (1% up to and including 3,000 DM, 5% above, rounded UP to the next cent); the recipient
// receives the full amount and collects it in-game; cancelling releases the reservation.
default CompletableFuture<Account> bankAccount(Player p) { return na(); }
/** ATM, tab 1. The player taps bills and coins; the menu sends the total. Backend takes the cash and CREATES a new RIA ID worth that amount. */
record Issued(boolean ok, String message, String riaId) {}
default CompletableFuture<Issued> atmCreateRia(Player p, long amountMinor) { return na(); }
/** ATM, tab 2. Look an RIA ID up so the menu can show the amount before payout. Return null/exceptional if unknown. */
record Voucher(String riaId, long amountMinor, String fromName) {}
default CompletableFuture<Voucher> atmLookup(Player p, String riaId) { return na(); }
/** ATM, tab 2. Pay the RIA ID out: toBank=false gives cash, toBank=true credits the player's bank account. One click, no confirmation. */
default CompletableFuture<Result> atmRedeem(Player p, String riaId, boolean toBank) { return na(); }
/** Cash withdrawal from the RIA account. The menu builds amountMinor from the bills and coins the player tapped.
* The backend debits the account and gives the player that cash (however cash is represented), or returns Result.no (insufficient funds, inventory full...). */
default CompletableFuture<Result> bankWithdraw(Player p, long amountMinor) { return na(); }
default CompletableFuture<List<Transfer>> bankTransfers(Player p) { return na(); }
default CompletableFuture<Result> bankSend(Player p, UUID to, long amountMinor) { return na(); }
default CompletableFuture<Result> bankCancel(Player p, long transferId) { return na(); }
/** transferId -1 collects every incoming transfer. */
default CompletableFuture<Result> bankCollect(Player p, long transferId) { return na(); }
}

View file

@ -0,0 +1,61 @@
package com.dunerealms.menus;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.entity.Player;
/**
* 6 rows. Left: your private account. Centre: Send RIA, Withdraw cash, Collect transfers.
* Right: pending transfers: outgoing ones cancel on click (releases the reservation), incoming ones collect on click.
*/
final class BankMenu extends Menu {
private static final int[] LIST = {15, 16, 24, 25, 33, 34};
BankMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); }
String id() { return "bank"; }
Skin skin() { return Skin.GOLD; }
String title() { return "Rihla · Money Transfer"; }
String subtitle() { return "Corrino Group. Your private account. Send and collect transfers."; }
int rows() { return 6; }
void draw() {
backdrop(Material.BLACK_STAINED_GLASS_PANE);
for (int i = 0; i < 9; i += 2) put(i, Ui.pane(Material.CYAN_STAINED_GLASS_PANE));
for (int s : new int[]{12, 14, 21, 23, 30, 32}) put(s, Ui.pane(Material.YELLOW_STAINED_GLASS_PANE));
back(45);
put(13, Ui.item(Material.WRITABLE_BOOK, "<yellow><b>Send RIA</b>", "<gray>Choose an amount, pick a person.", "<gray>Tax: " + Rihla.rateText()),
t -> go(new TransferMenu(plugin, player, this, 10_000)));
put(22, Ui.item(Material.PAPER, "<green><b>Withdraw cash</b>", "<gray>Take bills and coins from your account"),
t -> go(new AtmMenu(plugin, player, this, AtmMenu.Tab.WITHDRAW)));
put(31, Ui.item(Material.CHEST, "<green>Collect transfers", "<gray>Loading…"));
put(47, Ui.item(Material.BOOK, "<aqua>Statement", "<gray>Opens your full statement in User CP"), t -> {
player.sendMessage(Ui.text("<gold>Your statement: <click:open_url:'https://cp.dunerealms.com/#bank/bank-overview'><aqua><u>open User CP</u></click>"));
});
put(11, Ui.item(Material.NAME_TAG, "<gold><b>Your account", "<gray>Loading…"));
load(backend().bankAccount(player), a -> {
put(11, Ui.item(Material.NAME_TAG, "<gold><b>Your account", "<gray>Account: <white>" + a.accountNo()));
put(20, Ui.glow(Ui.item(Material.GOLD_BLOCK, "<gold><b>Balance", "<white>" + Ui.dm(a.balanceMinor()))));
put(29, Ui.item(Material.IRON_BARS, "<gray>Reserved for transfers", "<white>" + Ui.dm(a.reservedMinor()), "<dark_gray>Amount plus tax, until collected"));
var collect = Ui.item(Material.CHEST, "<green><b>Collect transfers", "<gray>Waiting: <gold>" + Ui.dm(a.collectableMinor()),
a.collectableMinor() > 0 ? "<yellow>Click to collect everything" : "<dark_gray>Nothing waiting");
put(31, a.collectableMinor() > 0 ? Ui.glow(collect) : collect, t -> act(backend().bankCollect(player, -1)));
});
load(backend().bankTransfers(player), list -> {
for (int i = 0; i < Math.min(LIST.length, list.size()); i++) row(LIST[i], list.get(i));
if (list.isEmpty()) put(24, Ui.item(Material.PAPER, "<gray>No pending transfers"));
});
put(49, Ui.item(Material.OAK_SIGN, "<gold>Transfer tax", "<gray>1% of the amount up to 3,000 DM", "<gray>5% of the amount above 3,000 DM",
"<gray>The recipient gets the full amount."));
}
private void row(int slot, Backend.Transfer t) {
if (t.direction().equals("OUT"))
put(slot, Ui.item(Material.ORANGE_DYE, "<gold>To " + t.counterparty() + " · " + Ui.dm(t.amountMinor()),
"<gray>Tax: <white>" + Ui.dm(t.taxMinor()), "<gray>" + t.when(), "", "<yellow>Click to cancel and release the reservation"),
c -> act(backend().bankCancel(player, t.id())));
else
put(slot, Ui.glow(Ui.item(Material.LIME_DYE, "<green>From " + t.counterparty() + " · " + Ui.dm(t.amountMinor()),
"<gray>" + t.when(), "", "<yellow>Click to collect")),
c -> act(backend().bankCollect(player, t.id())));
}
}

View file

@ -0,0 +1,51 @@
package com.dunerealms.menus;
import java.util.List;
import java.util.function.IntConsumer;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
/** Floodgate forms, built from the same menu definition. Same API calls as the existing DunerealmsGUI BedrockForms. */
final class Bedrock {
private Bedrock() {}
static boolean is(Player p) {
if (!Bukkit.getPluginManager().isPluginEnabled("floodgate")) return false;
try { return Impl.is(p); } catch (LinkageError missing) { return false; }
}
static void show(JavaPlugin plugin, Player p, String title, String subtitle, List<String> info, List<Card> cards,
IntConsumer pick, Runnable closed) {
try { Impl.show(plugin, p, title, subtitle, info, cards, pick, closed); }
catch (LinkageError missing) { closed.run(); }
}
private static String label(Card c) {
List<String> lore = c.lore().stream().filter(s -> !s.isBlank()).limit(2).toList();
String sub = String.join(" · ", lore);
if (sub.length() > 60) sub = sub.substring(0, 57) + "…";
return sub.isEmpty() ? c.title() : c.title() + "\n" + sub;
}
private static final class Impl {
static boolean is(Player p) { return org.geysermc.floodgate.api.FloodgateApi.getInstance().isFloodgatePlayer(p.getUniqueId()); }
static void show(JavaPlugin plugin, Player p, String title, String subtitle, List<String> info, List<Card> cards,
IntConsumer pick, Runnable closed) {
StringBuilder content = new StringBuilder(subtitle == null ? "" : subtitle);
for (String line : info) { if (content.length() > 0) content.append('\n'); content.append(line); }
var form = org.geysermc.cumulus.form.SimpleForm.builder().title(title).content(content.toString());
for (Card c : cards) form.button(label(c));
form.closedOrInvalidResultHandler(closed);
form.validResultHandler(result -> {
int index = result.clickedButtonId();
if (!plugin.isEnabled()) return;
Bukkit.getScheduler().runTask(plugin, () -> {
if (p.isOnline() && index >= 0 && index < cards.size()) pick.accept(cards.get(index).slot());
});
});
if (!org.geysermc.floodgate.api.FloodgateApi.getInstance().sendForm(p.getUniqueId(), form.build())) closed.run();
}
}
}

View file

@ -0,0 +1,6 @@
package com.dunerealms.menus;
import java.util.List;
/** One clickable thing on a menu, in renderer-neutral form (used for Bedrock forms and fullscreen). */
public record Card(int slot, String title, List<String> lore, String material) {}

View file

@ -0,0 +1,37 @@
package com.dunerealms.menus;
import io.papermc.paper.event.player.AsyncChatEvent;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
/** One-line text input for Java and Bedrock alike: the next chat line is captured (not broadcast). "cancel" aborts. */
final class ChatPrompt implements Listener {
private static final Map<UUID, Consumer<String>> WAIT = new ConcurrentHashMap<>();
private final DuneMenusPlugin plugin;
ChatPrompt(DuneMenusPlugin plugin) { this.plugin = plugin; }
static void ask(Player p, String prompt, Consumer<String> done) {
WAIT.put(p.getUniqueId(), done);
p.sendMessage(Ui.text(prompt + " <dark_gray>(type <white>cancel</white> to go back)"));
}
@EventHandler(priority = EventPriority.LOWEST)
public void onChat(AsyncChatEvent e) {
var cb = WAIT.remove(e.getPlayer().getUniqueId());
if (cb == null) return;
e.setCancelled(true);
String text = PlainTextComponentSerializer.plainText().serialize(e.message()).trim();
Bukkit.getScheduler().runTask(plugin, () -> cb.accept(text.equalsIgnoreCase("cancel") ? null : text));
}
@EventHandler public void onQuit(PlayerQuitEvent e) { WAIT.remove(e.getPlayer().getUniqueId()); }
}

View file

@ -0,0 +1,35 @@
package com.dunerealms.menus;
import org.bukkit.Material;
import org.bukkit.entity.Player;
/** 6 rows. The crest in the middle, a plus-shaped spine of duties, and four diagonal spokes. */
final class ClanMenu extends Menu {
ClanMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); }
String id() { return "clan"; }
Skin skin() { return Skin.CLAN; }
String title() { return "House & Clan · Hearth"; }
String subtitle() { return "“A House is only as strong as its people.”"; }
int rows() { return 6; }
private void spoke(int slot, Material m, String name, String sub, String action) {
put(slot, Ui.item(m, name, "<gray>" + sub), t -> act(backend().orgAction(player, "clan", action)));
}
void draw() {
backdrop(Material.BLACK_STAINED_GLASS_PANE);
for (int s : new int[]{13, 21, 23, 31}) put(s, Ui.pane(Material.GREEN_STAINED_GLASS_PANE));
back(45);
put(22, Ui.item(Material.WHITE_BANNER, "<green><b>Your clan", "<gray>Loading…"));
load(backend().org(player, "clan"), o -> put(22, Ui.glow(Ui.item(Material.WHITE_BANNER, "<green><b>" + o.name(),
"<gray>Role: <white>" + o.role(), "<gray>Members: <white>" + o.members(), "<gray>Vault: <gold>" + Ui.dm(o.vaultMinor())))));
put(4, Ui.item(Material.PLAYER_HEAD, "<green>Members", "<gray>Your roster"), t -> go(new MembersMenu(plugin, player, this, "clan")));
spoke(40, Material.RED_BED, "<green>Clan home", "Teleport to base", "home");
spoke(20, Material.FILLED_MAP, "<gold>Territory", "Claims and borders", "claims");
spoke(24, Material.ENDER_CHEST, "<gold>Vault", "Shared funds", "vault");
spoke(11, Material.LEAD, "<aqua>Allies", "Friendly clans", "allies");
spoke(15, Material.DIAMOND_SWORD, "<red>Wars", "Active conflicts", "wars");
put(29, Ui.item(Material.IRON_SWORD, "<red>War muster", "<gray>Set your team"), t -> go(new WarMenu(plugin, player, this)));
spoke(33, Material.WRITABLE_BOOK, "<green>Invite", "Bring someone in", "invite");
}
}

View file

@ -0,0 +1,41 @@
package com.dunerealms.menus;
import org.bukkit.Material;
import org.bukkit.entity.Player;
/** 6 rows. Three labelled bands: Finance, People, Operations. Reads left to right like a ledger. */
final class CompanyMenu extends Menu {
CompanyMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); }
String id() { return "company"; }
Skin skin() { return Skin.COMPANY; }
String title() { return "Company · Ledger Hall"; }
String subtitle() { return "“Fortunes are built in ledgers before they are built in stone.”"; }
int rows() { return 6; }
private void tool(int slot, Material m, String name, String sub, String action) {
put(slot, Ui.item(m, name, "<gray>" + sub), t -> act(backend().orgAction(player, "company", action)));
}
void draw() {
backdrop(Material.BLACK_STAINED_GLASS_PANE);
for (int r = 1; r <= 3; r++) for (int c = 1; c <= 8; c++) put(r * 9 + c, Ui.pane(Material.CYAN_STAINED_GLASS_PANE));
back(45);
put(9, Ui.item(Material.GOLD_INGOT, "<gold><b>Finance"));
put(18, Ui.item(Material.PLAYER_HEAD, "<aqua><b>People"));
put(27, Ui.item(Material.LIGHTNING_ROD, "<white><b>Operations"));
put(4, Ui.item(Material.COPPER_BLOCK, "<aqua><b>Your company", "<gray>Loading…"));
load(backend().org(player, "company"), o -> {
put(4, Ui.glow(Ui.item(Material.COPPER_BLOCK, "<aqua><b>" + o.name(), "<gray>Role: <white>" + o.role(), "<gray>Members: <white>" + o.members())));
put(10, Ui.item(Material.GOLD_INGOT, "<gold>Balance", "<white>" + Ui.dm(o.vaultMinor())));
});
tool(11, Material.ENDER_CHEST, "<gold>Vault", "Move funds", "vault");
tool(12, Material.BOOK, "<gold>Transactions", "Recent activity", "transactions");
put(19, Ui.item(Material.PLAYER_HEAD, "<aqua>Members", "<gray>Your team"), t -> go(new MembersMenu(plugin, player, this, "company")));
tool(20, Material.NAME_TAG, "<aqua>Roles", "Who can do what", "roles");
tool(21, Material.WRITABLE_BOOK, "<aqua>Invite", "Bring someone in", "invite");
put(28, Ui.item(Material.EMERALD, "<green>Exchange", "<gray>Buy and sell"), t -> go(new ExchangeMenu(plugin, player, this)));
put(29, Ui.item(Material.BLAZE_POWDER, "<gold>Spice buyers", "<gray>Sell and collect"), t -> go(new SpiceMenu(plugin, player, this)));
tool(30, Material.MINECART, "<white>War transport", "Move your people", "war-transport");
tool(31, Material.LODESTONE, "<white>Home block", "Claims and deed", "claims");
}
}

View file

@ -0,0 +1,89 @@
package com.dunerealms.menus;
import java.util.List;
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;
import org.bukkit.plugin.java.JavaPlugin;
public final class DuneMenusPlugin extends JavaPlugin implements TabExecutor {
static final List<String> IDS = List.of("hub", "travel", "exchange", "clan", "company", "missions",
"spice", "war", "politics", "house", "equipment", "bank", "atm", "withdraw");
private Backend backend;
@Override
public void onEnable() {
saveDefaultConfig();
backend = JarvisBackend.create(this);
getLogger().info("Backend: " + backend.getClass().getSimpleName());
getServer().getPluginManager().registerEvents(new MenuListener(), this);
getServer().getPluginManager().registerEvents(new ChatPrompt(this), this);
getCommand("dm").setExecutor(this);
getCommand("dm").setTabCompleter(this);
}
Backend backend() { return backend; }
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;
if (getConfig().getBoolean("fullscreen.enabled", false) && fullscreen() != null) return Menu.Mode.FULLSCREEN;
return Menu.Mode.INVENTORY;
}
/** 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 ClanMenu(this, p, parent);
case "company" -> new CompanyMenu(this, p, parent);
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 "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 (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; }
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();
}
}

View file

@ -0,0 +1,28 @@
package com.dunerealms.menus;
import org.bukkit.Material;
import org.bukkit.entity.Player;
/** 3 rows. Left to right: your item, what it needs, the result. Click the result to refit at once. */
final class EquipmentMenu extends Menu {
EquipmentMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); }
String id() { return "equipment"; }
Skin skin() { return Skin.FORGE; }
String title() { return "Quartermaster · Refit"; }
String subtitle() { return "“Good gear can be made whole again.”"; }
int rows() { return 3; }
void draw() {
backdrop(Material.BLACK_STAINED_GLASS_PANE);
for (int s : new int[]{11, 12, 14, 15}) put(s, Ui.pane(Material.LIGHT_BLUE_STAINED_GLASS_PANE));
back(18);
load(backend().refitQuote(player), q -> {
put(10, Ui.item(q.icon(), "<white><b>" + q.itemName(), "<gray>Your original item"));
put(13, Ui.item(Material.IRON_INGOT, "<aqua><b>Needs", q.costs().stream().map(c -> "<gray>" + c).toArray(String[]::new)));
if (q.possible())
put(16, Ui.glow(Ui.item(Material.SMITHING_TABLE, "<green><b>Refit now", "<gray>" + q.note())), t -> act(backend().refit(player)));
else
put(16, Ui.item(Material.BARRIER, "<red>Can't refit yet", "<gray>" + q.note()));
});
}
}

View file

@ -0,0 +1,82 @@
package com.dunerealms.menus;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.entity.Player;
/** 6 rows. Vertical tabs on the left, a 7x4 shelf of goods, toolbar underneath. "Sell" is a price stall. */
final class ExchangeMenu extends Menu {
private static final List<Integer> SHELF = new ArrayList<>();
static { for (int r = 1; r <= 4; r++) for (int c = 2; c <= 8; c++) SHELF.add(r * 9 + c); }
private String tab = "buy";
private int page = 0;
private long price = 10_000;
ExchangeMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); }
String id() { return "exchange"; }
Skin skin() { return Skin.MARKET; }
String title() { return "Exchange · Merchant Hall"; }
String subtitle() { return "“Coin, cargo and rumour change hands here.”"; }
int rows() { return 6; }
private void tabButton(int slot, Material m, String label, String key) {
var item = Ui.item(m, (tab.equals(key) ? "<gold><b>" : "<gray>") + label);
if (tab.equals(key)) Ui.glow(item);
put(slot, item, t -> { tab = key; page = 0; redraw(); });
}
void draw() {
backdrop(Material.BROWN_STAINED_GLASS_PANE);
tabButton(9, Material.EMERALD, "Goods", "buy");
tabButton(18, Material.NETHERITE_CHESTPLATE, "Kits", "kits");
tabButton(27, Material.ENDER_CHEST, "My listings", "mine");
tabButton(36, Material.GOLD_NUGGET, "Sell", "sell");
back(46);
put(51, Ui.item(Material.CHEST, "<green>Collect purchases", "<gray>Move paid items to your inventory"),
t -> act(backend().collectPurchases(player)));
load(backend().balance(player), b -> put(47, Ui.item(Material.GOLD_INGOT, "<gold>Balance", "<white>" + Ui.dm(b))));
if (tab.equals("sell")) drawStall(); else drawShelf();
}
private void drawShelf() {
load(backend().listings(player, tab, page), pg -> {
boolean mine = tab.equals("mine");
for (int i = 0; i < SHELF.size() && i < pg.items().size(); i++) {
var l = pg.items().get(i);
put(SHELF.get(i), Ui.item(l.icon(), l.quantity(), "<white>" + l.title() + " <gray>· <gold>" + Ui.dm(l.priceMinor()),
"<gray>Seller: <white>" + l.seller(), "<gray>In stock: <white>" + l.quantity(), "",
mine ? "<yellow>Click to withdraw this listing"
: "<yellow>Click <gray>buy 1 <dark_gray>· <yellow>Shift-click <gray>buy " + Math.min(16, l.quantity())),
t -> {
if (mine) act(backend().withdraw(player, l));
else if (l.purchasable()) act(backend().buy(player, l, t.isShiftClick() && l.kitVersion() == null ? Math.min(16, l.quantity()) : 1));
});
}
put(49, Ui.item(Material.PAPER, "<gray>Page " + (page + 1)));
if (page > 0) put(45, Ui.item(Material.ARROW, "<gray>◀ Previous"), t -> { page--; redraw(); });
if (pg.hasNext()) put(53, Ui.item(Material.ARROW, "<gray>Next ▶"), t -> { page++; redraw(); });
});
}
private void chip(int slot, long delta) {
boolean up = delta > 0;
put(slot, Ui.item(up ? Material.LIME_DYE : Material.RED_DYE, (up ? "<green>+" : "<red>−") + Ui.dm(Math.abs(delta))),
t -> { price = Math.max(100, price + delta); redraw(); });
}
private void drawStall() {
var held = player.getInventory().getItemInMainHand().clone();
int heldSlot = player.getInventory().getHeldItemSlot();
long shownPrice = price;
boolean has = !held.getType().isAir();
put(13, has ? held.clone() : Ui.item(Material.BARRIER, "<red>Nothing in your hand"));
put(22, Ui.item(Material.OAK_SIGN, "<gray>Hold the item you want to sell", "<gray>in your main hand, set a price,", "<gray>then list it."));
chip(28, -10_000); chip(29, -1_000); chip(30, -100);
chip(32, 100); chip(33, 1_000); chip(34, 10_000);
put(31, Ui.item(Material.GOLD_NUGGET, "<gold><b>" + Ui.dm(price), "<gray>Price per item"));
put(40, Ui.glow(Ui.item(Material.EMERALD, "<green><b>List for " + Ui.dm(price))),
t -> { if (!has) { player.sendMessage(Ui.text("<red>Hold an item first.")); return; } act(backend().sell(player, held, heldSlot, shownPrice)); });
}
}

View file

@ -0,0 +1,18 @@
package com.dunerealms.menus;
import java.util.List;
import java.util.function.IntConsumer;
import org.bukkit.entity.Player;
/**
* Optional Bukkit service. Register an implementation (for example one that renders the HTML/CSS in /web
* through MCGUI or DuneFullscreenPaper) and set fullscreen.enabled: true. DuneMenus then hands every
* Java-edition menu to it; if open() returns false the player simply gets the chest menu.
*/
public interface FullscreenProvider {
/** id is the template name, for example "travel" or "exchange" (matches web/templates/<id>.html). */
record Screen(String id, String title, String subtitle, List<Card> cards, List<String> info) {}
/** Server thread. Call exactly one of select / close later, never inside open(). */
boolean open(Player viewer, Screen screen, IntConsumer select, Runnable close);
}

View file

@ -0,0 +1,28 @@
package com.dunerealms.menus;
import org.bukkit.Material;
import org.bukkit.entity.Player;
/** 3 rows. Five Houses arranged as a pentagon. One click declares allegiance. */
final class HouseMenu extends Menu {
private static final int[] DAIS = {4, 11, 15, 20, 24};
HouseMenu(DuneMenusPlugin plugin, Player p, Menu parent) { super(plugin, p, parent); }
String id() { return "house"; }
Skin skin() { return Skin.HOUSE; }
String title() { return "Choose your House"; }
String subtitle() { return "“Every story begins with a banner.”"; }
int rows() { return 3; }
void draw() {
backdrop(Material.BLACK_STAINED_GLASS_PANE);
back(18);
load(backend().houses(player), houses -> {
for (int i = 0; i < Math.min(DAIS.length, houses.size()); i++) {
var h = houses.get(i);
put(DAIS[i], Ui.item(h.banner(), "<#eed49a><b>" + h.name(), "<gray>" + h.motto(), "", "<yellow>Click to join"),
t -> load(backend().chooseHouse(player, h), r -> { say(r); end(); }));
}
});
}
}

View file

@ -0,0 +1,34 @@
package com.dunerealms.menus;
import org.bukkit.Material;
import org.bukkit.entity.Player;
/** 4 rows. The House crest on top, two rows of doors, and the Postbank and ATM at the bottom. */
final class HubMenu extends Menu {
HubMenu(DuneMenusPlugin plugin, Player p) { super(plugin, p, null); }
String id() { return "hub"; }
Skin skin() { return Skin.GOLD; }
String title() { return "Dune Realms"; }
String subtitle() { return "“The caravan endures. Where will you lead it?”"; }
int rows() { return 4; }
private void door(int slot, Material m, String name, String sub, String menu) {
put(slot, Ui.item(m, name, "<gray>" + sub), t -> go(plugin.create(menu, player, this)));
}
void draw() {
backdrop(Material.BLACK_STAINED_GLASS_PANE);
for (int i = 0; i < 9; i += 2) put(i, Ui.pane(Material.CYAN_STAINED_GLASS_PANE)); // holo strip
door(4, Material.WHITE_BANNER, "<#eed49a><b>Your House", "Allegiance and your Mentat", "house");
door(10, Material.COMPASS, "<#7fd6e8><b>Travel", "Imperial Guild passage", "travel");
door(12, Material.EMERALD, "<#f2c94c><b>Exchange", "Buy and sell", "exchange");
door(14, Material.WRITABLE_BOOK, "<#9fc27a><b>Missions", "Your journal", "missions");
door(16, Material.ANVIL, "<#7fb2d9><b>Equipment", "Refit your gear", "equipment");
door(19, Material.GREEN_BANNER, "<#4fbf8a><b>Clan", "Your people", "clan");
door(21, Material.COPPER_BLOCK, "<#5cc8d6><b>Company", "Your business", "company");
door(23, Material.LECTERN, "<#b07ce8><b>Politics", "Decisions of your office", "politics");
door(25, Material.BLAZE_POWDER, "<#e07b2e><b>Spice", "Sell and collect", "spice");
door(29, Material.GOLD_BLOCK, "<#f2c94c><b>Imperial Postbank", "Your account", "bank");
door(33, Material.LIGHTNING_ROD, "<#7fd6e8><b>ATM", "Quick deposit and withdrawal", "atm");
}
}

View file

@ -0,0 +1,317 @@
package com.dunerealms.menus;
import com.dunerealms.jarvis.JarvisTranslator;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.inventory.ItemStack;
final class JarvisBackend implements Backend {
private final JavaPlugin plugin;
private final JarvisTranslator jarvis;
private final Set<UUID> pending = new HashSet<>();
private final Map<UUID, Purchase> retries = new HashMap<>();
private record Purchase(Listing offer, int amount, UUID reference) {}
@FunctionalInterface private interface Call<T> {
T run() throws Exception;
}
private JarvisBackend(JavaPlugin plugin, JarvisTranslator jarvis) {
this.plugin = plugin;
this.jarvis = jarvis;
}
static Backend create(JavaPlugin plugin) {
var bridge = Bukkit.getPluginManager().getPlugin("JarvisTranslator");
if (bridge instanceof JarvisTranslator jarvis && jarvis.isEnabled()) return new JarvisBackend(plugin, jarvis);
plugin.getLogger().warning("J.A.R.V.I.S. is unavailable. Menu actions are disabled.");
return new Backend() {};
}
private <T> CompletableFuture<T> remote(Player player, Call<T> call) {
if (!Bukkit.isPrimaryThread() || !player.isOnline() || !jarvis.isEnabled())
return CompletableFuture.failedFuture(new Unavailable());
UUID world = player.getWorld().getUID();
var future = new CompletableFuture<T>();
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
T value = call.run();
Bukkit.getScheduler().runTask(plugin, () -> {
if (player.isOnline() && world.equals(player.getWorld().getUID())) future.complete(value);
else future.completeExceptionally(new Unavailable());
});
} catch (Exception failure) {
Bukkit.getScheduler().runTask(plugin, () -> future.completeExceptionally(failure));
}
});
return future;
}
private CompletableFuture<Result> once(Player player, Call<CompletableFuture<Result>> callback) {
UUID id = player.getUniqueId();
if (!pending.add(id)) return CompletableFuture.completedFuture(Result.no("J.A.R.V.I.S. is processing your action."));
try {
return callback.run().whenComplete((value, error) -> pending.remove(id));
} catch (Exception failure) {
pending.remove(id);
return CompletableFuture.failedFuture(failure);
}
}
@Override public CompletableFuture<Page> listings(Player player, String tab, int page) {
if (!Set.of("buy", "kits", "mine").contains(tab) || page < 0)
return CompletableFuture.failedFuture(new IllegalArgumentException("Invalid Exchange page."));
var input = action(tab.equals("kits") ? "read_kits" : "read");
input.addProperty("page", page);
if (!tab.equals("kits")) input.addProperty("mine", tab.equals("mine"));
UUID id = player.getUniqueId();
return remote(player, () -> accepted(jarvis.requestExchange(id, input))).thenApply(data -> {
var items = new ArrayList<Listing>();
for (var entry : array(data, "listings")) {
var row = entry.getAsJsonObject();
boolean kit = tab.equals("kits");
try {
var item = kit ? Material.NETHERITE_CHESTPLATE : jarvis.exchangeIcon(row).getType();
items.add(new Listing(text(row, kit ? "kitsetId" : "id"), display(row,"title"), item, display(row,"seller"),
row.get("priceMinor").getAsLong(), kit ? 1 : row.get("quantity").getAsInt(),
kit ? row.get("listingVersion").getAsInt() : null, !kit || yes(row,"purchaseAvailable")));
} catch (RuntimeException invalid) {
plugin.getLogger().warning("Skipped an unsupported Exchange listing");
}
}
return new Page(List.copyOf(items), yes(data,"hasNext"));
});
}
@Override public CompletableFuture<Result> buy(Player player, Listing offer, int quantity) {
UUID id = player.getUniqueId();
return once(player, () -> {
if (!offer.purchasable() || quantity < 1 || quantity > offer.quantity() || offer.priceMinor() < 1)
return CompletableFuture.completedFuture(Result.no("This offer is unavailable."));
var purchase = retries.computeIfAbsent(id, ignored -> new Purchase(offer, quantity, UUID.randomUUID()));
if (!purchase.offer().equals(offer) || purchase.amount() != quantity)
return CompletableFuture.completedFuture(Result.no("Retry the same listing and quantity before starting a new purchase."));
var query = purchaseRequest(offer, quantity, purchase.reference());
return remote(player, () -> jarvis.requestExchange(id, query)).thenApply(response -> {
retries.remove(id);
if (response.has("rejectedStatus")) return Result.no(reason(response));
try {
if (offer.kitVersion() == null) jarvis.exchangeDeliver(player);
else jarvis.refreshKits(player);
} catch (Exception unavailable) {
return Result.yes("Purchase paid. Delivery remains queued.");
}
return Result.yes("Purchase paid.");
});
});
}
@Override public CompletableFuture<Result> sell(Player player, ItemStack expected, int slot, long priceMinor) {
return once(player, () -> {
var held = expected.clone();
if (held.isEmpty() || slot != player.getInventory().getHeldItemSlot() ||
!held.equals(player.getInventory().getItemInMainHand()) || priceMinor < 1 || priceMinor > 100_000_000)
return CompletableFuture.completedFuture(Result.no("Hold a valid listing item and choose a valid price."));
int amount = Math.min(64, held.getAmount());
UUID owner = player.getUniqueId(), reference = UUID.randomUUID();
var query = action("prepare_sale");
query.addProperty("requestId", reference.toString());
query.addProperty("amount", amount);
query.addProperty("priceMinor", priceMinor);
return remote(player, () -> accepted(jarvis.requestExchange(owner, query))).thenApply(permit -> {
try {
jarvis.exchangePublish(player, permit, reference, held, slot, amount, priceMinor);
return Result.yes("Listing published.");
} catch (Exception failure) {
return Result.no("The listing was not confirmed.");
}
});
});
}
@Override public CompletableFuture<Result> withdraw(Player player, Listing offer) {
return once(player, () -> {
if (offer.kitVersion() != null || !offer.id().matches("[1-9][0-9]{0,18}"))
return CompletableFuture.completedFuture(Result.no("This listing cannot be withdrawn here."));
long id = Long.parseLong(offer.id());
UUID owner = player.getUniqueId(), reference = UUID.randomUUID();
var query = action("prepare_cancel");
query.addProperty("requestId", reference.toString());
return remote(player, () -> accepted(jarvis.requestExchange(owner, query))).thenApply(permit -> {
try {
return Result.yes("Returned " + jarvis.exchangeCancel(player, permit, reference, id) + " items.");
} catch (Exception failure) {
return Result.no("Withdrawal was not confirmed.");
}
});
});
}
@Override public CompletableFuture<Result> collectPurchases(Player player) {
return once(player, () -> CompletableFuture.completedFuture(
Result.yes("Collected " + jarvis.exchangeDeliver(player) + " items.")));
}
@Override public CompletableFuture<List<Mission>> missions(Player player) {
UUID owner = player.getUniqueId();
return remote(player, () -> {
var result = new ArrayList<Mission>();
for (String kind : List.of("personal","pol")) for (var entry : quests(owner,kind)) {
var row = entry.getAsJsonObject();
boolean claim = yes(row,"canClaim") && !websiteOnly(row);
String current = text(row,"state");
String state = claim || current.equals("active") ? "ACTIVE" :
Set.of("completed","claimed").contains(current) ? "DONE" : canStart(row) ? "AVAILABLE" : "ACTIVE";
long target = row.has("target") ? row.get("target").getAsLong() : 0;
long progress = row.has("progress") ? row.get("progress").getAsLong() : 0;
int percent = target <= 0 ? 0 : (int)Math.max(0, Math.min(100, Math.round(progress * 100d / target)));
result.add(new Mission(kind+":"+text(row,"id"), display(row,"title"), Material.WRITABLE_BOOK,
state, percent, claim, display(row,"objective"), revision(row)));
}
return List.copyOf(result);
});
}
@Override public CompletableFuture<Result> missionAction(Player player, Mission mission, boolean claim) {
UUID owner = player.getUniqueId();
return once(player, () -> remote(player, () -> {
String[] key = mission.id().split(":", 2);
if (key.length != 2 || !Set.of("personal","pol").contains(key[0])) return Result.no("Invalid mission.");
for (var entry : quests(owner,key[0])) {
var row = entry.getAsJsonObject();
if (!key[1].equals(text(row,"id"))) continue;
if (websiteOnly(row) || (claim ? !yes(row,"canClaim") : !canStart(row)))
return Result.no("That mission action is unavailable.");
var query = action(claim ? "claim" : "start");
query.addProperty("kind",key[0]);
query.addProperty("definitionId",key[1]);
query.addProperty("confirmed",true);
query.addProperty("requestId",UUID.randomUUID().toString());
if (claim) {
if (mission.revision() == null || !mission.revision().equals(revision(row)))
return Result.no("Mission progress changed. Reopen the journal.");
query.addProperty("revision",mission.revision());
}
accepted(jarvis.requestQuests(owner,query));
return Result.yes(claim ? "Verified quest reward recorded." : "Mission accepted.");
}
return Result.no("That mission is no longer available.");
}));
}
@Override public CompletableFuture<List<House>> houses(Player player) {
UUID owner = player.getUniqueId();
return remote(player, () -> {
var data = accepted(jarvis.requestHouse(owner, null, 0, null));
var choices = new ArrayList<House>();
for (var entry : array(data,"choices")) {
var house = entry.getAsJsonObject();
String id = text(house,"id");
Material banner = switch (id) {
case "atreides" -> Material.GREEN_BANNER;
case "corrino" -> Material.YELLOW_BANNER;
case "fremen" -> Material.ORANGE_BANNER;
case "harkonnen" -> Material.RED_BANNER;
case "ordos" -> Material.CYAN_BANNER;
default -> null;
};
if (banner != null) choices.add(new House(id,display(house,"name"),display(house,"motto"),
banner,data.get("version").getAsInt()));
}
return List.copyOf(choices);
});
}
@Override public CompletableFuture<Result> chooseHouse(Player player, House choice) {
UUID owner = player.getUniqueId();
return once(player, () -> remote(player, () -> {
accepted(jarvis.requestHouse(owner,choice.id(),choice.version(),UUID.randomUUID()));
return Result.yes("House allegiance saved in J.A.R.V.I.S.");
}));
}
private JsonArray quests(UUID owner, String kind) throws Exception {
var query = action("read");
query.addProperty("kind",kind);
return array(accepted(jarvis.requestQuests(owner,query)),"quests");
}
private static Long revision(JsonObject row) {
return row.has("revision")&&!row.get("revision").isJsonNull() ? row.get("revision").getAsLong() : null;
}
static JsonObject purchaseRequest(Listing offer, int quantity, UUID reference) {
var query = action(offer.kitVersion() == null ? "buy" : "buy_kit");
query.addProperty("requestId", reference.toString());
query.addProperty("priceMinor", offer.priceMinor());
query.addProperty("confirmed", true);
if (offer.kitVersion() == null) {
query.addProperty("listingId", offer.id());
query.addProperty("amount", quantity);
} else {
query.addProperty("kitsetId", offer.id());
query.addProperty("listingVersion", offer.kitVersion());
}
return query;
}
static boolean canStart(JsonObject row) {
return !websiteOnly(row) && yes(row,"canStart") && !yes(row,"canClaim") &&
!Set.of("active","completed","claimed").contains(text(row,"state")) &&
(!row.has("cooldownUntil") || row.get("cooldownUntil").isJsonNull() ||
row.get("cooldownUntil").getAsLong() <= System.currentTimeMillis());
}
private static boolean websiteOnly(JsonObject row) {
if (!row.has("executionRequirements") || !row.get("executionRequirements").isJsonObject()) return false;
var requirements = row.getAsJsonObject("executionRequirements");
return yes(requirements,"website") && !yes(requirements,"minecraft");
}
private static JsonObject action(String name) {
var input = new JsonObject();
input.addProperty("action",name);
return input;
}
private static JsonObject accepted(JsonObject response) throws IOException {
if (response == null || response.has("rejectedStatus") || (response.has("ok") && !yes(response,"ok")))
throw new IOException(reason(response));
return response;
}
private static String reason(JsonObject response) {
String message = response == null ? "" : text(response,"message");
return message.isBlank() ? "J.A.R.V.I.S. rejected the request." : message;
}
private static JsonArray array(JsonObject row, String key) {
return row.has(key) && row.get(key).isJsonArray() ? row.getAsJsonArray(key) : new JsonArray();
}
private static String text(JsonObject row, String key) {
return row.has(key) && !row.get(key).isJsonNull() ? row.get(key).getAsString() : "";
}
private static String display(JsonObject row, String key) {
return MiniMessage.miniMessage().escapeTags(text(row,key));
}
private static boolean yes(JsonObject row, String key) {
return row.has(key) && !row.get(key).isJsonNull() && row.get(key).getAsBoolean();
}
}

Some files were not shown because too many files have changed in this diff Show more