forked from unimatrix/web
Replace rejected GUI with owner-supplied painted DuneMenus ZIP
This commit is contained in:
parent
cd2c30923a
commit
aca4e5e168
38 changed files with 386 additions and 1787 deletions
|
|
@ -62,7 +62,7 @@ jobs:
|
|||
set -euo pipefail
|
||||
gradle --no-daemon -p DuneMenus test jar
|
||||
mkdir -p dunemenus-artifacts
|
||||
cp DuneMenus/build/libs/DuneMenus.jar dunemenus-artifacts/
|
||||
python3 tools/build-dunemenus-release.py dunemenus-artifacts
|
||||
printf '%s\n' "$(git rev-parse HEAD)" > dunemenus-artifacts/SOURCE_COMMIT
|
||||
(cd dunemenus-artifacts && sha256sum -- DuneMenus.jar SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
|
|
@ -70,22 +70,3 @@ jobs:
|
|||
name: ${{ github.repository == 'dev/MC' && 'DuneMenus-Development' || 'DuneMenus' }}
|
||||
path: dunemenus-artifacts/
|
||||
if-no-files-found: error
|
||||
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '25'
|
||||
- name: Build optional Paper 26.2 fullscreen provider
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gradle --no-daemon -p DuneFullscreenPaper test jar
|
||||
mkdir -p fullscreen-artifacts
|
||||
cp DuneFullscreenPaper/build/libs/DuneFullscreenPaper.jar fullscreen-artifacts/
|
||||
printf '%s\n' "$(git rev-parse HEAD)" > fullscreen-artifacts/SOURCE_COMMIT
|
||||
(cd fullscreen-artifacts && sha256sum -- DuneFullscreenPaper.jar SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Fullscreen-Paper-Development
|
||||
path: fullscreen-artifacts/
|
||||
if-no-files-found: error
|
||||
|
|
|
|||
|
|
@ -1,7 +0,0 @@
|
|||
# Optional Paper fullscreen roleplay provider
|
||||
|
||||
DuneGit builds this provider as a separate development artifact. It requires Paper 26.2 build 135 and Java 25. Build `DuneRealmsGUI` first, then run `gradle -p DuneFullscreenPaper test jar` with Java 25 and Gradle 9.2.1.
|
||||
|
||||
The Java Decisions dashboard uses this provider only for UUIDs listed under `development.fullscreen-decisions-viewers` in the DunerealmsGUI config. Quest dashboards, turn-ins and next-mission screens use `development.fullscreen-quest-viewers`. Branded organisation modules use `development.fullscreen-organisation-viewers`, Exchange browse, listing and kit shelves, plus loose-item and kit checkout, use `development.fullscreen-exchange-viewers`, and House or Mentat screens use `development.fullscreen-house-viewers`. Keep these allowlists empty on live servers. Existing menus handle unavailable providers, invalid card slots, documents outside the 54-card inventory limit, and quest text that exceeds the native layout.
|
||||
|
||||
Larger documents retain their server-provided slots and show four entries per page in Decisions, quests and organisation modules, and six in Exchange and House views. The mounted view can still expose vanilla overlays such as the experience bar, crosshair, chat and system notifications.
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
plugins {
|
||||
java
|
||||
id("io.papermc.paperweight.userdev") version "2.0.0-beta.23"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
paperweight.paperDevBundle("26.2.build.135-stable")
|
||||
compileOnly(files("../DuneMenus/build/libs/DuneMenus.jar"))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
}
|
||||
|
||||
repositories { mavenCentral() }
|
||||
// Teardown tests exercise the provider's lifecycle without bootstrapping a Paper server.
|
||||
configurations.testRuntimeClasspath {
|
||||
exclude(group = "io.papermc.paper", module = "dev-bundle")
|
||||
}
|
||||
tasks.test { useJUnitPlatform() }
|
||||
|
||||
java { toolchain.languageVersion.set(JavaLanguageVersion.of(25)) }
|
||||
tasks.withType<JavaCompile>().configureEach { options.encoding = "UTF-8" }
|
||||
tasks.jar { archiveFileName.set("DuneFullscreenPaper.jar") }
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
pluginManagement {
|
||||
repositories {
|
||||
gradlePluginPortal()
|
||||
maven("https://repo.papermc.io/repository/maven-public/")
|
||||
}
|
||||
}
|
||||
rootProject.name = "DuneFullscreenPaper"
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
package com.dunerealms.fullscreen;
|
||||
|
||||
import com.dunerealms.services.DecisionsViewTransport;
|
||||
import io.papermc.paper.ServerBuildInfo;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.plugin.ServicePriority;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
public final class FullscreenProvider extends JavaPlugin {
|
||||
private PaperDecisionsScene scenes;
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
var build = ServerBuildInfo.buildInfo();
|
||||
if (!build.minecraftVersionId().equals("26.2") || build.buildNumber().orElse(-1) != 135 ||
|
||||
!build.isBrandCompatible(ServerBuildInfo.BRAND_PAPER_ID)) {
|
||||
getLogger().info("Fullscreen Decisions requires Paper 26.2 build 135.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
scenes = new PaperDecisionsScene(this);
|
||||
Bukkit.getPluginManager().registerEvents(scenes, this);
|
||||
Bukkit.getServicesManager().register(DecisionsViewTransport.class, scenes, this, ServicePriority.Normal);
|
||||
com.dunerealms.menus.FullscreenProvider menus = (viewer, screen, select, close) -> {
|
||||
var cards = new java.util.ArrayList<DecisionsViewTransport.Card>();
|
||||
for (var card : screen.cards()) {
|
||||
cards.add(new DecisionsViewTransport.Card(card.slot(), card.title(), card.lore(), true, card.material()));
|
||||
}
|
||||
int infoSlot = 54;
|
||||
for (String line : screen.info()) {
|
||||
cards.add(new DecisionsViewTransport.Card(infoSlot++, line, java.util.List.of(), false));
|
||||
}
|
||||
return scenes.open(viewer, new DecisionsViewTransport.Document(screen.title(), screen.subtitle(), cards), select, close);
|
||||
};
|
||||
Bukkit.getServicesManager().register(com.dunerealms.menus.FullscreenProvider.class, menus, this, ServicePriority.Normal);
|
||||
} catch (LinkageError unavailable) {
|
||||
getLogger().warning("Fullscreen Decisions runtime is unavailable: " + unavailable.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
Bukkit.getServicesManager().unregisterAll(this);
|
||||
if (scenes != null) scenes.close();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,48 +0,0 @@
|
|||
package com.dunerealms.fullscreen;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
final class SceneTeardown {
|
||||
private SceneTeardown() {}
|
||||
|
||||
record Position(UUID world, double x, double y, double z) {}
|
||||
|
||||
static boolean restore(Position saved, BooleanSupplier teleport, Supplier<Position> current) {
|
||||
return teleport.getAsBoolean() && saved.equals(current.get());
|
||||
}
|
||||
|
||||
static void run(BooleanSupplier restore, Runnable select, Runnable dismiss, Runnable rejected,
|
||||
Consumer<Throwable> report, Runnable... cleanup) {
|
||||
boolean clean = true;
|
||||
for (Runnable step : cleanup) {
|
||||
try {
|
||||
step.run();
|
||||
} catch (RuntimeException | LinkageError failure) {
|
||||
clean = false;
|
||||
report.accept(failure);
|
||||
}
|
||||
}
|
||||
|
||||
boolean restored = false;
|
||||
try {
|
||||
restored = restore.getAsBoolean();
|
||||
} catch (RuntimeException | LinkageError failure) {
|
||||
report.accept(failure);
|
||||
}
|
||||
|
||||
if (select != null && restored && clean) {
|
||||
try {
|
||||
select.run();
|
||||
} catch (RuntimeException | LinkageError failure) {
|
||||
dismiss.run();
|
||||
report.accept(failure);
|
||||
}
|
||||
} else {
|
||||
dismiss.run();
|
||||
if (select != null || !restored) rejected.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
name: DuneFullscreenPaper
|
||||
main: com.dunerealms.fullscreen.FullscreenProvider
|
||||
version: 0.1.0
|
||||
api-version: '26.2'
|
||||
depend: [DuneMenus]
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
package com.dunerealms.fullscreen;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SceneTeardownTest {
|
||||
private final SceneTeardown.Position saved = new SceneTeardown.Position(UUID.randomUUID(), 10.5, 64, 7.5);
|
||||
|
||||
@Test void cancelledReturnDoesNotRunSelection() {
|
||||
assertRejected(() -> SceneTeardown.restore(saved, () -> false, () -> saved));
|
||||
}
|
||||
|
||||
@Test void redirectedReturnDoesNotRunSelection() {
|
||||
assertRejected(() -> SceneTeardown.restore(saved, () -> true, () -> new SceneTeardown.Position(saved.world(), 10.5, 70, 7.5)));
|
||||
}
|
||||
|
||||
@Test void returnToSameCoordinatesInAnotherWorldDoesNotRunSelection() {
|
||||
assertRejected(() -> SceneTeardown.restore(saved, () -> true,
|
||||
() -> new SceneTeardown.Position(UUID.randomUUID(), saved.x(), saved.y(), saved.z())));
|
||||
}
|
||||
|
||||
@Test void exactReturnRunsSelectionOnceAfterCleanup() {
|
||||
var calls = new ArrayList<String>();
|
||||
SceneTeardown.run(() -> SceneTeardown.restore(saved, () -> true, () -> saved),
|
||||
() -> calls.add("selected"), () -> fail("Unexpected dismissal"), () -> fail("Unexpected rejection"),
|
||||
failure -> fail(failure), () -> calls.add("cleanup"));
|
||||
assertEquals(List.of("cleanup", "selected"), calls);
|
||||
}
|
||||
|
||||
@Test void cleanupFailureStillRestoresAndReleasesSession() {
|
||||
var calls = new ArrayList<String>();
|
||||
SceneTeardown.run(() -> { calls.add("restored"); return true; }, () -> fail("Unsafe selection"),
|
||||
() -> calls.add("dismissed"), () -> calls.add("rejected"), failure -> calls.add("reported"),
|
||||
() -> { throw new IllegalStateException("failed to restore camera"); },
|
||||
() -> calls.add("removed entities"));
|
||||
assertEquals(List.of("reported", "removed entities", "restored", "dismissed", "rejected"), calls);
|
||||
}
|
||||
|
||||
@Test void restorationExceptionStillReleasesSession() {
|
||||
var calls = new ArrayList<String>();
|
||||
SceneTeardown.run(() -> { throw new IllegalStateException("teleport failed"); }, null,
|
||||
() -> calls.add("dismissed"), () -> calls.add("rejected"), failure -> calls.add("reported"));
|
||||
assertEquals(List.of("reported", "dismissed", "rejected"), calls);
|
||||
}
|
||||
|
||||
@Test void incomingTeleportReleaseLeavesDestinationAlone() {
|
||||
var calls = new ArrayList<String>();
|
||||
SceneTeardown.run(() -> true, null, () -> calls.add("dismissed"),
|
||||
() -> fail("Unexpected rejection"), failure -> fail(failure), () -> calls.add("cleanup"));
|
||||
assertEquals(List.of("cleanup", "dismissed"), calls);
|
||||
}
|
||||
|
||||
private void assertRejected(java.util.function.BooleanSupplier restoration) {
|
||||
var calls = new ArrayList<String>();
|
||||
SceneTeardown.run(restoration, () -> fail("Unsafe selection"), () -> calls.add("dismissed"),
|
||||
() -> calls.add("rejected"), failure -> fail(failure));
|
||||
assertEquals(List.of("dismissed", "rejected"), calls);
|
||||
}
|
||||
}
|
||||
25
DuneMenus/docs/NEW-GUI.md
Normal file
25
DuneMenus/docs/NEW-GUI.md
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
# New DuneRealms menu (painted full-screen chest)
|
||||
|
||||
Java players now get a 6-row chest whose title draws a painted 176x222 background (resource pack font `dunerealms:gui`).
|
||||
Each menu keeps its own layout: its real items sit on the painted panel; panes/fillers are hidden so the art shows.
|
||||
Clicks go through the Menu's own buttons, so every J.A.R.V.I.S. call is unchanged. Bedrock still uses Floodgate forms.
|
||||
|
||||
## Changed files (everything else, including JarvisBackend and Backend, is untouched)
|
||||
- `GlyphChestProvider.java` (new): the renderer, registered as the `FullscreenProvider` service.
|
||||
- `FullscreenProvider.java`: `Screen` also carries the menu's item contents.
|
||||
- `Menu.java`: passes a copy of its inventory to the provider.
|
||||
- `DuneMenusPlugin.java`: registers the provider when `fullscreen.enabled` is true; adds `/dm calibrate` (admin).
|
||||
- `config.yml`: `fullscreen.enabled: true`.
|
||||
- `tools/build_gui_backgrounds.py`: paints the 12 backgrounds and `font/gui.json`.
|
||||
|
||||
## Deploy
|
||||
1. Merge `gui-pack/assets/dunerealms/` into the central pack (adds `font/gui.json` and `textures/gui/bg/*.png`). Republish the pack and update its SHA-1.
|
||||
2. Build DuneMenus (`gradle test jar`, Java 21) and replace the plugin.
|
||||
3. As an admin run `/dm calibrate`: you should see numbered paper markers sitting inside the painted sockets.
|
||||
If the art is shifted, adjust `ascent` (13) in `font/gui.json`; if the title text is shifted, adjust the `` advance (-177) there.
|
||||
4. Open `/dm`, `/dm travel`, `/dm spice` ... and check each screen.
|
||||
|
||||
## Not verified (nothing was compiled or run by the author)
|
||||
- Compilation against Paper 1.21.8, in-game alignment, shadow on the background glyph, and Bedrock behaviour.
|
||||
- Menus with more than 54 slots are not supported (the chest is 6 rows).
|
||||
- Backgrounds are per accent colour (gold, travel, market, clan, company, quest, spice, war, politics, house, forge), not one painting per screen.
|
||||
|
|
@ -57,6 +57,11 @@ public final class DuneMenusPlugin extends DuneServicesPlugin implements TabExec
|
|||
getLogger().info("Backend: " + backend.getClass().getSimpleName());
|
||||
getServer().getPluginManager().registerEvents(new MenuListener(this), this);
|
||||
getServer().getPluginManager().registerEvents(new ChatPrompt(this), this);
|
||||
if (getConfig().getBoolean("fullscreen.enabled", true)) {
|
||||
glyphChest = new GlyphChestProvider(this);
|
||||
getServer().getPluginManager().registerEvents(glyphChest, this);
|
||||
getServer().getServicesManager().register(FullscreenProvider.class, glyphChest, this, org.bukkit.plugin.ServicePriority.Normal);
|
||||
}
|
||||
getCommand("dm").setExecutor(this);
|
||||
getCommand("dm").setTabCompleter(this);
|
||||
getServer().getScheduler().runTask(this, () -> nativeRoutes = new NativeMenuRoutes(this));
|
||||
|
|
@ -67,6 +72,7 @@ public final class DuneMenusPlugin extends DuneServicesPlugin implements TabExec
|
|||
super.onDisable();
|
||||
}
|
||||
|
||||
private GlyphChestProvider glyphChest;
|
||||
Backend backend() { return backend; }
|
||||
|
||||
@Override
|
||||
|
|
@ -150,6 +156,11 @@ public final class DuneMenusPlugin extends DuneServicesPlugin implements TabExec
|
|||
}
|
||||
if (!(s instanceof Player p)) { s.sendMessage("Players only."); return true; }
|
||||
if (!p.hasPermission("dunemenus.use")) { p.sendMessage("No permission."); return true; }
|
||||
if (a.length == 1 && a[0].equalsIgnoreCase("calibrate")) {
|
||||
if (!p.hasPermission("dunemenus.admin")) { p.sendMessage("No permission."); return true; }
|
||||
if (glyphChest == null) p.sendMessage("fullscreen.enabled is false."); else glyphChest.calibrate(p);
|
||||
return true;
|
||||
}
|
||||
if (a.length == 1 && a[0].equalsIgnoreCase("item")) {
|
||||
p.sendMessage(backend().claimCodex(p).message());
|
||||
return true;
|
||||
|
|
@ -173,7 +184,7 @@ public final class DuneMenusPlugin extends DuneServicesPlugin implements TabExec
|
|||
@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"))
|
||||
return java.util.stream.Stream.concat(IDS.stream(), java.util.stream.Stream.of("reload", "calibrate"))
|
||||
.filter(x -> x.startsWith(a[0].toLowerCase())).toList();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,14 +4,10 @@ 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.
|
||||
*/
|
||||
/** Presentation contract for the supplied painted menu provider. */
|
||||
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) {}
|
||||
record Screen(String id, String title, String subtitle, List<Card> cards, List<String> info,
|
||||
org.bukkit.inventory.ItemStack[] contents) {}
|
||||
|
||||
/** Server thread. Call exactly one of select / close later, never inside open(). */
|
||||
boolean open(Player viewer, Screen screen, IntConsumer select, Runnable close);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,137 @@
|
|||
package com.dunerealms.menus;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.IntConsumer;
|
||||
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.TextColor;
|
||||
import net.kyori.adventure.text.format.TextDecoration;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.inventory.InventoryCloseEvent;
|
||||
import org.bukkit.event.inventory.InventoryDragEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
/**
|
||||
* The DuneRealms full-screen menu for Java players. A 6-row chest whose title carries a painted 176x222 background
|
||||
* (resource pack font dunerealms:gui) and whose slots hold the menu's real items, so every menu keeps its own layout.
|
||||
* Clicks go back through the Menu's own button handlers, so all J.A.R.V.I.S. calls stay exactly as they were.
|
||||
*
|
||||
* Title layout: [-8 shift][background glyph][-177 shift][+8 shift][title text]. The glyph is 704x888 shown at height 222
|
||||
* (scale 0.25), so it is 176 px wide and advances 177. Run /dm calibrate in game once to confirm the alignment.
|
||||
*/
|
||||
final class GlyphChestProvider implements FullscreenProvider, Listener {
|
||||
private static final Key GUI_FONT = Key.key("dunerealms", "gui");
|
||||
private static final Key DEFAULT_FONT = Key.key("minecraft", "default");
|
||||
private static final String SHIFT = "" + "%s" + "" + "龜"; // -8, glyph, -177, +8
|
||||
|
||||
/** menu id to background glyph (code points match assets/dunerealms/font/gui.json). */
|
||||
private static final Map<String, Character> BACKGROUNDS = Map.ofEntries(
|
||||
Map.entry("hub", ''), Map.entry("bank", ''), Map.entry("atm", ''), Map.entry("withdraw", ''),
|
||||
Map.entry("travel", ''), Map.entry("exchange", ''), Map.entry("clan", ''),
|
||||
Map.entry("company", ''), Map.entry("missions", ''), Map.entry("spice", ''),
|
||||
Map.entry("war", ''), Map.entry("politics", ''), Map.entry("house", ''),
|
||||
Map.entry("equipment", ''), Map.entry("calibrate", ''));
|
||||
private static final char DEFAULT_BACKGROUND = '';
|
||||
|
||||
private static final class Session implements InventoryHolder {
|
||||
Inventory inventory;
|
||||
final Set<Integer> clickable = new HashSet<>();
|
||||
IntConsumer select;
|
||||
Runnable close;
|
||||
boolean handled;
|
||||
@Override public Inventory getInventory() { return inventory; }
|
||||
}
|
||||
|
||||
private final DuneMenusPlugin plugin;
|
||||
private final Map<UUID, Session> sessions = new HashMap<>();
|
||||
private final Map<UUID, Long> lastClick = new HashMap<>();
|
||||
|
||||
GlyphChestProvider(DuneMenusPlugin plugin) { this.plugin = plugin; }
|
||||
|
||||
@Override
|
||||
public boolean open(Player viewer, Screen screen, IntConsumer select, Runnable close) {
|
||||
Session session = new Session();
|
||||
session.select = select;
|
||||
session.close = close;
|
||||
Component title = Component.text(String.format(SHIFT, BACKGROUNDS.getOrDefault(screen.id(), DEFAULT_BACKGROUND)), NamedTextColor.WHITE)
|
||||
.font(GUI_FONT).decoration(TextDecoration.ITALIC, false)
|
||||
.append(Component.text(screen.title(), TextColor.fromHexString("#F5EAD0"))
|
||||
.font(DEFAULT_FONT).decoration(TextDecoration.BOLD, true).decoration(TextDecoration.ITALIC, false));
|
||||
session.inventory = Bukkit.createInventory(session, 54, title);
|
||||
for (Card card : screen.cards()) if (card.slot() >= 0 && card.slot() < 54) session.clickable.add(card.slot());
|
||||
ItemStack[] contents = screen.contents();
|
||||
for (int i = 0; contents != null && i < Math.min(contents.length, 54); i++) {
|
||||
ItemStack item = contents[i];
|
||||
if (item == null || item.getType().isAir() || blank(item)) continue;
|
||||
session.inventory.setItem(i, item);
|
||||
}
|
||||
Session old = sessions.put(viewer.getUniqueId(), session);
|
||||
if (old != null) old.handled = true; // the new screen replaces the old one: do not report it as closed
|
||||
viewer.openInventory(session.inventory);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Test screen: every slot is a named marker over the painted socket grid, so any misalignment is visible. */
|
||||
void calibrate(Player viewer) {
|
||||
ItemStack[] contents = new ItemStack[54];
|
||||
for (int i = 0; i < 54; i++) {
|
||||
contents[i] = Ui.item(Material.PAPER, "<yellow>R" + (i / 9 + 1) + " C" + (i % 9 + 1));
|
||||
}
|
||||
open(viewer, new Screen("calibrate", "Calibration", "", java.util.List.of(), java.util.List.of(), contents),
|
||||
slot -> { }, () -> { });
|
||||
}
|
||||
|
||||
/** Backdrop panes and tooltip-less fillers are skipped so the painted art shows through. */
|
||||
private static boolean blank(ItemStack item) {
|
||||
if (item.getType().name().endsWith("_PANE")) return true;
|
||||
var meta = item.getItemMeta();
|
||||
return meta != null && meta.isHideTooltip();
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onClick(InventoryClickEvent event) {
|
||||
if (!(event.getView().getTopInventory().getHolder() instanceof Session session)) return;
|
||||
event.setCancelled(true); // nothing in a menu can be taken or moved
|
||||
if (event.getClickedInventory() != event.getView().getTopInventory() || session.handled) return;
|
||||
if (!session.clickable.contains(event.getSlot())) return;
|
||||
UUID id = event.getWhoClicked().getUniqueId();
|
||||
long now = System.currentTimeMillis();
|
||||
Long before = lastClick.put(id, now);
|
||||
if (before != null && now - before < 150) return; // swallow double-clicks so nothing is bought twice
|
||||
session.handled = true; // Menu.handle will redraw (new session) or close
|
||||
session.select.accept(event.getSlot());
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onDrag(InventoryDragEvent event) {
|
||||
if (event.getView().getTopInventory().getHolder() instanceof Session) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onClose(InventoryCloseEvent event) {
|
||||
if (!(event.getInventory().getHolder() instanceof Session session) || session.handled) return;
|
||||
session.handled = true;
|
||||
Session current = sessions.get(event.getPlayer().getUniqueId());
|
||||
if (current == session) sessions.remove(event.getPlayer().getUniqueId());
|
||||
session.close.run();
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
sessions.remove(event.getPlayer().getUniqueId());
|
||||
lastClick.remove(event.getPlayer().getUniqueId());
|
||||
}
|
||||
}
|
||||
|
|
@ -180,31 +180,14 @@ abstract class Menu implements InventoryHolder {
|
|||
if (mode == Mode.FULLSCREEN) {
|
||||
FullscreenProvider provider = plugin.fullscreen();
|
||||
boolean ok = provider != null && provider.open(player,
|
||||
new FullscreenProvider.Screen(id(), title(), subtitle(), cards, info),
|
||||
new FullscreenProvider.Screen(id(), title(), subtitle(), cards, info,
|
||||
java.util.Arrays.stream(inv.getContents()).map(i -> i == null ? null : i.clone()).toArray(ItemStack[]::new)),
|
||||
select, close);
|
||||
if (ok) return;
|
||||
List<io.papermc.paper.registry.data.dialog.ActionButton> choices = new ArrayList<>();
|
||||
for (Card card : cards) {
|
||||
choices.add(dialogButton(card.title(), String.join("\n", card.lore()), () -> select.accept(card.slot())));
|
||||
}
|
||||
choices.add(dialogButton("Close", "", close));
|
||||
String content = java.util.stream.Stream.concat(java.util.stream.Stream.of(subtitle()), info.stream())
|
||||
.filter(line -> !line.isBlank()).collect(java.util.stream.Collectors.joining("\n"));
|
||||
player.showDialog(io.papermc.paper.dialog.Dialog.create(builder -> builder.empty()
|
||||
.base(io.papermc.paper.registry.data.dialog.DialogBase.builder(Component.text(title()))
|
||||
.body(List.of(io.papermc.paper.registry.data.dialog.body.DialogBody.plainMessage(Component.text(content)))).build())
|
||||
.type(io.papermc.paper.registry.data.dialog.type.DialogType.multiAction(choices).build())));
|
||||
player.sendMessage(Component.text("The menu artwork is unavailable. Please reconnect after the resource pack loads."));
|
||||
closed();
|
||||
return;
|
||||
}
|
||||
Bedrock.show(plugin, player, title(), subtitle(), info, cards, select, close);
|
||||
}
|
||||
private io.papermc.paper.registry.data.dialog.ActionButton dialogButton(String label, String hint, Runnable action) {
|
||||
return io.papermc.paper.registry.data.dialog.ActionButton.builder(Component.text(label))
|
||||
.tooltip(Component.text(hint))
|
||||
.action(io.papermc.paper.registry.data.dialog.action.DialogAction.customClick((view, viewer) -> {
|
||||
if (player.equals(viewer)) Bukkit.getScheduler().runTask(plugin, action);
|
||||
}, net.kyori.adventure.text.event.ClickCallback.Options.builder().uses(1)
|
||||
.lifetime(java.time.Duration.ofMinutes(5)).build())).build();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ public abstract class DuneServicesPlugin extends JavaPlugin implements Listener,
|
|||
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;
|
||||
private MCGUIMenus modernMenus;
|
||||
|
||||
private EcologyArtwork ecologyArtwork;
|
||||
private QuestMenus quests;
|
||||
private WarMenus warMenus;
|
||||
|
|
@ -89,7 +89,7 @@ public abstract class DuneServicesPlugin extends JavaPlugin implements Listener,
|
|||
|
||||
organisations=new OrganisationMenus(this,bridge,p->fetch(p,null,0,null,data->mentat(p,data)),p->openGuild(p,null),p->fetch(p,null,0,null,data->select(p,data,null)),p->quests.open(p),p->quests.openDecisions(p,0),p->exchange.open(p),p->spice.open(p),p->guiPackLoaded.contains(p.getUniqueId()));
|
||||
registrar=new NamespacedKey("dunerealmsgui","house_registrar");
|
||||
modernMenus=new MCGUIMenus(this);
|
||||
|
||||
ecologyArtwork=new EcologyArtwork(this);
|
||||
proxyPacks=new ProxyPackBridge(this,this::receiveProxyArtworkStatus);
|
||||
new PlanetTexturePacks(this,proxyPacks);
|
||||
|
|
@ -106,7 +106,7 @@ public abstract class DuneServicesPlugin extends JavaPlugin implements Listener,
|
|||
Bukkit.getScheduler().runTaskTimer(this,()->{for(Player p:Bukkit.getOnlinePlayers()){refreshSidebar(p);}},80L,600L);
|
||||
getLogger().info("House selector and Mentat screens enabled; central J.A.R.V.I.S. bridge; no Core/Lobby replacement.");
|
||||
}
|
||||
@Override public void onDisable(){if(modernMenus!=null)modernMenus.close();if(nameplates!=null)nameplates.close();if(exchange!=null)exchange.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();}
|
||||
@Override public void onDisable(){if(nameplates!=null)nameplates.close();if(exchange!=null)exchange.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 player&&args.length==0){
|
||||
|
|
@ -267,7 +267,7 @@ public abstract class DuneServicesPlugin extends JavaPlugin implements Listener,
|
|||
if(!p.isOnline()||BedrockForms.isBedrock(p))return;
|
||||
if(proxyPacks.ownsCommon()){
|
||||
proxyPacks.requestStatus(p);
|
||||
if(lobby(p)){MCGUIMenus.offerPack(p);ecologyArtwork.offer(p);}
|
||||
if(lobby(p)){ecologyArtwork.offer(p);}
|
||||
return;
|
||||
}
|
||||
var pack=guiPack(p);
|
||||
|
|
@ -276,7 +276,7 @@ public abstract class DuneServicesPlugin extends JavaPlugin implements Listener,
|
|||
// Replace only the network pack, never the separately managed planet pack.
|
||||
offeredGuiPacks.put(p.getUniqueId(),pack);
|
||||
p.addResourcePack(NetworkArtworkPolicy.PACK_ID,pack.url(),java.util.HexFormat.of().parseHex(pack.hash()),"DuneRealms menus and item artwork",true);
|
||||
if(lobby(p)){MCGUIMenus.offerPack(p);ecologyArtwork.offer(p);}
|
||||
if(lobby(p)){ecologyArtwork.offer(p);}
|
||||
}
|
||||
@EventHandler public void join(PlayerJoinEvent e){Bukkit.getScheduler().runTaskLater(this,()->{
|
||||
Player p=e.getPlayer();if(!p.isOnline())return;
|
||||
|
|
@ -352,10 +352,10 @@ public abstract class DuneServicesPlugin extends JavaPlugin implements Listener,
|
|||
public void protectMenuPlayer(org.bukkit.event.entity.EntityDamageEvent event){
|
||||
if(event.getEntity() instanceof Player player&&(
|
||||
player.getOpenInventory().getTopInventory().getHolder() instanceof DuneMenuInventory||
|
||||
MCGUIMenus.isOpen(player)||GuiSession.hasVisibleForm(player.getUniqueId(),player.getWorld().getUID())))event.setCancelled(true);
|
||||
GuiSession.hasVisibleForm(player.getUniqueId(),player.getWorld().getUID())))event.setCancelled(true);
|
||||
}
|
||||
@EventHandler public void close(InventoryCloseEvent e){if(e.getInventory().getHolder() instanceof Screen s)s.gate.expire();}
|
||||
@EventHandler public void quit(PlayerQuitEvent e){GuiSession.expire(e.getPlayer().getUniqueId());MCGUIMenus.forget(e.getPlayer().getUniqueId());guiPackLoaded.remove(e.getPlayer().getUniqueId());offeredGuiPacks.remove(e.getPlayer().getUniqueId());bookings.cancel(e.getPlayer().getUniqueId());boarding.remove(e.getPlayer().getUniqueId());requests.remove(e.getPlayer().getUniqueId());records.remove(e.getPlayer().getUniqueId());sidebar.hide(e.getPlayer());departure.removePlayer(e.getPlayer());}
|
||||
@EventHandler public void quit(PlayerQuitEvent e){GuiSession.expire(e.getPlayer().getUniqueId());guiPackLoaded.remove(e.getPlayer().getUniqueId());offeredGuiPacks.remove(e.getPlayer().getUniqueId());bookings.cancel(e.getPlayer().getUniqueId());boarding.remove(e.getPlayer().getUniqueId());requests.remove(e.getPlayer().getUniqueId());records.remove(e.getPlayer().getUniqueId());sidebar.hide(e.getPlayer());departure.removePlayer(e.getPlayer());}
|
||||
private void ensureRegistrar(){World world=Bukkit.getWorld("guild_lobby");if(world==null)return;Location at=world.getSpawnLocation().clone().add(2,0,0);at.getChunk().load();
|
||||
for(Entity entity:world.getEntities())if(entity.getPersistentDataContainer().has(registrar,PersistentDataType.BYTE))return;
|
||||
Villager npc=world.spawn(at,Villager.class);npc.setAI(false);npc.setInvulnerable(true);npc.setPersistent(true);npc.setSilent(true);npc.setCollidable(false);npc.setProfession(Villager.Profession.LIBRARIAN);npc.customName(Component.text("House Registrar · Choose your House",NamedTextColor.GOLD));npc.setCustomNameVisible(true);npc.getPersistentDataContainer().set(registrar,PersistentDataType.BYTE,(byte)1);
|
||||
|
|
|
|||
|
|
@ -1,130 +0,0 @@
|
|||
package com.dunerealms.services;
|
||||
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;
|
||||
private final JavaPlugin plugin;
|
||||
private final Map<UUID,Session> sessions=new HashMap<>();
|
||||
private final Set<UUID> closeHints=new HashSet<>(),gameplayReady=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 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;
|
||||
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"));
|
||||
try(var logo=plugin.getResource("mcgui/dunerealms-season-logo-v2.png")){
|
||||
if(logo==null)throw new IllegalStateException("Missing DuneRealms website logo");
|
||||
Files.copy(logo,base.getParent().resolve("art/dunerealms-season-logo-v2.png"),StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
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);
|
||||
packId=(UUID)Class.forName("ai.resourcepack.ui.framework.pack.ResourcePack",true,cl).getField("PACK_ID").get(null);
|
||||
packUrl=engine.getConfig().getString("resource-pack.public-url","");
|
||||
// MC GUI external-without-URL means the pack was delivered by lobby.
|
||||
if(packUrl.isBlank())packUrl="https://www.dunerealms.com/downloads/DuneRealms-MCGUI-0.8.6-1.21.11.zip";
|
||||
if(!packUrl.startsWith("https://"))throw new IllegalStateException("A hosted menu pack URL is required");
|
||||
packHash=java.security.MessageDigest.getInstance("SHA-1").digest(Files.readAllBytes(engine.getDataFolder().toPath().resolve("pack.zip")));
|
||||
active=this;Bukkit.getPluginManager().registerEvents(this,plugin);Bukkit.getScheduler().runTaskLater(plugin,()->Bukkit.getOnlinePlayers().forEach(this::offerGameplay),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){
|
||||
return show(p,title,description,inventory,actions,gate,null);
|
||||
}
|
||||
static boolean show(Player p,String title,String description,Inventory inventory,Map<Integer,Runnable> actions,GuiSession gate,MenuDocument.Branding branding){
|
||||
return active!=null&&active.present(p,title,description,inventory,actions,gate,branding);
|
||||
}
|
||||
static boolean isOpen(Player player){
|
||||
Session session=active==null?null:active.sessions.get(player.getUniqueId());
|
||||
return session!=null&&session.view!=null&&session.current();
|
||||
}
|
||||
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);}
|
||||
private void offerGameplay(Player p){if(p.isOnline()&&!BedrockForms.isBedrock(p)&&!p.getWorld().getName().equals("guild_lobby")&&gameplayOffered.add(p.getUniqueId()))sendPack(p);}
|
||||
@EventHandler public void playerJoined(PlayerJoinEvent e){Bukkit.getScheduler().runTaskLater(plugin,()->offerGameplay(e.getPlayer()),60L);}
|
||||
@EventHandler public void menuPackStatus(PlayerResourcePackStatusEvent e){if(packId==null||!packId.equals(e.getID())||e.getPlayer().getWorld().getName().equals("guild_lobby"))return;var id=e.getPlayer().getUniqueId();if(e.getStatus()==PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED)gameplayReady.add(id);else if(e.getStatus()!=PlayerResourcePackStatusEvent.Status.ACCEPTED&&e.getStatus()!=PlayerResourcePackStatusEvent.Status.DOWNLOADED)gameplayReady.remove(id);}
|
||||
private boolean present(Player p,String title,String description,Inventory inventory,Map<Integer,Runnable> actions,GuiSession suppliedGate,MenuDocument.Branding branding){
|
||||
if(framework==null||!engine.isEnabled()||!p.isOnline()||BedrockForms.isBedrock(p))return false;
|
||||
if(!p.getWorld().getName().equals("guild_lobby")&&!gameplayReady.contains(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=cards(inventory,actions);
|
||||
GuiSession gate=suppliedGate==null?new GuiSession(p.getUniqueId()):suppliedGate;
|
||||
Session old=sessions.remove(p.getUniqueId());if(old!=null)old.finish();
|
||||
try{
|
||||
Map<Integer,Runnable> callbacks=new HashMap<>(actions);callbacks.values().removeIf(Objects::isNull);
|
||||
Session s=new Session(p,title,description,cards,Map.copyOf(callbacks),gate,branding);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;}
|
||||
}
|
||||
static List<MenuDocument.Card> cards(Inventory inventory,Map<Integer,Runnable> actions){
|
||||
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.get(slot)==null&&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));
|
||||
}
|
||||
return List.copyOf(cards);
|
||||
}
|
||||
private final class Session implements InvocationHandler {
|
||||
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 MenuDocument.Branding branding;
|
||||
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,MenuDocument.Branding branding)throws Exception{this.branding=branding;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(),branding);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.");}});}}
|
||||
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());return null;}Runnable action=gate.claimAction(player.getUniqueId(),slot==-3?()->player.performCommand("menu"):actions.get(slot));if(action!=null){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 "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){}}
|
||||
}
|
||||
public void close(){if(active==this)active=null;for(Session s:List.copyOf(sessions.values()))s.finish();sessions.clear();drawings.shutdownNow();}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -1,63 +0,0 @@
|
|||
package com.dunerealms.services;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
/** Bridges the existing menu document and its server-side callbacks to an opt-in renderer. */
|
||||
final class NativeMenus {
|
||||
private NativeMenus() {}
|
||||
|
||||
static boolean show(JavaPlugin plugin, Player player, String setting, String title, String description,
|
||||
Inventory inventory, Map<Integer,Runnable> actions, GuiSession gate,
|
||||
DecisionsViewTransport.Style style, MenuDocument.Branding branding) {
|
||||
if (!plugin.getConfig().getStringList(setting).contains(player.getUniqueId().toString())) return false;
|
||||
var transport = Bukkit.getServicesManager().load(DecisionsViewTransport.class);
|
||||
if (transport == null) return false;
|
||||
var cards = MCGUIMenus.cards(inventory, actions).stream().map(card ->
|
||||
new DecisionsViewTransport.Card(card.slot(), card.title(), card.lore(), card.action(), card.material())).toList();
|
||||
return show(player, plugin, transport, title, description, cards, actions, gate, style, branding);
|
||||
}
|
||||
|
||||
static boolean showGuild(JavaPlugin plugin, Player player, String title, String description,
|
||||
List<DecisionsViewTransport.Card> cards, Map<Integer,Runnable> actions, GuiSession gate) {
|
||||
if (!plugin.getConfig().getStringList("development.fullscreen-guild-viewers").contains(player.getUniqueId().toString())) return false;
|
||||
var transport = Bukkit.getServicesManager().load(DecisionsViewTransport.class);
|
||||
return transport != null && show(player, plugin, transport, title, description, cards, actions, gate,
|
||||
DecisionsViewTransport.Style.GUILD, null);
|
||||
}
|
||||
|
||||
private static boolean show(Player player, JavaPlugin plugin, DecisionsViewTransport transport, String title,
|
||||
String description, List<DecisionsViewTransport.Card> cards, Map<Integer,Runnable> actions,
|
||||
GuiSession gate, DecisionsViewTransport.Style style, MenuDocument.Branding branding) {
|
||||
var identity = branding == null ? null :
|
||||
new DecisionsViewTransport.Identity(branding.logo(), branding.mentat(), branding.portrait());
|
||||
var document = new DecisionsViewTransport.Document(title, description, cards, style, identity);
|
||||
Map<Integer,Runnable> visibleActions = new HashMap<>();
|
||||
for (var card : cards) if (card.actionable()) visibleActions.put(card.slot(), actions.get(card.slot()));
|
||||
var callbacks = Map.copyOf(visibleActions);
|
||||
player.closeInventory();
|
||||
var world = player.getWorld().getUID();
|
||||
try {
|
||||
if (!transport.open(player, document, slot -> {
|
||||
if (!Bukkit.isPrimaryThread()) return;
|
||||
if (!player.isOnline() || !world.equals(player.getWorld().getUID())) {
|
||||
gate.expire();
|
||||
return;
|
||||
}
|
||||
var action = gate.claimAction(player.getUniqueId(), callbacks.get(slot));
|
||||
gate.expire();
|
||||
if (action != null) action.run();
|
||||
}, gate::expire)) return false;
|
||||
} catch (RuntimeException | LinkageError failure) {
|
||||
plugin.getLogger().warning("Development fullscreen view unavailable: " + failure.getClass().getSimpleName());
|
||||
return false;
|
||||
}
|
||||
gate.markFormVisible(world);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -22,7 +22,7 @@ final class OrganisationMenus implements Listener {
|
|||
|
||||
|
||||
private static final class Panel implements DuneMenuInventory {
|
||||
final UUID owner;final GuiSession gate;final Map<Integer,Runnable> actions=new HashMap<>();final Set<Integer> nativeReadOnly=new HashSet<>();final Map<Integer,BedrockForms.Choice> choices=new TreeMap<>();String title;String nativeSetting;DecisionsViewTransport.Style nativeStyle;boolean artwork;Inventory inventory;MenuDocument.Branding branding;
|
||||
final UUID owner;final GuiSession gate;final Map<Integer,Runnable> actions=new HashMap<>();final Set<Integer> nativeReadOnly=new HashSet<>();final Map<Integer,BedrockForms.Choice> choices=new TreeMap<>();String title;String nativeSetting;DecisionsViewTransport.Style nativeStyle;boolean artwork;Inventory inventory;
|
||||
Panel(Player p){owner=p.getUniqueId();gate=new GuiSession(owner);}
|
||||
public Inventory getInventory(){return inventory;}
|
||||
}
|
||||
|
|
@ -133,7 +133,6 @@ final class OrganisationMenus implements Listener {
|
|||
String logo=identity.has("logoPng")&&!identity.get("logoPng").isJsonNull()?identity.get("logoPng").getAsString():"";
|
||||
var advisor=identity.has("mentat")&&identity.get("mentat").isJsonObject()?identity.getAsJsonObject("mentat"):null;
|
||||
String advisorName=advisor==null?"":advisor.get("name").getAsString();
|
||||
panel.branding=new MenuDocument.Branding(logo,advisorName,advisor==null?-1:advisor.get("portrait").getAsInt());
|
||||
int count=row.has("members")?row.getAsJsonArray("members").size():1;String role=manage?"Leader / manager":"Member";
|
||||
JsonObject home=row.has("homeBlock")&&!row.get("homeBlock").isJsonNull()?row.getAsJsonObject("homeBlock"):null;
|
||||
String homeText=home==null?"Not set":home.get("worldName").getAsString();
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ final class QuestMenus implements Listener {
|
|||
private final Map<UUID,UUID> pending=new HashMap<>();
|
||||
private final Map<UUID,PolQuestNpc.Role> roleScope=new HashMap<>();
|
||||
private static final class Panel implements DuneMenuInventory {
|
||||
final UUID owner;final GuiSession gate;final Map<Integer,Runnable> actions=new HashMap<>();final List<BedrockForms.Choice> choices=new ArrayList<>();final List<String> descriptionNotes=new ArrayList<>();final Inventory inventory;final String title;DecisionsViewTransport.Style nativeStyle;String description="Your current J.A.R.V.I.S. mission journal";
|
||||
final UUID owner;final GuiSession gate;final Map<Integer,Runnable> actions=new HashMap<>();final List<BedrockForms.Choice> choices=new ArrayList<>();final List<String> descriptionNotes=new ArrayList<>();final Inventory inventory;final String title;String description="Your current J.A.R.V.I.S. mission journal";
|
||||
Panel(Player p,String title){owner=p.getUniqueId();gate=new GuiSession(owner);this.title=title;inventory=Bukkit.createInventory(this,54,Component.text(title,NamedTextColor.GOLD));}
|
||||
public Inventory getInventory(){return inventory;}
|
||||
}
|
||||
|
|
@ -35,12 +35,10 @@ final class QuestMenus implements Listener {
|
|||
private Panel panel(Player p,String title){var screen=new Panel(p,title);var filler=new ItemStack(Material.GRAY_STAINED_GLASS_PANE);var meta=filler.getItemMeta();meta.displayName(Component.empty());filler.setItemMeta(meta);for(int i=0;i<54;i++)screen.inventory.setItem(i,filler);return screen;}
|
||||
private Panel journalPanel(Player player,String title){
|
||||
var screen=panel(player,title);
|
||||
screen.nativeStyle=DecisionsViewTransport.Style.JOURNAL;
|
||||
return screen;
|
||||
}
|
||||
private Panel equipmentPanel(Player player,String title){
|
||||
var screen=panel(player,title);
|
||||
screen.nativeStyle=DecisionsViewTransport.Style.WORKSHOP;
|
||||
return screen;
|
||||
}
|
||||
private void put(Panel panel,int slot,String title,String description,Material material,Runnable action){
|
||||
|
|
@ -310,22 +308,6 @@ final class QuestMenus implements Listener {
|
|||
show(p,screen);
|
||||
},true);
|
||||
}
|
||||
private boolean showDevelopmentView(Player player,Panel screen){
|
||||
boolean decisions=screen.title.startsWith("NPC dashboard decision · ");
|
||||
boolean quests=screen.title.startsWith("NPC dashboard · ")||screen.title.startsWith("NPC turn-in · ")||
|
||||
screen.title.startsWith("NPC next quest · ");
|
||||
boolean detail=screen.title.startsWith("NPC turn-in decision · ")||screen.title.startsWith("NPC next quest decision · ");
|
||||
if(!decisions&&!detail&&!quests&&screen.nativeStyle==null)return false;
|
||||
String setting=decisions||detail?"development.fullscreen-decisions-viewers":"development.fullscreen-quest-viewers";
|
||||
String dialogue=screen.description;
|
||||
for(int index=screen.descriptionNotes.size()-1;index>=0;index--){
|
||||
String note=screen.descriptionNotes.get(index);
|
||||
if(dialogue.endsWith(note))dialogue=dialogue.substring(0,dialogue.length()-note.length());
|
||||
}
|
||||
return NativeMenus.show(plugin,player,setting,screen.title,dialogue,screen.inventory,screen.actions,screen.gate,
|
||||
detail?DecisionsViewTransport.Style.DECISION_DETAIL:
|
||||
screen.nativeStyle==null?DecisionsViewTransport.Style.AUTO:screen.nativeStyle,null);
|
||||
}
|
||||
private void decisionWebsite(Player p){decisionWebsite(p,null);}
|
||||
private void decisionWebsite(Player p,String decision){p.closeInventory();String url="https://clans.dunerealms.com/#quests/quests?xp=pol&view=decisions";if(decision!=null&&decision.matches("[A-Z0-9-]{1,32}"))url+="&decision="+decision;p.sendMessage(Component.text("Review POL decisions on the website →",NamedTextColor.GOLD).clickEvent(ClickEvent.openUrl(url)));}
|
||||
private void roleDecisionDetails(Player p,JsonObject contact,PolQuestNpc.Role role,JsonObject row,String account,String parameter){var screen=panel(p,"NPC turn-in decision · "+role.name());screen.description=dialogue(row,"introduction","");roleAvatar(screen,contact,role);String kind=text(row,"kind","");String fee=text(row,"feeMinor","0");String amount;try{amount=new java.math.BigDecimal(fee).movePointLeft(2).toPlainString()+" DM";}catch(NumberFormatException invalid){amount="—";}put(screen,13,text(row,"title","Decision"),"Required Reputation: "+text(row,"level","—")+"\nBase cost: "+amount+"\nAward: "+text(row,"reputation","—")+" Reputation",Material.BOOK,null);
|
||||
|
|
@ -420,7 +402,6 @@ final class QuestMenus implements Listener {
|
|||
private void details(Player p,String kind,JsonObject data,String branch,int page,JsonObject row){
|
||||
var role=roleScope.get(p.getUniqueId());var screen=role!=null&&kind.equals("pol")?panel(p,"NPC turn-in · "+role.name()):journalPanel(p,"Quest dossier");
|
||||
if(kind.equals("personal")&&Set.of("S1-H-01","S1-H-02").contains(text(row,"id","")))
|
||||
screen.nativeStyle=DecisionsViewTransport.Style.WORKSHOP;
|
||||
if(role!=null&&kind.equals("pol")){screen.description=yes(row,"canClaim")?dialogue(row,"turnIn",""):dialogue(row,"context","");roleAvatar(screen,data,role);}String title=text(row,"title","Quest"),state=text(row,"state","Pending"),description=text(row,"objective","Complete the verified objective.")+"\nProgress: "+text(row,"progress","0")+" / "+text(row,"target","0")+"\nState: "+state+"\n"+(kind.equals("pol")?"Reputation: ":"XP: ")+text(row,"xp","Not configured");
|
||||
if(row.has("personalXP")&&!row.get("personalXP").isJsonNull())description+="\nBase Personal XP: "+row.get("personalXP").getAsInt();if(row.has("baseDMMinor")&&!row.get("baseDMMinor").isJsonNull())description+="\nBase funded reward: "+String.format(Locale.ROOT,"%.2f DM",row.get("baseDMMinor").getAsLong()/100.0);
|
||||
put(screen,13,title,description,website(row)?Material.WRITABLE_BOOK:Material.LIGHT_BLUE_DYE,null);
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff