diff --git a/.forgejo/workflows/plugins.yml b/.forgejo/workflows/plugins.yml index d7241b8f..847b0b10 100644 --- a/.forgejo/workflows/plugins.yml +++ b/.forgejo/workflows/plugins.yml @@ -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 diff --git a/DuneFullscreenPaper/README.md b/DuneFullscreenPaper/README.md deleted file mode 100644 index 2a3361f2..00000000 --- a/DuneFullscreenPaper/README.md +++ /dev/null @@ -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. diff --git a/DuneFullscreenPaper/build.gradle.kts b/DuneFullscreenPaper/build.gradle.kts deleted file mode 100644 index 0b1b29c9..00000000 --- a/DuneFullscreenPaper/build.gradle.kts +++ /dev/null @@ -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().configureEach { options.encoding = "UTF-8" } -tasks.jar { archiveFileName.set("DuneFullscreenPaper.jar") } diff --git a/DuneFullscreenPaper/settings.gradle.kts b/DuneFullscreenPaper/settings.gradle.kts deleted file mode 100644 index baca26c0..00000000 --- a/DuneFullscreenPaper/settings.gradle.kts +++ /dev/null @@ -1,7 +0,0 @@ -pluginManagement { - repositories { - gradlePluginPortal() - maven("https://repo.papermc.io/repository/maven-public/") - } -} -rootProject.name = "DuneFullscreenPaper" diff --git a/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/FullscreenProvider.java b/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/FullscreenProvider.java deleted file mode 100644 index f65c56ac..00000000 --- a/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/FullscreenProvider.java +++ /dev/null @@ -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(); - 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(); - } -} diff --git a/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/PaperDecisionsScene.java b/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/PaperDecisionsScene.java deleted file mode 100644 index 115c6b5e..00000000 --- a/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/PaperDecisionsScene.java +++ /dev/null @@ -1,1137 +0,0 @@ -package com.dunerealms.fullscreen; - -import com.dunerealms.services.DecisionsViewTransport; -import java.util.function.IntConsumer; - -import java.awt.Color; -import java.awt.Font; -import java.awt.BasicStroke; -import java.awt.image.BufferedImage; -import java.util.*; -import io.netty.buffer.Unpooled; -import io.netty.channel.*; -import net.minecraft.core.*; -import net.minecraft.core.component.DataComponents; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.protocol.game.*; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.decoration.*; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.saveddata.maps.*; -import net.minecraft.world.scores.DisplaySlot; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.craftbukkit.entity.CraftPlayer; -import org.bukkit.craftbukkit.scoreboard.CraftScoreboard; -import org.bukkit.entity.Player; -import org.bukkit.event.*; -import org.bukkit.event.player.*; -import org.bukkit.map.MapPalette; -import org.bukkit.plugin.java.JavaPlugin; - -final class PaperDecisionsScene implements DecisionsViewTransport, Listener, AutoCloseable { - private static final String INPUT = "dune_fullscreen_decisions"; - private static final int COLS = 11, ROWS = 9; - private static final int STANDARD_PAGE = 4, THREE_COLUMN_PAGE = 6; - private static final int LAST_ROW = 5, LAST_CARD_HEIGHT = 64; - private static final int JOURNAL_WIDTH = 384; - private static final int JOURNAL_TEXT_WIDTH = 304; - private static final Font JOURNAL_TITLE = new Font(Font.SERIF, Font.BOLD, 24); - private static final Font JOURNAL_TEXT = new Font(Font.SANS_SERIF, Font.PLAIN, 16); - private static final Font CARD_TITLE = new Font(Font.SANS_SERIF, Font.BOLD, 17); - private static final Font CARD_LORE = new Font(Font.SANS_SERIF, Font.PLAIN, 13); - private static final int FULL_CARD_LORE_LINES = 5; - private static final Font FULL_CARD_LORE = new Font(Font.SANS_SERIF, Font.PLAIN, 12); - private static final Font CHECKOUT_TERMS = new Font(Font.SANS_SERIF, Font.BOLD, 15); - private static final Font COMPACT_CARD_TITLE = new Font(Font.SANS_SERIF, Font.BOLD, 13); - private static final Font COMPACT_CARD_LORE = new Font(Font.SANS_SERIF, Font.PLAIN, 11); - private static final Font SIDEBAR_TERMS = new Font(Font.SANS_SERIF, Font.PLAIN, 11); - private static final int SIDEBAR_TERMS_WIDTH = 108, SIDEBAR_TERMS_LINES = 16; - private static final Font ARCHIVE_LORE = new Font(Font.SANS_SERIF, Font.PLAIN, 12); - private static final int ARCHIVE_COLUMN_LINES = 7; - private static final int ARCHIVE_COLUMN_WIDTH = 177; - private static final int PREVIOUS = -1, NEXT = -2, EMPTY = -3; - private static final int CHECKOUT_BACK = 45, CHECKOUT_PRIMARY = 49, CHECKOUT_CONTROLS = 2; - private final Map scenes = new HashMap<>(); - private final JavaPlugin plugin; - // This range is private to each connection and reused on reopen to bound the client map cache. - private static final int FIRST_SCENE_MAP = 2_000_000_000; - - PaperDecisionsScene(JavaPlugin plugin) { - this.plugin = plugin; - } - - private record Tile(MapId map, BufferedImage normal, BufferedImage focused) {} - private record Page(int index, Style style, List cards) {} - private record Roleplay(String heading, String contact, Card portrait, Card world, Card summary) {} - - private static final class Scene { - final Player viewer; - final Location original; - final boolean gravity; - final Document document; - final Roleplay roleplay; - final IntConsumer select; - final Runnable dismiss; - final List entities = new ArrayList<>(); - final Map> buttons = new HashMap<>(); - Integer focus; - volatile Page page; - int mountId; - boolean presentationMasked; - volatile boolean closed; - boolean positioning; - - Scene(Player viewer, Document document, Roleplay roleplay, IntConsumer select, Runnable dismiss) { - this.viewer = viewer; - this.document = document; - this.roleplay = roleplay; - this.select = select; - this.dismiss = dismiss; - original = viewer.getLocation(); - gravity = viewer.hasGravity(); - page = page(this.document, 0); - } - } - - @Override public void close() { - List.copyOf(scenes.values()).forEach(scene -> finish(scene, true, true)); - } - - @Override public boolean open(Player viewer, Document document, IntConsumer select, Runnable dismiss) { - if (!(viewer instanceof CraftPlayer player) || !viewer.isOnline() || viewer.isDead() || - viewer.isInsideVehicle() || scenes.containsKey(viewer.getUniqueId()) || - !canPresent(document)) return false; - var pipeline = player.getHandle().connection.connection.channel.pipeline(); - if (pipeline.get("packet_handler") == null || pipeline.get(INPUT) != null) return false; - - Roleplay roleplay = roleplay(document); - Document visibleDocument = presentable(document, roleplay); - if (roleplay != null && !fitsRoleplay(visibleDocument, roleplay)) return false; - if (visibleDocument.style() != Style.AUTO && !fitsStyled(visibleDocument)) return false; - Scene scene = new Scene(viewer, visibleDocument, roleplay, select, dismiss); - var origin = scene.original; - var viewpoint = new Location(origin.getWorld(), origin.getBlockX() + .5, origin.getBlockY() + 6, - origin.getBlockZ() + .5, 0, 0); - if (!viewpoint.getBlock().isPassable() || !viewpoint.clone().add(0, 1, 0).getBlock().isPassable()) return false; - scenes.put(viewer.getUniqueId(), scene); - try { - viewer.setGravity(false); - scene.positioning = true; - if (!viewer.teleport(viewpoint) || !viewer.getLocation().equals(viewpoint)) { - finish(scene, false, false); - return false; - } - scene.positioning = false; - show(scene); - Bukkit.getScheduler().runTaskLater(plugin, () -> finish(scene, true, true), 2400); - return true; - } catch (RuntimeException | LinkageError error) { - plugin.getLogger().warning("Fullscreen Decisions could not open: " + error.getClass().getSimpleName()); - finish(scene, true, false); - return false; - } - } - private void show(Scene scene) { - var handle = ((CraftPlayer) scene.viewer).getHandle(); - var level = handle.level(); - var origin = scene.original; - paint(scene, true); - for (int row = 0; row < ROWS; row++) { - for (int col = 0; col < COLS; col++) { - var pos = new BlockPos(origin.getBlockX() + 5 - col, origin.getBlockY() + 11 - row, origin.getBlockZ() + 2); - var frame = new GlowItemFrame(level, pos, Direction.NORTH); - frame.setInvisible(true); - var map = new MapId(FIRST_SCENE_MAP + row * COLS + col); - var item = new net.minecraft.world.item.ItemStack(Items.FILLED_MAP); - item.set(DataComponents.MAP_ID, map); - frame.setItem(item, false, false); - add(scene, frame, Direction.NORTH.get3DDataValue()); - } - } - - var mount = new ArmorStand(level, handle.getX(), handle.getY() - 1.4, handle.getZ()); - var camera = new ArmorStand(level, handle.getX(), handle.getY(), handle.getZ()); - for (var stand : List.of(mount, camera)) { - stand.setInvisible(true); - stand.setNoGravity(true); - add(scene, stand, 0); - } - scene.mountId = mount.getId(); - handle.connection.send(passengers(scene.mountId, handle.getId())); - handle.connection.send(new ClientboundSetCameraPacket(camera)); - scene.presentationMasked = true; - maskHands(handle, true); - sidebar(scene.viewer, true); - handle.connection.send(new ClientboundSetActionBarTextPacket(net.minecraft.network.chat.Component.empty())); - var channel = handle.connection.connection.channel; - var ids = scene.entities.stream().map(Entity::getId).collect(java.util.stream.Collectors.toUnmodifiableSet()); - channel.pipeline().addBefore("packet_handler", INPUT, new ChannelInboundHandlerAdapter() { - private Integer focus; - private Page previous; - @Override public void channelRead(ChannelHandlerContext context, Object input) throws Exception { - if (!scene.closed) { - Page page = scene.page; - if (page != previous) { - previous = page; - focus = null; - } - if (input instanceof ServerboundMovePlayerPacket move && move.hasRotation()) { - Integer target = target(page, move.getYRot(0), move.getXRot(0)); - if (!Objects.equals(target, focus)) { - focus = target; - Bukkit.getScheduler().runTask(plugin, () -> { if (scene.page == page) focus(scene, target); }); - } - } - if (input instanceof ServerboundInteractPacket use && ids.contains(use.entityId())) { - Integer target = focus; - if (use.hand() == net.minecraft.world.InteractionHand.MAIN_HAND) - Bukkit.getScheduler().runTask(plugin, () -> { if (scene.page == page) select(scene, target); }); - return; - } - } - super.channelRead(context, input); - } - }); - } - - private static void sidebar(Player viewer, boolean masked) { - var scoreboard = ((CraftScoreboard) viewer.getScoreboard()).getHandle(); - var connection = ((CraftPlayer) viewer).getHandle().connection; - for (DisplaySlot slot : DisplaySlot.values()) { - if (slot != DisplaySlot.SIDEBAR && !slot.name().startsWith("TEAM_")) continue; - var objective = scoreboard.getDisplayObjective(slot); - if (objective != null) connection.send(new ClientboundSetDisplayObjectivePacket(slot, masked ? null : objective)); - } - } - - private static boolean canPresent(Document document) { - var cards = document.cards(); - return !cards.isEmpty() && cards.size() <= 54 && - cards.stream().allMatch(card -> card.slot() >= 0) && - cards.stream().map(Card::slot).distinct().count() == cards.size(); - } - - private static Page page(Document document, int index) { - if (document.style() == Style.EXCHANGE_CHECKOUT) return checkoutPage(document, index); - if (usesReadingPane(document.style())) return archivePage(document, index); - if (document.style() == Style.JOURNAL) return journalPage(document, index); - var cards = document.cards(); - int capacity = capacity(document.style()); - if (cards.size() <= capacity) return new Page(0, document.style(), cards); - int start = index * capacity; - int end = Math.min(start + capacity, cards.size()); - var visible = new ArrayList<>(cards.subList(start, end)); - while (visible.size() < capacity) visible.add(new Card(EMPTY, "", List.of(), false)); - String pageNumber = "Page " + (index + 1) + " / " + ((cards.size() + capacity - 1) / capacity); - visible.add(new Card(PREVIOUS, "Previous", List.of(pageNumber), index > 0)); - visible.add(new Card(NEXT, "Next", List.of(pageNumber), end < cards.size())); - return new Page(index, document.style(), List.copyOf(visible)); - } - - private static Page journalPage(Document document, int index) { - var back = document.cards().stream() - .filter(card -> card.actionable() && card.title().equals("Back")).findFirst().orElse(null); - var entries = document.cards().stream().filter(card -> card != back).toList(); - int start = index * 2; - int end = Math.min(start + 2, entries.size()); - int count = Math.max(1, (entries.size() + 1) / 2); - var blank = new Card(EMPTY, "", List.of(), false); - var visible = new ArrayList<>(entries.subList(start, end)); - while (visible.size() < 2) visible.add(blank); - var label = List.of("Page " + (index + 1) + " / " + count); - visible.add(new Card(PREVIOUS, "Previous", label, index > 0)); - visible.add(back == null ? blank : back); - visible.add(new Card(NEXT, "Next", label, end < entries.size())); - return new Page(index, document.style(), List.copyOf(visible)); - } - - private static Page archivePage(Document document, int index) { - var entries = document.cards().stream().filter(card -> isReadingEntry(document.style(), card)).toList(); - var actions = document.cards().stream().filter(card -> !isReadingEntry(document.style(), card)).toList(); - var entry = entries.get(index); - var visible = new ArrayList(); - var blank = new Card(EMPTY, "", List.of(), false); - visible.add(entry); // The reading pane is drawn separately from the interactive tiles. - visible.add(blank); - if (document.style() == Style.WORKSHOP) - visible.add(entry.actionable() ? new Card(entry.slot(), entry.title(), List.of(), true, entry.material()) : blank); - visible.addAll(actions); - while (visible.size() < STANDARD_PAGE) visible.add(blank); - if (entries.size() > 1) { - String number = "Page " + (index + 1) + " / " + entries.size(); - visible.add(new Card(PREVIOUS, "Previous", List.of(number), index > 0)); - visible.add(new Card(NEXT, "Next", List.of(number), index + 1 < entries.size())); - } - return new Page(index, document.style(), List.copyOf(visible)); - } - - private static Page checkoutPage(Document document, int index) { - var controls = document.cards().stream() - .filter(card -> card.slot() != CHECKOUT_BACK && card.slot() != CHECKOUT_PRIMARY) - .sorted(Comparator.comparingInt(card -> exchangeControlOrder(document.title(), card.slot()))).toList(); - int start = index * CHECKOUT_CONTROLS; - int end = Math.min(start + CHECKOUT_CONTROLS, controls.size()); - var visible = new ArrayList<>(controls.subList(start, end)); - while (visible.size() < CHECKOUT_CONTROLS) visible.add(new Card(EMPTY, "", List.of(), false)); - for (int slot : new int[]{CHECKOUT_BACK,CHECKOUT_PRIMARY}) { - visible.add(document.cards().stream().filter(card -> card.slot() == slot).findFirst().orElseThrow()); - } - if (controls.size() > CHECKOUT_CONTROLS) { - String number = "Page " + (index + 1) + " / " + ((controls.size() + CHECKOUT_CONTROLS - 1) / CHECKOUT_CONTROLS); - visible.add(new Card(PREVIOUS, "Previous", List.of(number), index > 0)); - visible.add(new Card(NEXT, "Next", List.of(number), end < controls.size())); - } - return new Page(index, document.style(), List.copyOf(visible)); - } - - private static int exchangeControlOrder(String title, int slot) { - return switch (title) { - case "Exchange · Add item" -> switch (slot) { - case 13 -> 0; - case 40 -> 1; - case 30 -> 2; - case 32 -> 3; - default -> 4; - }; - case "Exchange · Price" -> switch (slot) { - case 13 -> 0; - case 53 -> 1; - case 27 -> 2; - case 32 -> 3; - default -> 4; - }; - default -> switch (slot) { - case 30 -> 0; - case 32 -> 1; - case 31 -> 2; - default -> 3; - }; - }; - } - - private void paint(Scene scene, boolean initial) { - BufferedImage art = artwork(scene); - scene.buttons.clear(); - scene.focus = null; - for (int row = 0; row < ROWS; row++) { - for (int col = 0; col < COLS; col++) { - if (!initial && (row < 3 || row > 5 || col < 4 || col > 6 || (col == 5 && capacity(scene.page.style) == STANDARD_PAGE && !usesReadingPane(scene.page.style) && scene.page.style != Style.JOURNAL))) continue; - var map = new MapId(FIRST_SCENE_MAP + row * COLS + col); - var image = art.getSubimage(col * 128, row * 128, 128, 128); - var card = cardAt(scene.page, row, col); - boolean journalRow = scene.page.style == Style.JOURNAL && row < LAST_ROW; - var tile = new Tile(map, image, card == null || !card.actionable() ? image : - journalRow ? focusedJournalRow(image, col) : focused(image, row == LAST_ROW ? LAST_CARD_HEIGHT : 122)); - if (card != null && card.actionable()) - scene.buttons.computeIfAbsent(card.slot(), ignored -> new ArrayList<>()).add(tile); - pixels(scene, tile, false); - } - } - } - - private static void maskHands(net.minecraft.server.level.ServerPlayer player, boolean masked) { - var data = player.getEntityData().packAll(); - if (data != null) { - for (var value : data) { - if (value.id() != 0 || !(value.value() instanceof Byte flags)) continue; - var display = new net.minecraft.network.syncher.SynchedEntityData.DataValue<>( - value.id(), net.minecraft.network.syncher.EntityDataSerializers.BYTE, - masked ? (byte) (flags | 0x20) : flags); - player.connection.send(new ClientboundSetEntityDataPacket(player.getId(), List.of(display))); - break; - } - } - int offhand = net.minecraft.world.entity.player.Inventory.SLOT_OFFHAND; - for (int slot = 0; slot < 9; slot++) sendHandSlot(player, slot, masked); - sendHandSlot(player, offhand, masked); - } - - private static void sendHandSlot(net.minecraft.server.level.ServerPlayer player, int slot, boolean masked) { - var item = masked ? net.minecraft.world.item.ItemStack.EMPTY : player.getInventory().getItem(slot).copy(); - player.connection.send(new ClientboundSetPlayerInventoryPacket(slot, item)); - } - - private void add(Scene scene, Entity entity, int extra) { - var connection = ((CraftPlayer) scene.viewer).getHandle().connection; - scene.entities.add(entity); - if (entity instanceof ItemFrame) { - connection.send(new ClientboundAddEntityPacket(entity, extra, entity.blockPosition())); - } else { - connection.send(new ClientboundAddEntityPacket(entity.getId(), entity.getUUID(), entity.getX(), entity.getY(), - entity.getZ(), entity.getXRot(), entity.getYRot(), entity.getType(), extra, - net.minecraft.world.phys.Vec3.ZERO, entity.getYHeadRot())); - } - var data = entity.getEntityData().getNonDefaultValues(); - if (data != null) connection.send(new ClientboundSetEntityDataPacket(entity.getId(), data)); - } - - private ClientboundSetPassengersPacket passengers(int mount, int... riders) { - var buffer = new FriendlyByteBuf(Unpooled.buffer()); - try { - buffer.writeVarInt(mount); - buffer.writeVarIntArray(riders); - return ClientboundSetPassengersPacket.STREAM_CODEC.decode(buffer); - } finally { - buffer.release(); - } - } - - private void pixels(Scene scene, Tile tile, boolean focused) { - byte[] image = MapPalette.imageToBytes(focused ? tile.focused : tile.normal); - var patch = new MapItemSavedData.MapPatch(0, 0, 128, 128, image); - ((CraftPlayer) scene.viewer).getHandle().connection.send( - new ClientboundMapItemDataPacket(tile.map, (byte) 0, true, List.of(), patch)); - } - - private static int capacity(Style style) { - return style == Style.EXCHANGE || style == Style.HOUSE ? THREE_COLUMN_PAGE : STANDARD_PAGE; - } - - private static Card cardAt(Page page, int row, int col) { - if (row < 3 || row > LAST_ROW || col < 4 || col > 6) return null; - if (page.style == Style.JOURNAL) return page.cards.get(row == LAST_ROW ? col - 2 : row - 3); - if (usesReadingPane(page.style) && row == 3) return null; - if (col == 5 && (capacity(page.style) == STANDARD_PAGE || row == LAST_ROW)) return null; - int cap = capacity(page.style); - int index = row == LAST_ROW ? cap + (col == 4 ? 0 : 1) : - (row - 3) * (cap / 2) + (cap == THREE_COLUMN_PAGE ? col - 4 : (col - 4) / 2); - return index < page.cards.size() ? page.cards.get(index) : null; - } - - private static Integer target(Page page, float yaw, float pitch) { - if (!Float.isFinite(yaw) || !Float.isFinite(pitch) || Math.abs(yaw) > 45 || Math.abs(pitch) > 40) return null; - double x = -Math.tan(Math.toRadians(yaw)) * 2.46; - double y = Math.tan(Math.toRadians(pitch)) * 2.46; - if (Math.abs(x) > 1.5 || y > 1.02) return null; - Card card = cardAt(page, 4 + (int) Math.round(y), 5 - (int) Math.round(x)); - return card != null && card.actionable() ? card.slot() : null; - } - - private void focus(Scene scene, Integer slot) { - if (scene.closed || Objects.equals(scene.focus, slot)) return; - scene.focus = slot; - scene.buttons.forEach((action, tiles) -> tiles.forEach(tile -> pixels(scene, tile, action.equals(slot)))); - } - - private void select(Scene scene, Integer slot) { - if (scene.closed || slot == null || !scene.buttons.containsKey(slot)) return; - if (slot == PREVIOUS || slot == NEXT) { - scene.page = page(scene.document, scene.page.index + (slot == NEXT ? 1 : -1)); - paint(scene, false); - return; - } - finish(scene, true, true, () -> scene.select.accept(slot)); - } - - @EventHandler public void swap(PlayerSwapHandItemsEvent event) { - var scene = scenes.get(event.getPlayer().getUniqueId()); - if (scene == null) return; - event.setCancelled(true); - finish(scene, true, true); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void teleport(PlayerTeleportEvent event) { - interrupt(event.getPlayer()); - } - - @EventHandler public void changedWorld(PlayerChangedWorldEvent event) { - interrupt(event.getPlayer()); - } - - @EventHandler public void death(org.bukkit.event.entity.PlayerDeathEvent event) { - interrupt(event.getEntity()); - } - - @EventHandler public void quit(PlayerQuitEvent event) { - var scene = scenes.get(event.getPlayer().getUniqueId()); - if (scene != null) finish(scene, true, true); - } - - private void interrupt(Player viewer) { - var scene = scenes.get(viewer.getUniqueId()); - if (scene != null && !scene.positioning) finish(scene, false, true); - } - - private void finish(Scene scene, boolean restoreLocation, boolean dismiss) { - finish(scene, restoreLocation, dismiss, null); - } - - private void finish(Scene scene, boolean restoreLocation, boolean dismiss, Runnable selection) { - if (scene.closed) return; - scene.closed = true; - Player viewer = scene.viewer; - scenes.remove(viewer.getUniqueId(), scene); - var handle = ((CraftPlayer) viewer).getHandle(); - var connection = handle.connection; - boolean removePresentation = viewer.isOnline() && !scene.entities.isEmpty(); - Runnable terminal = dismiss ? scene.dismiss : () -> {}; - SceneTeardown.run( - () -> !restoreLocation || (viewer.isOnline() && - Objects.equals(viewer.getWorld(), scene.original.getWorld()) && - SceneTeardown.restore(positionOf(scene.original), () -> viewer.teleport(scene.original), - () -> positionOf(viewer.getLocation()))), - selection, - terminal, - () -> { - if (viewer.isOnline()) viewer.sendMessage(selection == null - ? "The fullscreen view closed, but your original position could not be restored." - : "The fullscreen view could not close normally. Your action was not run."); - }, - error -> plugin.getLogger().warning("Fullscreen teardown failed: " + error), - () -> { - var pipeline = connection.connection.channel.pipeline(); - if (pipeline.get(INPUT) != null) pipeline.remove(INPUT); - }, - () -> { if (removePresentation && scene.presentationMasked) maskHands(handle, false); }, - () -> { if (removePresentation && scene.presentationMasked) sidebar(viewer, false); }, - () -> { if (removePresentation) connection.send(new ClientboundSetCameraPacket(handle)); }, - () -> { if (removePresentation && scene.mountId != 0) connection.send(passengers(scene.mountId)); }, - () -> { - if (removePresentation) - connection.send(new ClientboundRemoveEntitiesPacket(scene.entities.stream().mapToInt(Entity::getId).toArray())); - }, - () -> viewer.setGravity(scene.gravity)); - } - - private static SceneTeardown.Position positionOf(Location location) { - return new SceneTeardown.Position(location.getWorld().getUID(), location.getX(), location.getY(), location.getZ()); - } - - private BufferedImage artwork(Scene scene) { - var image = new BufferedImage(COLS * 128, ROWS * 128, BufferedImage.TYPE_INT_RGB); - var draw = image.createGraphics(); - try { - Palette palette = palette(scene); - draw.setColor(palette.background); - draw.fillRect(0, 0, image.getWidth(), image.getHeight()); - draw.setColor(palette.accent); - if (scene.document.style() == Style.JOURNAL) { - drawJournal(draw, scene.document, scene.page, palette); - return image; - } - draw.setStroke(new BasicStroke(7)); - draw.drawRect(445, 335, 518, 374); - - String heading = scene.roleplay != null ? scene.roleplay.heading : - scene.document.style() == Style.AUTO ? scene.document.title() : styledTitle(scene.document); - setHeadingFont(draw, scene.document.style(), heading); - int headlineWidth = draw.getFontMetrics().stringWidth(heading); - draw.drawString(heading, (image.getWidth() - headlineWidth) / 2, 372); - if (scene.roleplay != null) drawRoleplay(draw, scene); - else if (usesReadingPane(scene.document.style())) drawArchive(draw, scene, palette); - else if (scene.document.style() != Style.AUTO) drawStyledIdentity(draw, scene, palette); - for (int row = 3; row <= LAST_ROW; row++) for (int col = 4; col <= 6; col++) { - Card card = cardAt(scene.page, row, col); - if (card == null || card.slot() == EMPTY) continue; - int x = col * 128; - int y = row * 128; - draw.setColor(card.actionable() ? palette.tile : new Color(55, 63, 66)); - boolean bottom = row == LAST_ROW; - draw.fillRect(x, y + 3, 128, bottom ? LAST_CARD_HEIGHT : 122); - if (card.slot() >= 0 && drawStyledCard(draw, scene.document, card, palette, x, y)) continue; - draw.setColor(Color.WHITE); - draw.setFont(CARD_TITLE); - writeWrapped(draw, card.title(), x + 7, y + 24, 114, bottom ? 2 : 3); - String lore = displayLore(scene.roleplay, card); - if (!lore.isBlank()) { - draw.setFont(CARD_LORE); - writeWrapped(draw, lore, x + 7, y + (card.slot() < 0 ? 45 : bottom ? 64 : 78), 114, bottom ? 2 : 3); - } - } - } finally { - draw.dispose(); - } - return image; - } - - private static boolean fitsJournal(java.awt.Graphics2D draw, Document document) { - draw.setFont(JOURNAL_TITLE); - if (!wrap(draw, document.title(), 323, 1).complete()) return false; - for (Card card : document.cards()) { - var title = journalRowTitle(draw, card); - if (!title.complete()) return false; - draw.setFont(JOURNAL_TEXT); - if (!wrapLore(draw, card.lore(), JOURNAL_TEXT_WIDTH, 5 - title.lines().size()).complete()) return false; - } - return true; - } - - private static Wrapped journalRowTitle(java.awt.Graphics2D draw, Card card) { - draw.setFont(JOURNAL_TITLE); - var title = wrap(draw, card.title(), JOURNAL_TEXT_WIDTH, 2); - if (title.complete()) return title; - draw.setFont(JOURNAL_TITLE.deriveFont(19f)); - return wrap(draw, card.title(), JOURNAL_TEXT_WIDTH, 2); - } - - private void drawJournal(java.awt.Graphics2D draw, Document document, Page page, Palette palette) { - var ink = new Color(34, 43, 39); - var binding = new Color(25, 58, 51); - var brass = new Color(199, 152, 72); - draw.setColor(new Color(12, 28, 27)); - draw.fillRoundRect(478, 330, 452, 386, 16, 16); - draw.setColor(brass); - draw.drawRoundRect(485, 337, 438, 372, 12, 12); - draw.setColor(binding); - draw.fillRoundRect(490, 342, 428, 362, 10, 10); - draw.setColor(brass); - draw.fillRect(510, 379, JOURNAL_WIDTH + 4, 2); - drawResource(draw, "/mcgui/dunerealms-season-logo-v2.png", 506, 349, 62, 24); - draw.setColor(palette.accent); - draw.setFont(JOURNAL_TITLE); - draw.drawString(document.title(), 578, 370); - - for (int row = 3; row < LAST_ROW; row++) { - Card card = cardAt(page, row, 5); - if (card == null || card.slot() == EMPTY) continue; - int y = row * 128; - draw.setColor(new Color(15, 36, 32)); - draw.fillRoundRect(514, y + 8, JOURNAL_WIDTH - 2, 116, 12, 12); - draw.setColor(card.actionable() ? palette.tile : new Color(188, 177, 149)); - draw.fillRoundRect(512, y + 4, JOURNAL_WIDTH, 116, 12, 12); - draw.setColor(brass); - draw.drawRoundRect(515, y + 7, JOURNAL_WIDTH - 7, 109, 9, 9); - draw.drawLine(530, y + 14, 530, y + 110); - draw.setColor(ink); - var title = journalRowTitle(draw, card).lines(); - int titleHeight = draw.getFontMetrics().getHeight(); - int textY = y + 31; - for (String line : title) { - draw.drawString(line, 543, textY); - textY += titleHeight; - } - if (card.actionable()) { - draw.setColor(binding); - draw.fillOval(856, y + 45, 28, 28); - draw.setColor(palette.accent); - draw.setStroke(new BasicStroke(2)); - draw.drawLine(864, y + 59, 876, y + 59); - draw.drawLine(871, y + 54, 876, y + 59); - draw.drawLine(871, y + 64, 876, y + 59); - draw.setStroke(new BasicStroke(1)); - } - draw.setColor(ink); - draw.setFont(JOURNAL_TEXT); - int baseline = textY - 8; - for (String line : wrapLore(draw, card.lore(), JOURNAL_TEXT_WIDTH, 5 - title.size()).lines()) { - draw.drawString(line, 543, baseline); - baseline += draw.getFontMetrics().getHeight(); - } - } - - for (int col = 4; col <= 6; col++) { - Card navigation = cardAt(page, LAST_ROW, col); - if (!navigation.actionable()) continue; - int x = col * 128; - draw.setColor(new Color(37, 78, 64)); - draw.fillRoundRect(x + 4, 648, 120, 48, 8, 8); - draw.setColor(brass); - draw.drawRoundRect(x + 4, 648, 119, 47, 8, 8); - draw.setColor(palette.accent); - draw.setFont(CARD_TITLE); - String label = navigation.title(); - draw.drawString(label, x + (128 - draw.getFontMetrics().stringWidth(label)) / 2, col == 5 ? 669 : 678); - } - String label = cardAt(page, LAST_ROW, 4).lore().getFirst(); - draw.setColor(palette.accent); - draw.setFont(JOURNAL_TEXT.deriveFont(13f)); - draw.drawString(label, 704 - draw.getFontMetrics().stringWidth(label) / 2, - cardAt(page, LAST_ROW, 5).actionable() ? 687 : 678); - } - - private static BufferedImage focusedJournalRow(BufferedImage normal, int column) { - var image = new BufferedImage(128, 128, BufferedImage.TYPE_INT_RGB); - var draw = image.createGraphics(); - try { - draw.drawImage(normal, 0, 0, null); - draw.setColor(new Color(249, 218, 155)); - draw.fillRect(0, 4, 128, 3); - draw.fillRect(0, 121, 128, 3); - if (column == 4) draw.fillRect(0, 4, 3, 120); - if (column == 6) draw.fillRect(125, 4, 3, 120); - } finally { - draw.dispose(); - } - return image; - } - - private record Palette(Color background, Color tile, Color accent) {} - - private static Palette palette(Scene scene) { - return switch (scene.document.style()) { - case WAR_MUSTER -> new Palette(new Color(38, 24, 28), new Color(78, 44, 53), new Color(245, 204, 177)); - case WORKSHOP -> new Palette(new Color(29, 37, 42), new Color(54, 73, 84), new Color(235, 219, 177)); - case DECISION_DETAIL -> new Palette(new Color(21, 33, 41), new Color(47, 69, 81), new Color(236, 203, 129)); - case ORGANISATION -> new Palette(new Color(16, 31, 37), new Color(29, 75, 79), new Color(142, 228, 211)); - case EXCHANGE, EXCHANGE_CHECKOUT -> new Palette(new Color(42, 28, 18), new Color(91, 62, 36), new Color(245, 208, 139)); - case CODEX, ITEM_ARCHIVE -> new Palette(new Color(40, 33, 24), new Color(90, 63, 37), new Color(246, 221, 158)); - case GUILD -> new Palette(new Color(14, 28, 47), new Color(28, 58, 83), new Color(188, 224, 249)); - case SPICE -> new Palette(new Color(54, 25, 16), new Color(105, 54, 33), new Color(255, 214, 133)); - case JOURNAL -> new Palette(new Color(18, 33, 30), new Color(239, 221, 177), new Color(255, 226, 159)); - case HOUSE -> new Palette(new Color(34, 26, 39), new Color(72, 52, 79), new Color(244, 211, 152)); - case AUTO -> scene.roleplay == null - ? new Palette(new Color(25, 40, 46), new Color(52, 93, 107), new Color(237, 199, 105)) - : new Palette(new Color(9, 33, 24), new Color(38, 80, 61), new Color(237, 199, 105)); - }; - } - - private static boolean fitsStyled(Document document) { - var graphics = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).createGraphics(); - try { - if (document.style() == Style.JOURNAL) return fitsJournal(graphics, document); - setHeadingFont(graphics, document.style(), styledTitle(document)); - if (!wrap(graphics, styledTitle(document), 500, 1).complete) return false; - if (document.style() == Style.EXCHANGE_CHECKOUT) { - if (document.description().isBlank() || !hasCheckoutAction(document, CHECKOUT_BACK) || - !hasCheckoutAction(document, CHECKOUT_PRIMARY)) return false; - graphics.setFont(CHECKOUT_TERMS); - var terms = checkoutTerms(graphics, document.description()); - if (terms.isEmpty() || terms.size() > 9) return false; - } - if (document.style() == Style.GUILD || document.style() == Style.WAR_MUSTER) { - graphics.setFont(SIDEBAR_TERMS); - var terms = sidebarTerms(graphics, document); - if (terms.lines().isEmpty() || !terms.complete()) return false; - } - if (usesReadingPane(document.style())) { - long navigationCount = document.cards().stream().filter(card -> !isReadingEntry(document.style(), card)).count(); - int maximumNavigation = document.style() == Style.WORKSHOP ? 1 : 2; - if (navigationCount > maximumNavigation || navigationCount == document.cards().size()) return false; - if (document.style() == Style.ITEM_ARCHIVE && navigationCount == 0) return false; - } - graphics.setFont(CARD_TITLE); - if (document.identity() != null && !wrap(graphics, document.identity().mentat(), 112, 2).complete) return false; - for (Card card : document.cards()) { - boolean seal = document.style() == Style.HOUSE && nativeArt(card.material()) != null; - graphics.setFont(CARD_TITLE); - if (usesReadingPane(document.style()) && isReadingEntry(document.style(), card)) { - if (!wrap(graphics, card.title(), 368, 1).complete) return false; - graphics.setFont(ARCHIVE_LORE); - if (!archiveLore(graphics, card).complete) return false; - if (document.style() == Style.WORKSHOP && card.actionable() && - !fitsFullCardTitle(graphics, document.style(), card)) return false; - continue; - } - if (usesFullCardLore(document.style()) || saleControls(document, card)) { - if (!fitsFullCardTitle(graphics, document.style(), card)) return false; - graphics.setFont(compactCardLore(document.style()) ? COMPACT_CARD_LORE : FULL_CARD_LORE); - if (!fullCardLore(graphics, document.style(), card).complete) return false; - continue; - } - if (!wrap(graphics, card.title(), 114, seal ? 2 : 3).complete) return false; - graphics.setFont(CARD_LORE); - if (!wrap(graphics, styledLore(document.style(), card), 114, seal ? 2 : 3).complete) return false; - } - return true; - } finally { - graphics.dispose(); - } - } - - private static void setHeadingFont(java.awt.Graphics2D draw, Style style, String title) { - int size = switch (style) { - case ITEM_ARCHIVE, GUILD, ORGANISATION, WORKSHOP, DECISION_DETAIL, WAR_MUSTER -> 28; - default -> 38; - }; - draw.setFont(new Font(Font.SANS_SERIF, Font.BOLD, size)); - if (style != Style.ORGANISATION) return; - while (size > 20 && draw.getFontMetrics().stringWidth(title) > 500) { - size--; - draw.setFont(draw.getFont().deriveFont((float) size)); - } - } - - private static boolean usesFullCardLore(Style style) { - return switch (style) { - case CODEX, ITEM_ARCHIVE, GUILD, SPICE, ORGANISATION, WORKSHOP, DECISION_DETAIL, WAR_MUSTER -> true; - default -> false; - }; - } - - private static boolean fitsFullCardTitle(java.awt.Graphics2D draw, Style style, Card card) { - boolean compact = compactCardTitle(style); - draw.setFont(compact ? COMPACT_CARD_TITLE : CARD_TITLE); - return wrap(draw, card.title(), 114, compact ? 3 : 2).complete(); - } - - private static boolean compactCardTitle(Style style) { - return style == Style.CODEX || style == Style.GUILD || style == Style.EXCHANGE_CHECKOUT || compactCardLore(style); - } - - private static boolean compactCardLore(Style style) { - return style == Style.SPICE || style == Style.ORGANISATION || style == Style.WORKSHOP || style == Style.DECISION_DETAIL || style == Style.WAR_MUSTER; - } - - private static boolean usesReadingPane(Style style) { - return style == Style.ITEM_ARCHIVE || style == Style.WORKSHOP; - } - - private static boolean isReadingEntry(Style style, Card card) { - if (style == Style.ITEM_ARCHIVE) return !card.actionable(); - return !card.actionable() || (!card.title().equals("Back") && !card.title().equals("Close")); - } - - private static Wrapped sidebarTerms(java.awt.Graphics2D draw, Document document) { - return wrapLore(draw, document.description().lines().toList(), SIDEBAR_TERMS_WIDTH, SIDEBAR_TERMS_LINES); - } - - private static Wrapped archiveLore(java.awt.Graphics2D draw, Card card) { - var entries = card.lore().stream().filter(line -> !line.matches("─+")).toList(); - return wrapLore(draw, entries, ARCHIVE_COLUMN_WIDTH, 2 * ARCHIVE_COLUMN_LINES); - } - - private void drawArchive(java.awt.Graphics2D draw, Scene scene, Palette palette) { - var card = scene.page.cards.getFirst(); - draw.setColor(palette.tile); - draw.fillRect(512, 386, 384, 123); - draw.setColor(Color.WHITE); - draw.setFont(CARD_TITLE); - draw.drawString(card.title(), 520, 404); - draw.setColor(palette.accent); - draw.drawLine(520, 407, 888, 407); - draw.setFont(ARCHIVE_LORE); - var lines = archiveLore(draw, card).lines(); - for (int i = 0; i < lines.size(); i++) { - int x = 520 + i / ARCHIVE_COLUMN_LINES * 184; - int y = 416 + i % ARCHIVE_COLUMN_LINES * draw.getFontMetrics().getHeight(); - draw.drawString(lines.get(i), x, y); - } - } - - private static String styledTitle(Document document) { - return switch (document.title()) { - case "Exchange · Purchase details" -> "Exchange checkout"; - case "Exchange · Add item" -> "Create listing"; - case "Exchange · Price" -> "Listing price"; - case "Exchange · Withdraw listing" -> "Withdraw listing"; - default -> document.title(); - }; - } - - private static boolean saleControls(Document document, Card card) { - return document.style() == Style.EXCHANGE_CHECKOUT && card.actionable() && - !document.title().equals("Exchange · Purchase details"); - } - - private static boolean hasCheckoutAction(Document document, int slot) { - return document.cards().stream().anyMatch(card -> card.slot() == slot && card.actionable()); - } - - private static List checkoutTerms(java.awt.Graphics2D graphics, String description) { - var lines = new ArrayList(); - for (String term : description.lines().toList()) { - var wrapped = wrap(graphics, term, 106, 9); - if (!wrapped.complete) return List.of(); - lines.addAll(wrapped.lines); - } - return lines; - } - - private static Wrapped fullCardLore(java.awt.Graphics2D draw, Style style, Card card) { - return wrapLore(draw, card.lore(), 114, compactCardLore(style) ? 6 : FULL_CARD_LORE_LINES); - } - - private static Wrapped wrapLore(java.awt.Graphics2D draw, List entries, int width, int limit) { - var lines = new ArrayList(); - for (String entry : entries) { - var wrapped = wrap(draw, entry, width, limit - lines.size()); - lines.addAll(wrapped.lines()); - if (!wrapped.complete()) return new Wrapped(lines, false); - } - return new Wrapped(lines, true); - } - - private static String styledLore(Style style, Card card) { - if (card.lore().isEmpty()) return ""; - if (style == Style.HOUSE && card.material().startsWith("house_")) - return card.lore().getFirst().equals("Your current House") ? card.lore().getFirst() : ""; - if (style == Style.EXCHANGE_CHECKOUT && !card.actionable()) return String.join(" ", card.lore()); - if (style == Style.EXCHANGE || style == Style.EXCHANGE_CHECKOUT) { - // The listing renderer appends the server price after the stored item lore. - for (int index = card.lore().size() - 1; index >= 0; index--) { - String line = card.lore().get(index); - if (line.endsWith(" DM each") || line.endsWith(" DM")) return line; - } - } - return card.lore().getFirst(); - } - - private void drawStyledIdentity(java.awt.Graphics2D draw, Scene scene, Palette palette) { - var document = scene.document; - var identity = document.identity(); - if (document.style() == Style.EXCHANGE) { - drawResource(draw, "/mcgui/native/exchange.png", 454, 343, 40, 31); - draw.setColor(palette.accent); - for (int row = 3; row <= 4; row++) draw.fillRect(510, row * 128 + 124, 388, 4); - return; - } - if (document.style() == Style.HOUSE) { - drawResource(draw, "/mcgui/dunerealms-season-logo-v2.png", 454, 343, 65, 31); - return; - } - draw.setColor(palette.background.darker()); - draw.fillRect(644, 389, 120, 232); - switch (document.style()) { - case GUILD, WAR_MUSTER -> { - draw.setColor(palette.accent); - draw.setFont(SIDEBAR_TERMS); - int y = 406; - for (String line : sidebarTerms(draw, document).lines()) { - draw.drawString(line, 649, y); - y += draw.getFontMetrics().getHeight(); - } - } - case SPICE -> drawSceneArt(draw, "npc_world_arrakis", 650, 422, 108, 162); - case CODEX -> { - drawResource(draw, "/mcgui/dunerealms-season-logo-v2.png", 650, 449, 108, 96); - draw.setColor(palette.accent); - draw.drawLine(650, 446, 758, 446); - draw.drawLine(650, 549, 758, 549); - } - case EXCHANGE_CHECKOUT -> { - draw.setColor(Color.WHITE); - draw.setFont(CHECKOUT_TERMS); - int y = 420; - for (String line : checkoutTerms(draw, document.description())) { - draw.drawString(line, 651, y); - y += draw.getFontMetrics().getHeight(); - } - } - case ORGANISATION -> { - if (identity == null || (identity.logo().isBlank() && identity.mentat().isBlank() && identity.portrait() < 0)) { - drawResource(draw, "/mcgui/dunerealms-season-logo-v2.png", 650, 449, 108, 96); - } else { - BufferedImage mark = organisationLogo(identity.logo()); - if (mark != null) drawImage(draw, mark, 660, 397, 88, 74); - if (identity.portrait() >= 0 && identity.portrait() <= 7) - drawSceneArt(draw, "npc_avatar_" + identity.portrait(), 662, 477, 84, 72); - draw.setColor(palette.accent); - draw.setFont(CARD_LORE); - writeWrapped(draw, identity.mentat().isBlank() ? "" : "Mentat", 649, 567, 110, 1); - draw.setFont(CARD_TITLE); - writeWrapped(draw, identity.mentat(), 649, 589, 110, 2); - } - } - - default -> {} - } - } - - private boolean drawStyledCard(java.awt.Graphics2D draw, Document document, Card card, Palette palette, int x, int y) { - Style style = document.style(); - if (style == Style.AUTO) return false; - String art = nativeArt(card.material()); - draw.setColor(palette.accent); - if (usesFullCardLore(style) || saleControls(document, card)) { - if (style == Style.ORGANISATION) draw.fillRect(x, y + 3, 4, 122); - draw.drawLine(x + 7, y + 48, x + 121, y + 48); - draw.setColor(Color.WHITE); - boolean compact = compactCardTitle(style); - draw.setFont(compact ? COMPACT_CARD_TITLE : CARD_TITLE); - writeWrapped(draw, card.title(), x + 7, y + (compact ? 15 : 21), 114, compact ? 3 : 2); - draw.setColor(palette.accent); - draw.setFont(compactCardLore(style) ? COMPACT_CARD_LORE : FULL_CARD_LORE); - int lineY = y + (compactCardLore(style) ? 55 : 64); - for (String line : fullCardLore(draw, style, card).lines()) { - draw.drawString(line, x + 7, lineY); - lineY += draw.getFontMetrics().getHeight(); - } - if (style == Style.GUILD && card.actionable() && card.material().startsWith("guild_world_")) { - drawSceneArt(draw, "npc_world_" + card.material().substring("guild_world_".length()), x + 70, y + 76, 51, 42); - } - return true; - } else if (style == Style.EXCHANGE || style == Style.EXCHANGE_CHECKOUT) { - draw.fillRect(x, y + 70, 128, 5); - draw.fillRect(x, y + 120, 128, 5); - } else if (art != null) { - drawResource(draw, art, x + 39, y + 7, 50, 48); - draw.setFont(CARD_TITLE); - writeWrapped(draw, card.title(), x + 7, y + 71, 114, 2); - draw.setFont(CARD_LORE); - writeWrapped(draw, styledLore(style, card), x + 7, y + 104, 114, 2); - return true; - } - draw.setColor(Color.WHITE); - draw.setFont(CARD_TITLE); - writeWrapped(draw, card.title(), x + 7, y + 24, 114, 3); - draw.setColor(palette.accent); - draw.setFont(CARD_LORE); - writeWrapped(draw, styledLore(style, card), x + 7, y + 87, 114, 3); - return true; - } - - private static String nativeArt(String key) { - if (key.matches("mentat_(atreides|corrino|fremen|harkonnen|ordos)")) - return "/mcgui/native/" + key.replace('_', '-') + "-v1.png"; - return switch (key) { - case "house_atreides" -> "/mcgui/native/house-aerdrecht-v1.png"; - case "house_corrino" -> "/mcgui/native/house-korenholt-v1.png"; - case "house_fremen" -> "/mcgui/native/house-vrijduin-v1.png"; - case "house_harkonnen" -> "/mcgui/native/house-harkveen-v1.png"; - case "house_ordos" -> "/mcgui/native/house-oordwijk-v1.png"; - default -> null; - }; - } - - private static BufferedImage organisationLogo(String value) { - if (value.length() > 110000 || value.isBlank()) return null; - try (var input = javax.imageio.ImageIO.createImageInputStream( - new java.io.ByteArrayInputStream(Base64.getDecoder().decode(value)))) { - var readers = javax.imageio.ImageIO.getImageReaders(input); - if (!readers.hasNext()) return null; - var reader = readers.next(); - try { - reader.setInput(input, true, true); - if (!reader.getFormatName().equalsIgnoreCase("png") || - reader.getWidth(0) > 512 || reader.getHeight(0) > 512) return null; - return reader.read(0); - } finally { - reader.dispose(); - } - } catch (IllegalArgumentException | java.io.IOException error) { - return null; - } - } - - private static Roleplay roleplay(Document document) { - String[] title = document.title().split(" · ", 2); - if (title.length != 2) return null; - String heading = switch (title[0]) { - case "NPC dashboard" -> "YOUR MISSIONS"; - case "NPC next quest" -> "YOUR NEXT MISSION"; - case "NPC turn-in decision" -> "POLITICAL DECISION"; - case "NPC next quest decision" -> "DECISION RECORDED"; - case "NPC turn-in" -> document.cards().stream().anyMatch(card -> - card.actionable() && (card.title().equals("Claim verified reward") || card.title().equals("Next quest"))) - ? "MISSION COMPLETE" : "MISSION TURN-IN"; - default -> null; - }; - if (heading == null) return null; - var portrait = document.cards().stream().filter(card -> card.material().matches("npc_avatar_[0-7]")).findFirst().orElse(null); - var world = document.cards().stream().filter(card -> card.material().matches("npc_world_[a-z_]+")).findFirst().orElse(null); - var summary = document.description().isBlank() ? document.cards().stream() - .filter(card -> card.material().equals("npc_summary")).findFirst().orElse(null) : null; - return new Roleplay(heading, portrait == null ? title[1] : portrait.title(), portrait, world, summary); - } - - private static Document presentable(Document document, Roleplay roleplay) { - if (roleplay == null) return document; - var cards = document.cards().stream() - .filter(card -> card.actionable() || card != roleplay.portrait && card != roleplay.world && card != roleplay.summary) - .toList(); - return new Document(document.title(), document.description(), cards, document.style(), document.identity()); - } - - private static String displayLore(Roleplay roleplay, Card card) { - if (card.lore().isEmpty()) return ""; - if (roleplay == null || card.slot() < 0) return card.lore().getFirst(); - if (!card.actionable()) return String.join(" ", card.lore()); - return roleplay.heading.equals("YOUR MISSIONS") && card.slot() >= 9 && card.slot() < 45 - ? card.lore().getFirst() : ""; - } - - private static boolean fitsRoleplay(Document document, Roleplay roleplay) { - var graphics = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).createGraphics(); - try { - graphics.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14)); - if (!wrap(graphics, roleplay.contact, 112, 2).complete) return false; - if (document.style() == Style.AUTO && !fitsCards(graphics, document, roleplay)) return false; - graphics.setFont(CARD_LORE); - String summary = roleplay.summary == null ? document.description() : String.join(" ", roleplay.summary.lore()); - return wrap(graphics, summary, 112, 6).complete; - } finally { - graphics.dispose(); - } - } - - private static boolean fitsCards(java.awt.Graphics2D graphics, Document document, Roleplay roleplay) { - for (Card card : document.cards()) { - graphics.setFont(CARD_TITLE); - if (!wrap(graphics, card.title(), 114, 3).complete) return false; - graphics.setFont(CARD_LORE); - if (!wrap(graphics, displayLore(roleplay, card), 114, 3).complete) return false; - } - return true; - } - - private void drawRoleplay(java.awt.Graphics2D draw, Scene scene) { - var role = scene.roleplay; - draw.setColor(new Color(23, 56, 40)); - draw.fillRect(644, 389, 120, 232); - String asset = role.portrait == null ? "npc_avatar_7" : role.portrait.material(); - drawSceneArt(draw, asset, 650, 395, 108, 83); - draw.setColor(new Color(250, 226, 169)); - draw.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14)); - writeWrapped(draw, role.contact, 648, 498, 112, 2); - draw.setColor(Color.WHITE); - draw.setFont(CARD_LORE); - String summary = role.summary == null ? scene.document.description() : String.join(" ", role.summary.lore()); - if (summary.isBlank() && role.world != null) drawSceneArt(draw, role.world.material(), 650, 518, 108, 78); - else writeWrapped(draw, summary, 648, 532, 112, 6); - } - - private void drawSceneArt(java.awt.Graphics2D draw, String asset, int x, int y, int width, int height) { - drawResource(draw, "/mcgui-npc-avatars/" + asset + ".png", x, y, width, height); - } - - private void drawResource(java.awt.Graphics2D draw, String resource, int x, int y, int width, int height) { - if (resource == null) return; - try (var stream = DecisionsViewTransport.class.getResourceAsStream(resource)) { - if (stream == null) return; - var image = javax.imageio.ImageIO.read(stream); - if (image == null) return; - drawImage(draw, image, x, y, width, height); - } catch (java.io.IOException error) { - plugin.getLogger().warning("Could not render fullscreen artwork: " + resource); - } - } - - private static void drawImage(java.awt.Graphics2D draw, BufferedImage image, int x, int y, int width, int height) { - double scale = Math.min((double) width / image.getWidth(), (double) height / image.getHeight()); - int w = (int) Math.round(image.getWidth() * scale), h = (int) Math.round(image.getHeight() * scale); - draw.drawImage(image, x + (width - w) / 2, y + (height - h) / 2, w, h, null); - } - - private record Wrapped(List lines, boolean complete) {} - - private static void writeWrapped(java.awt.Graphics2D draw, String text, int x, int y, int width, int lines) { - int lineHeight = draw.getFontMetrics().getHeight(); - for (String line : wrap(draw, text, width, lines).lines()) { - draw.drawString(line, x, y); - y += lineHeight; - } - } - - private static Wrapped wrap(java.awt.Graphics2D draw, String text, int width, int lines) { - var metrics = draw.getFontMetrics(); - var result = new ArrayList(); - String remaining = text.strip().replaceAll("\\s+", " "); - while (result.size() < lines && !remaining.isEmpty()) { - int end = remaining.length(); - while (end > 1 && metrics.stringWidth(remaining.substring(0, end)) > width) end--; - if (end < remaining.length()) { - int wordBreak = remaining.lastIndexOf(' ', end); - if (wordBreak > 0) end = wordBreak; - } - result.add(remaining.substring(0, end)); - remaining = remaining.substring(end).stripLeading(); - } - return new Wrapped(List.copyOf(result), remaining.isEmpty()); - } - - private BufferedImage focused(BufferedImage normal, int height) { - var image = new BufferedImage(128, 128, BufferedImage.TYPE_INT_RGB); - var draw = image.createGraphics(); - try { - draw.drawImage(normal, 0, 0, null); - draw.setColor(new Color(250, 224, 152)); - draw.setStroke(new BasicStroke(8)); - draw.drawRect(5, 5, 117, height - 5); - } finally { - draw.dispose(); - } - return image; - } -} diff --git a/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/SceneTeardown.java b/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/SceneTeardown.java deleted file mode 100644 index 9abc1710..00000000 --- a/DuneFullscreenPaper/src/main/java/com/dunerealms/fullscreen/SceneTeardown.java +++ /dev/null @@ -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 current) { - return teleport.getAsBoolean() && saved.equals(current.get()); - } - - static void run(BooleanSupplier restore, Runnable select, Runnable dismiss, Runnable rejected, - Consumer 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(); - } - } -} diff --git a/DuneFullscreenPaper/src/main/resources/plugin.yml b/DuneFullscreenPaper/src/main/resources/plugin.yml deleted file mode 100644 index e0a39528..00000000 --- a/DuneFullscreenPaper/src/main/resources/plugin.yml +++ /dev/null @@ -1,5 +0,0 @@ -name: DuneFullscreenPaper -main: com.dunerealms.fullscreen.FullscreenProvider -version: 0.1.0 -api-version: '26.2' -depend: [DuneMenus] diff --git a/DuneFullscreenPaper/src/test/java/com/dunerealms/fullscreen/SceneTeardownTest.java b/DuneFullscreenPaper/src/test/java/com/dunerealms/fullscreen/SceneTeardownTest.java deleted file mode 100644 index 1e358c24..00000000 --- a/DuneFullscreenPaper/src/test/java/com/dunerealms/fullscreen/SceneTeardownTest.java +++ /dev/null @@ -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(); - 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(); - 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(); - 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(); - 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(); - SceneTeardown.run(restoration, () -> fail("Unsafe selection"), () -> calls.add("dismissed"), - () -> calls.add("rejected"), failure -> fail(failure)); - assertEquals(List.of("dismissed", "rejected"), calls); - } -} diff --git a/DuneMenus/docs/NEW-GUI.md b/DuneMenus/docs/NEW-GUI.md new file mode 100644 index 00000000..bd6a0824 --- /dev/null +++ b/DuneMenus/docs/NEW-GUI.md @@ -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. diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/DuneMenusPlugin.java b/DuneMenus/src/main/java/com/dunerealms/menus/DuneMenusPlugin.java index 10edef35..2aeeb03a 100644 --- a/DuneMenus/src/main/java/com/dunerealms/menus/DuneMenusPlugin.java +++ b/DuneMenus/src/main/java/com/dunerealms/menus/DuneMenusPlugin.java @@ -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 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(); } } diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/FullscreenProvider.java b/DuneMenus/src/main/java/com/dunerealms/menus/FullscreenProvider.java index 5b9f99ba..654c6408 100644 --- a/DuneMenus/src/main/java/com/dunerealms/menus/FullscreenProvider.java +++ b/DuneMenus/src/main/java/com/dunerealms/menus/FullscreenProvider.java @@ -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/.html). */ - record Screen(String id, String title, String subtitle, List cards, List info) {} + record Screen(String id, String title, String subtitle, List cards, List 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); diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/GlyphChestProvider.java b/DuneMenus/src/main/java/com/dunerealms/menus/GlyphChestProvider.java new file mode 100644 index 00000000..c968c439 --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/GlyphChestProvider.java @@ -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 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 clickable = new HashSet<>(); + IntConsumer select; + Runnable close; + boolean handled; + @Override public Inventory getInventory() { return inventory; } + } + + private final DuneMenusPlugin plugin; + private final Map sessions = new HashMap<>(); + private final Map 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, "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()); + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/Menu.java b/DuneMenus/src/main/java/com/dunerealms/menus/Menu.java index 0b5500f4..d7683ab0 100644 --- a/DuneMenus/src/main/java/com/dunerealms/menus/Menu.java +++ b/DuneMenus/src/main/java/com/dunerealms/menus/Menu.java @@ -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 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(); - } - } diff --git a/DuneMenus/src/main/java/com/dunerealms/services/DuneServicesPlugin.java b/DuneMenus/src/main/java/com/dunerealms/services/DuneServicesPlugin.java index 535f5f28..edadf394 100644 --- a/DuneMenus/src/main/java/com/dunerealms/services/DuneServicesPlugin.java +++ b/DuneMenus/src/main/java/com/dunerealms/services/DuneServicesPlugin.java @@ -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); diff --git a/DuneMenus/src/main/java/com/dunerealms/services/MCGUIMenus.java b/DuneMenus/src/main/java/com/dunerealms/services/MCGUIMenus.java deleted file mode 100644 index 6d7177bd..00000000 --- a/DuneMenus/src/main/java/com/dunerealms/services/MCGUIMenus.java +++ /dev/null @@ -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 sessions=new HashMap<>(); - private final Set 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 actions,GuiSession gate){ - return show(p,title,description,inventory,actions,gate,null); - } - static boolean show(Player p,String title,String description,Inventory inventory,Map 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 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 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 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 cards(Inventory inventory,Map actions){ - List cards=new ArrayList<>();Set aliases=Collections.newSetFromMap(new IdentityHashMap<>());Set decorations=new HashSet<>(),transparent=new HashSet<>(); - var plain=PlainTextComponentSerializer.plainText(); - for(int slot=0;slot 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 cards;final Map 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 cards,Map 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();} -} diff --git a/DuneMenus/src/main/java/com/dunerealms/services/MenuDocument.java b/DuneMenus/src/main/java/com/dunerealms/services/MenuDocument.java deleted file mode 100644 index ff6a9669..00000000 --- a/DuneMenus/src/main/java/com/dunerealms/services/MenuDocument.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.dunerealms.services; -import java.nio.file.*; -import java.util.*; -import java.util.regex.*; - -/** Market-shaped presentation. All dynamic content is text; actions live in the server session. */ -final class MenuDocument { - record Branding(String logo,String mentat,int portrait){} - record Card(int slot,String title,List lore,String material,int amount,boolean action,String quality){} - static boolean compactControl(Card c){return c.action&&(Set.of("16","32","64").contains(c.title)||c.title.matches("[+−] (?:[0-9].*|Quantity)"));} - static String clean(String text){return text==null?"":text.replaceAll("[\\p{Co}\\p{Cc}&&[^\\n]]","").replaceAll("(?i)§[0-9a-fk-orx]","").trim();} - static String escape(String text){return clean(text).replace("&","&").replace("<","<").replace(">",">").replace("\"",""").replace("'","'");} - static String icon(Card card,Path root){ - String name=card.title.toLowerCase(Locale.ROOT),semantic=switch(name){case "clan","your clan"->"clan";case "company","your companies"->"company";case "pol","your political offices"->"politics";case "your house"->"house";case "your mentat"->"mentat";case "exchange"->"exchange";case "mission journal","missions & turn-ins"->"quests";case "spacing guild"->"travel";default->"";}; - if(!semantic.isEmpty()&&Files.isRegularFile(root.resolve("art/"+semantic+".png")))return "art/"+semantic+".png"; - String material=card.material; - if(Set.of("light_blue_dye","lime_dye").contains(material)&&!compactControl(card))material="quests"; - if(material.equals("paper")&&card.quality.isBlank()){if(name.contains("home block")||name.contains("homeblock"))material="lodestone";else if(name.contains("clan"))material="clan";else if(name.contains("company")||name.contains("organisation"))material="company";else if(name.contains("quest")||name.contains("mission"))material="quests";else if(name.startsWith("quantity"))material="chest";else if(name.contains("office")||name.contains("politic"))material="politics";else material="filled_map";} - if(!material.matches("[a-z0-9_]{1,70}"))return "";String relative="art/"+material+".png";return Files.isRegularFile(root.resolve(relative))?relative:""; - } - static String fact(Card c){for(String line:c.lore){Matcher m=Pattern.compile("[0-9][0-9,.]*\\s*DM").matcher(line);if(m.find())return m.group();}for(String line:c.lore)if(line.matches("(?i).*(progress|claimed|in progress|XP|complete).*"))return line.length()>35?line.substring(0,32)+"…":line;return c.amount>1?"× "+c.amount:c.action?"View →":"Details";} - static String html(String title,String description,String player,List cards,int selected,Path root){ - return html(title,description,player,cards,selected,root,null); - } - static String html(String title,String description,String player,List cards,int selected,Path root,Branding branding){ - if(title.equals("War Muster Room"))return warMusterRoom(description,player,cards,root); - if(title.startsWith("NPC dashboard · ")||title.startsWith("NPC turn-in · ")||title.startsWith("NPC next quest · ")||title.startsWith("NPC dashboard decision · ")||title.startsWith("NPC turn-in decision · ")||title.startsWith("NPC next quest decision · "))return roleplay(title,description,cards,selected,root); - int back=cards.stream().filter(c->c.action&&(c.title.equalsIgnoreCase("Back")||c.title.toLowerCase(Locale.ROOT).startsWith("back to "))).mapToInt(Card::slot).findFirst().orElse(-3); - List controls=cards.stream().filter(MenuDocument::compactControl).toList();cards=cards.stream().filter(c->!compactControl(c)).toList(); - String theme=branding==null?theme(title,cards):"organisation"; - Card detail=cards.stream().filter(c->c.slot==selected).findFirst().orElse(cards.isEmpty()?null:cards.get(0)); - StringBuilder b=new StringBuilder("DuneRealms
CHOAM · IMPERIAL SERVICES

").append(escape(title)).append("

").append(escape(player)).append("
"); - if(branding!=null&&(!branding.logo.isEmpty()||!branding.mentat.isEmpty())){ - b.append("
"); - if(branding.logo.length()<=110000&&branding.logo.matches("[A-Za-z0-9+/]+={0,2}")){ - b.append("\"Organisation"); - } - if(!branding.mentat.isEmpty()){ - if(branding.portrait>=0&&branding.portrait<=7){ - b.append("\"\""); - } - b.append("
Mentat

").append(escape(branding.mentat)).append("

"); - } - b.append("
"); - } - if(!clean(description).isBlank())b.append("

").append(escape(description).replace("\n","
")).append("

"); - if(!controls.isEmpty()){b.append("
");for(Card c:controls)b.append("");b.append("
");} - for(int i=0;i
");for(Card c:cards.subList(i,Math.min(i+4,cards.size()))){ - String image=icon(c,root);boolean direct=c.action&&(theme.equals("house")||theme.equals("organisation"));b.append(direct?""); - }b.append("
").append(theme.equals("quest")?"MISSIONS · YOUR JOURNEY CONTINUES":"DUNE REALMS · "+escape(title)).append("
");} - b.append("
J.A.R.V.I.S. · Your realm, connectedInspect a card · Scroll for more · Sneak to close
");return b.toString(); - } - static String warMusterRoom(String description,String player,List cards,Path root){ - Map positions=new HashMap<>();for(Card card:cards)positions.put(card.slot,card);Card own=cards.stream().filter(c->c.lore.stream().anyMatch(l->l.equals("Your team"))).findFirst().orElse(null);String side=own!=null&&own.title.startsWith("Red")?"red":"blue"; - StringBuilder b=new StringBuilder("
J.A.R.V.I.S. · CLAN WAR

WAR MUSTER ROOM

").append(escape(player)).append("

").append(escape(description).replace("\n"," · ")).append("

").append(escape(own==null?"YOUR TEAM":own.title)).append("

"); - int[] slots={19,20,21,22,28,29,30,31};for(int i=0;i").append(i+1).append("").append(escape(card.title)).append("").append(card.action?"▾":"◇").append("');}b.append("

PROVINCE & ROSTER STATUS

"); - for(int slot:new int[]{2,6}){Card c=positions.get(slot);if(c==null)continue;String color=c.title.startsWith("Red")?"red":"blue";b.append("
⚑").append(escape(c.title)).append("");for(String lore:c.lore)b.append("

").append(escape(lore)).append("

");b.append("
");}b.append("
");Card key=positions.get(34);if(key!=null){b.append("

TEAM ROSTER KEY

");for(String line:key.lore)b.append("

").append(escape(line)).append("

");b.append("
");}b.append("
");for(int slot:new int[]{45,47,49,51}){Card c=positions.get(slot);if(c==null)continue;b.append("");}b.append("

Auto-launch 15 minutes after scheduled start · Sneak to close

");return b.toString(); - } - private static final String WAR_CSS=""" - *{box-sizing:border-box}body{margin:0;padding:14px;background:linear-gradient(145deg,#142f25,#081e19);color:#f5e7bd;font-family:Minecraft,monospace;font-size:13px}.war-frame{border:3px solid #d3a84c;border-radius:12px;padding:12px 18px 9px;background:linear-gradient(150deg,#244735,#10291f);box-shadow:inset 0 0 0 2px #604d22,0 8px 22px #0009}header{display:flex;align-items:center;gap:16px;height:62px;border-bottom:2px solid #bf9746;padding-bottom:5px}header img{width:150px;height:54px;object-fit:contain}header div{flex:1}header small{color:#c9a958;font-size:10px;letter-spacing:2px}h1{margin:3px 0;font-size:24px;color:#f2d58b}header span{color:#c8d8be;font-size:10px}.close{width:33px;height:32px}.brief{font-size:10px;color:#e6ca85;line-height:1.4;margin:7px 0 10px}main{display:grid;grid-template-columns:1fr 1fr;gap:14px}.roster,.status{border:2px solid #c49c40;border-radius:7px;padding:8px;background:#0b221b}h2{font-size:15px;letter-spacing:1px;margin:0 0 7px;padding:6px;text-align:center;color:#fff0c6;border-bottom:1px solid #bc9848}.roster.blue h2{background:#234e82}.roster.red h2{background:#713a36}.slots{display:grid;grid-template-columns:1fr 1fr;gap:7px}.member{display:flex;align-items:center;gap:7px;min-height:47px;padding:4px;border:1px solid #c5a259;border-radius:4px;background:linear-gradient(90deg,#193d2c,#123025);color:#efdfb5;text-align:left;font:12px Minecraft,monospace}.member:hover{background:#42664c}.number{background:#24485f;border:1px solid #c6a253;border-radius:3px;width:23px;text-align:center;padding:6px 0}.red .number{background:#7c3535}.name{flex:1;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.member.empty{color:#9bafaa}.select{color:#dfb85f}.provinces{display:grid;grid-template-columns:1fr 1fr;gap:7px}.province{padding:8px;border:1px solid #c5a259;border-radius:5px;background:#213e35;min-height:105px}.province.blue{background:linear-gradient(145deg,#25567c,#162f43)}.province.red{background:linear-gradient(145deg,#884846,#442c2b)}.province strong{font-size:12px;color:#ffe7a1;display:block;margin-bottom:4px}.flag{float:right;color:#e2bd62;font-size:24px}.province p,.key p{font-size:10px;margin:3px 0;color:#e5dbc1;line-height:1.4}.key{margin-top:9px;border:1px solid #bb9144;padding:7px;border-radius:4px;background:#132f24}.key h3{margin:0 0 4px;font-size:12px;color:#f3cf7b}.key p:first-of-type{font-size:14px;color:#fff0b4;overflow-wrap:break-word}footer{display:flex;gap:10px;justify-content:center;margin-top:10px}button{font:12px Minecraft,monospace;padding:9px 14px;color:#fbe5aa;border:2px solid #c7a353;background:#183b2b;border-radius:5px}button[data-slot]:hover{background:#42664c}.save{background:linear-gradient(140deg,#f2d18b,#b58a39);color:#28230c;min-width:150px}.launch{min-width:145px;background:#543e20}.disabled{background:#394744;color:#a6b1ab;border-color:#65736b}.notice{text-align:center;color:#c8b77b;font-size:10px;margin:6px 0 0} - """; - static String roleplay(String title,String description,List cards,int selected,Path root){ - String[] parts=title.split(" · ",2);String mode=parts[0],name=parts.length==2?parts[1]:"Quest contact";boolean decision=mode.contains("decision"),dashboard=mode.startsWith("NPC dashboard"),next=mode.startsWith("NPC next quest");Card avatar=cards.stream().filter(c->c.material.matches("npc_avatar_[0-7]")).findFirst().orElse(null);String portrait=avatar==null?"":icon(avatar,root);if(portrait.isEmpty()&&Files.isRegularFile(root.resolve("art/npc_avatar_7.png")))portrait="art/npc_avatar_7.png";Card summary=cards.stream().filter(c->c.material.equals("npc_summary")).findFirst().orElse(null);Card world=cards.stream().filter(c->c.material.startsWith("npc_world_")).findFirst().orElse(null);Card pick=cards.stream().filter(c->dashboard&&c.action&&c.slot>=9&&c.slot<45&&c.slot==selected).findFirst().orElse(null); - String heading=decision?(dashboard?"YOUR DECISIONS":next?"DECISION RECORDED":"REVIEW DECISION"):dashboard?"YOUR MISSIONS":next?"YOUR NEXT MISSION":cards.stream().anyMatch(c->c.title.equals("Claim verified reward")||c.title.equals("Next quest"))?"MISSION COMPLETE":"MISSION TURN-IN"; - StringBuilder b=new StringBuilder("DuneRealms · Dialogue
━━

").append(escape(heading)).append("

━━
"); - if(summary!=null){b.append("
");for(String line:summary.lore){if(line.matches("Progress: [0-9]{1,3}%")){int percent=Math.max(0,Math.min(100,Integer.parseInt(line.substring(10,line.length()-1))));b.append("
");}else b.append("

").append(escape(line)).append("

");}b.append("
");} - if(!description.isBlank())b.append("

").append(escape(description)).append("

");else if(world!=null&&!dashboard){String art=icon(world,root);if(!art.isEmpty())b.append("");} - boolean paths=false;for(Card c:cards){if(c==avatar||c==summary||c==world)continue;if(dashboard&&c.action&&c.slot>=9&&c.slot<45){boolean available=c.lore.stream().anyMatch(l->l.equals("Eligible to accept"));if(available&&!paths){b.append("

AVAILABLE PATHS

");paths=true;}b.append("");continue;} - if(c.action)continue;b.append("

").append(escape(c.title)).append("

");for(String line:c.lore)b.append("

").append(escape(line)).append("

");b.append("
");} - for(Card c:cards){if(!c.action||dashboard&&c.slot>=9&&c.slot<45)continue;String action=c.title.equals("Claim verified reward")?"CLAIM & CONTINUE":c.title;boolean primary=c.slot==31||c.title.equals("Accept")||c.title.equals("Enact decision");b.append("");} - return b.append("
SHIFT TO CLOSE
").toString(); - } - private static final String DECISION_CSS=""" - body{background:#182126} - .frame{background:#253238;border:3px solid #b28d52;grid-template-columns:25% 75%;padding:24px} - .portrait{background:#202a2f;border-right:1px solid #927449;padding:18px 18px 115px;min-height:535px} - .nameplate{left:12px;right:12px} - .content{padding:4px 22px 30px;text-align:left} - header{border-bottom:2px solid #927449;margin-bottom:14px;padding:8px;background:#313b3b} - .dialogue{text-align:left;margin:12px 0;color:#f4e6cd} - .summary,.record{max-width:none;background:#202e37;border:1px solid #927449;margin:10px 0} - .mission{width:100%;min-height:48px;margin:7px 0;padding:9px 15px;border:1px solid #6f8b9a;border-left:4px solid #c49b5b;border-radius:3px;background:linear-gradient(#354c5a,#293c49)} - .mission span{color:#f1dab2}.mission:hover{background:#406072} - .secondary{width:auto;display:inline-block;margin:8px 10px 0 0} - footer{left:27%} - """; - private static final String ROLEPLAY_CSS=""" - *{box-sizing:border-box}body{margin:0;color:#f8edcf;background:#061c13;font-family:'Source Serif 4',Georgia,serif}.frame{position:relative;min-height:597px;width:100%;display:grid;grid-template-columns:30% 70%;background-image:url('art/quest-dialogue-frame.png');background-size:100% 100%;background-repeat:no-repeat;padding:18px 22px 42px}.portrait{position:relative;padding:17px 27px 122px 17px;display:flex;align-items:center;justify-content:center;min-height:500px}.avatar{width:100%;height:auto;max-height:370px;object-fit:contain;image-rendering:pixelated}.nameplate{position:absolute;bottom:10px;left:18px;right:36px;text-align:center}.nameplate h2{font-size:25px;line-height:1.08;margin:0;color:#f6e2a8}.nameplate p{font-style:italic;font-size:14px;color:#e5cb8f;margin:8px 4px}.content{padding:0 40px 30px 33px;min-width:0;text-align:center}header{display:flex;align-items:center;justify-content:center;gap:16px;color:#cfa94c}h1{margin:0 0 7px;color:#fff2cd;font-size:32px;letter-spacing:1px;line-height:1.1}.dialogue-art{width:80%;max-height:140px;object-fit:cover;border:1px solid #b59b58;margin:8px auto}.dialogue{font-size:17px;color:#f2dfb1;font-style:italic;margin:7px auto 12px;line-height:1.3;max-width:95%}.summary,.record{border:2px solid #bc9f52;border-radius:6px;padding:8px 14px;margin:9px auto;background:#05251bd9;max-width:96%}.bar{height:15px;border:1px solid #d9ba68;background:#09291d;margin:5px 20px}.bar div{height:100%;background:linear-gradient(#ffe17c,#c69a32)}.summary p,.record p{margin:4px 0;line-height:1.25;font-size:14px}.record h3{margin:2px 0 6px;font-size:20px;color:#f1d293}.paths{color:#f5e0a5;font-size:20px;letter-spacing:1px;margin:12px 0 6px}.mission,.primary,.secondary{background:linear-gradient(#113a29,#08281d);border:2px solid #c0a150;color:#f9ecc6;min-height:36px;padding:7px 15px;border-radius:7px;font:600 16px 'Source Serif 4',Georgia,serif;display:block;width:96%;margin:7px auto;box-shadow:inset 0 1px 0 #f5e0a450}.mission{text-align:left;display:flex;justify-content:space-between;gap:12px}.mission span{font-size:13px;color:#e8d09b}.mission.selected span{color:#3a2c0b}.mission.selected,.primary{background:linear-gradient(#ffe082,#c99a2d);color:#1b1a0b;border:2px solid #fff1b3;box-shadow:0 0 10px #e0ad4b66,inset 0 1px 0 #fff0b9}.primary{font-size:20px;font-weight:700;width:80%;text-transform:uppercase;min-height:43px}.secondary{width:72%;font-size:15px;min-height:33px}.mission:hover,.secondary:hover{border-color:#fff0b9}.hint{color:#cbb47d;font-style:italic;font-size:13px}footer{position:absolute;bottom:13px;left:32%;right:3%;text-align:center;font-size:13px;letter-spacing:3px;color:#f5dd98;font-weight:700} - """; - private static String theme(String title,List cards){ - String name=title.toLowerCase(Locale.ROOT); - if(name.startsWith("exchange"))return "exchange"; - if(name.contains("spice"))return "spice"; - if(name.equals("choose your house")||name.startsWith("your mentat"))return "house"; - if(name.contains("quest")||name.contains("mission")||name.contains("research")||name.contains("gurney"))return "quest"; - if(name.contains("clan")||name.contains("compan")||name.contains("organisation")|| - cards.stream().anyMatch(card->card.title.equals("Set Home Block")))return "organisation"; - return "realm"; - } - private static final String THEME_CSS=""" - .quest{--accent:#c6d8a9;--edge:#667f54;background:linear-gradient(160deg,#233129,#111d18)} - .quest .awning{height:8px;background:#667f54;border:0} - .quest main{grid-template-columns:minmax(235px,1fr) minmax(0,2fr)} - .quest .goods{grid-template-columns:1fr} - .quest .slot{flex-direction:row;text-align:left;gap:9px;padding:8px;background:#23372a;border:1px solid #667f54} - .quest .slot strong{flex:1;color:#f0efd7;max-height:none} - .quest .cubby{width:62px;height:62px;flex-shrink:0} - .quest .cubby img{width:49px;height:49px} - .quest .board,.spice .board{display:none} - .spice{--accent:#ffcd94;--edge:#aa6545;background:linear-gradient(160deg,#44261a,#251812)} - .spice .awning{height:8px;background:#aa6545;border:0} - .spice aside{background:linear-gradient(180deg,#573320,#301e15)} - .spice .goods{grid-template-columns:repeat(2,minmax(0,1fr))} - .spice .slot{padding:10px;background:#3d271c;border:1px solid #aa6545} - .spice .cubby{background:#2e1c15;border-color:#aa6545} - .organisation{--accent:#9ee3d7;--edge:#578f8e;--glow:#7dcab832;background:linear-gradient(160deg,#152d34,#0b2025)} - .organisation-identity{display:flex;align-items:center;gap:18px;padding:10px 18px;margin-bottom:12px;border:1px solid #578f8e;background:#152d34} - .organisation-identity img{width:88px;height:88px;object-fit:contain} - .organisation .awning{height:8px;background:#578f8e;border:0} - .organisation main{display:block}.organisation aside{display:none}.organisation .goods{grid-template-columns:repeat(2,minmax(0,1fr))} - .organisation .slot{flex-direction:row;text-align:left;gap:15px;padding:18px;background:#1a3840;border:1px solid #578f8e} - .organisation .cubby{width:110px;height:110px;flex-shrink:0} - .organisation .cubby img{width:90px;height:90px} - .organisation .board,.house .board{display:none} - .organisation h1,.organisation .slot strong{color:#d4efe9}.organisation .slot strong{font-size:16px;max-height:none} - .exchange{--accent:#f5d18c;--edge:#ae8755;background:linear-gradient(160deg,#372b20,#17130f)} - .exchange aside{background:linear-gradient(180deg,#473524,#251b14)} - .exchange .cubby{width:100%;height:135px;background:#1d1710;border-color:#9c754a}.exchange .slot{width:100%}.exchange .cubby img{width:102px;height:102px} - .house{--accent:#eed49a;--edge:#ae8a56;background:linear-gradient(160deg,#332c37,#191722)} - .house .awning{height:8px;background:#ae8a56;border:0} - .house aside{background:linear-gradient(180deg,#3c3142,#211a2b)} - .house .cubby{border-radius:50%;background:#281f31;border-color:#ae8a56} - .house .cubby img{width:54px;height:54px} - """; - private static final String CONTROL_CSS=".menu-nav,.quick-controls{display:flex;gap:6px;flex-wrap:wrap}.menu-nav button,.quick-controls button{border:1px solid #b69a50;border-radius:3px;background:linear-gradient(180deg,#28553b,#102f24);color:#f1d797;font-size:12px;padding:7px 10px;min-width:42px}.menu-nav button:hover,.quick-controls button:hover{background:#3a7149}.quick-controls{margin-bottom:12px;padding:9px;background:#071f17;border:1px solid #8c743d}"; - private static final String CSS=""" - *{box-sizing:border-box}html,body{margin:0;min-height:100%;font-family:Inter,sans-serif}body{border:3px solid #b69a50;box-shadow:inset 0 0 0 2px #122d1e;position:relative;color:#e9dfc1;--accent:#e1bc65;--edge:#8c743d;--glow:#e5bd5c30;background:radial-gradient(ellipse at 12% 20%,#a2803930,transparent 60%),linear-gradient(180deg,#09251de8,#041711fa),url(art/banner.png) center/cover}.ingame{--accent:#88c5e4;--edge:#477e93;--glow:#4babc330}.ingame .cubby{border-color:#477e93}.awning{height:22px;background:repeating-linear-gradient(90deg,#163d2b 0px,#163d2b 30px,#b69750 30px,#b69750 45px);box-shadow:inset 0 -8px 10px #0006,0 3px 4px #0005;border-bottom:4px solid #8e763f}header{height:91px;display:flex;align-items:center;gap:22px;padding:9px 30px}.logo{width:174px;height:66px;object-fit:contain;filter:drop-shadow(0 4px 8px #0008)}.heading{flex:1}.heading small{color:#aab89a;font-size:9px;letter-spacing:2.6px}h1{font:600 27px 'Source Serif 4',serif;color:#f1d797;margin:4px 0 0;line-height:1.15}.viewer{font-size:11px;color:#b9c6ac;white-space:nowrap}button{font-family:Inter,sans-serif;color:inherit;cursor:pointer}.close{font-family:Minecraft,monospace;background:#061c1688;border:1px solid #8e763f66;border-radius:2px;width:33px;height:33px;font-size:23px;color:#d9c798}.close:hover{background:#744633}main{display:grid;grid-template-columns:300px minmax(0,1fr);gap:22px;padding:0 30px;align-items:start}aside{position:relative;background:linear-gradient(180deg,#153629e8,#061c16f5);border:2px solid var(--edge);border-radius:2px;padding:15px 17px 18px;box-shadow:0 16px 35px #0007;min-height:430px;display:flex;flex-direction:column}aside:before,aside:after{content:"";position:absolute;width:10px;height:10px;border:3px solid #e6c575;pointer-events:none}aside:before{left:3px;top:3px;border-right:0;border-bottom:0}aside:after{right:3px;bottom:3px;border-left:0;border-top:0}.stage{height:140px;border-radius:10px;display:flex;align-items:center;justify-content:center;margin-bottom:13px;background:radial-gradient(circle at 50% 50%,var(--glow),transparent 68%),repeating-conic-gradient(from 0deg at 50% 60%,#dbc07118 0deg 12deg,transparent 12deg 36deg);overflow:hidden}.stage img{width:126px;height:126px;object-fit:contain;image-rendering:pixelated;filter:drop-shadow(0 10px 8px #0009)}.stage span{font-size:80px;color:var(--accent)}h2{font:600 23px 'Source Serif 4',serif;color:var(--accent);margin:0 0 7px;line-height:1.25}.quality{font-size:10px;letter-spacing:2px;margin:0 0 10px;padding:6px 8px;border:1px solid currentColor;border-radius:4px}.lore-box{margin-bottom:12px}.lore{font-size:12px;color:#b8c9b8;line-height:1.45;margin:7px 0;overflow-wrap:break-word}.section-title{font-size:11px;font-weight:600;color:var(--accent);border-top:1px solid #8b794644;padding-top:9px}.primary{margin-top:auto;min-height:41px;width:100%;border:1px solid #d9ba68;border-radius:2px;padding:10px;background:linear-gradient(180deg,#2f8d36,#145324);color:#fff1bd;font-family:Minecraft,monospace;font-weight:600;font-size:15px;box-shadow:inset 0 2px 0 #f6e9a96b,0 3px 0 #5f4e2b}.primary:hover{background:linear-gradient(180deg,#45a643,#20732f)}.shelves{min-width:0}.intro{font-size:11px;color:#b0c0af;line-height:1.45;margin:0 0 10px}.shelf{margin-bottom:14px}.goods{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;align-items:end;padding:0 9px 10px}.slot{display:flex;align-items:center;flex-direction:column;text-align:center;border:0;background:transparent;padding:3px 0;min-width:0}.cubby{height:75px;width:91px;display:flex;align-items:center;justify-content:center;border-radius:2px;border:2px solid #b69c5f66;background:linear-gradient(180deg,#03110eaa,#0b251b88);box-shadow:inset 0 5px 10px #0007}.cubby img{width:60px;height:60px;object-fit:contain;image-rendering:pixelated;filter:drop-shadow(0 4px 4px #0007)}.sigil{font-size:38px;color:var(--accent)}.slot:hover .cubby,.slot.selected .cubby{border-color:var(--accent);box-shadow:0 0 14px var(--glow),inset 0 0 20px var(--glow)}.slot strong{font-size:11px;line-height:1.25;color:#dfd0a7;margin:6px 0;max-height:29px;overflow:hidden}.tag{font:10px Minecraft,monospace;background:#e5d3a5;color:#282317;border-radius:4px;padding:4px 6px;box-shadow:0 2px 0 #7f6c3b;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.board{height:15px;border-radius:3px;padding:2px 11px;font:9px Minecraft,monospace;letter-spacing:1.5px;color:#d7c698;background:linear-gradient(180deg,#a7915b,#5a502f 40%,#353a21 75%,#1e291c);box-shadow:0 7px 10px #0007,inset 0 1px 0 #e2d2a66b}footer{display:flex;justify-content:space-between;gap:15px;padding:14px 32px 15px;color:#8eaa94;font-size:9px;line-height:1.4}.common{color:#eee}.uncommon{color:#7cda8a}.rare{color:#7dbaf0}.very_rare{color:#c08aec}.legendary{color:#edc45d}.mythic{color:#f28fe4}.relic{color:#fff1b6}@media(max-width:850px){main{grid-template-columns:250px minmax(0,1fr);padding:0 20px;gap:15px}.goods{grid-template-columns:repeat(3,minmax(0,1fr))}.logo{width:140px}header{padding:8px 20px;gap:12px}h1{font-size:24px}}@media(max-width:600px){main{grid-template-columns:1fr}.goods{grid-template-columns:repeat(3,minmax(0,1fr))}aside{min-height:0}aside:before,aside:after{content:"";position:absolute;width:10px;height:10px;border:3px solid #e6c575;pointer-events:none}aside:before{left:3px;top:3px;border-right:0;border-bottom:0}aside:after{right:3px;bottom:3px;border-left:0;border-top:0}.stage{height:100px}.viewer{display:none}.logo{width:120px}h1{font-size:19px}header{height:82px}.heading small{display:none}} - """; -} diff --git a/DuneMenus/src/main/java/com/dunerealms/services/NativeMenus.java b/DuneMenus/src/main/java/com/dunerealms/services/NativeMenus.java deleted file mode 100644 index c1b0a1b0..00000000 --- a/DuneMenus/src/main/java/com/dunerealms/services/NativeMenus.java +++ /dev/null @@ -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 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 cards, Map 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 cards, Map 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 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; - } -} diff --git a/DuneMenus/src/main/java/com/dunerealms/services/OrganisationMenus.java b/DuneMenus/src/main/java/com/dunerealms/services/OrganisationMenus.java index ca9bc9b4..9ba24670 100644 --- a/DuneMenus/src/main/java/com/dunerealms/services/OrganisationMenus.java +++ b/DuneMenus/src/main/java/com/dunerealms/services/OrganisationMenus.java @@ -22,7 +22,7 @@ final class OrganisationMenus implements Listener { private static final class Panel implements DuneMenuInventory { - final UUID owner;final GuiSession gate;final Map actions=new HashMap<>();final Set nativeReadOnly=new HashSet<>();final Map 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 actions=new HashMap<>();final Set nativeReadOnly=new HashSet<>();final Map 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(); diff --git a/DuneMenus/src/main/java/com/dunerealms/services/QuestMenus.java b/DuneMenus/src/main/java/com/dunerealms/services/QuestMenus.java index d6901199..a3336587 100644 --- a/DuneMenus/src/main/java/com/dunerealms/services/QuestMenus.java +++ b/DuneMenus/src/main/java/com/dunerealms/services/QuestMenus.java @@ -22,7 +22,7 @@ final class QuestMenus implements Listener { private final Map pending=new HashMap<>(); private final Map roleScope=new HashMap<>(); private static final class Panel implements DuneMenuInventory { - final UUID owner;final GuiSession gate;final Map actions=new HashMap<>();final List choices=new ArrayList<>();final List 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 actions=new HashMap<>();final List choices=new ArrayList<>();final List 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); diff --git a/DuneMenus/src/main/resources/config.yml b/DuneMenus/src/main/resources/config.yml index bd902557..6876558a 100644 --- a/DuneMenus/src/main/resources/config.yml +++ b/DuneMenus/src/main/resources/config.yml @@ -2,7 +2,7 @@ bedrock: forms: true # Floodgate players get native forms built from the same menus fullscreen: - enabled: false # true = use a registered FullscreenProvider service (see docs/FULLSCREEN.md) + enabled: true # DuneRealms painted full-screen menus (GlyphChestProvider). Needs the gui pack; run /dm calibrate once. resource-pack: logo-in-title: false # true = draw the DuneRealms logo glyph in every chest-menu title (needs the pack in /resourcepack) diff --git a/DuneMenus/src/main/resources/plugin.yml b/DuneMenus/src/main/resources/plugin.yml index 29e6b558..1d67333c 100644 --- a/DuneMenus/src/main/resources/plugin.yml +++ b/DuneMenus/src/main/resources/plugin.yml @@ -3,7 +3,7 @@ version: ${version} main: com.dunerealms.menus.DuneMenusPlugin api-version: '1.21' depend: [JarvisTranslator] -softdepend: [floodgate, DecentHolograms, DuneLobby, DuneCore, DuneEss, DuneNPC, Vault, ViaVersion, MCGUI] +softdepend: [floodgate, DecentHolograms, DuneLobby, DuneCore, DuneEss, DuneNPC, Vault, ViaVersion] commands: dm: description: Open a DuneRealms menu diff --git a/DuneMenus/src/test/java/com/dunerealms/services/MenuDocumentTest.java b/DuneMenus/src/test/java/com/dunerealms/services/MenuDocumentTest.java deleted file mode 100644 index f27503d7..00000000 --- a/DuneMenus/src/test/java/com/dunerealms/services/MenuDocumentTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.dunerealms.services; -import java.nio.file.Path; -import java.util.List; -import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; -class MenuDocumentTest { - @Test void compactTradeControlsActDirectlyAndNavigationUsesTheActualBackCallback(){ - var amount=new MenuDocument.Card(21,"16",List.of(),"chest",1,true,"");var price=new MenuDocument.Card(27,"− 0.01 DM",List.of(),"red_dye",1,true,"");var back=new MenuDocument.Card(45,"Back",List.of(),"arrow",1,true,""); - String html=MenuDocument.html("Exchange","","Player",List.of(amount,price,back),-1,Path.of(".")); - assertTrue(MenuDocument.compactControl(amount));assertTrue(MenuDocument.compactControl(price));assertFalse(MenuDocument.compactControl(back));assertTrue(html.contains("data-slot=\"21\">16"));assertFalse(html.contains("data-pick=\"21\""));assertTrue(html.contains("data-slot=\"-3\">⌂ Home"));assertTrue(html.contains("data-slot=\"45\">← Back")); - } - @Test void itemNamesAndLoreCannotBecomeHtmlOrCommands(){ - var card=new MenuDocument.Card(13,"",List.of(""),"../../secret",1,true,"legendary"); - String html=MenuDocument.html("Imperial Codex","