Replace GUI entry points with supplied DuneMenus presentation and JARVIS adapter

This commit is contained in:
unimatrixgit 2026-11-29 02:31:43 +01:00
commit c0d56632eb
3 changed files with 3274 additions and 14 deletions

View file

@ -22,6 +22,8 @@ import java.util.function.Consumer;
/** Lobby presentation only. Character authority and committed keys remain central. */
public final class DuneGUI extends JavaPlugin implements Listener,CommandExecutor {
public boolean presentSuppliedMenu(Player player,String title,String html,Map<Integer,Runnable> actions,Runnable close){return MCGUIMenus.showDocument(player,title,html,actions,close);}
public void warObjective(Player player,JsonObject target,Runnable capture){if(!Bukkit.isPrimaryThread()||!isEnabled())throw new IllegalStateException("Open objectives on the server thread");organisations.warObjective(player,target,capture);}
private HouseBridge bridge;
private OrganisationMenus organisations;
@ -91,6 +93,7 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
@Override public void onDisable(){if(modernMenus!=null)modernMenus.close();if(nameplates!=null)nameplates.close();if(exchange!=null)exchange.close();if(itemPreviews!=null)itemPreviews.close();if(quests!=null)quests.close();requests.clear();records.clear();bookings.clear();boarding.clear();if(guild!=null)guild.close();GuiSession.clear();if(sidebar!=null)sidebar.clear();for(var controller:detached.values())try{controller.restore();}catch(ReflectiveOperationException ignored){}detached.clear();if(departure!=null)departure.removeAll();for(Player p:Bukkit.getOnlinePlayers())if(p.getOpenInventory().getTopInventory().getHolder() instanceof Screen)p.closeInventory();}
private boolean lobby(Player p){return p.getWorld().getName().equals("guild_lobby");}
@Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args){
if(sender instanceof Player supplied&&SuppliedMenus.command(supplied,command.getName(),args))return true;
if(sender instanceof Player p&&command.getName().equals("sellall")){spice.sellAll(p,args.length==0?"guild":args[0].toLowerCase(Locale.ROOT));return true;}
if(sender instanceof Player p&&(command.getName().equals("spice")||command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("spice"))){spice.open(p);return true;}
if(sender instanceof Player player&&(command.getName().equals("exchange")||command.getName().equals("drgui")&&args.length==1&&args[0].equalsIgnoreCase("exchange"))){exchange.open(player);return true;}
@ -183,8 +186,8 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto
private void toggleSidebar(Player p){sidebar.toggle(p);p.sendMessage(Component.text(sidebar.enabled(p)?"Personal scoreboard enabled.":"Personal scoreboard hidden.",NamedTextColor.GOLD));if(sidebar.enabled(p)){JsonObject data=records.get(p.getUniqueId());if(data!=null)updateSidebar(p,data);refreshSidebar(p);}}
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=false) public void organisationContact(org.bukkit.event.player.PlayerInteractEntityEvent event){String marker=event.getRightClicked().getPersistentDataContainer().get(new NamespacedKey("dunerealms","organisation_home_npc"),PersistentDataType.STRING);if(marker==null)return;event.setCancelled(true);if(event.getHand()!=org.bukkit.inventory.EquipmentSlot.HAND)return;String[] parts=marker.split(":",2);if(parts.length!=2||!Set.of("clan","company").contains(parts[0]))return;try{String id=UUID.fromString(parts[1]).toString();organisations.openHomeNpc(event.getPlayer(),parts[0].equals("clan")?"clans":"companies",id);}catch(IllegalArgumentException ignored){}}
@EventHandler public void scoreboardCommand(PlayerCommandPreprocessEvent e){String command=e.getMessage().trim();if(command.equalsIgnoreCase("/scoreboard")){e.setCancelled(true);toggleSidebar(e.getPlayer());}}
@EventHandler(priority=EventPriority.HIGHEST) public void oldNavigator(PlayerInteractEvent e){if(e.getHand()!=EquipmentSlot.HAND||e.getItem()==null||!e.getItem().hasItemMeta()||!e.getAction().isRightClick())return;var data=e.getItem().getItemMeta().getPersistentDataContainer();for(var key:data.getKeys())if(data.has(key,PersistentDataType.STRING)&&"menu_opener".equals(data.get(key,PersistentDataType.STRING))){e.setCancelled(true);organisations.console(e.getPlayer());return;}}
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=true) public void legacyTravel(PlayerCommandPreprocessEvent e){String[] args=e.getMessage().substring(1).trim().toLowerCase(Locale.ROOT).split("\\s+");String label=args[0].replaceFirst("^[^:]+:","");if(label.equals("balance")||label.equals("bal")||label.equals("money")){e.setCancelled(true);if(!sidebar.enabled(e.getPlayer()))sidebar.toggle(e.getPlayer());refreshSidebar(e.getPlayer());return;}if(label.equals("exchange")){e.setCancelled(true);exchange.open(e.getPlayer());return;}if(label.equals("server")||label.equals("duneess")&&args.length>1&&args[1].equals("travel")){e.setCancelled(true);openGuild(e.getPlayer(),null);}}
@EventHandler(priority=EventPriority.HIGHEST) public void oldNavigator(PlayerInteractEvent e){if(e.getHand()!=EquipmentSlot.HAND||e.getItem()==null||!e.getItem().hasItemMeta()||!e.getAction().isRightClick())return;var data=e.getItem().getItemMeta().getPersistentDataContainer();for(var key:data.getKeys())if(data.has(key,PersistentDataType.STRING)&&"menu_opener".equals(data.get(key,PersistentDataType.STRING))){e.setCancelled(true);if(!SuppliedMenus.open(e.getPlayer(),"hub"))organisations.console(e.getPlayer());return;}}
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=true) public void legacyTravel(PlayerCommandPreprocessEvent e){String[] args=e.getMessage().substring(1).trim().toLowerCase(Locale.ROOT).split("\\s+");String label=args[0].replaceFirst("^[^:]+:","");if(label.equals("balance")||label.equals("bal")||label.equals("money")){e.setCancelled(true);if(!sidebar.enabled(e.getPlayer()))sidebar.toggle(e.getPlayer());refreshSidebar(e.getPlayer());return;}if(label.equals("exchange")){e.setCancelled(true);if(!SuppliedMenus.open(e.getPlayer(),"exchange"))exchange.open(e.getPlayer());return;}if(label.equals("server")||label.equals("duneess")&&args.length>1&&args[1].equals("travel")){e.setCancelled(true);if(!SuppliedMenus.open(e.getPlayer(),"travel"))openGuild(e.getPlayer(),null);}}
private void offerGuiPack(Player p){offerGuiPack(p,true);}
private void offerGuiPack(Player p,boolean force){
if(!p.isOnline()||BedrockForms.isBedrock(p))return;

View file

@ -26,7 +26,7 @@ final class MCGUIMenus implements AutoCloseable, Listener {
private final Path base;
MCGUIMenus(JavaPlugin plugin){
this.plugin=plugin;base=plugin.getDataFolder().toPath().resolve("mcgui/menu.html");
if(!plugin.getConfig().getBoolean("mcgui.enabled",false))return;
if(!plugin.getConfig().getBoolean("mcgui.enabled",true))return;
engine=Bukkit.getPluginManager().getPlugin("MCGUI");if(engine==null||!engine.isEnabled())return;
try{
ClassLoader cl=engine.getClass().getClassLoader();Class<?> api=Class.forName("ai.resourcepack.ui.framework.api.UIFramework",true,cl);
@ -48,8 +48,18 @@ final class MCGUIMenus implements AutoCloseable, Listener {
}catch(Exception failure){framework=null;plugin.getLogger().warning("MC GUI adapter unavailable: "+failure.getClass().getSimpleName());}
}
static boolean show(Player p,String title,String description,Inventory inventory,Map<Integer,Runnable> actions,GuiSession gate){
if(SuppliedMenus.service(p,title,description,inventory,actions,gate))return true;
return active!=null&&active.present(p,title,description,inventory,actions,gate);
}
static boolean showDocument(Player p,String title,String html,Map<Integer,Runnable> actions,Runnable closed){
if(active==null||active.framework==null||!p.isOnline()||BedrockForms.isBedrock(p))return false;
try{if(!Boolean.TRUE.equals(active.hasPack.invoke(active.framework,p))){active.sendPack(p);return false;}
Session old=active.sessions.remove(p.getUniqueId());if(old!=null)old.finish();
Session next=active.new Session(p,title,"",List.of(),Map.copyOf(actions),null);
next.suppliedHtml=html;next.onClose=closed;active.sessions.put(p.getUniqueId(),next);p.closeInventory();next.schedule();
Bukkit.getScheduler().runTaskLater(active.plugin,()->{if(active.sessions.remove(p.getUniqueId(),next)){next.finish();next.onClose.run();}},2400L);return true;
}catch(Exception failure){active.plugin.getLogger().warning("Supplied menu presentation unavailable: "+failure.getClass().getSimpleName());return false;}
}
static void forget(UUID player){if(active!=null){active.closeHints.remove(player);active.gameplayReady.remove(player);active.gameplayOffered.remove(player);}}
static void offerPack(Player p){if(active!=null&&!BedrockForms.isBedrock(p))active.sendPack(p);}
private void sendPack(Player p){p.addResourcePack(packId,packUrl,packHash,"DuneRealms interactive menus",true);}
@ -77,20 +87,21 @@ final class MCGUIMenus implements AutoCloseable, Listener {
try{
Session s=new Session(p,title,description,cards,Map.copyOf(actions),gate);sessions.put(p.getUniqueId(),s);p.closeInventory();s.schedule();
Bukkit.getScheduler().runTaskLater(plugin,()->{if(sessions.get(p.getUniqueId())==s){s.finish();sessions.remove(p.getUniqueId());}},2400L);return true;
}catch(Exception failure){gate.expire();plugin.getLogger().warning("MC GUI menu unavailable: "+failure.getClass().getSimpleName());p.sendMessage("This menu is temporarily unavailable. Reopen your Imperial Codex.");return true;}
}catch(Exception failure){if(gate!=null)gate.expire();plugin.getLogger().warning("MC GUI menu unavailable: "+failure.getClass().getSimpleName());p.sendMessage("This menu is temporarily unavailable. Reopen your Imperial Codex.");return true;}
}
private final class Session implements InvocationHandler {
String suppliedHtml;Runnable onClose=()->{};boolean actionClosing;
final Player player;final UUID world;final String title,description;final List<MenuDocument.Card> cards;final Map<Integer,Runnable> actions;final GuiSession gate;final Object canvas;
final AtomicBoolean queued=new AtomicBoolean();volatile boolean alive=true;volatile int hovered=-1;volatile int picked=-1;volatile double scroll;volatile Object frame;Object view;
Session(Player p,String title,String description,List<MenuDocument.Card> cards,Map<Integer,Runnable> actions,GuiSession gate)throws Exception{player=p;world=p.getWorld().getUID();this.title=title;this.description=description;this.cards=List.copyOf(cards);this.actions=actions;this.gate=gate;canvas=makeCanvas.invoke(framework,12,7);}
void schedule(){if(!alive||!queued.compareAndSet(false,true))return;drawings.submit(()->{
int expected=hovered,selected=picked;double offset=scroll;
try{
String html=MenuDocument.html(title,description,player.getName(),cards,selected,base.getParent());Object page=pageOf.invoke(null,html,base,loader);
String html=suppliedHtml!=null?suppliedHtml:MenuDocument.html(title,description,player.getName(),cards,selected,base.getParent());Object page=pageOf.invoke(null,html,base,loader);
Object paintState=none;Object document=page.getClass().getField("document").get(page);String selector=expected<=-100?"[data-pick=\""+(-100-expected)+"\"]":"[data-slot=\""+expected+"\"]";Object element=document.getClass().getMethod("selectFirst",String.class).invoke(document,selector);if(element!=null)paintState=hoverState.invoke(null,element,null);Object next=render.invoke(null,page,1536,896,1.5,offset,paintState);
if(!alive)return;draw.invoke(canvas,next.getClass().getMethod("image").invoke(next),0,0);frame=next;
Bukkit.getScheduler().runTask(plugin,()->{if(!current())return;if(view==null)try{Object proxy=Proxy.newProxyInstance(contentType.getClassLoader(),new Class<?>[]{contentType},this);view=openView.invoke(framework,player,proxy,defaultOptions);if(closeHints.add(player.getUniqueId()))player.sendMessage("Press Shift to close this menu.");}catch(Exception e){finish();sessions.remove(player.getUniqueId());player.sendMessage("The menu could not open. Load the menu pack and reopen your Codex.");plugin.getLogger().warning("MC GUI view failed: "+e.getClass().getSimpleName());}});
}catch(Exception|LinkageError e){if(alive){plugin.getLogger().log(java.util.logging.Level.WARNING,"MC GUI render failed",e);Bukkit.getScheduler().runTask(plugin,()->{if(current()){finish();sessions.remove(player.getUniqueId(),this);player.sendMessage("The new menu could not be drawn. Please retry /menu.");}});}}
Bukkit.getScheduler().runTask(plugin,()->{if(!current())return;if(view==null)try{Object proxy=Proxy.newProxyInstance(contentType.getClassLoader(),new Class<?>[]{contentType},this);view=openView.invoke(framework,player,proxy,defaultOptions);if(closeHints.add(player.getUniqueId()))player.sendMessage("Press Shift to close this menu.");}catch(Exception e){finish();sessions.remove(player.getUniqueId());onClose.run();player.sendMessage("The menu could not open. Load the menu pack and reopen your Codex.");plugin.getLogger().warning("MC GUI view failed: "+e.getClass().getSimpleName());}});
}catch(Exception|LinkageError e){if(alive){plugin.getLogger().log(java.util.logging.Level.WARNING,"MC GUI render failed",e);Bukkit.getScheduler().runTask(plugin,()->{if(current()){finish();sessions.remove(player.getUniqueId(),this);onClose.run();player.sendMessage("The new menu could not be drawn. Please retry /menu.");}});}}
finally{queued.set(false);if(alive&&(expected!=hovered||selected!=picked||offset!=scroll))schedule();}
});}
boolean current(){return alive&&player.isOnline()&&world.equals(player.getWorld().getUID())&&sessions.get(player.getUniqueId())==this;}
@ -99,16 +110,16 @@ final class MCGUIMenus implements AutoCloseable, Listener {
switch(method.getName()){
case "canvas":return alive?canvas:null;
case "pointer":{int next=slot((int)args[1],(int)args[2]);if(next!=hovered){hovered=next;schedule();}return null;}
case "click":{int slot=slot((int)args[1],(int)args[2]);if(!current())return null;if(slot<=-100){picked=-100-slot;scroll=0;schedule();return null;}if(slot==-1){finish();sessions.remove(player.getUniqueId());return null;}Runnable action=slot==-3?()->player.performCommand("menu"):actions.get(slot);if(action!=null&&gate.claim(player.getUniqueId())){finish();sessions.remove(player.getUniqueId());Bukkit.getScheduler().runTask(plugin,()->{if(player.isOnline()&&world.equals(player.getWorld().getUID()))action.run();});}return null;}
case "click":{int slot=slot((int)args[1],(int)args[2]);if(!current())return null;if(slot<=-100){picked=-100-slot;scroll=0;schedule();return null;}if(slot==-1){finish();sessions.remove(player.getUniqueId());onClose.run();return null;}Runnable action=slot==-3?()->player.performCommand("menu"):actions.get(slot);if(action!=null&&(gate==null||gate.claim(player.getUniqueId()))){actionClosing=true;finish();sessions.remove(player.getUniqueId());Bukkit.getScheduler().runTask(plugin,()->{if(player.isOnline()&&world.equals(player.getWorld().getUID()))action.run();});}return null;}
case "scroll":{Object f=frame;if(f!=null){double max=((Number)f.getClass().getMethod("maxScroll").invoke(f)).doubleValue();scroll=Math.max(0,Math.min(max,scroll+(int)args[3]*90));schedule();}return null;}
case "closed":alive=false;gate.expire();sessions.remove(player.getUniqueId(),this);return null;
case "closed":alive=false;if(gate!=null)gate.expire();sessions.remove(player.getUniqueId(),this);if(!actionClosing)onClose.run();return null;
case "toString":return "DuneRealms menu view";
case "hashCode":return System.identityHashCode(proxy);
case "equals":return proxy==args[0];
default:return null;
}
}
void finish(){alive=false;gate.expire();if(view!=null)try{Class.forName("ai.resourcepack.ui.framework.api.View",true,engine.getClass().getClassLoader()).getMethod("close").invoke(view);}catch(Exception ignored){}}
void finish(){alive=false;if(gate!=null)gate.expire();if(view!=null)try{Class.forName("ai.resourcepack.ui.framework.api.View",true,engine.getClass().getClassLoader()).getMethod("close").invoke(view);}catch(Exception ignored){}}
}
public void close(){if(active==this)active=null;for(Session s:List.copyOf(sessions.values()))s.finish();sessions.clear();drawings.shutdownNow();}
}

