Restore retained native menu facade and safe service navigation
This commit is contained in:
parent
6807bbcdde
commit
ea16e0e93d
19 changed files with 231 additions and 19 deletions
|
|
@ -18,3 +18,6 @@
|
|||
- Use the canonical illustrated website logo with proportional containment. Package/cache artwork locally and keep remote requests out of menu opening.
|
||||
|
||||
- Owner approved compact card density across Java menus: standard cards approximately 25% smaller, Exchange navigation as a toolbar, and mission cards in a grid. Preserve readable prices and click targets.
|
||||
- Before changing this foundation, run the retained NativeMenus public-ABI and lifecycle tests, native route tests, pending-purchase safety tests, and pinned MCGUI renderer checks for containment, icon centering and original action hitboxes. Source tests alone do not prove connected-client actions work.
|
||||
- Inspect and reuse existing JARVIS keys, records and authoritative service flows first. Preserve callback identity, lifecycle gates and pending payment references; do not create alternate domain engines to work around a presentation fault.
|
||||
- An accepted release must be tagged and backed up only after actual functional acceptance. Never freeze a known broken candidate or deploy a documentation-only artifact.
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import java.security.MessageDigest
|
||||
plugins { java }
|
||||
group = "com.dunerealms"
|
||||
version = "2.0.3"
|
||||
version = "2.0.4"
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven("https://repo.papermc.io/repository/maven-public/")
|
||||
|
|
@ -10,6 +10,7 @@ repositories {
|
|||
dependencies {
|
||||
compileOnly(project(":JarvisConnector"))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
||||
testImplementation("org.mockito:mockito-core:5.15.2")
|
||||
testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
|
||||
testImplementation(project(":JarvisConnector"))
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import org.bukkit.entity.Player;
|
|||
* 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 }
|
||||
enum Tab { HOME, DEPOSIT, REDEEM, WITHDRAW }
|
||||
private static final int[] BILLS = {10, 11, 12, 19, 20};
|
||||
private static final int[] COINS = {14, 15, 16};
|
||||
private static final List<DunemarkDenomination> NOTES = List.of(DunemarkDenomination.NOTE_10, DunemarkDenomination.NOTE_20,
|
||||
|
|
@ -31,10 +31,13 @@ final class AtmMenu extends Menu {
|
|||
Skin skin() { return tab == Tab.REDEEM ? Skin.GOLD : Skin.TRAVEL; }
|
||||
String title() { return "Rihla ATM"; }
|
||||
String subtitle() { return switch (tab) {
|
||||
case HOME -> "Choose a cash service. Bills and coins are selected inside the operation.";
|
||||
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; }
|
||||
@Override boolean renderWhileLoading(){return true;}
|
||||
@Override boolean navigationWhileLoading(int slot){return slot==0||slot==1||slot==2||slot==36;}
|
||||
|
||||
private void tabButton(int slot, Material m, String label, Tab t) {
|
||||
var item = Ui.item(m, (tab == t ? "<green><b>" : "<gray>") + label);
|
||||
|
|
@ -42,7 +45,8 @@ final class AtmMenu extends Menu {
|
|||
}
|
||||
|
||||
private void add(int slot, DunemarkDenomination denomination) {
|
||||
put(slot, denomination.displayItem(), c -> {
|
||||
var selector=denomination.displayItem();var meta=selector.getItemMeta();meta.displayName(net.kyori.adventure.text.Component.text(Ui.dm(denomination.faceMinor())));meta.lore(List.of(net.kyori.adventure.text.Component.text("Select one for this "+(tab==Tab.DEPOSIT?"deposit":"withdrawal"))));selector.setItemMeta(meta);
|
||||
put(slot, selector, c -> {
|
||||
if (selected.size() < 36) selected.add(denomination);
|
||||
redraw();
|
||||
});
|
||||
|
|
@ -55,6 +59,7 @@ final class AtmMenu extends Menu {
|
|||
tabButton(1, Material.NAME_TAG, "Redeem RIA ID", Tab.REDEEM);
|
||||
tabButton(2, Material.GOLD_INGOT, "Withdraw cash", Tab.WITHDRAW);
|
||||
back(36);
|
||||
if(tab==Tab.HOME)return;
|
||||
if (tab == Tab.REDEEM) drawRedeem(); else drawCash();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -81,6 +81,27 @@ public final class DuneMenusPlugin extends JavaPlugin implements TabExecutor {
|
|||
player.sendMessage("The native Exchange service is temporarily unavailable. Please retry later.");
|
||||
}
|
||||
|
||||
void openNativeService(Player player,String id){
|
||||
var gui=getServer().getPluginManager().getPlugin("DunerealmsGUI");
|
||||
if(gui!=null&&gui.isEnabled())try{gui.getClass().getMethod("openNativeMenu",Player.class,String.class).invoke(gui,player,id);return;}catch(ReflectiveOperationException failure){getLogger().warning("Native service entry failed: "+id+" / "+failure.getClass().getSimpleName());}
|
||||
player.sendMessage("The native "+id+" service is temporarily unavailable.");
|
||||
}
|
||||
void closeNativePresentation(Player player){var gui=getServer().getPluginManager().getPlugin("DunerealmsGUI");if(gui!=null&&gui.isEnabled())try{gui.getClass().getMethod("closeSuppliedMenu",Player.class).invoke(gui,player);}catch(ReflectiveOperationException failure){getLogger().warning("Native presentation close failed");}}
|
||||
public boolean show(JavaPlugin owner,Player player,String title,org.bukkit.inventory.Inventory model,Map<Integer,Runnable> actions,java.util.function.BooleanSupplier gate){
|
||||
if(!getServer().isPrimaryThread()||!owner.isEnabled()||!player.isOnline()||!player.hasPermission("dunemenus.use"))return false;
|
||||
new LegacyInventoryMenu(this,owner,player,title,model,actions,gate).open();return true;
|
||||
}
|
||||
public boolean show(JavaPlugin owner,Player player,String title,org.bukkit.inventory.Inventory model,Map<Integer,Runnable> actions){return show(owner,player,title,model,actions,()->true);}
|
||||
public boolean isCurrent(Player player,org.bukkit.inventory.Inventory model){var menu=openMenus.get(player.getUniqueId());return menu instanceof LegacyInventoryMenu legacy&&legacy.matches(model);}
|
||||
public void close(Player player,org.bukkit.inventory.Inventory model){var menu=openMenus.get(player.getUniqueId());if(menu instanceof LegacyInventoryMenu legacy&&legacy.matches(model))legacy.finish();}
|
||||
public boolean showChoices(JavaPlugin owner,Player player,String title,String description,List<?> choices){
|
||||
if(choices.size()>54||!getServer().isPrimaryThread())return false;
|
||||
var model=getServer().createInventory(null,Math.max(9,((choices.size()+8)/9)*9));var actions=new HashMap<Integer,Runnable>();
|
||||
try{int slot=0;for(Object choice:choices){String label=(String)choice.getClass().getMethod("label").invoke(choice),detail=(String)choice.getClass().getMethod("description").invoke(choice);Runnable action=(Runnable)choice.getClass().getMethod("action").invoke(choice);var item=new org.bukkit.inventory.ItemStack(org.bukkit.Material.PAPER);var meta=item.getItemMeta();meta.displayName(Component.text(label));meta.lore(List.of(Component.text(detail)));item.setItemMeta(meta);model.setItem(slot,item);if(action!=null)actions.put(slot,action);slot++;}}catch(ReflectiveOperationException|ClassCastException failure){getLogger().warning("Native choice contract differs: "+failure.getClass().getSimpleName());return false;}
|
||||
if(!owner.isEnabled()||!player.isOnline()||!player.hasPermission("dunemenus.use"))return false;
|
||||
new LegacyInventoryMenu(this,owner,player,title,description,model,actions,()->true).open();return true;
|
||||
}
|
||||
|
||||
public void openMenu(Player player, String menu) {
|
||||
if (player.hasPermission("dunemenus.use")) create(menu, player, null).open();
|
||||
}
|
||||
|
|
@ -145,6 +166,7 @@ public final class DuneMenusPlugin extends JavaPlugin implements TabExecutor {
|
|||
}
|
||||
|
||||
Menu create(String id, Player p, Menu parent) {
|
||||
if(NativeServiceMenu.IDS.contains(id.toLowerCase(java.util.Locale.ROOT)))return new NativeServiceMenu(this,p,parent,id.toLowerCase(java.util.Locale.ROOT));
|
||||
return switch (id.toLowerCase()) {
|
||||
case "travel" -> new TravelMenu(this, p, parent);
|
||||
case "exchange" -> new ExchangeMenu(this, p, parent);
|
||||
|
|
@ -159,7 +181,7 @@ public final class DuneMenusPlugin extends JavaPlugin implements TabExecutor {
|
|||
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 "atm" -> new AtmMenu(this, p, parent, AtmMenu.Tab.HOME);
|
||||
case "withdraw" -> new AtmMenu(this, p, parent, AtmMenu.Tab.WITHDRAW);
|
||||
default -> new HubMenu(this, p);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -0,0 +1,13 @@
|
|||
package com.dunerealms.menus;
|
||||
import java.util.*;import java.util.function.BooleanSupplier;
|
||||
import org.bukkit.entity.Player;import org.bukkit.inventory.Inventory;import org.bukkit.plugin.java.JavaPlugin;
|
||||
/** Exact adapter for retained Core/Ess NativeMenus. Their gate and callbacks remain authoritative. */
|
||||
final class LegacyInventoryMenu extends Menu {
|
||||
private final JavaPlugin owner;private final Inventory model;private final String heading,note;private final Map<Integer,Runnable> actions;private final BooleanSupplier gate;private final UUID world;
|
||||
LegacyInventoryMenu(DuneMenusPlugin plugin,JavaPlugin owner,Player player,String title,Inventory model,Map<Integer,Runnable> actions,BooleanSupplier gate){this(plugin,owner,player,title,"",model,actions,gate);}
|
||||
LegacyInventoryMenu(DuneMenusPlugin plugin,JavaPlugin owner,Player player,String title,String description,Inventory model,Map<Integer,Runnable> actions,BooleanSupplier gate){super(plugin,player,null);note=description;this.owner=owner;this.model=model;heading=title;this.actions=Map.copyOf(actions);this.gate=gate;world=player.getWorld().getUID();}
|
||||
boolean matches(Inventory expected){return model==expected&&owner.isEnabled()&&player.isOnline()&&world.equals(player.getWorld().getUID())&&plugin.hasOpenMenu(player,this);}
|
||||
void finish(){end();plugin.closeNativePresentation(player);}
|
||||
String id(){return ServiceSection.of(heading);}Skin skin(){return Skin.GOLD;}String title(){return heading;}String subtitle(){return note;}int rows(){return Math.max(1,Math.min(6,(model.getSize()+8)/9));}
|
||||
void draw(){for(int slot=0;slot<model.getSize()&&slot<54;slot++){var item=model.getItem(slot);if(item==null)continue;var action=actions.get(slot);if(action==null)put(slot,item.clone());else put(slot,item.clone(),click->{if(matches(model)&&gate.getAsBoolean())action.run();});}}
|
||||
}
|
||||
|
|
@ -44,6 +44,8 @@ abstract class Menu implements InventoryHolder {
|
|||
abstract void draw();
|
||||
String subtitle() { return ""; }
|
||||
boolean launchNative() { return false; }
|
||||
boolean renderWhileLoading() { return false; }
|
||||
boolean navigationWhileLoading(int slot) { return false; }
|
||||
|
||||
@Override public Inventory getInventory() { return inv; }
|
||||
protected Backend backend() { return plugin.backend(); }
|
||||
|
|
@ -89,18 +91,20 @@ abstract class Menu implements InventoryHolder {
|
|||
redrawn = true; gen++; pending = 0;
|
||||
inv.clear(); buttons.clear();
|
||||
draw();
|
||||
if (pending == 0) present();
|
||||
if (pending == 0 || renderWhileLoading()) present();
|
||||
}
|
||||
|
||||
final void handle(int slot, ClickType type) {
|
||||
Button b = buttons.get(slot);
|
||||
if (b == null || !active || pending != 0) return;
|
||||
player.playSound(player.getLocation(), skin().click(), 0.5f, 1.2f);
|
||||
if (b == null || !active || pending != 0 && !navigationWhileLoading(slot)) return;
|
||||
clickFeedback();
|
||||
redrawn = false;
|
||||
b.click(type);
|
||||
if (active && !redrawn && pending == 0) present(); // keep forms/screens alive
|
||||
}
|
||||
|
||||
protected void clickFeedback() { player.playSound(player.getLocation(), skin().click(), 0.5f, 1.2f); }
|
||||
|
||||
// ---------------------------------------------------------------- drawing helpers
|
||||
protected void backdrop(Material m) { ItemStack p = Ui.pane(m); for (int i = 0; i < inv.getSize(); i++) inv.setItem(i, p); }
|
||||
protected void put(int slot, ItemStack item) { if (slot >= 0 && slot < inv.getSize()) inv.setItem(slot, item); }
|
||||
|
|
@ -118,7 +122,7 @@ abstract class Menu implements InventoryHolder {
|
|||
if (err != null) {
|
||||
Throwable cause = err instanceof CompletionException && err.getCause() != null ? err.getCause() : err;
|
||||
player.sendMessage(Ui.text(cause instanceof Backend.Unavailable
|
||||
? "<red>This service isn't connected to the new menus yet."
|
||||
? "<red>J.A.R.V.I.S. could not complete this request. Reopen this menu."
|
||||
: "<red>Something went wrong. Please try again."));
|
||||
} else ok.accept(value);
|
||||
if (g == gen && pending == 0) present();
|
||||
|
|
|
|||
|
|
@ -0,0 +1,11 @@
|
|||
package com.dunerealms.menus;
|
||||
import java.util.Set;import org.bukkit.entity.Player;
|
||||
/** Only the presentation changes; original JARVIS/native service callbacks own behaviour. */
|
||||
final class NativeServiceMenu extends Menu {
|
||||
static final Set<String> IDS=Set.of("hub","travel","exchange","clan","company","missions","spice","war","politics","lore","mentat","house","equipment");
|
||||
private final String target;
|
||||
NativeServiceMenu(DuneMenusPlugin plugin,Player player,Menu parent,String target){super(plugin,player,parent);this.target=target;}
|
||||
@Override boolean launchNative(){plugin.openNativeService(player,target);return true;}
|
||||
String id(){return target;}Skin skin(){return Skin.GOLD;}String title(){return "Imperial services";}int rows(){return 6;}
|
||||
void draw(){throw new IllegalStateException("Native service presentation required");}
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
package com.dunerealms.menus;
|
||||
import java.util.Locale;
|
||||
final class ServiceSection {
|
||||
static String of(String title){String t=title.toLowerCase(Locale.ROOT);if(t.contains("war")||t.contains("muster"))return "war";if(t.contains("quest")||t.contains("mission"))return "missions";if(t.contains("exchange"))return "exchange";if(t.contains("spice"))return "spice";if(t.contains("guild")||t.contains("travel")||t.contains("navigator"))return "travel";if(t.contains("clan")||t.contains("company")||t.contains("house"))return "house";return "hub";}
|
||||
}
|
||||
|
|
@ -9,7 +9,7 @@ final class SuppliedDocument {
|
|||
static List<String> lines(String text,int width){List<String> out=new ArrayList<>();String rest=clean(text);while(rest.length()>width){int split=rest.lastIndexOf(' ',width);if(split<width/2)split=width;out.add(rest.substring(0,split));rest=rest.substring(split).stripLeading();}if(!rest.isBlank())out.add(rest);return out;}
|
||||
static List<String> summary(Card card){List<String> ordered=new ArrayList<>();for(String pattern:List.of("(?i).*\\bDM\\b.*","(?i).*(available|in stock).*","(?i).*seller:.*"))for(String line:card.lore())if(clean(line).matches(pattern)&&!ordered.contains(line))ordered.add(line);for(String line:card.lore())if(!ordered.contains(line))ordered.add(line);List<String> out=new ArrayList<>();for(String line:ordered)out.addAll(lines(line,24));return out;}
|
||||
static String image(Card c,Map<Integer,String> images){String image=images.getOrDefault(c.slot(),"");return image.matches("pack/assets/[a-z0-9_/.-]+\\.png")&&!image.contains("..")?"<img class='item-icon' src='"+image+"'>":symbol(c);}
|
||||
static boolean marketTool(Card c){return Set.of(1,4,7,45,48,49,50,53).contains(c.slot())&&Set.of("Buy","Buy items","Kits","My listings","Sell item","Imperial Codex","Collect purchases","Previous","Next","Back").contains(clean(c.title()));}
|
||||
static boolean marketTool(Card c){return Set.of(1,4,7,45,46,48,49,50,53).contains(c.slot())&&Set.of("Buy","Buy items","Kits","My listings","Sell item","Imperial Codex","Collect purchases","Resume pending purchase","Previous","Next","Back").contains(clean(c.title()));}
|
||||
static String kind(Card c){if(!c.material().equals("arrow"))return "card";String t=clean(c.title()).toLowerCase(Locale.ROOT);return t.contains("back")?"back":t.contains("previous")||t.contains("next")?"pager":"card";}
|
||||
static String html(String id,String title,String subtitle,List<Card> cards,List<String> info){return html(id,title,subtitle,cards,info,Map.of());}
|
||||
static String html(String id,String title,String subtitle,List<Card> cards,List<String> info,Map<Integer,String> images){return html(id,title,subtitle,cards,info,images,-1);}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,116 @@
|
|||
package com.dunerealms.menus;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.ClickType;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Exercises actual menu lifecycle without a server, inventory mutations or financial requests. */
|
||||
class NativeMenuLifecycleTest {
|
||||
@Test void retainedActionSeesCurrentInventoryAndGateRemainsAuthoritative() {
|
||||
try (var bukkit = mockStatic(Bukkit.class)) {
|
||||
var f = new Fixture(bukkit);
|
||||
JavaPlugin owner = mock(JavaPlugin.class);
|
||||
when(owner.isEnabled()).thenReturn(true);
|
||||
Inventory original = mock(Inventory.class);
|
||||
when(original.getSize()).thenReturn(9);
|
||||
when(original.getItem(0)).thenReturn(f.item);
|
||||
AtomicBoolean allowed = new AtomicBoolean(false);
|
||||
Runnable action = mock(Runnable.class);
|
||||
var menu = spy(new LegacyInventoryMenu(f.plugin, owner, f.player, "Navigator", original,
|
||||
Map.of(0, action), allowed::get));
|
||||
doNothing().when(menu).clickFeedback();
|
||||
when(f.plugin.hasOpenMenu(f.player, menu)).thenReturn(true);
|
||||
menu.open();
|
||||
menu.handle(0, ClickType.LEFT);
|
||||
verifyNoInteractions(action);
|
||||
allowed.set(true);
|
||||
doAnswer(call -> { assertTrue(menu.matches(original)); return null; }).when(action).run();
|
||||
menu.handle(0, ClickType.LEFT);
|
||||
verify(action).run();
|
||||
assertFalse(menu.matches(mock(Inventory.class)));
|
||||
when(f.plugin.hasOpenMenu(f.player, menu)).thenReturn(false);
|
||||
menu.handle(0, ClickType.LEFT);
|
||||
verifyNoMoreInteractions(action);
|
||||
when(f.plugin.hasOpenMenu(f.player, menu)).thenReturn(true);
|
||||
when(owner.isEnabled()).thenReturn(false);
|
||||
menu.handle(0, ClickType.LEFT);
|
||||
verifyNoMoreInteractions(action);
|
||||
}
|
||||
}
|
||||
|
||||
@Test void navigationSurvivesSlowReadsButActionAndStaleCompletionDoNot() {
|
||||
try (var bukkit = mockStatic(Bukkit.class)) {
|
||||
var f = new Fixture(bukkit);
|
||||
var scheduler = mock(BukkitScheduler.class);
|
||||
bukkit.when(Bukkit::getScheduler).thenReturn(scheduler);
|
||||
doAnswer(call -> { ((Runnable) call.getArgument(1)).run(); return null; })
|
||||
.when(scheduler).runTask(eq(f.plugin), any(Runnable.class));
|
||||
class LoadingMenu extends Menu {
|
||||
final CompletableFuture<String> first = new CompletableFuture<>();
|
||||
int page, actions, completions;
|
||||
LoadingMenu() { super(f.plugin, f.player, null); }
|
||||
String id(){return "hub";} Skin skin(){return Skin.GOLD;}
|
||||
String title(){return "Loading";} int rows(){return 1;}
|
||||
boolean renderWhileLoading(){return true;}
|
||||
boolean navigationWhileLoading(int slot){return slot==0;}
|
||||
protected void clickFeedback(){}
|
||||
void draw(){
|
||||
put(0,f.item,click->{page++;redraw();});
|
||||
put(1,f.item,click->actions++);
|
||||
if(page==0)load(first,value->completions++);
|
||||
}
|
||||
}
|
||||
var menu = new LoadingMenu();
|
||||
menu.open();
|
||||
verify(f.provider).open(eq(f.player),any(),any(),any());
|
||||
menu.handle(1,ClickType.LEFT);
|
||||
assertEquals(0,menu.actions);
|
||||
menu.handle(0,ClickType.LEFT);
|
||||
assertEquals(1,menu.page);
|
||||
menu.first.complete("old page");
|
||||
assertEquals(0,menu.completions);
|
||||
menu.handle(1,ClickType.LEFT);
|
||||
assertEquals(1,menu.actions);
|
||||
menu.closed();
|
||||
menu.handle(1,ClickType.LEFT);
|
||||
assertEquals(1,menu.actions);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Fixture {
|
||||
final DuneMenusPlugin plugin=mock(DuneMenusPlugin.class);
|
||||
final Player player=mock(Player.class);
|
||||
final FullscreenProvider provider=mock(FullscreenProvider.class);
|
||||
final ItemStack item=mock(ItemStack.class);
|
||||
Fixture(org.mockito.MockedStatic<Bukkit> bukkit){
|
||||
var world=mock(World.class);when(world.getUID()).thenReturn(UUID.randomUUID());
|
||||
when(player.getWorld()).thenReturn(world);when(player.isOnline()).thenReturn(true);
|
||||
when(plugin.modeFor(player)).thenReturn(Menu.Mode.FULLSCREEN);
|
||||
when(plugin.titleFor(any(Menu.class))).thenReturn(Component.text("Menu"));
|
||||
when(plugin.fullscreen()).thenReturn(provider);when(provider.open(any(),any(),any(),any())).thenReturn(true);
|
||||
var meta=mock(ItemMeta.class);when(meta.displayName()).thenReturn(Component.text("Action"));
|
||||
when(item.getItemMeta()).thenReturn(meta);when(item.getType()).thenReturn(org.bukkit.Material.PAPER);
|
||||
when(item.clone()).thenReturn(item);
|
||||
var contents=new HashMap<Integer,ItemStack>();var inventory=mock(Inventory.class);
|
||||
when(inventory.getSize()).thenReturn(9);
|
||||
doAnswer(c->{contents.clear();return null;}).when(inventory).clear();
|
||||
doAnswer(c->{contents.put(c.getArgument(0),c.getArgument(1));return null;}).when(inventory).setItem(anyInt(),any());
|
||||
when(inventory.getItem(anyInt())).thenAnswer(c->contents.get(c.getArgument(0)));
|
||||
when(inventory.getContents()).thenAnswer(c->{var result=new ItemStack[9];contents.forEach((slot,value)->result[slot]=value);return result;});
|
||||
bukkit.when(()->Bukkit.createInventory(any(org.bukkit.inventory.InventoryHolder.class),anyInt(),any(Component.class))).thenReturn(inventory);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
package com.dunerealms.menus;
|
||||
import java.util.*;import java.util.function.BooleanSupplier;import org.bukkit.entity.Player;import org.bukkit.inventory.Inventory;import org.bukkit.plugin.java.JavaPlugin;import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*;
|
||||
/** Contract taken from actual retained Core/Ess NativeMenus, not from the new renderer implementation. */
|
||||
class RetainedNativeMenusAbiTest {
|
||||
@Test void retainedInventoryFacadeCanFindExactBooleanShowSignatures()throws Exception{
|
||||
assertEquals(boolean.class,DuneMenusPlugin.class.getMethod("show",JavaPlugin.class,Player.class,String.class,Inventory.class,Map.class,BooleanSupplier.class).getReturnType());
|
||||
assertEquals(boolean.class,DuneMenusPlugin.class.getMethod("show",JavaPlugin.class,Player.class,String.class,Inventory.class,Map.class).getReturnType());
|
||||
}
|
||||
@Test void retainedCurrentCloseAndChoiceFacadeArePresent()throws Exception{
|
||||
assertEquals(boolean.class,DuneMenusPlugin.class.getMethod("isCurrent",Player.class,Inventory.class).getReturnType());assertEquals(void.class,DuneMenusPlugin.class.getMethod("close",Player.class,Inventory.class).getReturnType());assertEquals(boolean.class,DuneMenusPlugin.class.getMethod("showChoices",JavaPlugin.class,Player.class,String.class,String.class,List.class).getReturnType());
|
||||
}
|
||||
@Test void allPublicServiceRoutesHaveNativeEntriesInsteadOfPartialAlternateBackends(){assertEquals(Set.of("hub","travel","exchange","clan","company","missions","spice","war","politics","lore","mentat","house","equipment"),NativeServiceMenu.IDS);}
|
||||
}
|
||||
|
|
@ -14,7 +14,7 @@ class SuppliedDocumentTest {
|
|||
@Test void pagingControlsDoNotOverlapTheBackAction(){
|
||||
String html=SuppliedDocument.html("exchange","Market","",List.of(new Card(45,"Previous",List.of(),"arrow"),new Card(46,"Back",List.of(),"arrow"),new Card(53,"Next",List.of(),"arrow")),List.of());
|
||||
assertTrue(html.contains("class='market-tool' data-slot='45'"));
|
||||
assertTrue(html.contains("class='back n0' data-slot='46'"));
|
||||
assertTrue(html.contains("class='market-tool' data-slot='46'"));
|
||||
assertTrue(html.contains("class='market-tool' data-slot='53'"));
|
||||
}
|
||||
@Test void legacyHitboxAliasesBecomeOneCardWithoutDroppingDistinctActions(){
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
plugins { java }
|
||||
group = "com.dunerealms"
|
||||
version = "1.1.37"
|
||||
version = "1.1.38"
|
||||
repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/"); maven("https://repo.opencollab.dev/main/") }
|
||||
dependencies {
|
||||
compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
|
||||
|
|
|
|||
|
|
@ -239,6 +239,11 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
|
|||
if(id.equals(selection(data))&&data.has("keyId")&&!data.get("keyId").isJsonNull()){mentat(p,data);return;}
|
||||
fetch(p,id,data.get("version").getAsInt(),UUID.randomUUID(),saved->{p.sendMessage(Component.text("House allegiance confirmed in J.A.R.V.I.S.",NamedTextColor.GREEN));mentat(p,saved);});
|
||||
}
|
||||
public void openNativeMenu(Player player,String id){
|
||||
if(!Bukkit.isPrimaryThread()||!player.isOnline())throw new IllegalStateException("Native menus require an online player on the server thread");
|
||||
switch(id){case "hub"->organisations.console(player);case "exchange"->exchange.open(player);case "spice"->spice.open(player);case "travel"->openGuild(player,null);case "clan"->organisations.open(player,"clans");case "company"->organisations.open(player,"companies");case "politics"->organisations.open(player,"offices");case "missions"->quests.open(player);case "war"->warMenus.open(player);case "lore"->organisations.lore(player);case "mentat"->fetch(player,null,0,null,data->mentat(player,data));case "house"->fetch(player,null,0,null,data->select(player,data,selection(data)));case "equipment"->quests.quartermaster(player,()->exchange.open(player),()->exchange.openKits(player));default->throw new IllegalArgumentException("Unknown native menu");}
|
||||
}
|
||||
public void closeSuppliedMenu(Player player){MCGUIMenus.dismiss(player);}
|
||||
public void openExchangeMenu(Player player){if(!Bukkit.isPrimaryThread()||!player.isOnline())throw new IllegalStateException("Exchange entry requires an online player on the server thread");exchange.open(player);}
|
||||
private void mentat(Player p,JsonObject data){
|
||||
String house=selection(data);if(house==null){select(p,data,null);return;}
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ final class ExchangeMenus implements Listener,AutoCloseable {
|
|||
private final Map<UUID,UUID> pending=new HashMap<>();private final Set<UUID> delivering=new HashSet<>();
|
||||
private final Map<UUID,Purchase> retries=new HashMap<>();
|
||||
private record Draft(ItemStack item,int slot,int amount,long price){Draft quantity(int n){return new Draft(item,slot,n,price);}Draft price(long n){return new Draft(item,slot,amount,n);}}
|
||||
private record Purchase(JsonObject row,int amount,UUID request){Purchase quantity(int n){return new Purchase(row,n,UUID.randomUUID());}}
|
||||
record Purchase(JsonObject row,int amount,UUID request){Purchase quantity(int n){return new Purchase(row,n,UUID.randomUUID());}}
|
||||
private static final class Panel implements InventoryHolder {
|
||||
final UUID owner,world;final GuiSession gate;final Map<Integer,Runnable> actions=new HashMap<>();final List<BedrockForms.Choice> choices=new ArrayList<>();final Inventory inventory;final String title;final boolean artwork;String description="Central bank · J.A.R.V.I.S. Exchange";
|
||||
Panel(Player p,String title,boolean artwork,int screen){owner=p.getUniqueId();world=p.getWorld().getUID();gate=new GuiSession(owner);this.title=title;this.artwork=artwork;inventory=Bukkit.createInventory(this,54,artwork?Component.text(ExchangeArtwork.background(screen),NamedTextColor.WHITE).font(net.kyori.adventure.key.Key.key("dunerealms:exchange")):Component.text(title,NamedTextColor.GOLD));}
|
||||
|
|
@ -27,7 +27,7 @@ final class ExchangeMenus implements Listener,AutoCloseable {
|
|||
}
|
||||
private final java.util.concurrent.ConcurrentMap<UUID,org.bukkit.conversations.Conversation> priceInputs=new java.util.concurrent.ConcurrentHashMap<>();
|
||||
ExchangeMenus(JavaPlugin plugin,HouseBridge bridge,Consumer<Player> back,Predicate<Player> artwork){this.plugin=plugin;this.bridge=bridge;this.back=back;this.artwork=artwork;Bukkit.getPluginManager().registerEvents(this,plugin);Bukkit.getScheduler().runTaskTimer(plugin,()->{for(Player p:Bukkit.getOnlinePlayers())deliver(p,false);},80L,1200L);}
|
||||
void open(Player p){deliver(p,false);var retry=retries.get(p.getUniqueId());if(retry!=null){purchase(p,retry);return;}list(p,false,0);}
|
||||
void open(Player p){deliver(p,false);list(p,false,0);}
|
||||
void openKits(Player p){deliver(p,false);kits(p,0);}
|
||||
private static String money(long value){return BigDecimal.valueOf(value,2).toPlainString()+" DM";}
|
||||
static long price(String text){return ExchangePrice.parse(text);}
|
||||
|
|
@ -43,7 +43,7 @@ final class ExchangeMenus implements Listener,AutoCloseable {
|
|||
private JsonObject action(String action){var q=new JsonObject();q.addProperty("action",action);return q;}
|
||||
private void list(Player p,boolean mine,int page){var q=action("read");q.addProperty("mine",mine);q.addProperty("page",page);request(p,q,data->{var s=panel(p,mine?"Exchange · Your listings":"Exchange · Buy");button(s,1,Material.EMERALD,"Buy","Browse all available items",()->list(p,false,0));button(s,4,Material.NETHERITE_CHESTPLATE,"Kits","Published organisation stillsuit kits",()->kits(p,0));button(s,7,Material.CHEST,"My listings","Manage your existing listings",()->list(p,true,0));int index=0;for(var value:data.getAsJsonArray("listings")){var row=value.getAsJsonObject();int slot=10+(index/6)*9+index%6;index++;try{var item=bridge.exchangeIcon(row);var meta=item.getItemMeta();List<Component> lore=new ArrayList<>(meta.hasLore()?meta.lore():List.of());lore.add(Component.text(" "));lore.add(Component.text("Seller: "+row.get("seller").getAsString(),NamedTextColor.GRAY));lore.add(Component.text(row.get("quantity").getAsInt()+" available · "+money(row.get("priceMinor").getAsLong())+" each",NamedTextColor.GOLD));meta.lore(lore);item.setItemMeta(meta);s.inventory.setItem(slot,item);Runnable pick=()->{if(row.get("sellerUuid").getAsString().equals(p.getUniqueId().toString()))withdraw(p,row);else purchase(p,new Purchase(row,1,UUID.randomUUID()));};s.actions.put(slot,pick);s.choices.add(new BedrockForms.Choice(row.get("title").getAsString(),money(row.get("priceMinor").getAsLong())+" · "+row.get("quantity").getAsInt()+" available",pick));}catch(Exception unsupported){s.inventory.setItem(slot,icon(Material.BARRIER,"Unsupported item","This version cannot display the stored item."));}}
|
||||
if(index==0)s.inventory.setItem(22,icon(Material.PAPER,"No listings",mine?"No own listings. Hold an item and choose Sell item.":"Check again after players publish goods."));
|
||||
if(page>0)button(s,45,Material.ARROW,"Previous","Page "+page,()->list(p,mine,page-1));if(data.get("hasNext").getAsBoolean())button(s,53,Material.ARROW,"Next","More listings",()->list(p,mine,page+1));button(s,48,Material.BOOK,"Imperial Codex","Return to your services",()->back.accept(p));button(s,49,Material.HOPPER,"Sell item","List the item in your main hand",()->draft(p));button(s,50,Material.CHEST_MINECART,"Collect purchases","Deliver paid items waiting for inventory space",()->{deliver(p,true);list(p,mine,page);});show(p,s);
|
||||
if(page>0)button(s,45,Material.ARROW,"Previous","Page "+page,()->list(p,mine,page-1));if(data.get("hasNext").getAsBoolean())button(s,53,Material.ARROW,"Next","More listings",()->list(p,mine,page+1));button(s,48,Material.BOOK,"Imperial Codex","Return to your services",()->back.accept(p));button(s,49,Material.HOPPER,"Sell item","List the item in your main hand",()->draft(p));button(s,50,Material.CHEST_MINECART,"Collect purchases","Deliver paid items waiting for inventory space",()->{deliver(p,true);list(p,mine,page);});resumeButton(p,s);show(p,s);
|
||||
});}
|
||||
private void draft(Player p){var item=p.getInventory().getItemInMainHand();if(item.isEmpty()){p.sendMessage("Hold the item you want to sell first.");return;}sell(p,new Draft(item.clone(),p.getInventory().getHeldItemSlot(),Math.min(64,item.getAmount()),100));}
|
||||
private void sell(Player p,Draft draft){var s=panel(p,"Exchange · Add item");s.description=draft.item.getType().name()+" · "+draft.amount+" items\n"+money(draft.price)+" per item\nTotal: "+money(draft.price*draft.amount);s.inventory.setItem(13,draft.item.clone());quantityPresets(s,Math.min(64,draft.item.getAmount()),amount->sell(p,draft.quantity(amount)));button(s,30,Material.RED_DYE,"− Quantity","Sell "+draft.amount+" items",()->sell(p,draft.quantity(Math.max(1,draft.amount-1))));button(s,31,Material.PAPER,"Quantity: "+draft.amount,"Maximum "+Math.min(64,draft.item.getAmount()),()->sell(p,draft));button(s,32,Material.LIME_DYE,"+ Quantity","Add one item",()->sell(p,draft.quantity(Math.min(Math.min(64,draft.item.getAmount()),draft.amount+1))));button(s,40,Material.GOLD_INGOT,"Price: "+money(draft.price),"Price per item · total "+money(draft.price*draft.amount),()->editPrice(p,draft));button(s,45,Material.ARROW,"Back","Return to your listings",()->list(p,true,0));button(s,49,Material.EMERALD,"Confirm listing","Move "+draft.amount+" items into the Exchange",()->{UUID id=UUID.randomUUID();var q=action("prepare_sale");q.addProperty("requestId",id.toString());q.addProperty("amount",draft.amount);q.addProperty("priceMinor",draft.price);request(p,q,permit->{try{bridge.exchangePublish(p,permit,id,draft.item,draft.slot,draft.amount,draft.price);p.sendMessage("Listing published. Items are held by the Exchange until sold or withdrawn.");list(p,true,0);}catch(Exception e){p.sendMessage(e.getMessage()==null?"The listing was not confirmed.":e.getMessage());}});});show(p,s);}
|
||||
|
|
@ -52,7 +52,7 @@ final class ExchangeMenus implements Listener,AutoCloseable {
|
|||
long[] steps={1,100,1000,10000};for(int i=0;i<steps.length;i++){long step=steps[i];button(s,27+i,Material.RED_DYE,"− "+money(step),"Decrease the price per item",()->editPrice(p,draft.price(Math.max(1,draft.price-step))));button(s,32+i,Material.LIME_DYE,"+ "+money(step),"Increase the price per item",()->editPrice(p,draft.price(Math.min(100000000,draft.price+step))));}
|
||||
button(s,45,Material.ARROW,"Back to listing","Review the current price before publishing",()->sell(p,draft));button(s,49,Material.EMERALD,"Use price: "+money(draft.price),"Review the listing before publishing",()->sell(p,draft));button(s,53,Material.NAME_TAG,"Type exact price","Optional private text entry",()->typePrice(p,draft));show(p,s);
|
||||
}
|
||||
private void quantityPresets(Panel s,int available,IntConsumer choose){for(int i=0;i<3;i++){int amount=new int[]{16,32,64}[i];button(s,21+i,Material.CHEST,String.valueOf(amount),"Set quantity · maximum "+available,()->choose.accept(Math.min(amount,available)));}}
|
||||
private void quantityPresets(Panel s,int available,IntConsumer choose){int slot=21;for(int amount:ExchangeQuantity.presets(available))button(s,slot++,Material.CHEST,String.valueOf(amount),"Set quantity · maximum "+available,()->choose.accept(amount));}
|
||||
private void typePrice(Player p,Draft draft){
|
||||
if(BedrockForms.isBedrock(p)){BedrockForms.input(plugin,p,"Listing price","Dunemarks per item",BigDecimal.valueOf(draft.price,2).toPlainString(),text->{try{sell(p,draft.price(price(text.trim())));}catch(IllegalArgumentException e){p.sendMessage(e.getMessage());sell(p,draft);}});return;}
|
||||
if(p.isConversing()){p.sendMessage("Finish your current text entry first, or type cancel.");return;}
|
||||
|
|
@ -70,9 +70,11 @@ final class ExchangeMenus implements Listener,AutoCloseable {
|
|||
}).buildConversation(p);
|
||||
priceInputs.put(owner,conversation);conversation.begin();
|
||||
}
|
||||
private void purchase(Player p,Purchase purchase){if(purchase.row.has("kitsetId")){kitPurchase(p,purchase);return;}var row=purchase.row;var s=panel(p,"Exchange · Confirm purchase");s.description=row.get("title").getAsString()+"\nSeller: "+row.get("seller").getAsString()+"\nQuantity: "+purchase.amount+" · Total: "+money(row.get("priceMinor").getAsLong()*purchase.amount);try{s.inventory.setItem(13,bridge.exchangeIcon(row));}catch(Exception bad){p.sendMessage("This item cannot be delivered by your current version.");return;}quantityPresets(s,Math.min(64,row.get("quantity").getAsInt()),amount->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(amount)));button(s,30,Material.RED_DYE,"− Quantity","Buy "+purchase.amount,()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.max(1,purchase.amount-1))));button(s,31,Material.PAPER,"Quantity: "+purchase.amount,money(row.get("priceMinor").getAsLong())+" per item",()->purchase(p,purchase));button(s,32,Material.LIME_DYE,"+ Quantity","Maximum "+Math.min(64,row.get("quantity").getAsInt()),()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.min(Math.min(64,row.get("quantity").getAsInt()),purchase.amount+1))));button(s,45,Material.ARROW,"Back","Return to the Exchange",()->{if(retries.containsKey(p.getUniqueId())){p.sendMessage("Resolve the previous purchase by retrying the same confirmation first.");purchase(p,purchase);}else list(p,false,0);});button(s,49,Material.EMERALD,(retries.containsKey(p.getUniqueId())?"Retry purchase · ":"Buy · ")+money(row.get("priceMinor").getAsLong()*purchase.amount),"Pay from your central personal bank account",()->{retries.put(p.getUniqueId(),purchase);var q=action("buy");q.addProperty("requestId",purchase.request.toString());q.addProperty("listingId",row.get("id").getAsString());q.addProperty("amount",purchase.amount);q.addProperty("priceMinor",row.get("priceMinor").getAsLong());q.addProperty("confirmed",true);request(p,q,receipt->{retries.remove(p.getUniqueId());p.sendMessage("Purchase confirmed: "+money(receipt.get("totalMinor").getAsLong())+". Your items are ready for delivery.");if(receipt.has("rebateMinor")&&receipt.get("rebateMinor").getAsLong()>0)p.sendMessage("Ordos trade incentive credited: "+money(receipt.get("rebateMinor").getAsLong())+".");deliver(p,true);list(p,false,0);},error->{p.sendMessage(error+" Retry this confirmation with the same purchase reference.");purchase(p,purchase);});});show(p,s);}
|
||||
private void kits(Player p,int page){var q=action("read_kits");q.addProperty("page",page);request(p,q,data->{var s=panel(p,"Exchange · Kits");button(s,1,Material.EMERALD,"Buy items","Browse loose goods",()->list(p,false,0));button(s,4,Material.NETHERITE_CHESTPLATE,"Kits","Published organisation designs",()->kits(p,0));button(s,7,Material.CHEST,"My listings","Manage your existing listings",()->list(p,true,0));int index=0;for(var value:data.getAsJsonArray("listings")){var row=value.getAsJsonObject();int slot=10+(index/6)*9+index%6;index++;String title=row.get("title").getAsString(),description=row.get("seller").getAsString()+" · "+row.get("items").getAsInt()+" items · "+money(row.get("priceMinor").getAsLong());if(row.get("purchaseAvailable").getAsBoolean())button(s,slot,Material.NETHERITE_CHESTPLATE,title,description,()->kitPurchase(p,new Purchase(row.deepCopy(),1,UUID.randomUUID())));else{s.inventory.setItem(slot,icon(Material.GRAY_DYE,title,description,"Organisation banking is unavailable"));s.description+="\n"+title+" · unavailable";}}if(page>0)button(s,45,Material.ARROW,"Previous","Previous kits",()->kits(p,page-1));button(s,49,Material.ARROW,"Back","Imperial Codex",()->back.accept(p));if(data.get("hasNext").getAsBoolean())button(s,53,Material.ARROW,"Next","More kits",()->kits(p,page+1));show(p,s);});}
|
||||
private void kitPurchase(Player p,Purchase purchase){var row=purchase.row;var s=panel(p,"Exchange · Confirm purchase");s.description=row.get("title").getAsString()+"\nOrganisation: "+row.get("seller").getAsString()+"\n"+row.get("items").getAsInt()+" items · "+money(row.get("priceMinor").getAsLong());s.inventory.setItem(13,icon(Material.NETHERITE_CHESTPLATE,row.get("title").getAsString(),row.get("seller").getAsString(),row.get("items").getAsInt()+" items"));button(s,45,Material.ARROW,"Back","Kit catalogue",()->{if(retries.containsKey(p.getUniqueId())){p.sendMessage("Resolve the previous purchase with the same reference first.");kitPurchase(p,purchase);}else kits(p,0);});button(s,49,Material.EMERALD,(retries.containsKey(p.getUniqueId())?"Retry kit · ":"Buy kit · ")+money(row.get("priceMinor").getAsLong()),"Pay personally; proceeds go to the organisation",()->{retries.put(p.getUniqueId(),purchase);var q=action("buy_kit");q.addProperty("requestId",purchase.request.toString());q.addProperty("kitsetId",row.get("kitsetId").getAsString());q.add("listingVersion",row.get("listingVersion"));q.add("priceMinor",row.get("priceMinor"));q.addProperty("confirmed",true);request(p,q,receipt->{retries.remove(p.getUniqueId());p.sendMessage("Kit purchased: "+money(receipt.get("totalMinor").getAsLong())+". Delivery follows automatically; make room for the complete kit.");try{bridge.refreshKits(p);}catch(Exception unavailable){p.sendMessage("Your kit remains owed until the next inventory sync.");}kits(p,0);},error->{p.sendMessage(error+" Retry this confirmation with the same reference.");kitPurchase(p,purchase);});});show(p,s);}
|
||||
static Purchase resume(Purchase requested,Purchase unresolved){return unresolved==null?requested:unresolved;}
|
||||
private void resumeButton(Player p,Panel panel){var retry=retries.get(p.getUniqueId());if(retry!=null)button(panel,46,Material.CLOCK,"Resume pending purchase","Retry the original purchase reference; no new order",()->purchase(p,retry));}
|
||||
private void purchase(Player p,Purchase purchase){var existing=resume(purchase,retries.get(p.getUniqueId()));if(existing!=purchase){purchase(p,existing);return;}if(purchase.row.has("kitsetId")){kitPurchase(p,purchase);return;}var row=purchase.row;var s=panel(p,"Exchange · Confirm purchase");s.description=row.get("title").getAsString()+"\nSeller: "+row.get("seller").getAsString()+"\nQuantity: "+purchase.amount+" · Total: "+money(row.get("priceMinor").getAsLong()*purchase.amount);try{s.inventory.setItem(13,bridge.exchangeIcon(row));}catch(Exception bad){p.sendMessage("This item cannot be delivered by your current version.");return;}quantityPresets(s,Math.min(64,row.get("quantity").getAsInt()),amount->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(amount)));button(s,30,Material.RED_DYE,"− Quantity","Buy "+purchase.amount,()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.max(1,purchase.amount-1))));button(s,31,Material.PAPER,"Quantity: "+purchase.amount,money(row.get("priceMinor").getAsLong())+" per item",()->purchase(p,purchase));button(s,32,Material.LIME_DYE,"+ Quantity","Maximum "+Math.min(64,row.get("quantity").getAsInt()),()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.min(Math.min(64,row.get("quantity").getAsInt()),purchase.amount+1))));button(s,45,Material.ARROW,"Back","Return to the Exchange",()->list(p,false,0));button(s,49,Material.EMERALD,(retries.containsKey(p.getUniqueId())?"Retry purchase · ":"Buy · ")+money(row.get("priceMinor").getAsLong()*purchase.amount),"Pay from your central personal bank account",()->{retries.put(p.getUniqueId(),purchase);var q=action("buy");q.addProperty("requestId",purchase.request.toString());q.addProperty("listingId",row.get("id").getAsString());q.addProperty("amount",purchase.amount);q.addProperty("priceMinor",row.get("priceMinor").getAsLong());q.addProperty("confirmed",true);request(p,q,receipt->{retries.remove(p.getUniqueId());p.sendMessage("Purchase confirmed: "+money(receipt.get("totalMinor").getAsLong())+". Your items are ready for delivery.");if(receipt.has("rebateMinor")&&receipt.get("rebateMinor").getAsLong()>0)p.sendMessage("Ordos trade incentive credited: "+money(receipt.get("rebateMinor").getAsLong())+".");deliver(p,true);list(p,false,0);},error->{p.sendMessage(error+" Retry this confirmation with the same purchase reference.");purchase(p,purchase);});});show(p,s);}
|
||||
private void kits(Player p,int page){var q=action("read_kits");q.addProperty("page",page);request(p,q,data->{var s=panel(p,"Exchange · Kits");button(s,1,Material.EMERALD,"Buy items","Browse loose goods",()->list(p,false,0));button(s,4,Material.NETHERITE_CHESTPLATE,"Kits","Published organisation designs",()->kits(p,0));button(s,7,Material.CHEST,"My listings","Manage your existing listings",()->list(p,true,0));int index=0;for(var value:data.getAsJsonArray("listings")){var row=value.getAsJsonObject();int slot=10+(index/6)*9+index%6;index++;String title=row.get("title").getAsString(),description=row.get("seller").getAsString()+" · "+row.get("items").getAsInt()+" items · "+money(row.get("priceMinor").getAsLong());if(row.get("purchaseAvailable").getAsBoolean())button(s,slot,Material.NETHERITE_CHESTPLATE,title,description,()->kitPurchase(p,new Purchase(row.deepCopy(),1,UUID.randomUUID())));else{s.inventory.setItem(slot,icon(Material.GRAY_DYE,title,description,"Organisation banking is unavailable"));s.description+="\n"+title+" · unavailable";}}resumeButton(p,s);if(page>0)button(s,45,Material.ARROW,"Previous","Previous kits",()->kits(p,page-1));button(s,49,Material.ARROW,"Back","Imperial Codex",()->back.accept(p));if(data.get("hasNext").getAsBoolean())button(s,53,Material.ARROW,"Next","More kits",()->kits(p,page+1));show(p,s);});}
|
||||
private void kitPurchase(Player p,Purchase purchase){var existing=resume(purchase,retries.get(p.getUniqueId()));if(existing!=purchase){purchase(p,existing);return;}var row=purchase.row;var s=panel(p,"Exchange · Confirm purchase");s.description=row.get("title").getAsString()+"\nOrganisation: "+row.get("seller").getAsString()+"\n"+row.get("items").getAsInt()+" items · "+money(row.get("priceMinor").getAsLong());s.inventory.setItem(13,icon(Material.NETHERITE_CHESTPLATE,row.get("title").getAsString(),row.get("seller").getAsString(),row.get("items").getAsInt()+" items"));button(s,45,Material.ARROW,"Back","Kit catalogue",()->kits(p,0));button(s,49,Material.EMERALD,(retries.containsKey(p.getUniqueId())?"Retry kit · ":"Buy kit · ")+money(row.get("priceMinor").getAsLong()),"Pay personally; proceeds go to the organisation",()->{retries.put(p.getUniqueId(),purchase);var q=action("buy_kit");q.addProperty("requestId",purchase.request.toString());q.addProperty("kitsetId",row.get("kitsetId").getAsString());q.add("listingVersion",row.get("listingVersion"));q.add("priceMinor",row.get("priceMinor"));q.addProperty("confirmed",true);request(p,q,receipt->{retries.remove(p.getUniqueId());p.sendMessage("Kit purchased: "+money(receipt.get("totalMinor").getAsLong())+". Delivery follows automatically; make room for the complete kit.");try{bridge.refreshKits(p);}catch(Exception unavailable){p.sendMessage("Your kit remains owed until the next inventory sync.");}kits(p,0);},error->{p.sendMessage(error+" Retry this confirmation with the same reference.");kitPurchase(p,purchase);});});show(p,s);}
|
||||
private void withdraw(Player p,JsonObject row){var s=panel(p,"Exchange · Withdraw listing");try{s.inventory.setItem(13,bridge.exchangeIcon(row));}catch(Exception bad){p.sendMessage("This stored item cannot be decoded.");return;}button(s,45,Material.ARROW,"Back","Your listings",()->list(p,true,0));button(s,49,Material.CHEST,"Withdraw "+row.get("quantity").getAsInt()+" items","Return all unsold stock to your inventory",()->{UUID id=UUID.randomUUID();var q=action("prepare_cancel");q.addProperty("requestId",id.toString());request(p,q,permit->{try{int quantity=bridge.exchangeCancel(p,permit,id,Long.parseLong(row.get("id").getAsString()));p.sendMessage("Listing withdrawn. Returned "+quantity+" items.");list(p,true,0);}catch(Exception e){p.sendMessage(e.getMessage()==null?"The listing was not withdrawn.":e.getMessage());}});});show(p,s);}
|
||||
private void deliver(Player p,boolean explain){if(!p.isOnline()||!delivering.add(p.getUniqueId()))return;UUID id=p.getUniqueId();var q=action("pending");Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject response=null;try{response=bridge.exchange(id,q);}catch(Exception ignored){}var data=response;if(!plugin.isEnabled())return;Bukkit.getScheduler().runTask(plugin,()->{delivering.remove(id);if(!p.isOnline())return;if(data==null||!data.has("pending")){if(explain)p.sendMessage("Paid deliveries remain queued. Reopen the Exchange to try again.");return;}if(data.getAsJsonArray("pending").isEmpty()){if(explain)p.sendMessage("No paid items are waiting for delivery.");return;}try{int count=bridge.exchangeDeliver(p);if(explain||count>0)p.sendMessage(count>0?"J.A.R.V.I.S. delivered "+count+" purchased items.":"Make inventory space. Your paid items remain queued.");}catch(Exception unavailable){if(explain)p.sendMessage("Paid items remain queued until your shared inventory is ready.");}});});}
|
||||
@EventHandler public void join(PlayerJoinEvent e){Bukkit.getScheduler().runTaskLater(plugin,()->deliver(e.getPlayer(),false),60L);}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,5 @@
|
|||
package com.dunerealms.gui;
|
||||
import java.util.*;
|
||||
final class ExchangeQuantity {
|
||||
static List<Integer> presets(int available){return List.of(16,32,64).stream().filter(n->n<=available).toList();}
|
||||
}
|
||||
|
|
@ -16,6 +16,7 @@ import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
|
|||
/** Uses MC GUI's public canvas and HTML renderer APIs; never executes page commands. */
|
||||
final class MCGUIMenus implements AutoCloseable, Listener {
|
||||
private static MCGUIMenus active;
|
||||
static void dismiss(Player player){if(active==null)return;Session session=active.sessions.remove(player.getUniqueId());if(session!=null){session.actionClosing=true;session.finish();session.onClose.run();}}
|
||||
private final JavaPlugin plugin;
|
||||
private final Map<UUID,Session> sessions=new HashMap<>();
|
||||
private final Set<UUID> closeHints=new HashSet<>(),gameplayOffered=new HashSet<>();
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
name: DunerealmsGUI
|
||||
main: com.dunerealms.gui.DuneGUI
|
||||
version: 1.1.37
|
||||
version: 1.1.38
|
||||
api-version: '1.21.8'
|
||||
depend: [JarvisTranslator]
|
||||
softdepend: [Citizens, MCGUI, DecentHolograms, DuneLobby, DuneCore, DuneEss, DuneNPC, Vault, floodgate, ViaVersion]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,6 @@
|
|||
package com.dunerealms.gui;
|
||||
import com.google.gson.JsonObject;import java.util.*;import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*;
|
||||
class ExchangeBrowseSafetyTest {
|
||||
@Test void unresolvedAttemptKeepsOriginalReferenceQuantityAndListing(){var old=new JsonObject();old.addProperty("id","9");var pending=new ExchangeMenus.Purchase(old,1,UUID.randomUUID());var candidate=new ExchangeMenus.Purchase(new JsonObject(),64,UUID.randomUUID());var result=ExchangeMenus.resume(candidate,pending);assertSame(pending,result);assertEquals(pending.request(),result.request());assertEquals(1,result.amount());assertEquals("9",result.row().get("id").getAsString());assertSame(candidate,ExchangeMenus.resume(candidate,null));}
|
||||
@Test void quantityPresetsCannotAdvertiseUnavailableAmounts(){assertEquals(List.of(),ExchangeQuantity.presets(1));assertEquals(List.of(16),ExchangeQuantity.presets(24));assertEquals(List.of(16,32),ExchangeQuantity.presets(32));assertEquals(List.of(16,32,64),ExchangeQuantity.presets(64));}
|
||||
}
|
||||
Loading…
Reference in a new issue

Staff