138 lines
17 KiB
Java
138 lines
17 KiB
Java
package com.dunerealms.gui;
|
|
import java.lang.reflect.*;
|
|
import java.nio.file.*;
|
|
import java.util.*;
|
|
import java.util.concurrent.*;
|
|
import java.util.concurrent.atomic.AtomicBoolean;
|
|
import org.bukkit.*;
|
|
import org.bukkit.entity.Player;
|
|
import org.bukkit.event.*;
|
|
import org.bukkit.event.player.*;
|
|
import org.bukkit.inventory.*;
|
|
import org.bukkit.plugin.Plugin;
|
|
import org.bukkit.plugin.java.JavaPlugin;
|
|
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<>();
|
|
private final ExecutorService drawings=Executors.newSingleThreadExecutor(r->{Thread t=new Thread(r,"DuneRealms-menu-render");t.setDaemon(true);return t;});
|
|
private Plugin engine;private Object framework,loader,none;private Class<?> contentType,optionsType;private Object defaultOptions;
|
|
private Method makeCanvas,openView,hasPack,pageOf,render,draw,hoverState;
|
|
private UUID packId;private String packUrl;private byte[] packHash;
|
|
private boolean serverOwnedPack;private MenuPackReadiness readiness;
|
|
private final Path base;
|
|
MCGUIMenus(JavaPlugin plugin){
|
|
this.plugin=plugin;base=plugin.getDataFolder().toPath().resolve("mcgui/menu.html");
|
|
if(!plugin.getConfig().getBoolean("mcgui.enabled",true))return;
|
|
var pinFile=plugin.getDataFolder().toPath().resolve("menu-pack.yml").toFile();
|
|
var settings=org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(pinFile);
|
|
var pin=MenuPackPolicy.select(settings.getString("url"),settings.getString("sha1"),settings.getString("sha256"),settings.getString("source-commit"),settings.getString("delivery","stacked"),settings.getString("pack-id"));
|
|
if(pin==null){plugin.getLogger().warning("Built menu-pack.yml publication pin is required; world packs were left unchanged.");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);
|
|
framework=api.getMethod("get").invoke(null);makeCanvas=api.getMethod("canvas",int.class,int.class);hasPack=api.getMethod("hasPack",Player.class);
|
|
contentType=Class.forName("ai.resourcepack.ui.framework.api.ViewContent",true,cl);optionsType=Class.forName("ai.resourcepack.ui.framework.api.ViewOptions",true,cl);
|
|
defaultOptions=optionsType.getField("DEFAULT").get(null);openView=api.getMethod("openView",Player.class,contentType,optionsType);
|
|
Class<?> page=Class.forName("ai.resourcepack.ui.html.Page",true,cl),load=Class.forName("ai.resourcepack.ui.html.Page$Loader",true,cl),state=Class.forName("ai.resourcepack.ui.html.css.Selector$State",true,cl),renderer=Class.forName("ai.resourcepack.ui.html.HtmlRenderer",true,cl);
|
|
Files.createDirectories(base.getParent());Path avatarArt=base.getParent().resolve("art");Files.createDirectories(avatarArt);for(int i=0;i<8;i++){String name="npc_avatar_"+i+".png";try(var source=plugin.getResource("mcgui-npc-avatars/"+name)){if(source!=null)Files.copy(source,avatarArt.resolve(name),StandardCopyOption.REPLACE_EXISTING);}}for(String world:List.of("caladan","giedi_prime","kaitain","sigma_draconis_iv","arrakis","guild_lobby","imperial")){String name="npc_world_"+world+".png";try(var source=plugin.getResource("mcgui-npc-avatars/"+name)){if(source!=null)Files.copy(source,avatarArt.resolve(name),StandardCopyOption.REPLACE_EXISTING);}}try(var source=plugin.getResource("mcgui-npc-avatars/quest-dialogue-frame.png")){if(source!=null)Files.copy(source,avatarArt.resolve("quest-dialogue-frame.png"),StandardCopyOption.REPLACE_EXISTING);}loader=load.getConstructor(boolean.class,Path.class).newInstance(false,base.getParent().resolve("cache"));
|
|
pageOf=page.getMethod("of",String.class,Path.class,load);none=state.getField("NONE").get(null);render=renderer.getMethod("render",page,int.class,int.class,double.class,double.class,state);
|
|
for(Method m:renderer.getMethods())if(m.getName().equals("state")&&m.getParameterCount()==2)hoverState=m;
|
|
Class<?> canvas=Class.forName("ai.resourcepack.ui.framework.api.Canvas",true,cl);draw=canvas.getMethod("draw",java.awt.image.BufferedImage.class,int.class,int.class);
|
|
serverOwnedPack=pin.serverOwned();
|
|
if(serverOwnedPack){
|
|
var properties=new java.util.Properties();try(var input=Files.newInputStream(Path.of("server.properties"))){properties.load(input);}
|
|
if(!MenuPackPolicy.serverMatches(properties,pin))throw new IllegalStateException("Server resource-pack pin differs from unified menu configuration");
|
|
packId=UUID.fromString(MenuPackPolicy.UNIFIED_ID);
|
|
}else packId=(UUID)Class.forName("ai.resourcepack.ui.framework.pack.ResourcePack",true,cl).getField("PACK_ID").get(null);
|
|
if(!engine.getConfig().getString("resource-pack.mode","").equals("external")||!engine.getConfig().getString("resource-pack.public-url","").isBlank()||engine.getConfig().getBoolean("telemetry",true))throw new IllegalStateException("MCGUI must use external merged mode with telemetry disabled");
|
|
readiness=new MenuPackReadiness(packId,serverOwnedPack);
|
|
packUrl=pin.url();packHash=HexFormat.of().parseHex(pin.sha1());
|
|
active=this;Bukkit.getPluginManager().registerEvents(this,plugin);Bukkit.getScheduler().runTaskLater(plugin,()->Bukkit.getOnlinePlayers().forEach(p->{configurationJoined(p);offerGameplay(p);}),60L);plugin.getLogger().info("MC GUI presentation connected for all DuneRealms menus; Jarvis callbacks retained.");
|
|
}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(!active.readiness.loaded(p.getUniqueId())||!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 boolean isMenuPack(UUID id){return active!=null&&id.equals(active.packId);}
|
|
static boolean assetsLoaded(Player player){if(active==null||active.framework==null)return false;try{return active.readiness.loaded(player.getUniqueId())&&Boolean.TRUE.equals(active.hasPack.invoke(active.framework,player));}catch(Exception failure){return false;}}
|
|
static void forget(UUID player){if(active!=null){active.closeHints.remove(player);if(active.readiness!=null)active.readiness.forget(player);active.gameplayOffered.remove(player);}}
|
|
static void offerPack(Player p){if(active!=null&&!BedrockForms.isBedrock(p))active.sendPack(p);}
|
|
private void sendPack(Player p){if(!serverOwnedPack&&p.isOnline()&&!readiness.loaded(p.getUniqueId())&&gameplayOffered.add(p.getUniqueId()))p.addResourcePack(packId,packUrl,packHash,"DuneRealms interactive menus",true);}
|
|
private void offerGameplay(Player p){if(p.isOnline()&&!BedrockForms.isBedrock(p))sendPack(p);}
|
|
@EventHandler public void playerJoined(PlayerJoinEvent e){configurationJoined(e.getPlayer());Bukkit.getScheduler().runTaskLater(plugin,()->offerGameplay(e.getPlayer()),60L);}
|
|
private void configurationJoined(Player p){if(serverOwnedPack&&readiness.configurationJoined(p.getUniqueId(),p.getResourcePackStatus()))loadedLog(p);}
|
|
private void loadedLog(Player p){if(serverOwnedPack)plugin.getLogger().info("Central resource pack loaded for "+p.getName()+" UUID "+packId);}
|
|
@EventHandler public void menuPackStatus(PlayerResourcePackStatusEvent e){if(readiness==null||packId==null||!packId.equals(e.getID()))return;if(readiness.status(e.getPlayer().getUniqueId(),e.getID(),e.getStatus()))loadedLog(e.getPlayer());if(e.getStatus()!=PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED&&e.getStatus()!=PlayerResourcePackStatusEvent.Status.ACCEPTED&&e.getStatus()!=PlayerResourcePackStatusEvent.Status.DOWNLOADED)gameplayOffered.remove(e.getPlayer().getUniqueId());}
|
|
private boolean present(Player p,String title,String description,Inventory inventory,Map<Integer,Runnable> actions,GuiSession suppliedGate){
|
|
if(framework==null||!engine.isEnabled()||!p.isOnline()||BedrockForms.isBedrock(p))return false;
|
|
if(!p.getWorld().getName().equals("guild_lobby")&&!readiness.loaded(p.getUniqueId()))return false;
|
|
try{if(!Boolean.TRUE.equals(hasPack.invoke(framework,p))){if(p.getWorld().getName().equals("guild_lobby")){sendPack(p);p.sendMessage("Loading the lobby menu artwork. Reopen your menu after loading.");}else return false;return true;}}catch(Exception e){p.sendMessage("The new menu is temporarily unavailable. Please retry /menu.");return true;}
|
|
List<MenuDocument.Card> cards=new ArrayList<>();Set<Runnable> aliases=Collections.newSetFromMap(new IdentityHashMap<>());Set<String> decorations=new HashSet<>(),transparent=new HashSet<>();
|
|
var plain=PlainTextComponentSerializer.plainText();
|
|
for(int slot=0;slot<inventory.getSize();slot++){
|
|
ItemStack item=inventory.getItem(slot);if(item==null||item.getType().isAir())continue;
|
|
var meta=item.getItemMeta();String name=MenuDocument.clean(meta!=null&&meta.hasDisplayName()?plain.serialize(meta.displayName()):item.getType().name().replace('_',' '));
|
|
if(name.isBlank()||!actions.containsKey(slot)&&item.getType().name().endsWith("STAINED_GLASS_PANE"))continue;
|
|
List<String> lore=meta!=null&&meta.hasLore()?meta.lore().stream().map(plain::serialize).map(MenuDocument::clean).filter(s->!s.isBlank()).toList():List.of();
|
|
if(meta!=null&&meta.hasItemModel()&&meta.getItemModel().getKey().equals("drgui_transparent")&&!transparent.add(name+lore))continue;Runnable action=actions.get(slot);if(action!=null&&!aliases.add(action)||action==null&&!decorations.add(name+item.getType()+lore))continue;
|
|
String material=item.getType().name().toLowerCase(Locale.ROOT),quality="";if(meta!=null){String art=meta.getPersistentDataContainer().get(new NamespacedKey("dunerealms","menu_art"),org.bukkit.persistence.PersistentDataType.STRING);if(art!=null&&art.matches("[a-z0-9_]{1,70}"))material=art;}
|
|
if(meta!=null)for(var key:meta.getPersistentDataContainer().getKeys())if(key.getKey().equals("quality")){String value=meta.getPersistentDataContainer().get(key,org.bukkit.persistence.PersistentDataType.STRING);if(value!=null)quality=value;}
|
|
cards.add(new MenuDocument.Card(slot,name,lore,material,item.getAmount(),action!=null,quality));
|
|
}
|
|
GuiSession gate=suppliedGate==null?new GuiSession(p.getUniqueId()):suppliedGate;
|
|
Session old=sessions.remove(p.getUniqueId());if(old!=null)old.finish();
|
|
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){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=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());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;}
|
|
int slot(int x,int y){Object f=frame;if(f==null)return -2;try{Object e=f.getClass().getMethod("elementAt",double.class,double.class).invoke(f,x/1.5,y/1.5);if(e==null)return -2;Object button=e.getClass().getMethod("closest",String.class).invoke(e,"[data-slot],[data-pick]");if(button==null)return -2;String action=(String)button.getClass().getMethod("attr",String.class).invoke(button,"data-slot");if(!action.isEmpty())return Integer.parseInt(action);String pick=(String)button.getClass().getMethod("attr",String.class).invoke(button,"data-pick");return -100-Integer.parseInt(pick);}catch(Exception e){return -2;}}
|
|
public Object invoke(Object proxy,Method method,Object[] args)throws Throwable{
|
|
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());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;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;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();}
|
|
}
|

Staff