View file

@ -0,0 +1,21 @@
package com.dunerealms.gui;
import java.util.*;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
/** Presentation bridge only. Native NPC/service actions remain owned by their original backend. */
final class SuppliedMenus {
private SuppliedMenus(){}
static boolean open(Player p,String id){return call("openMenu",new Class<?>[]{Player.class,String.class},p,id);}
static boolean command(Player p,String command,String[] args){
String id=switch(command){case "exchange","spice","clan","company","house","mentat"->command;case "polgui"->"politics";case "warmuster"->"war";case "guildtravel"->args.length==0?"travel":null;case "drgui"->args.length==0?"hub":args.length==1?switch(args[0].toLowerCase(Locale.ROOT)){case "quests"->"missions";case "hub","travel","exchange","clan","company","missions","spice","war","politics","house","equipment","bank","atm","withdraw","lore","mentat"->args[0].toLowerCase(Locale.ROOT);default->null;}:null;default->null;};
return id!=null&&open(p,id);
}
static boolean service(Player p,String title,String description,Inventory inventory,Map<Integer,Runnable> actions,GuiSession supplied){
GuiSession gate=supplied==null?new GuiSession(p.getUniqueId()):supplied;
Map<Integer,Runnable> guarded=new HashMap<>();actions.forEach((slot,action)->guarded.put(slot,()->{if(gate.claim(p.getUniqueId()))action.run();}));
return call("presentService",new Class<?>[]{Player.class,String.class,String.class,String.class,Inventory.class,Map.class},p,section(title),title,description,inventory,guarded);
}
static String section(String title){String t=title.toLowerCase(Locale.ROOT);if(t.contains("war")||t.contains("muster"))return "war";if(t.contains("quest")||t.contains("mission")||t.startsWith("npc "))return "missions";if(t.contains("exchange"))return "exchange";if(t.contains("spice"))return "spice";if(t.contains("guild")||t.contains("travel"))return "travel";if(t.contains("clan"))return "clan";if(t.contains("company"))return "company";if(t.contains("politic"))return "politics";if(t.contains("house")||t.contains("mentat"))return "house";return "hub";}
private static boolean call(String method,Class<?>[] types,Object...args){var plugin=Bukkit.getPluginManager().getPlugin("DuneMenus");if(plugin==null||!plugin.isEnabled())return false;try{plugin.getClass().getMethod(method,types).invoke(plugin,args);return true;}catch(ReflectiveOperationException failure){plugin.getLogger().warning("Menu bridge failed: "+failure.getClass().getSimpleName());return false;}}
}