diff --git a/.forgejo/workflows/compact-menu-links.yml b/.forgejo/workflows/compact-menu-links.yml new file mode 100644 index 00000000..5610ac0f --- /dev/null +++ b/.forgejo/workflows/compact-menu-links.yml @@ -0,0 +1,52 @@ +name: Compact Dune Menu Overlay +on: + workflow_dispatch: + push: + branches: ['fix/compact-menu-links-*'] + +jobs: + compact-menu-links: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test menu routes and package only scoped UI classes + shell: bash + run: | + set -euo pipefail + for module in DuneRealmsGUI DuneMenus DuneLobby; do + gradle --no-daemon -p "$module" test jar + done + mkdir compact-menu-links + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from plugin_menu_polish import CLASSES + from plugin_wild_update import read_archive, write_archive + for module, jar in {"gui":"DuneRealmsGUI/build/libs/DunerealmsGUI.jar", "menus":"DuneMenus/build/libs/DuneMenus.jar", "lobby":"DuneLobby/build/libs/DuneRealms-Lobby.jar"}.items(): + source = read_archive(Path(jar).read_bytes()) + entries = list(CLASSES[module]) + if module in ("gui", "menus"): entries.append("com/dunerealms/" + module + "/MenuPolish.class") + Path("compact-menu-links/" + module + ".zip").write_bytes(write_archive({e:source[e] for e in entries})) + PY + cp tools/{plugin_menu_polish.py,plugin_wild_update.py,CompactMenuMerge.java} compact-menu-links/ + printf '%s\n' "$GITHUB_SHA" > compact-menu-links/SOURCE_COMMIT + (cd compact-menu-links && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Compact-Menu-Links + path: compact-menu-links + if-no-files-found: error diff --git a/.forgejo/workflows/lobby-builder-safety.yml b/.forgejo/workflows/lobby-builder-safety.yml new file mode 100644 index 00000000..dc1cb93c --- /dev/null +++ b/.forgejo/workflows/lobby-builder-safety.yml @@ -0,0 +1,51 @@ +name: Profile-safe Lobby Builder +on: + workflow_dispatch: + push: + branches: ['fix/compact-menu-links-*'] +jobs: + builder-safety: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: '9.2.1' + - name: Test inventory isolation and package the scoped classes + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneRealms-minecraft-only test jar + gradle --no-daemon -p DuneStaff test jar + mkdir lobby-builder-safety + PYTHONPATH=tools python3 - <<'PY' + from pathlib import Path + from plugin_builder_multiverse import CORE, BUILDER, CORE_CLASSES, LEASE, BUILDER_CLASSES + from plugin_wild_update import read_archive, write_archive + for name, jar, entries in [ + ("core", "DuneRealms-minecraft-only/build/libs/DuneRealms-Core.jar", [CORE+n for n in CORE_CLASSES+[LEASE]]), + ("builder", "DuneStaff/build/libs/DuneStaff.jar", [BUILDER+n for n in BUILDER_CLASSES]) + ]: + compiled=read_archive(Path(jar).read_bytes()) + Path("lobby-builder-safety/"+name+".zip").write_bytes(write_archive({n:compiled[n] for n in entries})) + PY + cp tools/{plugin_builder_multiverse.py,plugin_wild_update.py,BuilderProfileCoreOverlay.java} lobby-builder-safety/ + printf '%s\n' "$GITHUB_SHA" > lobby-builder-safety/SOURCE_COMMIT + (cd lobby-builder-safety && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Lobby-Builder-Safety + path: lobby-builder-safety + if-no-files-found: error diff --git a/.forgejo/workflows/multiverse-core-lobby.yml b/.forgejo/workflows/multiverse-core-lobby.yml new file mode 100644 index 00000000..ba982ee0 --- /dev/null +++ b/.forgejo/workflows/multiverse-core-lobby.yml @@ -0,0 +1,29 @@ +name: Reviewed Lobby Multiverse Core +on: + workflow_dispatch: + push: + branches: ['fix/compact-menu-links-*'] +jobs: + multiverse-core: + runs-on: dune-ci + steps: + - name: Check out exact revision + shell: bash + env: + REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + git init . + git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA" + git checkout --detach FETCH_HEAD + - name: Verify the official Core input and package Lobby configuration + shell: bash + run: | + set -euo pipefail + python3 tools/test_multiverse_core.py -v + python3 tools/stage_multiverse_core.py multiverse-core-lobby "$GITHUB_SHA" + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Multiverse-Core-Lobby + path: multiverse-core-lobby + if-no-files-found: error diff --git a/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java b/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java index a3000630..9142ba78 100644 --- a/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java +++ b/DuneLobby/src/main/java/com/example/dunelobby/DuneLobby.java @@ -180,7 +180,7 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec e.getPlayer().sendMessage("The Spacing Guild menu is unavailable."); } } - case "exchange" -> { if(Bukkit.getPluginCommand("dune")!=null) e.getPlayer().performCommand("dune exchange"); else e.getPlayer().sendMessage(ChatColor.GOLD+"Koopkring market integration requires DuneCore on this backend."); } + case "exchange" -> { if(!e.getPlayer().performCommand("dunerealmsgui:exchange")) e.getPlayer().sendMessage("The Exchange service is temporarily unavailable."); } case "water","spice" -> trade(e.getPlayer(),role); } } @@ -207,29 +207,11 @@ public final class DuneLobby extends JavaPlugin implements Listener, CommandExec } } - private void departure(Player player,String planet) { - TravelMenu menu=new TravelMenu(planet); ItemStack confirm=new ItemStack(Material.LIME_CONCRETE); ItemMeta meta=confirm.getItemMeta(); - meta.setDisplayName("Confirm departure: "+planet); meta.setLore(List.of("DuneEss fares and access rules apply when installed.")); confirm.setItemMeta(meta); - menu.inventory.setItem(4,confirm); - com.example.dunegui.NativeMenus.show(this,player,"Guild departure",List.of( - new com.example.dunegui.NativeMenus.Choice("Confirm departure: "+planet,"DuneEss fares and access rules apply.",()->depart(player,planet)), - new com.example.dunegui.NativeMenus.Choice("Cancel","",player::closeInventory))); - } + private void departure(Player player,String planet) { depart(player,planet); } private void depart(Player player,String planet) { - long now=System.currentTimeMillis(); if(now-travelCooldown.getOrDefault(player.getUniqueId(),0L)<5000) return; - travelCooldown.put(player.getUniqueId(),now); - Bukkit.getScheduler().runTask(this,()-> { - player.closeInventory(); - if(Bukkit.getPluginCommand("duneess")!=null) { player.performCommand("duneess travel "+planet); return; } - World target=Bukkit.getWorld(planet); - if(target!=null) { player.teleport(target.getSpawnLocation()); return; } - String server=getConfig().getString("servers."+planet,""); - if(server.isBlank()) { player.sendMessage("No destination configured."); return; } - try { - ByteArrayOutputStream bytes=new ByteArrayOutputStream(); DataOutputStream out=new DataOutputStream(bytes); out.writeUTF("Connect"); out.writeUTF(server); - player.sendPluginMessage(this,"BungeeCord",bytes.toByteArray()); player.sendMessage("Guild departure requested. If you remain here, the destination or proxy is unavailable."); - } catch(IOException ex) { player.sendMessage("Guild departure could not be requested."); } - }); + // Boarding remains with the authenticated current Guild quote and confirmation flow. + if (!player.performCommand("dunerealmsgui:guildtravel")) + player.sendMessage("The Spacing Guild menu is temporarily unavailable."); } @EventHandler public void drag(InventoryDragEvent e) { if(e.getView().getTopInventory().getHolder() instanceof TravelMenu) e.setCancelled(true); } @EventHandler public void quit(PlayerQuitEvent e) { travelCooldown.remove(e.getPlayer().getUniqueId()); } diff --git a/DuneMenus/docs/menu-audit-20261205.json b/DuneMenus/docs/menu-audit-20261205.json new file mode 100644 index 00000000..076197e9 --- /dev/null +++ b/DuneMenus/docs/menu-audit-20261205.json @@ -0,0 +1,91 @@ +{ + "scope": "Current six Paper backends; source routes and saved Citizens records; no production payments or quest claims executed", + "menuFamilies": [ + "hub", + "travel", + "exchange", + "clan", + "company", + "missions", + "spice", + "war", + "politics", + "house", + "equipment", + "bank", + "atm", + "withdraw", + "transfer" + ], + "nativeServiceRoutes": [ + "hub", + "travel", + "exchange", + "clan", + "company", + "missions", + "spice", + "war", + "politics", + "lore", + "cookbook", + "mentat", + "house", + "equipment" + ], + "repairs": [ + "Explicit current Exchange Broker command", + "Departure pads open current authenticated Guild menu without legacy direct teleport fallback", + "Guild return menu gains Back to Imperial Codex", + "Empty NPC mission views link to the current mission journal", + "Cookbook command offered in completion and explicit Codex route", + "Permission refusal produces feedback instead of a silent menu" + ], + "guild": { + "primaryWorldsWithSavedNavigator": [ + "arrakis", + "caladan", + "giedi_prime", + "kaitain", + "sigma_draconis_iv" + ], + "lobby": "Guild Navigator Liaison", + "enabledOnAllSix": true, + "otherDimensions": "Guild command and marked-NPC handler are world independent; outside guild_lobby the menu presents the existing central return operation. No new NPC spawned or travel authority bypassed." + }, + "npcPurposeReview": { + "savedRecords": 45, + "snapshotCaution": "Disk registry snapshot is not a fresh connected-client or spawned-entity census.", + "legacyCopies": { + "lobby_arrakis": { + "unmappedQuestRoles": [ + "esmar_tuek", + "stilgar", + "shadout_mapes", + "chani", + "liet_kynes", + "alia_atreides", + "war_marshal" + ], + "ambientSmugglerCopies": 3 + }, + "lobby_base": { + "quartermasterCopy": 1 + } + }, + "clarity": "Water and spice sellers in Guild Lobby barter explicitly non-redeemable samples; they are not the Arrakis Melange buyers. Dynamic Home Block NPC retains its organisation service. Fixed Esmar starts contracts, Staban receives deliveries. No NPC records removed.", + "conditionalRoleReview": { + "glossu_rabban": "No built-in branch or fixed decision entry; central dossier/cargo assignments may still give this role work. Verify catalogue before removal.", + "irulan_corrino": "No built-in branch or fixed decision entry; central dossier/cargo assignments may still give this role work. Verify catalogue before removal." + } + }, + "notClaimed": "Full live client coverage across every faction, permission, quest state, Java and Bedrock remains a separate player validation; fixtures do not spend money, advance quests, or transfer live players.", + "localValidation": { + "unitTests": 252, + "failed": 0, + "renderedControls": 334, + "renderer": "Exact installed MCGUI 0.8.6", + "standardCardWidthAndHeightRatio": 0.75, + "retainedVariants": "Lobby and planet GUI/Menu classes assembled without unrelated archive changes; method-level audit excludes only explicit target methods." + } +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/DuneMenusPlugin.java b/DuneMenus/src/main/java/com/dunerealms/menus/DuneMenusPlugin.java index dcdef0e9..f06a89ee 100644 --- a/DuneMenus/src/main/java/com/dunerealms/menus/DuneMenusPlugin.java +++ b/DuneMenus/src/main/java/com/dunerealms/menus/DuneMenusPlugin.java @@ -112,12 +112,14 @@ public final class DuneMenusPlugin extends JavaPlugin implements TabExecutor { public void openMenu(Player player, String menu) { if (player.hasPermission("dunemenus.use")) create(menu, player, null).open(); + else player.sendMessage("You do not have permission to open this menu."); } public void presentService(Player player, String section, String title, String description, org.bukkit.inventory.Inventory inventory, Map actions) { if (player.hasPermission("dunemenus.use")) new ServiceMenu(this, player, section, title, description, inventory, actions).open(); + else player.sendMessage("You do not have permission to open this menu."); } void organisationServices(Player player,String kind,String id) { @@ -229,7 +231,7 @@ public final class DuneMenusPlugin extends JavaPlugin implements TabExecutor { @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", "cookbook")) .filter(x -> x.startsWith(a[0].toLowerCase())).toList(); } } diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/MenuPolish.java b/DuneMenus/src/main/java/com/dunerealms/menus/MenuPolish.java new file mode 100644 index 00000000..1dc6f85f --- /dev/null +++ b/DuneMenus/src/main/java/com/dunerealms/menus/MenuPolish.java @@ -0,0 +1,38 @@ +package com.dunerealms.menus; + +/** Presentation only: original slot identifiers and callbacks remain unchanged. */ +final class MenuPolish { + private MenuPolish() {} + static String apply(String html) { + if (html.contains("/* compact-dune-cards */")) return html; + return html.replace("", "/* compact-dune-cards */" + CSS + ""); + } + private static final String CSS = """ + +/* Compact service cards: 75% of their previous dimensions; retain the Dune palette. */ +.card{width:13.875%;height:103.5px;padding:5px;border-radius:8px;box-shadow:inset 0 0 0 1px #0a231f,0 2px 6px #071713} +.card:hover{box-shadow:inset 0 0 0 1px #0a231f,0 2px 8px #071713} +.hub .card{width:13.875%;min-height:66.75px}.journal .card{width:23.25%;height:103.5px;min-height:51px;padding:6px} +.council .card{width:25.875%;height:103.5px;min-height:86.25px}.bank .card{width:18%;min-height:75px} +.card .emblem{font-size:19.5px;width:24px;height:24px;line-height:20px;padding:1px;margin:0 auto 2px;border-radius:6px;box-shadow:none;text-shadow:none} +.card .item-icon{width:20px;height:20px}.card h2{font-size:11.5px;line-height:1.15;height:26.45px;overflow:hidden;margin:0 0 2px}.card p{font-size:9.5px;line-height:1.2;max-height:22.8px;overflow:hidden;margin:1px 0}.card p+p{max-height:11.4px}.house-choices .card p{max-height:11.4px}.locked.card{height:auto;min-height:103.5px}.locked.card p{max-height:none} +.house-choices .card{width:19.5%;height:78.75px;min-height:78.75px}.house-choices .card h2{font-size:11px} +.house-choices .card .emblem{font-size:19.5px;width:24px;height:24px;line-height:20px}.house-choices .card .item-icon{width:20px;height:20px} +.constellation{height:auto;min-height:262.5px;display:flex;flex-wrap:wrap;gap:12px;justify-content:center;align-items:flex-start;align-content:flex-start;padding:12px 0 36px} +.constellation .card{position:relative;top:auto;left:auto;right:auto;width:129.75px;height:54px;min-height:54px;padding:6px;border-radius:8px} +.constellation .locked.card{height:auto;min-height:63px}.constellation .back{position:absolute;bottom:0;left:0} +.detail-link{right:4px;top:4px;font-size:8px;padding:1px 3px;border-radius:5px} +.goods{width:75%;margin:0 auto;gap:12px}.travel .goods{gap:18px}.community .goods{gap:15px}.quest .goods{gap:7.5px}.hub .goods{max-width:637.5px;width:75%} +.slot{min-height:93px;padding:8.25px 5px 7.5px;border-width:2px;border-radius:8px;box-shadow:inset 0 0 0 1px #081d1b,0 2px 5px #091d17} +.slot:hover,.slot.selected{box-shadow:inset 0 0 0 1px #081d1b,0 2px 7px #091d17} +.hub .slot{min-height:99px}.slot strong,.hub .slot strong{font-size:12px;line-height:1.2;overflow-wrap:break-word} +.slot .cubby,.travel .cubby{width:36px;height:36px;border-radius:7px}.slot .cubby img{width:30px;height:30px} +.travel .slot{min-height:108.75px}.quest .slot{min-height:57.75px;padding:5px 11.25px;grid-template-columns:42.75px 1fr;column-gap:9.75px} +.quest .slot strong{font-size:15px}.quest .slot .cubby{width:36px;height:36px}.slot .tag{font-size:10px;margin-top:4.5px}.slot .cubby{margin-bottom:5.25px}.quest .slot .cubby{margin:0} +.mission{width:72%;min-height:27px;padding:5px 11px;font-size:12px;border-width:1px;border-radius:6px} +.mission span{font-size:11px}.primary{width:60%;min-height:32.25px;padding:5px 11px;font-size:15px;border-width:1px;border-radius:6px} +.secondary{width:54%;min-height:24.75px;padding:4.5px 11px;font-size:11.25px;border-width:1px;border-radius:6px} +.slots{width:75%;margin:0 auto;gap:5.25px}.member{min-height:35.25px;border-radius:6px;font-size:11px}.member .number{width:17.25px;padding:4.5px 0;font-size:9px} +@media(max-width:600px){.goods,.hub .goods{width:100%}.slot strong,.hub .slot strong{font-size:12px}} + """; +} diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/SuppliedDocument.java b/DuneMenus/src/main/java/com/dunerealms/menus/SuppliedDocument.java index f33c2cdb..78a83488 100644 --- a/DuneMenus/src/main/java/com/dunerealms/menus/SuppliedDocument.java +++ b/DuneMenus/src/main/java/com/dunerealms/menus/SuppliedDocument.java @@ -36,7 +36,7 @@ final class SuppliedDocument { b.append("
");int index=0; int summaryLimit=id.equals("exchange")?2:1; for(Card c:cards){b.append(c.enabled()?"":"");} - b.append("
");for(String line:info)b.append("

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

");return b.append("
◆ J.A.R.V.I.S. ◆THE SPICE MUST FLOW
").toString(); + b.append("
");for(String line:info)b.append("

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

");return MenuPolish.apply(b.append("
◆ J.A.R.V.I.S. ◆THE SPICE MUST FLOW
").toString()); } private static final String CSS=""" .locked.card,.constellation .locked.card{color:#c0c4c8;background:#262c30;border-color:#72777a}.locked.card p{color:#c0c4c8}.constellation .locked.card{height:84px} .rihla-brand{height:62px;overflow:hidden;background:#faf6ed;border:1px solid #b59349}.rihla-logo{display:block;width:146px;height:auto;align-self:flex-start}.cash-controls{display:flex;justify-content:space-between;position:relative;z-index:3;padding:10px 0}.cash-action{border:1px solid #c6a154;background:#123b2d;padding:12px 24px;font-size:16px}.cash-action[data-slot='24']{order:2;background:#3f5a26}.cash-action[data-slot='36']{order:1}.receipt .facts{background:#102a24;border:1px solid #b59349;padding:18px;margin:12px auto;max-width:650px}.receipt .facts p{font-size:14px;line-height:1.6} *{box-sizing:border-box}body{margin:0;padding:12px;background:#03100f;color:#f1e7cd;font-family:Georgia,serif;font-size:13px}button{font-family:Georgia,serif;color:#f4df9d;cursor:pointer}.frame{min-height:570px;border:2px solid #b69149;outline:1px solid #645334;outline-offset:5px;background:#081e1b;position:relative;overflow:hidden}header{height:78px;border-bottom:2px solid #ae8943;background:linear-gradient(90deg,#102f29,#041512);display:flex;align-items:center;padding:8px 22px;gap:22px}.brand{display:flex;align-items:center;gap:8px;color:#d6ad58;font-size:38px;border-right:1px solid #7c683b;padding-right:20px}.brand span{font-size:16px;line-height:17px;letter-spacing:3px}.heading{flex:1}small{font-size:10px;letter-spacing:3px;color:#ad985f}h1{font-size:26px;margin:5px 0 0;color:#eed995;letter-spacing:1px}.close{width:31px;height:31px;border:1px solid #a58b4d;background:#112922;font-size:24px}.scene{position:relative;min-height:411px;padding:0 28px;overflow:hidden;background:linear-gradient(#162d30,#53665a 58%,#a88c52)}.quote{text-align:center;font-style:italic;position:relative;z-index:1;padding:12px 0 8px;margin:0;color:#f4e7bf}.dune{position:absolute;left:-12%;width:125%;height:180px;border-radius:55% 70% 0 0;pointer-events:none}.rear{bottom:0;background:#b4955a;transform:rotate(-8deg)}.front{bottom:-90px;background:#635a38;transform:rotate(9deg)}.moon{position:absolute;right:15%;top:23px;background:#e4dbb6;border-radius:50%;width:45px;height:45px;opacity:.55}main{position:relative;z-index:2}.doors,.bank{display:flex;flex-wrap:wrap;gap:12px;justify-content:center;align-items:flex-start;padding:12px 0 35px}.card{background:linear-gradient(135deg,#173e35,#0c201d);border:1px solid #b59349;box-shadow:inset 0 0 0 3px #0a231f,0 3px 8px #071713;padding:9px;height:140px;position:relative;display:block;text-align:left;width:16.875%;overflow:hidden}.card>div{width:100%;min-width:0}.card .emblem{display:block;width:38px;height:38px;line-height:32px;margin:0 auto 4px;padding:2px;border:1px solid #8b784c;background:#09251f;box-shadow:inset 0 0 0 2px #143a30;text-align:center}.market-tools{display:flex;flex-wrap:wrap;gap:8px;justify-content:center;position:relative;z-index:2;padding:8px 0}.market-tool{display:flex;align-items:center;gap:6px;border:1px solid #8b784c;background:#12352c;padding:6px 10px;font-size:11px}.tool-icon{display:block;width:24px;height:24px;line-height:24px;text-align:center}.tool-icon .item-icon{width:24px;height:24px}.detail-link{position:absolute;right:10px;top:10px;font-size:10px;padding:4px 6px;border:1px solid #8b784c;background:#163a30;color:#e4cd91}.detail-link:hover{background:#315c45}.item-icon{width:32px;height:32px;object-fit:contain;image-rendering:pixelated}.brand-logo{width:158px;height:58px;object-fit:contain}.brand{width:180px;flex-shrink:0;padding-right:0;justify-content:center}.card h2{line-height:1.2}.card p{line-height:1.25;white-space:normal;overflow-wrap:break-word}.item-details{border:1px solid #786338;background:#102a24;margin-top:12px;padding:16px}.item-details p{overflow-wrap:break-word}.card h2{overflow-wrap:break-word;white-space:normal}.card:hover{background:linear-gradient(135deg,#315c45,#183c32);border-color:#f3d784}.emblem{font-size:26px;color:var(--accent);width:35px;flex-shrink:0;text-align:center}h2{font-size:14px;margin:0 0 6px}p{margin:2px 0;font-size:10px;line-height:1.35;color:#d1d3bc}.back{position:absolute;bottom:2px;left:0;background:#12372c;border:1px solid #ad8c48;padding:7px 12px;display:flex;align-items:center;gap:8px}.pager{border:1px solid #ad8c48;background:#12372c;padding:10px;display:flex;gap:8px;align-items:center}.back .emblem,.pager .emblem{font-size:17px;width:22px;height:22px;line-height:18px;border:0;padding:0;margin:0;box-shadow:none;background:transparent}.back .item-icon,.pager .item-icon{width:20px;height:20px}.back h2{margin:0;font-size:12px}.back p{display:none}.hub .card{width:16.5%;min-height:89px}.hub .emblem{font-size:26px}.journal{display:flex;flex-wrap:wrap;justify-content:center;gap:12px;padding:8px 0 45px}.journal .card{width:30%;height:140px;min-height:68px;padding:9px}.journal .card p{display:block;margin:2px 0}.council{display:flex;flex-wrap:wrap;gap:16px;justify-content:center;padding:20px 8% 44px}.council .card{width:34.5%;height:140px;min-height:115px;border-top:3px solid var(--accent)}.bank .card{width:22.5%;min-height:100px}.travel .scene{background:radial-gradient(ellipse at center,#123a40,#061317)}.travel .dune,.travel .moon{display:none}.constellation{height:350px;position:relative}.constellation .card{position:absolute;width:173px;height:72px;min-height:68px;border-color:#74aeb6;background:linear-gradient(135deg,#173e43,#091c23)}.constellation .card .emblem{display:none}.constellation .n0{top:0;left:36%}.constellation .n1{top:98px;left:0}.constellation .n2{top:98px;right:0}.constellation .n3{top:225px;left:12%}.constellation .n4{top:225px;right:12%}.constellation .back{bottom:0}.guild{position:absolute;top:168px;left:44%;font-size:52px;color:#c4dcdf;text-align:center}.guild span{display:block;font-size:11px;letter-spacing:2px}.orbit{position:absolute;border:1px solid #467b84;width:62%;height:170px;top:130px;left:19%;border-radius:50%;transform:rotate(24deg)}.orbit.two{transform:rotate(-24deg)}footer{height:76px;padding:9px 22px;background:#0b211c;border-top:1px solid #a88b47;display:flex;align-items:center;gap:22px}.facts{position:relative;padding:12px 0 24px;z-index:2}.facts p{font-size:11px;color:#c0c9b2}.seal{font-size:10px;letter-spacing:2px;color:#bda464}.war .scene{background:linear-gradient(#2e2424,#182c26)}.spice .scene{background:linear-gradient(#715232,#bc9251)}.politics .scene{background:linear-gradient(#2f2444,#132c27)} diff --git a/DuneMenus/src/rendererTest/java/com/dunerealms/menus/RendererVerification.java b/DuneMenus/src/rendererTest/java/com/dunerealms/menus/RendererVerification.java index 85ff7960..356ca93f 100644 --- a/DuneMenus/src/rendererTest/java/com/dunerealms/menus/RendererVerification.java +++ b/DuneMenus/src/rendererTest/java/com/dunerealms/menus/RendererVerification.java @@ -27,7 +27,26 @@ public class RendererVerification { String html=SuppliedDocument.html(id,"DuneRealms · "+id,"Service information",cards,List.of("Read-only account and permission details")); Path file=dir.resolve(id+"-matrix.html");Files.writeString(file,html);var page=Page.of(html,file,loader);var frame=HtmlRenderer.render(page,1536,896,1.5,0,Selector.State.NONE); if(!page.problems.isEmpty())throw new AssertionError(id+" parser problems "+page.problems); + int marker=html.indexOf("/* compact-dune-cards */"),styleEnd=html.indexOf("",marker); + String baseline=html.substring(0,marker)+html.substring(styleEnd); + var oldPage=Page.of(baseline,dir.resolve(id+"-before.html"),loader); + var oldFrame=HtmlRenderer.render(oldPage,1536,896,1.5,0,Selector.State.NONE); + var oldBox=oldFrame.boundsOf(oldPage.document.selectFirst("main .card")); + var newBox=frame.boundsOf(page.document.selectFirst("main .card")); + if(Math.abs(newBox.getWidth()/oldBox.getWidth()-.75)>.002 || Math.abs(newBox.getHeight()/oldBox.getHeight()-.75)>.002) + throw new AssertionError(id+" card size must be 75%: "+oldBox+" -> "+newBox); + ImageIO.write(frame.image(),"png",dir.resolve(id+"-matrix-engine.png").toFile()); + int styleClose=html.indexOf(""); + String withoutTextClipping=html.substring(0,styleClose)+".card p,.card p+p,.house-choices .card p{max-height:none;overflow:visible}"+html.substring(styleClose); + var fullPage=Page.of(withoutTextClipping,dir.resolve(id+"-full-money.html"),loader); + var fullFrame=HtmlRenderer.render(fullPage,1536,896,1.5,0,Selector.State.NONE); + var displayed=page.document.select("main .card p");var complete=fullPage.document.select("main .card p"); + for(int n=0;n",readOnlyMarker); + var readOnlyBefore=Page.of(readOnlyHtml.substring(0,readOnlyMarker)+readOnlyHtml.substring(readOnlyEnd),dir.resolve("read-only-before.html"),loader); + var readOnlyOldFrame=HtmlRenderer.render(readOnlyBefore,1536,896,1.5,0,Selector.State.NONE); + var readOnlyBox=readOnlyFrame.boundsOf(readOnlyPage.document.selectFirst("main .card"));var readOnlyOldBox=readOnlyOldFrame.boundsOf(readOnlyBefore.document.selectFirst("main .card")); + if(Math.abs(readOnlyBox.getHeight()/readOnlyOldBox.getHeight()-.75)>.002 || !readOnlyPage.document.select("main [data-slot]").isEmpty())throw new AssertionError("Read-only card sizing or authority changed"); verifyNavigators(dir,loader); verifyHouseChoices(dir,loader); var actualIcon=Path.of("../network/resource-pack/central/overlay/assets/dunerealms/textures/item/equipment/legendary_mk14_axe.png");Path iconTarget=dir.resolve("pack/assets/dunerealms/textures/item/equipment/legendary_mk14_axe.png");Files.createDirectories(iconTarget.getParent());Files.copy(actualIcon,iconTarget,StandardCopyOption.REPLACE_EXISTING); @@ -78,9 +104,10 @@ public class RendererVerification { throw new AssertionError("House text outside card: "+bounds+" vs "+box); } } - if(onFirstRow!=3)throw new AssertionError("Expected three House cards across, got "+onFirstRow); + int expectedColumns=page.document.selectFirst("main").hasClass("house-choices")?4:3; + if(onFirstRow!=expectedColumns)throw new AssertionError("Expected "+expectedColumns+" compact House cards across, got "+onFirstRow); ImageIO.write(frame.image(),"png",dir.resolve("house-choices-engine.png").toFile()); - System.out.println("House selector: five original actions, three columns, contained text"); + System.out.println("House selector: five original actions, variant-preserving compact columns, contained text"); } private static void verifyNavigators(Path dir,Page.Loader loader)throws Exception{ diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/DuneCore.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/DuneCore.java index 1bb2b3ad..d94da43b 100644 --- a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/DuneCore.java +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/DuneCore.java @@ -74,6 +74,12 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu sharedDatabase.transaction(player, selected, operation); } + public UUID freezeBuilderProfile(Player player) throws Exception { + if (sharedDatabase == null) throw new java.sql.SQLException("Shared profile unavailable"); + restoreOrdosArmor(player.getUniqueId()); + return sharedDatabase.freezeBuilderProfile(player, selected); + } + public Politics politics(){return politics;} public String factionOf(Player player){return selected.getOrDefault(player.getUniqueId(),"");} public void persistPlayers(){savePlayers();} diff --git a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/SharedDatabase.java b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/SharedDatabase.java index 3f77566f..f253aab9 100644 --- a/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/SharedDatabase.java +++ b/DuneRealms-minecraft-only/src/main/java/com/example/dunerealms/SharedDatabase.java @@ -18,6 +18,8 @@ public final class SharedDatabase implements AutoCloseable { private final String url, user, password; // Main-thread only. A dedicated connection owns the advisory lock until quit. private final Map sessions = new HashMap<>(); + private record BuilderLease(UUID token, Connection connection) {} + private final Map builderLeases = new HashMap<>(); public SharedDatabase(JavaPlugin plugin) throws SQLException { this.plugin = plugin; @@ -128,6 +130,89 @@ public final class SharedDatabase implements AutoCloseable { } } + /** Durably checkpoint the survival profile before any Builder inventory changes. */ + public UUID freezeBuilderProfile(Player player, Map factions) throws Exception { + UUID id = player.getUniqueId(); + Connection connection = sessions.get(id); + if (connection == null || connection.isClosed() || !connection.getAutoCommit() || builderLeases.containsKey(id)) { + throw new SQLException("An owned, unfrozen shared profile is required"); + } + player.closeInventory(); + writePlayer(player, factions, false); + UUID token = UUID.randomUUID(); + builderLeases.put(id, new BuilderLease(token, connection)); + return token; + } + + /** Read the committed survival checkpoint using the same profile-owning connection. */ + public void thawBuilderProfile(Player player, UUID token) throws Exception { + UUID id = player.getUniqueId(); + BuilderLease lease = builderLeases.get(id); + Connection connection = sessions.get(id); + if (lease == null || !lease.token().equals(token) || lease.connection() != connection + || connection.isClosed() || !connection.getAutoCommit()) { + throw new SQLException("The Builder checkpoint no longer belongs to this session"); + } + ItemStack[] inventory; + int level, total, slot; + float progress; + try (PreparedStatement query = connection.prepareStatement( + "SELECT inventory,experience_level,experience_progress,total_experience,held_slot FROM dune_players WHERE uuid=? AND session_open=TRUE")) { + bindBuilderUuid(query, connection, id); + try (ResultSet row = query.executeQuery()) { + if (!row.next()) throw new SQLException("Committed Builder checkpoint is missing"); + inventory = decode(row.getString("inventory")); + level = row.getInt("experience_level"); + progress = row.getFloat("experience_progress"); + total = row.getInt("total_experience"); + slot = row.getInt("held_slot"); + } + } + if (inventory.length != player.getInventory().getContents().length || level < 0 || total < 0 + || !Float.isFinite(progress) || progress < 0 || progress >= 1 || slot < 0 || slot > 8) { + throw new IOException("Invalid committed Builder checkpoint"); + } + player.getInventory().setContents(inventory); + player.setLevel(level); + player.setExp(progress); + player.setTotalExperience(total); + player.getInventory().setHeldItemSlot(slot); + builderLeases.remove(id); + } + + private static void bindBuilderUuid(PreparedStatement query, Connection connection, UUID id) throws SQLException { + if (connection.getMetaData().getDatabaseProductName().equalsIgnoreCase("PostgreSQL")) query.setObject(1, id); + else query.setString(1, id.toString()); + } + + private boolean preserveFrozenBuilderProfile(Player player, Connection connection, boolean release) throws SQLException { + UUID id = player.getUniqueId(); + BuilderLease lease = builderLeases.get(id); + if (lease == null) return false; + if (lease.connection() != connection || connection.isClosed() || !connection.getAutoCommit()) { + throw new SQLException("The Builder profile connection is no longer owned"); + } + if (release) { + // The survival checkpoint is already durable. Never serialize creative inventory on quit. + try (PreparedStatement query = connection.prepareStatement( + "UPDATE dune_players SET session_open=FALSE WHERE uuid=? AND session_open=TRUE")) { + bindBuilderUuid(query, connection, id); + if (query.executeUpdate() != 1) throw new SQLException("Could not close the Builder profile checkpoint"); + } + } + return true; + } + + private void requireUnfrozenBuilderProfile(Player player) throws SQLException { + if (builderLeases.containsKey(player.getUniqueId())) { + throw new SQLException("Inventory transactions are unavailable in Builder"); + } + } + + private void forgetBuilderProfile(Player player) { + builderLeases.remove(player.getUniqueId()); + } + public void savePlayer(Player p, Map factions) throws Exception { writePlayer(p, factions, false); } @@ -139,6 +224,7 @@ public final class SharedDatabase implements AutoCloseable { p.closeInventory(); // Return cursor and crafting items before the final snapshot. writePlayer(p, factions, true); } finally { + forgetBuilderProfile(p); Connection c = sessions.remove(p.getUniqueId()); if (c != null) c.close(); } @@ -146,7 +232,7 @@ public final class SharedDatabase implements AutoCloseable { private void writePlayer(Player p, Map factions, boolean release) throws Exception { Connection c = sessions.get(p.getUniqueId()); - if (c == null) return; + if (c == null || preserveFrozenBuilderProfile(p, c, release)) return; // Never reconnect here: a replacement connection would not own the session lock. String inventory = encode(p.getInventory().getContents()); try (PreparedStatement q = c.prepareStatement( @@ -184,6 +270,7 @@ public final class SharedDatabase implements AutoCloseable { public void transaction(Player p, Map factions, java.util.function.Consumer operation) throws Exception { Connection c = sessions.get(p.getUniqueId()); if (c == null) throw new SQLException("A loaded shared network profile is required to trade"); + requireUnfrozenBuilderProfile(p); ItemStack[] before = Arrays.stream(p.getInventory().getContents()) .map(item -> item == null ? null : item.clone()).toArray(ItemStack[]::new); int priorLevel=p.getLevel(),priorTotal=p.getTotalExperience();float priorProgress=p.getExp(); @@ -221,6 +308,7 @@ public final class SharedDatabase implements AutoCloseable { for (Connection c : sessions.values()) try { c.close(); } catch (SQLException ex) { plugin.getLogger().warning("Profile connection close failed: " + ex.getMessage()); } sessions.clear(); + builderLeases.clear(); } public String loadPolitics() throws SQLException { diff --git a/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/SharedDatabaseTest.java b/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/SharedDatabaseTest.java index 262f2c29..7dde71e5 100644 --- a/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/SharedDatabaseTest.java +++ b/DuneRealms-minecraft-only/src/test/java/com/example/dunerealms/SharedDatabaseTest.java @@ -79,6 +79,47 @@ class SharedDatabaseTest { DriverManager.deregisterDriver(driver); } + @Test void builderCheckpointRejectsCreativeWritesAndRestoresCommittedInventory() throws Exception { + db.loadPlayer(player, factions); + when(owner.getAutoCommit()).thenReturn(true); + var meta = mock(DatabaseMetaData.class); + when(meta.getDatabaseProductName()).thenReturn("PostgreSQL"); + when(owner.getMetaData()).thenReturn(meta); + var encoded = org.mockito.ArgumentCaptor.forClass(String.class); + UUID token = db.freezeBuilderProfile(player, factions); + assertNotNull(token); + verify(update, atLeastOnce()).setString(eq(2), encoded.capture()); + var checkpoint = encoded.getValue(); + assertNotNull(checkpoint); + clearInvocations(update, inventory); + db.savePlayer(player, factions); + assertThrows(SQLException.class, () -> db.transaction(player, Map.of(), connection -> fail("creative transaction ran"))); + assertThrows(SQLException.class, () -> db.thawBuilderProfile(player, UUID.randomUUID())); + verifyNoInteractions(update, inventory); + when(update.executeQuery()).thenReturn(profile); + when(profile.getString("inventory")).thenReturn(checkpoint); + db.thawBuilderProfile(player, token); + verify(inventory).setContents(any(ItemStack[].class)); + db.savePlayer(player, factions); + verify(update).setString(eq(2), anyString()); + } + + @Test void quittingBuilderClosesOnlyTheDurableMarker() throws Exception { + db.loadPlayer(player, factions); + when(owner.getAutoCommit()).thenReturn(true); + var meta = mock(DatabaseMetaData.class); + when(meta.getDatabaseProductName()).thenReturn("PostgreSQL"); + when(owner.getMetaData()).thenReturn(meta); + db.freezeBuilderProfile(player, factions); + clearInvocations(owner, update, inventory); + db.releasePlayer(player, factions); + verify(owner).prepareStatement("UPDATE dune_players SET session_open=FALSE WHERE uuid=? AND session_open=TRUE"); + verify(update).setObject(1, id); + verify(update, never()).setString(eq(2), anyString()); + verifyNoInteractions(inventory); + assertFalse(db.isLoaded(id)); + } + @Test void failedLockNeverLoadsOrSavesLocalItems() throws Exception { when(lockResult.getBoolean(1)).thenReturn(false); assertThrows(SQLException.class, () -> db.loadPlayer(player, factions)); diff --git a/DuneRealmsGUI/build.gradle.kts b/DuneRealmsGUI/build.gradle.kts index e4f8d0b4..0cdbef67 100644 --- a/DuneRealmsGUI/build.gradle.kts +++ b/DuneRealmsGUI/build.gradle.kts @@ -1,3 +1,4 @@ +import java.security.MessageDigest plugins { java } group = "com.dunerealms" version = "1.1.41-house1" @@ -18,3 +19,28 @@ sourceSets.main { java.srcDirs("../citizens-common/src/main/java", "../pack-sess tasks.processResources { from(rootProject.file("../network/content-assets/cookbook/spice-crafting.json")) } + +val mcguiRuntime = providers.gradleProperty("mcguiRuntime") +val rendererRuntimeFiles = mcguiRuntime.map { files(it) }.getOrElse(files()) +val rendererTest by sourceSets.creating { + compileClasspath += sourceSets.main.get().output + rendererRuntimeFiles + runtimeClasspath += sourceSets.main.get().output + rendererRuntimeFiles +} +val verifyRendererRuntime by tasks.registering { + doLast { + require(mcguiRuntime.isPresent) { "Supply -PmcguiRuntime=" } + val jar = file(mcguiRuntime.get()) + require(jar.isFile) { "MCGUI runtime file not found" } + val hash = MessageDigest.getInstance("SHA-256").digest(jar.readBytes()).joinToString("") { "%02x".format(it) } + require(hash == "69a454291cc27c36cdbc680bfbde245a90a3913de53cc1591c502a5a49124300") { "MCGUI runtime differs from reviewed test input" } + logger.lifecycle("Renderer verification: MCGUI0.8.6 SHA-256 {}", hash) + } +} +tasks.named(rendererTest.compileJavaTaskName) { dependsOn(verifyRendererRuntime) } +tasks.register("verifyMenuRenderer") { + dependsOn(rendererTest.classesTaskName) + classpath = rendererTest.runtimeClasspath + mainClass.set("com.dunerealms.gui.CompactRendererVerification") + jvmArgs("-Djava.awt.headless=true") + args(providers.gradleProperty("rendererOutput").getOrElse(layout.buildDirectory.dir("renderer-verification").get().asFile.absolutePath)) +} diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java index 88e787a6..170cb8f3 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java @@ -148,6 +148,7 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto panel.inventory=Bukkit.createInventory(panel,54,Component.text(title,NamedTextColor.GOLD)); panel.inventory.setItem(22,icon(player,"Return to Guild Lobby",detail,"drgui_transparent",Material.COMPASS)); panel.actions.put(22,returnToLobby); + button(panel,player,45,"Back","Imperial Codex",Material.ARROW,()->organisations.console(player)); if(MCGUIMenus.show(player,title,detail,panel.inventory,panel.actions,panel.gate))return; player.openInventory(panel.inventory); expire(panel); diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/MenuDocument.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/MenuDocument.java index f2813d46..a392188f 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/MenuDocument.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/MenuDocument.java @@ -50,13 +50,13 @@ final class MenuDocument { String image=icon(c,root);b.append(""); }b.append(""); - b.append("
J.A.R.V.I.S. · Your realm, connectedClick an action · Scroll for more · Sneak to close
");return b.toString(); + b.append("
J.A.R.V.I.S. · Your realm, connectedClick an action · Scroll for more · Sneak to close
");return MenuPolish.apply(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(); + 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 MenuPolish.apply(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} @@ -73,7 +73,7 @@ final class MenuDocument { if(dashboard&&pick!=null)b.append(""); if(dashboard&&pick==null&&cards.stream().anyMatch(c->c.action&&c.slot>=9&&c.slot<45))b.append("

Select an entry to continue.

"); 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("Confirm and execute");b.append("");} - return b.append("
SHIFT TO CLOSE
").toString(); + return MenuPolish.apply(b.append("
SHIFT TO CLOSE
").toString()); } 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} diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/MenuPolish.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/MenuPolish.java new file mode 100644 index 00000000..2b918c1f --- /dev/null +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/MenuPolish.java @@ -0,0 +1,38 @@ +package com.dunerealms.gui; + +/** Presentation only: original slot identifiers and callbacks remain unchanged. */ +final class MenuPolish { + private MenuPolish() {} + static String apply(String html) { + if (html.contains("/* compact-dune-cards */")) return html; + return html.replace("", "/* compact-dune-cards */" + CSS + ""); + } + private static final String CSS = """ + +/* Compact service cards: 75% of their previous dimensions; retain the Dune palette. */ +.card{width:13.875%;height:103.5px;padding:5px;border-radius:8px;box-shadow:inset 0 0 0 1px #0a231f,0 2px 6px #071713} +.card:hover{box-shadow:inset 0 0 0 1px #0a231f,0 2px 8px #071713} +.hub .card{width:13.875%;min-height:66.75px}.journal .card{width:23.25%;height:103.5px;min-height:51px;padding:6px} +.council .card{width:25.875%;height:103.5px;min-height:86.25px}.bank .card{width:18%;min-height:75px} +.card .emblem{font-size:19.5px;width:24px;height:24px;line-height:20px;padding:1px;margin:0 auto 2px;border-radius:6px;box-shadow:none;text-shadow:none} +.card .item-icon{width:20px;height:20px}.card h2{font-size:11.5px;line-height:1.15;height:26.45px;overflow:hidden;margin:0 0 2px}.card p{font-size:9.5px;line-height:1.2;max-height:22.8px;overflow:hidden;margin:1px 0}.card p+p{max-height:11.4px}.house-choices .card p{max-height:11.4px}.locked.card{height:auto;min-height:103.5px}.locked.card p{max-height:none} +.house-choices .card{width:19.5%;height:78.75px;min-height:78.75px}.house-choices .card h2{font-size:11px} +.house-choices .card .emblem{font-size:19.5px;width:24px;height:24px;line-height:20px}.house-choices .card .item-icon{width:20px;height:20px} +.constellation{height:auto;min-height:262.5px;display:flex;flex-wrap:wrap;gap:12px;justify-content:center;align-items:flex-start;align-content:flex-start;padding:12px 0 36px} +.constellation .card{position:relative;top:auto;left:auto;right:auto;width:129.75px;height:54px;min-height:54px;padding:6px;border-radius:8px} +.constellation .locked.card{height:auto;min-height:63px}.constellation .back{position:absolute;bottom:0;left:0} +.detail-link{right:4px;top:4px;font-size:8px;padding:1px 3px;border-radius:5px} +.goods{width:75%;margin:0 auto;gap:12px}.travel .goods{gap:18px}.community .goods{gap:15px}.quest .goods{gap:7.5px}.hub .goods{max-width:637.5px;width:75%} +.slot{min-height:93px;padding:8.25px 5px 7.5px;border-width:2px;border-radius:8px;box-shadow:inset 0 0 0 1px #081d1b,0 2px 5px #091d17} +.slot:hover,.slot.selected{box-shadow:inset 0 0 0 1px #081d1b,0 2px 7px #091d17} +.hub .slot{min-height:99px}.slot strong,.hub .slot strong{font-size:12px;line-height:1.2;overflow-wrap:break-word} +.slot .cubby,.travel .cubby{width:36px;height:36px;border-radius:7px}.slot .cubby img{width:30px;height:30px} +.travel .slot{min-height:108.75px}.quest .slot{min-height:57.75px;padding:5px 11.25px;grid-template-columns:42.75px 1fr;column-gap:9.75px} +.quest .slot strong{font-size:15px}.quest .slot .cubby{width:36px;height:36px}.slot .tag{font-size:10px;margin-top:4.5px}.slot .cubby{margin-bottom:5.25px}.quest .slot .cubby{margin:0} +.mission{width:72%;min-height:27px;padding:5px 11px;font-size:12px;border-width:1px;border-radius:6px} +.mission span{font-size:11px}.primary{width:60%;min-height:32.25px;padding:5px 11px;font-size:15px;border-width:1px;border-radius:6px} +.secondary{width:54%;min-height:24.75px;padding:4.5px 11px;font-size:11.25px;border-width:1px;border-radius:6px} +.slots{width:75%;margin:0 auto;gap:5.25px}.member{min-height:35.25px;border-radius:6px;font-size:11px}.member .number{width:17.25px;padding:4.5px 0;font-size:9px} +@media(max-width:600px){.goods,.hub .goods{width:100%}.slot strong,.hub .slot strong{font-size:12px}} + """; +} diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/QuestMenus.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/QuestMenus.java index 782a5cf9..51f96be8 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/QuestMenus.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/QuestMenus.java @@ -58,7 +58,7 @@ final class QuestMenus implements Listener { if(selected!=null){var row=available.stream().filter(q->selected.equals(text(q,"id",""))).findFirst().orElse(null);if(row!=null){roleSelected(p,data,role,row);return;}} var screen=panel(p,"NPC dashboard · "+role.name());screen.description="";roleAvatar(screen,data,role);int active=0,ready=0,claimed=0;for(var e:data.getAsJsonArray("quests")){var q=e.getAsJsonObject();if(!roleAllowed(data,role,q))continue;if(text(q,"state","").equals("claimed"))claimed++;else if(yes(q,"canClaim"))ready++;else if(text(q,"state","").equals("active"))active++;}String stats=active+" active · "+ready+" ready · "+claimed+" claimed";if(data.has("npcSummary")&&data.get("npcSummary").isJsonObject()){var rep=data.getAsJsonObject("npcSummary");stats+="\nReputation "+text(rep,"xp","—")+" / "+text(rep,"nextXP","—");if(rep.has("percent")&&!rep.get("percent").isJsonNull())stats+="\nProgress: "+Math.max(0,Math.min(100,rep.get("percent").getAsInt()))+"%";}put(screen,5,"Mission overview",stats,Material.PAPER,null);var summary=screen.inventory.getItem(5);var meta=summary.getItemMeta();meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","menu_art"),org.bukkit.persistence.PersistentDataType.STRING,"npc_summary");summary.setItemMeta(meta);screen.inventory.setItem(5,summary);var ordered=new ArrayList(available);ordered.sort(Comparator.comparingInt(q->Set.of("active","completed").contains(text(q,"state",""))?0:1)); int slot=9;for(var q:ordered){if(slot>=45)break;String status=Set.of("active","completed").contains(text(q,"state",""))?"Progress: "+text(q,"progress","0")+" / "+text(q,"target","1"):"Eligible to accept";put(screen,slot++,text(q,"title","Mission"),status+"\n"+text(q,"id","")+" · "+text(q,"objective",""),Material.WRITABLE_BOOK,()->roleSelected(p,data,role,q));} - if(ordered.isEmpty())put(screen,13,"No eligible missions","Read the website journal for the full record.",Material.MAP,null); + if(ordered.isEmpty())put(screen,13,"Open your mission journal","No missions are available from this contact right now.\nBrowse your other story arcs and current objectives.",Material.MAP,()->open(p)); if(role.key().equals("esmar_tuek")){ put(screen,47,"Smuggler Navigator","Review personal passage to another world.",Material.COMPASS,()->smugglerMenu(p,data,role)); if(role.world().equals("arrakis"))put(screen,48,"Smuggling contracts","Start a delivery with Esmar Tuek",Material.CHEST,()->p.performCommand("dunenpc smuggle contract")); diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/SuppliedMenus.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/SuppliedMenus.java index ff60505d..8640046b 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/SuppliedMenus.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/SuppliedMenus.java @@ -8,9 +8,12 @@ final class SuppliedMenus { private SuppliedMenus(){} static boolean open(Player p,String id){return call("openMenu",new Class[]{Player.class,String.class},p,id);} static boolean command(Player p,String command,String[] args){ - String id=switch(command){case "exchange","spice","clan","company","house","mentat"->command;case "polgui"->"politics";case "warmuster"->"war";case "guildtravel"->args.length==0?"travel":null;case "drgui"->args.length==0?"hub":args.length==1?switch(args[0].toLowerCase(Locale.ROOT)){case "quests"->"missions";case "hub","travel","exchange","clan","company","missions","spice","war","politics","house","equipment","bank","atm","withdraw","lore","mentat"->args[0].toLowerCase(Locale.ROOT);default->null;}:null;default->null;}; + String id=route(command,args); return id!=null&&open(p,id); } + static String route(String command,String[] args){ + return switch(command){case "exchange","spice","clan","company","house","mentat"->command;case "polgui"->"politics";case "warmuster"->"war";case "guildtravel"->args.length==0?"travel":null;case "drgui"->args.length==0?"hub":args.length==1?switch(args[0].toLowerCase(Locale.ROOT)){case "quests"->"missions";case "hub","travel","exchange","clan","company","missions","spice","war","politics","house","equipment","bank","atm","withdraw","lore","cookbook","mentat"->args[0].toLowerCase(Locale.ROOT);default->null;}:null;default->null;}; + } static boolean service(Player p,String title,String description,Inventory inventory,Map actions,GuiSession supplied){ GuiSession gate=supplied==null?new GuiSession(p.getUniqueId()):supplied; Map guarded=new HashMap<>();actions.forEach((slot,action)->guarded.put(slot,()->{if(gate.claim(p.getUniqueId()))action.run();})); diff --git a/DuneRealmsGUI/src/rendererTest/java/com/dunerealms/gui/CompactRendererVerification.java b/DuneRealmsGUI/src/rendererTest/java/com/dunerealms/gui/CompactRendererVerification.java new file mode 100644 index 00000000..87c14573 --- /dev/null +++ b/DuneRealmsGUI/src/rendererTest/java/com/dunerealms/gui/CompactRendererVerification.java @@ -0,0 +1,44 @@ +package com.dunerealms.gui; +import java.nio.file.*;import java.util.*;import javax.imageio.ImageIO; +import ai.resourcepack.ui.html.*;import ai.resourcepack.ui.html.css.Selector; +public class CompactRendererVerification { + public static void main(String[] args)throws Exception{ + Path out=Path.of(args[0]);Files.createDirectories(out);var loader=new Page.Loader(false,out.resolve("cache"));int checked=0; + Files.createDirectories(out.resolve("art")); + for(Path source:List.of(Path.of("../DuneMenus/src/main/resources/menu-art/art"),Path.of("src/main/resources/mcgui-npc-avatars"))) + try(var paths=Files.list(source)){for(Path file:paths.filter(Files::isRegularFile).toList())Files.copy(file,out.resolve("art").resolve(file.getFileName()),StandardCopyOption.REPLACE_EXISTING);} + var cards=new ArrayList(); + for(int n=0;n<12;n++)cards.add(new MenuDocument.Card(n,"Service "+n,List.of("Authoritative service detail","100.00 DM"),"book",1,true,"")); + cards.add(new MenuDocument.Card(45,"Back",List.of(),"arrow",1,true,"")); + for(String title:List.of("Imperial Codex","Equipment","Spacing Guild","Mission journal","Clan","Company","Political offices","Exchange","Rihla ATM","NPC dashboard · Adviser","NPC turn-in · Adviser","War Muster Room")){ + var rows=cards; + if(title.equals("War Muster Room")){ + rows=new ArrayList<>();rows.add(new MenuDocument.Card(2,"Blue · Own",List.of("Your team"),"blue_banner",1,false,"")); + rows.add(new MenuDocument.Card(6,"Red · Opponent",List.of("Read only"),"red_banner",1,false,"")); + for(int slot:new int[]{19,20,21,22,28,29,30,31})rows.add(new MenuDocument.Card(slot,"Member",List.of(),"player_head",1,true,"")); + for(int slot:new int[]{45,47,49})rows.add(new MenuDocument.Card(slot,"Action",List.of(),"arrow",1,true,"")); + } + String html=MenuDocument.html(title,"Current verified services","Fixture",rows,-1,out); + var page=Page.of(html,out.resolve(title.hashCode()+".html"),loader);var frame=HtmlRenderer.render(page,1536,896,1.5,0,Selector.State.NONE); + if(!page.problems.isEmpty())throw new AssertionError(title+page.problems.toString()); + if(page.document.selectFirst(".slot")!=null){ + int marker=html.indexOf("/* compact-dune-cards */"),end=html.indexOf("",marker); + var oldPage=Page.of(html.substring(0,marker)+html.substring(end),out.resolve("before-"+title.hashCode()+".html"),loader); + var oldFrame=HtmlRenderer.render(oldPage,1536,896,1.5,0,Selector.State.NONE); + var before=oldFrame.boundsOf(oldPage.document.selectFirst(".slot"));var after=frame.boundsOf(page.document.selectFirst(".slot")); + if(Math.abs(after.getWidth()/before.getWidth()-.75)>.002 || Math.abs(after.getHeight()/before.getHeight()-.75)>.002)throw new AssertionError(title+" expected 75% card dimensions "+before+" -> "+after); + System.out.println(title+" scale width="+after.getWidth()/before.getWidth()+" height="+after.getHeight()/before.getHeight()); + } + var controls=page.document.select("[data-slot],[data-pick]");if(controls.isEmpty())throw new AssertionError(title+" no controls"); + for(var element:controls){var box=frame.boundsOf(element);if(box==null||box.isEmpty())throw new AssertionError(title+" hidden control"); + double scroll=Math.max(0,Math.min(frame.maxScroll(),box.getCenterY()-260)); + var visible=HtmlRenderer.render(page,1536,896,1.5,scroll,Selector.State.NONE);var hit=visible.elementAt(box.getCenterX(),box.getCenterY()-scroll); + if(hit==null || hit.closest("[data-slot],[data-pick]")!=element)throw new AssertionError(title+" unreachable "+element+" box="+box); + checked++; + } + ImageIO.write(frame.image(),"png",out.resolve(title.hashCode()+".png").toFile()); + System.out.println(title+": "+controls.size()+" controls reachable"); + } + System.out.println("PASS "+checked+" native/fallback UI controls"); + } +} diff --git a/DuneRealmsGUI/src/test/java/com/dunerealms/gui/MenuEntryRoutesTest.java b/DuneRealmsGUI/src/test/java/com/dunerealms/gui/MenuEntryRoutesTest.java new file mode 100644 index 00000000..5b466d89 --- /dev/null +++ b/DuneRealmsGUI/src/test/java/com/dunerealms/gui/MenuEntryRoutesTest.java @@ -0,0 +1,18 @@ +package com.dunerealms.gui; +import java.util.Set; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +class MenuEntryRoutesTest { + @Test void everyCodexServiceHasAnExplicitEntryIncludingCookbook(){ + for(String id:Set.of("hub","travel","exchange","clan","company","missions","spice","war","politics","house","equipment","bank","atm","withdraw","lore","cookbook","mentat")) + assertEquals(id,SuppliedMenus.route("drgui",new String[]{id}),id); + assertEquals("missions",SuppliedMenus.route("drgui",new String[]{"quests"})); + } + @Test void guildEntryDoesNotDependOnAWorldAndTargetedCancellationRemainsNative(){ + assertEquals("travel",SuppliedMenus.route("guildtravel",new String[]{})); + assertNull(SuppliedMenus.route("guildtravel",new String[]{"cancel"})); + assertNull(SuppliedMenus.route("drgui",new String[]{"previewitem","id","1"})); + assertNull(SuppliedMenus.route("drgui",new String[]{"movenpc","stilgar"})); + assertNull(SuppliedMenus.route("drgui",new String[]{"unknown"})); + } +} diff --git a/DuneStaff/src/main/java/com/example/dunelobby/BuilderMultiverse.java b/DuneStaff/src/main/java/com/example/dunelobby/BuilderMultiverse.java new file mode 100644 index 00000000..85edb6ba --- /dev/null +++ b/DuneStaff/src/main/java/com/example/dunelobby/BuilderMultiverse.java @@ -0,0 +1,43 @@ +package com.example.dunelobby; + +import java.util.concurrent.CompletableFuture; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +/** Optional local-world transport. Does not import, load or generate worlds. */ +final class BuilderMultiverse { + private static final String API = "org.mvplugins.multiverse.core.MultiverseCoreApi"; + private static final String MODE = "org.mvplugins.multiverse.core.teleportation.PassengerMode"; + private static final String MODES = MODE + "s"; + + static CompletableFuture teleport(Player player, Location destination) { + var result = new CompletableFuture(); + var plugin = Bukkit.getPluginManager().getPlugin("Multiverse-Core"); + if (plugin == null || !plugin.isEnabled() || destination.getWorld() == null) { + result.complete(false); + return result; + } + try { + var loader = plugin.getClass().getClassLoader(); + var api = loader.loadClass(API).getMethod("get").invoke(null); + var teleporter = api.getClass().getMethod("getSafetyTeleporter").invoke(api); + var action = teleporter.getClass().getMethod("to", Location.class).invoke(teleporter, destination); + var actions = action.getClass(); + actions.getMethod("by", CommandSender.class).invoke(action, player); + actions.getMethod("passengerMode", loader.loadClass(MODE)) + .invoke(action, loader.loadClass(MODES).getField("DISMOUNT_ALL").get(null)); + var teleport = actions.getMethod("teleport", Entity.class); + var success = teleport.getReturnType().getMethod("onSuccess", Runnable.class); + var failure = teleport.getReturnType().getMethod("onFailure", Runnable.class); + var attempt = teleport.invoke(action, player); + success.invoke(attempt, (Runnable) () -> result.complete(true)); + failure.invoke(attempt, (Runnable) () -> result.complete(false)); + } catch (ReflectiveOperationException | LinkageError | RuntimeException unavailable) { + result.complete(false); + } + return result; + } +} diff --git a/DuneStaff/src/main/java/com/example/dunelobby/BuilderSharedProfiles.java b/DuneStaff/src/main/java/com/example/dunelobby/BuilderSharedProfiles.java new file mode 100644 index 00000000..c6375fe1 --- /dev/null +++ b/DuneStaff/src/main/java/com/example/dunelobby/BuilderSharedProfiles.java @@ -0,0 +1,109 @@ +package com.example.dunelobby; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Set; +import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +/** Keeps pre-transfer local inventory snapshots subordinate to the shared profile. */ +final class BuilderSharedProfiles { + private static final String SHARED_INVENTORY = "network.share-lobby-inventory"; + + static boolean allowTransfer(Player player, Path snapshot) { + if (Files.exists(snapshot)) return true; + if (sharingCore() == null) return true; + player.sendMessage("The build world is temporarily unavailable while shared inventories are protected."); + return false; + } + + /** + * Handles shared-mode snapshots. Only local-only mode may continue into the + * original inventory and ender-chest restore. + */ + static boolean restore(Player player, Path snapshot, boolean travel, boolean inBuilder, + Set returning) throws IOException { + JavaPlugin core = sharingCore(); + if (core == null) return false; + if (!Files.exists(snapshot) || !loaded(core, player.getUniqueId())) return true; + if (inBuilder) { + if (!travel) return true; + var state = YamlConfiguration.loadConfiguration(snapshot.toFile()); + var destination = state.getLocation("return"); + String name = state.getString("mode"); + if (destination == null || destination.getWorld() == null || name == null) return true; + GameMode mode = GameMode.valueOf(name); + returning.add(player.getUniqueId()); + try { + if (!player.teleport(destination)) return true; + player.setGameMode(mode); + } finally { + returning.remove(player.getUniqueId()); + } + } + quarantine(snapshot); + return true; + } + + static boolean shared() { + return sharingCore() != null; + } + + static boolean isolationAvailable(Player player) { + JavaPlugin core = sharingCore(); + if (core == null || !loaded(core, player.getUniqueId())) return false; + try { + core.getClass().getMethod("freezeBuilderProfile", Player.class); + var database = core.getClass().getMethod("sharedDatabase").invoke(core); + database.getClass().getMethod("thawBuilderProfile", Player.class, UUID.class); + return true; + } catch (ReflectiveOperationException | LinkageError unavailable) { + return false; + } + } + + static UUID freeze(Player player) throws ReflectiveOperationException { + JavaPlugin core = sharingCore(); + if (core == null || !loaded(core, player.getUniqueId())) throw new IllegalStateException("No shared profile"); + return (UUID) core.getClass().getMethod("freezeBuilderProfile", Player.class).invoke(core, player); + } + + static void thaw(Player player, UUID token) throws ReflectiveOperationException { + JavaPlugin core = sharingCore(); + if (core == null || !loaded(core, player.getUniqueId())) throw new IllegalStateException("No shared profile"); + var database = core.getClass().getMethod("sharedDatabase").invoke(core); + database.getClass().getMethod("thawBuilderProfile", Player.class, UUID.class).invoke(database, player, token); + } + + private static JavaPlugin sharingCore() { + var registered = Bukkit.getPluginManager().getPlugin("DuneCore"); + if (!(registered instanceof JavaPlugin core) || !core.getConfig().getBoolean(SHARED_INVENTORY, false)) return null; + return core; + } + + private static boolean loaded(JavaPlugin core, UUID player) { + if (!core.isEnabled()) return false; + try { + var database = core.getClass().getMethod("sharedDatabase").invoke(core); + return database != null && Boolean.TRUE.equals(database.getClass().getMethod("isLoaded", UUID.class) + .invoke(database, player)); + } catch (ReflectiveOperationException | LinkageError unavailable) { + return false; + } + } + + private static void quarantine(Path snapshot) throws IOException { + if (!Files.isRegularFile(snapshot, LinkOption.NOFOLLOW_LINKS)) { + throw new IOException("Builder recovery snapshot is not a regular file"); + } + Path retained = snapshot.resolveSibling(snapshot.getFileName() + ".shared-" + UUID.randomUUID()); + Files.move(snapshot, retained, StandardCopyOption.ATOMIC_MOVE); + } +} diff --git a/DuneStaff/src/main/java/com/example/dunelobby/BuilderTransfer.java b/DuneStaff/src/main/java/com/example/dunelobby/BuilderTransfer.java index 2a9cc667..021bd533 100644 --- a/DuneStaff/src/main/java/com/example/dunelobby/BuilderTransfer.java +++ b/DuneStaff/src/main/java/com/example/dunelobby/BuilderTransfer.java @@ -44,6 +44,10 @@ public final class BuilderTransfer implements Listener { private static final String WORLD = "lobby_arrakis"; private static final String ACCESS = "dune.buildtransfer"; + private record SharedBuild(Location origin, GameMode mode, UUID token) {} + private final Map sharedBuilds = new HashMap<>(); + private record PendingTransfer(UUID destination) {} + private final Map multiversePending = new HashMap<>(); private final Map permissions = new HashMap<>(); private World builderWorld; private final java.util.Set returning = new java.util.HashSet<>(); @@ -58,6 +62,12 @@ public final class BuilderTransfer implements Listener { } public void start() { + var declared = owner.getCommand("buildtransfer"); + if (declared != null) { + declared.setExecutor((sender, ignored, label, arguments) -> execute(sender)); + Bukkit.getPluginManager().registerEvents(this, owner); + return; + } var commandMap = Bukkit.getCommandMap(); if (commandMap.getCommand("buildtransfer") != null) { throw new IllegalStateException("A build transfer command is already registered"); @@ -66,12 +76,7 @@ public final class BuilderTransfer implements Listener { "/buildtransfer", java.util.List.of()) { @Override public boolean execute(CommandSender sender, String label, String[] arguments) { if (!testPermission(sender)) return true; - if (sender instanceof Player player) transfer(player); - else { - World world = loadWorld(); - sender.sendMessage(world == null ? "Build world unavailable" : "BUILD_WORLD_READY " + world.getKey()); - } - return true; + return BuilderTransfer.this.execute(sender); } }; command.setPermission(ACCESS); @@ -79,6 +84,15 @@ public final class BuilderTransfer implements Listener { Bukkit.getPluginManager().registerEvents(this, owner); } + private boolean execute(CommandSender sender) { + if (sender instanceof Player player) transfer(player); + else { + World world = loadWorld(); + sender.sendMessage(world == null ? "Build world unavailable" : "BUILD_WORLD_READY " + world.getKey()); + } + return true; + } + public void stop() { if (command != null) { var commandMap = Bukkit.getCommandMap(); @@ -87,7 +101,8 @@ public final class BuilderTransfer implements Listener { command.unregister(commandMap); } for (Player player : Bukkit.getOnlinePlayers()) { - if (Files.exists(snapshot(player))) recover(player, true); + if (!sharedBuilds.containsKey(player.getUniqueId()) && !multiversePending.containsKey(player.getUniqueId()) + && Files.exists(snapshot(player))) recover(player, true); } } @@ -111,15 +126,17 @@ public final class BuilderTransfer implements Listener { return snapshotDirectory.resolve(player.getUniqueId() + ".yml"); } - private void save(Player player) throws IOException { + private void save(Player player, boolean shared) throws IOException { Path target = snapshot(player); Files.createDirectories(target.getParent()); Path pending = target.resolveSibling(target.getFileName() + ".tmp"); var state = new YamlConfiguration(); state.set("return", player.getLocation()); state.set("mode", player.getGameMode().name()); - state.set("inventory", java.util.Arrays.asList(player.getInventory().getContents())); - state.set("ender", java.util.Arrays.asList(player.getEnderChest().getContents())); + if (!shared) { + state.set("inventory", java.util.Arrays.asList(player.getInventory().getContents())); + state.set("ender", java.util.Arrays.asList(player.getEnderChest().getContents())); + } state.save(pending.toFile()); Files.move(pending, target, StandardCopyOption.ATOMIC_MOVE); } @@ -133,6 +150,7 @@ public final class BuilderTransfer implements Listener { private void restore(Player player, boolean travel) throws IOException { Path file = snapshot(player); if (!Files.exists(file)) return; + if (BuilderSharedProfiles.restore(player, file, travel, inBuilder(player.getWorld()), returning)) return; var state = YamlConfiguration.loadConfiguration(file.toFile()); Location destination = state.getLocation("return"); GameMode mode = GameMode.valueOf(state.getString("mode")); @@ -156,17 +174,31 @@ public final class BuilderTransfer implements Listener { } private void transfer(Player player) { + if (multiversePending.containsKey(player.getUniqueId())) { + player.sendMessage("A build-world transfer is already in progress."); + return; + } + var active = sharedBuilds.get(player.getUniqueId()); + if (active != null) { + leaveSharedBuilder(player, active); + return; + } try { if (Files.exists(snapshot(player))) { restore(player, true); return; } + if (BuilderSharedProfiles.shared()) { + if (BuilderSharedProfiles.isolationAvailable(player)) enterSharedBuilder(player); + else BuilderSharedProfiles.allowTransfer(player, snapshot(player)); + return; + } World world = loadWorld(); if (world == null) { player.sendMessage("The Arrakis build world is unavailable."); return; } - save(player); + save(player, false); if (!player.teleport(world.getSpawnLocation())) { restore(player, false); return; @@ -174,22 +206,121 @@ public final class BuilderTransfer implements Listener { player.getInventory().clear(); player.getEnderChest().clear(); player.setGameMode(GameMode.CREATIVE); - var attachment = player.addAttachment(owner); - permissions.put(player.getUniqueId(), attachment); - attachment.setPermission("worldedit.*", true); - for (var permission : Bukkit.getPluginManager().getPermissions()) { - if (permission.getName().startsWith("worldedit.")) attachment.setPermission(permission, true); - } + grantWorldEdit(player); } catch (IOException | RuntimeException error) { owner.getLogger().warning("Build transfer failed for " + player.getUniqueId() + ": " + error.getMessage()); player.sendMessage("Build transfer could not be completed."); } } + private void enterSharedBuilder(Player player) throws IOException { + World world = loadWorld(); + if (world == null || inBuilder(player.getWorld())) { + player.sendMessage("The Arrakis build world is unavailable."); + return; + } + UUID id = player.getUniqueId(); + Location origin = player.getLocation(); + GameMode mode = player.getGameMode(); + save(player, true); + startMultiverse(player, world.getSpawnLocation(), success -> { + try { + if (!success || !inBuilder(player.getWorld())) { + if (!inBuilder(player.getWorld())) Files.deleteIfExists(snapshot(player)); + player.sendMessage("The build-world transfer did not complete."); + return; + } + UUID token = BuilderSharedProfiles.freeze(player); + sharedBuilds.put(id, new SharedBuild(origin, mode, token)); + player.getInventory().clear(); + player.setGameMode(GameMode.CREATIVE); + grantWorldEdit(player); + } catch (Exception failure) { + owner.getLogger().warning("A shared Builder transfer could not be completed safely."); + if (inBuilder(player.getWorld())) player.kickPlayer("Your shared inventory is safe. Reconnect to return from Builder."); + } + }); + } + + private void leaveSharedBuilder(Player player, SharedBuild active) { + player.setItemOnCursor(null); + player.closeInventory(); + var creativeItems = player.getInventory().getContents(); + player.getInventory().clear(); + removeWorldEdit(player); + player.setGameMode(active.mode()); + startMultiverse(player, active.origin(), success -> { + if (inBuilder(player.getWorld())) { + player.getInventory().setContents(creativeItems); + player.setGameMode(GameMode.CREATIVE); + grantWorldEdit(player); + player.sendMessage("The return transfer did not complete. Try /buildtransfer again."); + return; + } + try { + BuilderSharedProfiles.thaw(player, active.token()); + removeWorldEdit(player); + player.setGameMode(active.mode()); + sharedBuilds.remove(player.getUniqueId(), active); + Files.deleteIfExists(snapshot(player)); + } catch (Exception failure) { + owner.getLogger().warning("The committed survival inventory could not be restored."); + player.setGameMode(active.mode()); + player.kickPlayer("Your shared inventory is safe. Reconnect to reload it."); + } + }); + } + + private void startMultiverse(Player player, Location destination, java.util.function.Consumer action) { + UUID id = player.getUniqueId(); + var pending = new PendingTransfer(destination.getWorld().getUID()); + multiversePending.put(id, pending); + BuilderMultiverse.teleport(player, destination).whenComplete((success, failure) -> { + Runnable finish = () -> { + if (multiversePending.get(id) != pending || Bukkit.getPlayer(id) != player) return; + multiversePending.remove(id); + action.accept(failure == null && Boolean.TRUE.equals(success)); + }; + // Defer even when immediate: the WorldChanged/teleport handlers need the permit until the event unwinds. + if (owner.isEnabled()) Bukkit.getScheduler().runTask(owner, finish); + }); + } + + private void grantWorldEdit(Player player) { + var attachment = player.addAttachment(owner); + permissions.put(player.getUniqueId(), attachment); + attachment.setPermission("worldedit.*", true); + for (var permission : Bukkit.getPluginManager().getPermissions()) { + if (permission.getName().startsWith("worldedit.")) attachment.setPermission(permission, true); + } + } + + private void removeWorldEdit(Player player) { + var attachment = permissions.remove(player.getUniqueId()); + if (attachment != null) player.removeAttachment(attachment); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void blockSharedEnderUse(org.bukkit.event.inventory.InventoryOpenEvent event) { + if (sharedBuilds.containsKey(event.getPlayer().getUniqueId()) + && event.getInventory().getType() == org.bukkit.event.inventory.InventoryType.ENDER_CHEST) { + event.setCancelled(true); + } + } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void boundary(PlayerTeleportEvent event) { if (event.getTo() == null || inBuilder(event.getFrom().getWorld()) == inBuilder(event.getTo().getWorld())) return; Player player = event.getPlayer(); + PendingTransfer expected = multiversePending.get(player.getUniqueId()); + if (expected != null) { + if (!expected.destination().equals(event.getTo().getWorld().getUID())) event.setCancelled(true); + return; + } + if (sharedBuilds.containsKey(player.getUniqueId())) { + event.setCancelled(true); + return; + } if (inBuilder(event.getTo().getWorld()) && player.hasPermission(ACCESS) && Files.exists(snapshot(player))) return; if (inBuilder(event.getFrom().getWorld()) && returning.contains(player.getUniqueId())) return; event.setCancelled(true); @@ -197,6 +328,7 @@ public final class BuilderTransfer implements Listener { @EventHandler(priority = EventPriority.LOWEST) public void worldChanged(PlayerChangedWorldEvent event) { + if (multiversePending.containsKey(event.getPlayer().getUniqueId()) || sharedBuilds.containsKey(event.getPlayer().getUniqueId())) return; if (inBuilder(event.getFrom()) && !inBuilder(event.getPlayer().getWorld()) && !returning.contains(event.getPlayer().getUniqueId())) recover(event.getPlayer(), false); } @@ -207,6 +339,18 @@ public final class BuilderTransfer implements Listener { @EventHandler(priority = EventPriority.LOWEST) public void quit(PlayerQuitEvent event) { + UUID id = event.getPlayer().getUniqueId(); + multiversePending.remove(id); + SharedBuild active = sharedBuilds.remove(id); + if (active != null) { + // Core releases the frozen DB checkpoint independently of quit listener order. + // Keep vanilla's local save free of creative inventory and mode, too. + var player = event.getPlayer(); + player.getInventory().clear(); + player.setGameMode(active.mode()); + removeWorldEdit(player); + return; + } recover(event.getPlayer(), false); } diff --git a/DuneStaff/src/main/java/com/example/dunelobby/LegacyBuilderPlugin.java b/DuneStaff/src/main/java/com/example/dunelobby/LegacyBuilderPlugin.java new file mode 100644 index 00000000..58da90e2 --- /dev/null +++ b/DuneStaff/src/main/java/com/example/dunelobby/LegacyBuilderPlugin.java @@ -0,0 +1,17 @@ +package com.example.dunelobby; + +import org.bukkit.plugin.java.JavaPlugin; + +/** Standalone entry point for Lobby installations that still use DuneBuilder. */ +public final class LegacyBuilderPlugin extends JavaPlugin { + private BuilderTransfer transfer; + + @Override public void onEnable() { + transfer = new BuilderTransfer(this, getDataFolder().toPath()); + transfer.start(); + } + + @Override public void onDisable() { + if (transfer != null) transfer.stop(); + } +} diff --git a/DuneStaff/src/main/resources/plugin.yml b/DuneStaff/src/main/resources/plugin.yml index d24a03af..9a02744e 100644 --- a/DuneStaff/src/main/resources/plugin.yml +++ b/DuneStaff/src/main/resources/plugin.yml @@ -3,7 +3,7 @@ main: com.dunerealms.staff.DuneStaff version: 1.1.0 api-version: '1.21.8' provides: [DuneBan, DuneProtect] -softdepend: [CoreProtect, WorldEdit, WorldGuard, DuneCore, DuneMenus, LuckPerms] +softdepend: [CoreProtect, WorldEdit, WorldGuard, DuneCore, DuneMenus, LuckPerms, Multiverse-Core] commands: duneprotect: description: Block history, building tools and protected regions diff --git a/DuneStaff/src/test/java/com/example/dunelobby/BuilderSharedProfilesTest.java b/DuneStaff/src/test/java/com/example/dunelobby/BuilderSharedProfilesTest.java new file mode 100644 index 00000000..2050d1fa --- /dev/null +++ b/DuneStaff/src/test/java/com/example/dunelobby/BuilderSharedProfilesTest.java @@ -0,0 +1,92 @@ +package com.example.dunelobby; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Set; +import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class BuilderSharedProfilesTest { + private static final UUID PLAYER = UUID.fromString("00000000-0000-4000-8000-000000000101"); + @TempDir Path directory; + + public abstract static class TestCore extends JavaPlugin { + public abstract TestDatabase sharedDatabase(); + } + + public abstract static class TestDatabase { + public abstract boolean isLoaded(UUID player); + } + + private org.mockito.MockedStatic core(boolean enabled, boolean loaded) { + var bukkit = mockStatic(Bukkit.class); + var plugins = mock(PluginManager.class); + var plugin = mock(TestCore.class); + var database = mock(TestDatabase.class); + var config = new YamlConfiguration(); + config.set("network.share-lobby-inventory", enabled); + bukkit.when(Bukkit::getPluginManager).thenReturn(plugins); + when(plugins.getPlugin("DuneCore")).thenReturn(plugin); + when(plugin.getConfig()).thenReturn(config); + when(plugin.isEnabled()).thenReturn(true); + when(plugin.sharedDatabase()).thenReturn(database); + when(database.isLoaded(PLAYER)).thenReturn(loaded); + return bukkit; + } + + @Test void confirmedSharedLoadQuarantinesStaleSnapshotWithoutTouchingInventory() throws Exception { + var file = directory.resolve("snapshot.yml"); + Files.writeString(file, "inventory: [stale]\nender: [stale]\n"); + var stale = Files.readAllBytes(file); + var player = mock(Player.class); + when(player.getUniqueId()).thenReturn(PLAYER); + try (var ignored = core(true, true)) { + assertTrue(BuilderSharedProfiles.restore(player, file, true, false, Set.of())); + } + assertFalse(Files.exists(file)); + try (var files = Files.list(directory)) { + var retained = files.toList(); + assertEquals(1, retained.size()); + assertArrayEquals(stale, Files.readAllBytes(retained.getFirst())); + } + verify(player).getUniqueId(); + verifyNoMoreInteractions(player); + } + + @Test void failedSharedLoadDoesNotRestoreOrRemoveLocalData() throws Exception { + var file = directory.resolve("snapshot.yml"); + Files.writeString(file, "inventory: [stale]\n"); + var stale = Files.readAllBytes(file); + var player = mock(Player.class); + when(player.getUniqueId()).thenReturn(PLAYER); + try (var ignored = core(true, false)) { + assertTrue(BuilderSharedProfiles.restore(player, file, true, true, Set.of())); + assertFalse(BuilderSharedProfiles.allowTransfer(player, directory.resolve("missing.yml"))); + } + assertArrayEquals(stale, Files.readAllBytes(file)); + verify(player).getUniqueId(); + verify(player).sendMessage("The build world is temporarily unavailable while shared inventories are protected."); + verifyNoMoreInteractions(player); + } + + @Test void localOnlyStillUsesOriginalBuilderRestoreAndEntry() throws Exception { + var file = directory.resolve("snapshot.yml"); + Files.writeString(file, "inventory: [legacy]\n"); + var player = mock(Player.class); + try (var ignored = core(false, false)) { + assertFalse(BuilderSharedProfiles.restore(player, file, true, false, Set.of())); + assertTrue(BuilderSharedProfiles.allowTransfer(player, directory.resolve("missing.yml"))); + } + assertTrue(Files.exists(file)); + verifyNoInteractions(player); + } +} diff --git a/network/lobby/MULTIVERSE.md b/network/lobby/MULTIVERSE.md new file mode 100644 index 00000000..c9e874a1 --- /dev/null +++ b/network/lobby/MULTIVERSE.md @@ -0,0 +1,40 @@ +# Lobby Multiverse + +The immutable official Multiverse-Core 5.8.2 input is recorded in +`multiverse-core.json`, including both verified hashes and its original license. +Only Lobby receives this plugin. Multiverse-Inventories, NetherPortals and other +optional modules are not installed. + +`multiverse-config.yml` keeps current world creation, generators, game modes, +flight, entity policy, portals, login destinations and respawns under their +existing owners. It does not import or generate worlds. Multiverse's native +configuration format marker is 5.2, as generated by this exact plugin version. +The registered DuneCore network inventory remains authoritative. + +The local transfer integration must use the Multiverse asynchronous safety +teleporter against an existing loaded world, with checked success, cancellation, +session and quit handling. The integration must not route Guild server passages +through Multiverse or restore stale local inventories after shared profile load. + +An isolated Paper 26.2.135 run with the pinned plugin verified that the API loads, +the conservative settings remain effective, the Multiverse world registry stays +empty, and Paper retains its existing three test dimensions. This is startup and +configuration evidence, not a connected-player transfer or production claim. + +The paired Builder source checkpoints the survival profile under its existing +database lock, prevents sandbox inventory from being saved or traded, and restores +the committed profile after a confirmed return. A disconnect closes the durable +checkpoint without writing creative items. Old local Builder snapshots cannot +overwrite a loaded shared profile. The ender chest is never cleared for a shared +build session and cannot be opened there. + +The assembled legacy Builder passed actual Paper 26.2.135, WorldEdit and official +Multiverse tests for entry, refused entry, pending return, refused return, successful +return, repeated entry and disconnect cleanup in unmanaged test worlds. The +retained Core graft also passed a separate isolated MySQL test using its real +constructor and GET_LOCK behavior, with no production profile or privilege changes. + +The dedicated build packages the official JAR, reviewed configuration, license, +source pin and checksums. Activation needs an ordinary controlled Lobby restart +after profile-safe transfer validation. Do not hot-load it or replace any other +plugin with a general full-build JAR. diff --git a/network/lobby/multiverse-LICENSE.md b/network/lobby/multiverse-LICENSE.md new file mode 100644 index 00000000..a5dc3a8b --- /dev/null +++ b/network/lobby/multiverse-LICENSE.md @@ -0,0 +1,6 @@ +Copyright (c) 2011, The Multiverse Team All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the The Multiverse Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/network/lobby/multiverse-config.yml b/network/lobby/multiverse-config.yml new file mode 100644 index 00000000..f77d9328 --- /dev/null +++ b/network/lobby/multiverse-config.yml @@ -0,0 +1,23 @@ +# Multiverse manages local transfers, not the shared network inventory. +# Existing world owners retain creation, generators, spawn and game-mode policy. +version: 5.2 +world: + auto-import-default-worlds: false + auto-import-3rd-party-worlds: false + enforce-access: false + enforce-gamemode: false + enforce-flight: false + apply-entity-spawn-rate: false + apply-entity-spawn-limit: false + auto-purge-entities: false +teleport: + teleport-intercept: false +spawn: + first-spawn-override: false + enable-join-destination: false + default-respawn-in-overworld: false + default-respawn-within-same-world: false + enforce-respawn-at-world-spawn: false +misc: + auto-detect-generator-plugins: false + show-donation-message: false diff --git a/network/lobby/multiverse-core.json b/network/lobby/multiverse-core.json new file mode 100644 index 00000000..8bcfbe70 --- /dev/null +++ b/network/lobby/multiverse-core.json @@ -0,0 +1,15 @@ +{ + "plugin": "Multiverse-Core", + "version": "5.8.2", + "projectId": "3wmN97b8", + "versionId": "de7TbcZG", + "filename": "multiverse-core-5.8.2.jar", + "url": "https://cdn.modrinth.com/data/3wmN97b8/versions/de7TbcZG/multiverse-core-5.8.2.jar", + "sha256": "792252b6bbcf17c94ab8385e595281c830d7a40c946aea1832d8a010702bb630", + "sha512": "1165c96755229583477d120485b49ddf731f44a97e17b99f955892e8e90d1f6b24d2e06bd15b6fc4240197c32970592a2af2febe31044afed949dc2d722d17a8", + "source": "https://github.com/Multiverse/Multiverse-Core/tree/5.8.2", + "license": "BSD-3-Clause", + "scope": ["lobby"], + "inventoryOwner": "DuneCore shared network profile", + "optionalModulesInstalled": [] +} diff --git a/tools/BuilderProfileCoreOverlay.java b/tools/BuilderProfileCoreOverlay.java new file mode 100644 index 00000000..cb43748a --- /dev/null +++ b/tools/BuilderProfileCoreOverlay.java @@ -0,0 +1,141 @@ +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.*; + +final class BuilderProfileCoreOverlay implements Opcodes { + private static final String DB = "com/example/dunerealms/SharedDatabase"; + private static final String CORE = "com/example/dunerealms/DuneCore"; + private static final String PLAYER = "Lorg/bukkit/entity/Player;"; + private static final String MAP = "Ljava/util/Map;"; + private static final String CONNECTION = "Ljava/sql/Connection;"; + private static final String GUARD = "(" + PLAYER + CONNECTION + "Z)Z"; + private static final String LEASE = DB + "$BuilderLease"; + + public static void main(String[] args) throws Exception { + if (args.length != 5) throw new IllegalArgumentException("Expected retained DB/Core, donor DB/Core and output directory"); + var retainedBytes = Files.readAllBytes(Path.of(args[0])); + var coreBytes = Files.readAllBytes(Path.of(args[1])); + var retained = read(retainedBytes, DB); + var core = read(coreBytes, CORE); + var donor = read(Files.readAllBytes(Path.of(args[2])), DB); + var donorCore = read(Files.readAllBytes(Path.of(args[3])), CORE); + var field = donor.fields.stream().filter(f -> f.name.equals("builderLeases") && f.desc.equals(MAP)).findFirst().orElseThrow(); + if (retained.fields.stream().anyMatch(f -> f.name.equals(field.name))) throw new IllegalArgumentException("Builder leases already exist"); + retained.fields.add(field); + if (retained.nestMembers == null) retained.nestMembers = new ArrayList<>(); + retained.nestMembers.add(LEASE); + retained.innerClasses.add(donor.innerClasses.stream().filter(c -> c.name.equals(LEASE)).findFirst().orElseThrow()); + + var constructor = method(retained, "", "(Lorg/bukkit/plugin/java/JavaPlugin;)V"); + var init = new InsnList(); + init.add(new VarInsnNode(ALOAD, 0)); + init.add(new TypeInsnNode(NEW, "java/util/HashMap")); + init.add(new InsnNode(DUP)); + init.add(new MethodInsnNode(INVOKESPECIAL, "java/util/HashMap", "", "()V", false)); + init.add(new FieldInsnNode(PUTFIELD, DB, field.name, MAP)); + var parent = constructor.instructions.iterator(); + while (parent.hasNext()) { + var next = parent.next(); + if (next instanceof MethodInsnNode call && call.getOpcode() == INVOKESPECIAL + && call.owner.equals("java/lang/Object") && call.name.equals("")) { + constructor.instructions.insert(next, init); + break; + } + } + if (init.size() != 0) throw new IllegalArgumentException("Missing retained superclass constructor"); + constructor.maxStack = Math.max(constructor.maxStack, 3); + + for (String name : List.of("freezeBuilderProfile", "thawBuilderProfile", "bindBuilderUuid", + "preserveFrozenBuilderProfile", "requireUnfrozenBuilderProfile", "forgetBuilderProfile")) { + var matches = donor.methods.stream().filter(m -> m.name.equals(name)).toList(); + if (matches.size() != 1 || retained.methods.stream().anyMatch(m -> m.name.equals(name))) + throw new IllegalArgumentException("Unexpected donor or retained method " + name); + retained.methods.add(matches.getFirst()); + } + + var write = method(retained, "writePlayer", "(" + PLAYER + MAP + "Z)V"); + var writePrefix = new InsnList(); + writePrefix.add(new VarInsnNode(ALOAD, 0)); + writePrefix.add(new VarInsnNode(ALOAD, 1)); + writePrefix.add(new VarInsnNode(ALOAD, 0)); + writePrefix.add(new FieldInsnNode(GETFIELD, DB, "sessions", MAP)); + uuid(writePrefix); + writePrefix.add(new MethodInsnNode(INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", true)); + writePrefix.add(new TypeInsnNode(CHECKCAST, "java/sql/Connection")); + writePrefix.add(new VarInsnNode(ILOAD, 3)); + writePrefix.add(new MethodInsnNode(INVOKEVIRTUAL, DB, "preserveFrozenBuilderProfile", GUARD, false)); + var old = new LabelNode(); + writePrefix.add(new JumpInsnNode(IFEQ, old)); + writePrefix.add(new InsnNode(RETURN)); + writePrefix.add(old); + writePrefix.add(new FrameNode(F_SAME, 0, null, 0, null)); + write.instructions.insert(writePrefix); + write.maxStack = Math.max(write.maxStack, 4); + + var transaction = method(retained, "transaction", "(" + PLAYER + MAP + "Ljava/util/function/Consumer;)V"); + transaction.instructions.insert(callPlayer("requireUnfrozenBuilderProfile")); + transaction.maxStack = Math.max(transaction.maxStack, 2); + + var release = method(retained, "releasePlayer", "(" + PLAYER + MAP + ")V"); + int cleanupSites = 0; + for (var instruction : release.instructions.toArray()) { + if (instruction instanceof FieldInsnNode access && access.getOpcode() == GETFIELD + && access.owner.equals(DB) && access.name.equals("sessions")) { + var receiver = access.getPrevious(); + if (!(receiver instanceof VarInsnNode load) || load.getOpcode() != ALOAD || load.var != 0) + throw new IllegalArgumentException("Unexpected release cleanup boundary"); + release.instructions.insertBefore(receiver, callPlayer("forgetBuilderProfile")); + cleanupSites++; + } + } + if (cleanupSites != 2) throw new IllegalArgumentException("Expected normal and exceptional release cleanup"); + release.maxStack = Math.max(release.maxStack, 2); + + var close = method(retained, "close", "()V"); + var reset = new InsnList(); + reset.add(new VarInsnNode(ALOAD, 0)); + reset.add(new FieldInsnNode(GETFIELD, DB, field.name, MAP)); + reset.add(new MethodInsnNode(INVOKEINTERFACE, "java/util/Map", "clear", "()V", true)); + close.instructions.insert(reset); + close.maxStack = Math.max(close.maxStack, 1); + + core.methods.add(method(donorCore, "freezeBuilderProfile", "(" + PLAYER + ")Ljava/util/UUID;")); + write(retainedBytes, retained, Path.of(args[4], "SharedDatabase.class")); + write(coreBytes, core, Path.of(args[4], "DuneCore.class")); + } + + private static void uuid(InsnList code) { + code.add(new VarInsnNode(ALOAD, 1)); + code.add(new MethodInsnNode(INVOKEINTERFACE, "org/bukkit/entity/Player", "getUniqueId", "()Ljava/util/UUID;", true)); + } + + private static InsnList callPlayer(String name) { + var code = new InsnList(); + code.add(new VarInsnNode(ALOAD, 0)); + code.add(new VarInsnNode(ALOAD, 1)); + code.add(new MethodInsnNode(INVOKEVIRTUAL, DB, name, "(" + PLAYER + ")V", false)); + return code; + } + + private static ClassNode read(byte[] bytes, String name) { + var node = new ClassNode(); + new ClassReader(bytes).accept(node, 0); + if (!node.name.equals(name)) throw new IllegalArgumentException("Unexpected class: " + node.name); + return node; + } + + private static MethodNode method(ClassNode node, String name, String descriptor) { + return node.methods.stream().filter(m -> m.name.equals(name) && m.desc.equals(descriptor)).findFirst().orElseThrow(); + } + + private static void write(byte[] original, ClassNode modified, Path output) throws Exception { + var writer = new ClassWriter(new ClassReader(original), 0); + modified.accept(writer); + Files.write(output, writer.toByteArray()); + } +} diff --git a/tools/BuilderSharedProfilesOverlay.java b/tools/BuilderSharedProfilesOverlay.java new file mode 100644 index 00000000..e451f2e2 --- /dev/null +++ b/tools/BuilderSharedProfilesOverlay.java @@ -0,0 +1,75 @@ +import java.nio.file.Files; +import java.nio.file.Path; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.FrameNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.VarInsnNode; + +class BuilderSharedProfilesOverlay { + private static final String OWNER = "com/example/dunelobby/BuilderTransfer"; + private static final String GUARD = "com/example/dunelobby/BuilderSharedProfiles"; + private static final String PLAYER = "Lorg/bukkit/entity/Player;"; + private static final String PATH = "Ljava/nio/file/Path;"; + + public static void main(String[] args) throws Exception { + if (args.length != 2) throw new IllegalArgumentException("Expected baseline and output classes"); + var reader = new ClassReader(Files.readAllBytes(Path.of(args[0]))); + var retained = new ClassNode(); + reader.accept(retained, 0); + if (!OWNER.equals(retained.name)) throw new IllegalArgumentException("Unexpected legacy Builder implementation"); + var restore = retained.methods.stream().filter(m -> m.name.equals("restore") && m.desc.equals("(" + PLAYER + "Z)V")) + .findFirst().orElseThrow(); + var transfer = retained.methods.stream().filter(m -> m.name.equals("transfer") && m.desc.equals("(" + PLAYER + ")V")) + .findFirst().orElseThrow(); + + var recover = snapshot(); + recover.add(new VarInsnNode(Opcodes.ILOAD, 2)); + recover.add(new VarInsnNode(Opcodes.ALOAD, 0)); + recover.add(new VarInsnNode(Opcodes.ALOAD, 1)); + recover.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE, "org/bukkit/entity/Player", "getWorld", + "()Lorg/bukkit/World;", true)); + recover.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, OWNER, "inBuilder", "(Lorg/bukkit/World;)Z", false)); + recover.add(new VarInsnNode(Opcodes.ALOAD, 0)); + recover.add(new FieldInsnNode(Opcodes.GETFIELD, OWNER, "returning", "Ljava/util/Set;")); + recover.add(new MethodInsnNode(Opcodes.INVOKESTATIC, GUARD, "restore", + "(" + PLAYER + PATH + "ZZLjava/util/Set;)Z", false)); + finish(recover, Opcodes.IFEQ); + restore.instructions.insert(recover); + restore.maxStack = Math.max(restore.maxStack, 5); + + var enter = snapshot(); + enter.add(new MethodInsnNode(Opcodes.INVOKESTATIC, GUARD, "allowTransfer", "(" + PLAYER + PATH + ")Z", false)); + finish(enter, Opcodes.IFNE); + transfer.instructions.insert(enter); + transfer.maxStack = Math.max(transfer.maxStack, 3); + + var writer = new ClassWriter(reader, 0); + retained.accept(writer); + Files.write(Path.of(args[1]), writer.toByteArray()); + } + + private static InsnList snapshot() { + var code = new InsnList(); + code.add(new VarInsnNode(Opcodes.ALOAD, 1)); + code.add(new VarInsnNode(Opcodes.ALOAD, 0)); + code.add(new VarInsnNode(Opcodes.ALOAD, 1)); + code.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, OWNER, "snapshot", "(" + PLAYER + ")" + PATH, false)); + return code; + } + + private static void finish(InsnList code, int jump) { + var old = new LabelNode(); + code.add(new JumpInsnNode(jump, old)); + code.add(new InsnNode(Opcodes.RETURN)); + code.add(old); + code.add(new FrameNode(Opcodes.F_SAME, 0, null, 0, null)); + } +} diff --git a/tools/CompactMenuMerge.java b/tools/CompactMenuMerge.java new file mode 100644 index 00000000..45f98f04 --- /dev/null +++ b/tools/CompactMenuMerge.java @@ -0,0 +1,101 @@ +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Handle; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InvokeDynamicInsnNode; +import org.objectweb.asm.tree.MethodNode; + +class CompactMenuMerge { + private static final String GUI = "com/dunerealms/gui/"; + private static final Map> TARGETS = Map.of( + GUI + "DuneGUI", Set.of("guildReturnMenu"), + GUI + "QuestMenus", Set.of("roleJournal"), + GUI + "SuppliedMenus", Set.of("command", "route"), + "com/dunerealms/menus/DuneMenusPlugin", Set.of("openMenu", "presentService", "onTabComplete"), + "com/example/dunelobby/DuneLobby", Set.of("entityInteract", "departure", "depart")); + + + public static void main(String[] args) throws Exception { + if (args.length != 3) throw new IllegalArgumentException("Expected retained, donor and output classes"); + var retainedReader = new ClassReader(Files.readAllBytes(Path.of(args[0]))); + var retained = parse(retainedReader); + var donor = parse(new ClassReader(Files.readAllBytes(Path.of(args[1])))); + if (retained.name.equals("com/dunerealms/gui/MenuDocument") || retained.name.equals("com/dunerealms/menus/SuppliedDocument")) { + int expected = retained.name.endsWith("/MenuDocument") ? 6 : 7; + int changed = 0; + for (var method : retained.methods) { + if (!method.name.equals("html") || org.objectweb.asm.Type.getArgumentTypes(method.desc).length != expected) continue; + for (var instruction : method.instructions.toArray()) { + if (instruction instanceof org.objectweb.asm.tree.MethodInsnNode call && call.owner.endsWith("/MenuPolish")) + throw new IllegalArgumentException("Style already installed"); + if (instruction.getOpcode() == org.objectweb.asm.Opcodes.ARETURN) + method.instructions.insertBefore(instruction, new org.objectweb.asm.tree.MethodInsnNode( + org.objectweb.asm.Opcodes.INVOKESTATIC, retained.name.substring(0,retained.name.lastIndexOf('/')+1)+"MenuPolish", + "apply", "(Ljava/lang/String;)Ljava/lang/String;", false)); + } + changed++; + } + if (changed != 1) throw new IllegalArgumentException("Unexpected document overloads"); + var writer = new ClassWriter(retainedReader, 0); retained.accept(writer); + Files.write(Path.of(args[2]), writer.toByteArray()); return; + } + var targets = TARGETS.get(retained.name); + if (targets == null || !retained.name.equals(donor.name)) throw new IllegalArgumentException("Unexpected overlay class"); + var additions = new LinkedHashMap(); + var renamed = new HashMap(); + for (String target : targets.stream().sorted().toList()) { + var method = donor.methods.stream().filter(m -> m.name.equals(target)).toList(); + if (method.size() != 1) throw new IllegalArgumentException("Expected one donor method " + target); + prepare(donor, method.getFirst(), additions, renamed); + } + for (var entry : additions.entrySet()) { + var method = entry.getValue(); + if (!targets.contains(method.name) && + retained.methods.stream().anyMatch(old -> old.name.equals(method.name) && old.desc.equals(method.desc))) { + throw new IllegalArgumentException("Unexpected existing helper " + method.name); + } + retained.methods.removeIf(old -> old.name.equals(method.name) && old.desc.equals(method.desc)); + retained.methods.add(method); + } + var writer = new ClassWriter(retainedReader, 0); + retained.accept(writer); + Files.write(Path.of(args[2]), writer.toByteArray()); + } + + private static void prepare(ClassNode donor, MethodNode method, Map copies, + Map renamed) { + String key = method.name + method.desc; + if (copies.putIfAbsent(key, method) != null) return; + for (var instruction : method.instructions) { + if (!(instruction instanceof InvokeDynamicInsnNode dynamic)) continue; + for (int i = 0; i < dynamic.bsmArgs.length; i++) { + if (!(dynamic.bsmArgs[i] instanceof Handle handle) || !handle.getOwner().equals(donor.name) || + !handle.getName().startsWith("lambda$")) continue; + String original = handle.getName() + handle.getDesc(); + String replacement = renamed.get(original); + if (replacement == null) { + var helper = donor.methods.stream().filter(m -> m.name.equals(handle.getName()) && + m.desc.equals(handle.getDesc())).findFirst().orElseThrow(); + replacement = "compactMenu$" + handle.getName(); + renamed.put(original, replacement); + helper.name = replacement; + prepare(donor, helper, copies, renamed); + } + dynamic.bsmArgs[i] = new Handle(handle.getTag(), handle.getOwner(), replacement, + handle.getDesc(), handle.isInterface()); + } + } + } + + private static ClassNode parse(ClassReader reader) { + var node = new ClassNode(); + reader.accept(node, 0); + return node; + } +} diff --git a/tools/plugin_builder_multiverse.py b/tools/plugin_builder_multiverse.py new file mode 100644 index 00000000..20914b25 --- /dev/null +++ b/tools/plugin_builder_multiverse.py @@ -0,0 +1,88 @@ +"""Build the paired Lobby Core and standalone Builder updates from exact inputs.""" +import argparse +import os +from pathlib import Path +import subprocess +from tempfile import TemporaryDirectory + +from plugin_wild_update import digest, read_archive, write_archive + +CORE_SHA = "3cc3b9a918f1691503c374a035e51ed295fedf879d2fc083ea8b1dd0b89dea0a" +BUILDER_SHA = "18f8878b18f249ff97728542a63effedb1d19f473168b9ab7ec8ef8f11c25538" +CORE = "com/example/dunerealms/" +BUILDER = "com/example/dunelobby/" +CORE_CLASSES = ["SharedDatabase.class", "DuneCore.class"] +LEASE = "SharedDatabase$BuilderLease.class" +BUILDER_CLASSES = [ + "BuilderTransfer.class", "BuilderTransfer$1.class", "BuilderTransfer$VoidTerrain.class", + "BuilderTransfer$SharedBuild.class", "BuilderTransfer$PendingTransfer.class", + "BuilderSharedProfiles.class", "BuilderMultiverse.class", "LegacyBuilderPlugin.class", +] + + +def checked_archive(file, sha): + data = file.read_bytes() + if digest(data) != sha: + raise ValueError(f"Unexpected checksum for {file.name}") + return read_archive(data) + + +def assemble(core, builder, core_donor, core_donor_sha, staff_donor, staff_donor_sha, output, classpath): + retained_core = checked_archive(core, CORE_SHA) + retained_builder = checked_archive(builder, BUILDER_SHA) + compiled_core = checked_archive(core_donor, core_donor_sha) + compiled_staff = checked_archive(staff_donor, staff_donor_sha) + + if CORE + LEASE in retained_core: + raise ValueError("Retained Core already contains a Builder lease") + if set(name for name in retained_builder if name.startswith(BUILDER) and name.endswith(".class")) != { + BUILDER + "BuilderTransfer.class", BUILDER + "BuilderTransfer$VoidTerrain.class" + }: + raise ValueError("Unexpected classes in retained Builder") + + keys = [CORE + name for name in CORE_CLASSES] + java_home = os.environ.get("JAVA_HOME") + executable = "java.exe" if os.name == "nt" else "java" + java = str(Path(java_home) / "bin" / executable) if java_home else executable + helper = Path(__file__).with_name("BuilderProfileCoreOverlay.java") + with TemporaryDirectory() as temporary: + root = Path(temporary) + files = [] + for source, prefix in ((retained_core, "retained-"), (compiled_core, "donor-")): + for name in keys: + file = root / (prefix + Path(name).name) + file.write_bytes(source[name]) + files.append(str(file)) + subprocess.run([java, "--class-path", classpath, str(helper), *files, str(root)], check=True) + for name in keys: + retained_core[name] = (root / Path(name).name).read_bytes() + retained_core[CORE + LEASE] = compiled_core[CORE + LEASE] + + descriptor = retained_builder["plugin.yml"] + main = b"main: com.example.dunelobby.BuilderTransfer" + dependency = b"depend: [WorldEdit]" + if descriptor.count(main) != 1 or descriptor.count(dependency) != 1 or b"softdepend:" in descriptor: + raise ValueError("Unexpected retained Builder command descriptor") + line = b"\r\n" if b"\r\n" in descriptor else b"\n" + retained_builder["plugin.yml"] = descriptor.replace(main, b"main: com.example.dunelobby.LegacyBuilderPlugin").replace( + dependency, dependency + line + b"softdepend: [DuneCore, Multiverse-Core]" + ) + for name in BUILDER_CLASSES: + retained_builder[BUILDER + name] = compiled_staff[BUILDER + name] + + output.mkdir() + (output / core.name).write_bytes(write_archive(retained_core)) + (output / builder.name).write_bytes(write_archive(retained_builder)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("core", type=Path) + parser.add_argument("builder", type=Path) + parser.add_argument("core_donor", type=Path) + parser.add_argument("core_donor_sha") + parser.add_argument("staff_donor", type=Path) + parser.add_argument("staff_donor_sha") + parser.add_argument("output", type=Path) + parser.add_argument("classpath", help="ASM core and tree JARs") + assemble(**vars(parser.parse_args())) diff --git a/tools/plugin_builder_shared_profiles.py b/tools/plugin_builder_shared_profiles.py new file mode 100644 index 00000000..5aebb4bb --- /dev/null +++ b/tools/plugin_builder_shared_profiles.py @@ -0,0 +1,46 @@ +"""Graft the shared inventory guard onto the retained Lobby Builder JAR.""" +import argparse +import os +from pathlib import Path +import subprocess +from tempfile import TemporaryDirectory + +from plugin_wild_update import digest, read_archive, write_archive + +PREFIX = "com/example/dunelobby/" +BUILDER = PREFIX + "BuilderTransfer.class" +GUARD = PREFIX + "BuilderSharedProfiles.class" +BASELINE = "18f8878b18f249ff97728542a63effedb1d19f473168b9ab7ec8ef8f11c25538" + + +def assemble(baseline, donor, donor_sha, output, classpath): + existing = baseline.read_bytes() + compiled = donor.read_bytes() + if digest(existing) != BASELINE or digest(compiled) != donor_sha: + raise ValueError("Unexpected Builder baseline or donor checksum") + archive = read_archive(existing) + payload = read_archive(compiled) + if GUARD in archive: + raise ValueError("Builder already contains the shared profile guard") + java_home = os.environ.get("JAVA_HOME") + executable = "java.exe" if os.name == "nt" else "java" + java = str(Path(java_home) / "bin" / executable) if java_home else executable + helper = Path(__file__).with_name("BuilderSharedProfilesOverlay.java") + with TemporaryDirectory() as temp: + old, new = (Path(temp) / name for name in ("retained.class", "guarded.class")) + old.write_bytes(archive[BUILDER]) + subprocess.run([java, "--class-path", classpath, str(helper), str(old), str(new)], check=True) + archive[BUILDER] = new.read_bytes() + archive[GUARD] = payload[GUARD] + with output.open("xb") as candidate: + candidate.write(write_archive(archive)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("baseline", type=Path) + parser.add_argument("donor", type=Path) + parser.add_argument("donor_sha") + parser.add_argument("output", type=Path) + parser.add_argument("classpath", help="ASM core and tree JARs") + assemble(**vars(parser.parse_args())) diff --git a/tools/plugin_menu_polish.py b/tools/plugin_menu_polish.py new file mode 100644 index 00000000..9af473b6 --- /dev/null +++ b/tools/plugin_menu_polish.py @@ -0,0 +1,54 @@ +"""Assemble reviewed compact-menu methods onto the installed plugin variants.""" +import argparse +import os +from pathlib import Path +import subprocess +from tempfile import TemporaryDirectory + +from plugin_wild_update import digest, read_archive, write_archive + +CLASSES = { + "gui": ("com/dunerealms/gui/MenuDocument.class", "com/dunerealms/gui/DuneGUI.class", "com/dunerealms/gui/QuestMenus.class", "com/dunerealms/gui/SuppliedMenus.class"), + "menus": ("com/dunerealms/menus/SuppliedDocument.class", "com/dunerealms/menus/DuneMenusPlugin.class"), + "lobby": ("com/example/dunelobby/DuneLobby.class",), +} + + + +def assemble(module, baseline, baseline_sha, donor, donor_sha, output, classpath): + baseline_bytes = baseline.read_bytes() + donor_bytes = donor.read_bytes() + if digest(baseline_bytes) != baseline_sha or digest(donor_bytes) != donor_sha: + raise ValueError("Unexpected baseline or donor checksum") + retained = read_archive(baseline_bytes) + compiled = read_archive(donor_bytes) + java_home = os.environ.get("JAVA_HOME") + executable = "java.exe" if os.name == "nt" else "java" + java = str(Path(java_home) / "bin" / executable) if java_home else executable + helper = Path(__file__).with_name("CompactMenuMerge.java") + with TemporaryDirectory() as temporary: + temp = Path(temporary) + for index, entry in enumerate(CLASSES[module]): + old, new, merged = (temp / f"{index}-{name}.class" for name in ("retained", "donor", "merged")) + old.write_bytes(retained[entry]) + new.write_bytes(compiled[entry]) + subprocess.run([java, "--class-path", classpath, str(helper), str(old), str(new), str(merged)], check=True) + retained[entry] = merged.read_bytes() + if module in ("gui", "menus"): + entry = "com/dunerealms/" + module + "/MenuPolish.class" + if entry in retained: raise ValueError("Menu styling already installed") + retained[entry] = compiled[entry] + with output.open("xb") as candidate: + candidate.write(write_archive(retained)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("module", choices=CLASSES) + parser.add_argument("baseline", type=Path) + parser.add_argument("baseline_sha") + parser.add_argument("donor", type=Path) + parser.add_argument("donor_sha") + parser.add_argument("output", type=Path) + parser.add_argument("classpath", help="ASM core and tree JARs") + assemble(**vars(parser.parse_args())) diff --git a/tools/stage_multiverse_core.py b/tools/stage_multiverse_core.py new file mode 100644 index 00000000..967a3e31 --- /dev/null +++ b/tools/stage_multiverse_core.py @@ -0,0 +1,52 @@ +"""Package the immutable official Multiverse-Core input for Lobby only.""" +import argparse +import hashlib +import io +import json +from pathlib import Path +import re +from urllib.request import Request, urlopen +import zipfile + +ROOT = Path(__file__).resolve().parents[1] + +def verify(data, pin): + for kind in ("sha256", "sha512"): + if hashlib.new(kind, data).hexdigest() != pin[kind]: + raise ValueError("Unexpected official Multiverse checksum") + with zipfile.ZipFile(io.BytesIO(data)) as jar: + descriptor = jar.read("plugin.yml").decode() + for key, value in (("name", "Multiverse-Core"), ("version", pin["version"])): + if not re.search(r"^" + key + r":\s*['\"]?" + re.escape(value) + r"['\"]?\s*$", descriptor, re.M): + raise ValueError("Unexpected Multiverse plugin identity") + if pin["scope"] != ["lobby"] or pin["optionalModulesInstalled"]: + raise ValueError("Only Core on Lobby is authorized") + +def stage(output, source, supplied=None): + if not re.fullmatch(r"[a-f0-9]{40}", source): + raise ValueError("An exact source commit is required") + pin_path = ROOT / "network/lobby/multiverse-core.json" + pin = json.loads(pin_path.read_text()) + if supplied: + data = supplied.read_bytes() + else: + request = Request(pin["url"], headers={"User-Agent": "DuneRealms-reviewed-build/1"}) + with urlopen(request, timeout=60) as response: + data = response.read(8 * 1024 * 1024 + 1) + verify(data, pin) + output.mkdir(exist_ok=False) + (output / pin["filename"]).write_bytes(data) + (output / "config.yml").write_bytes((ROOT / "network/lobby/multiverse-config.yml").read_bytes()) + (output / "multiverse-core.json").write_bytes(pin_path.read_bytes()) + (output / "LICENSE-Multiverse-Core.md").write_bytes((ROOT / "network/lobby/multiverse-LICENSE.md").read_bytes()) + (output / "SOURCE_COMMIT").write_text(source + "\n") + sums = [hashlib.sha256(p.read_bytes()).hexdigest() + " " + p.name for p in sorted(output.iterdir())] + (output / "SHA256SUMS").write_text("\n".join(sums) + "\n") + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + parser.add_argument("source") + parser.add_argument("--supplied", type=Path) + args = parser.parse_args() + stage(args.output, args.source, args.supplied) diff --git a/tools/test_multiverse_core.py b/tools/test_multiverse_core.py new file mode 100644 index 00000000..f8b07d2f --- /dev/null +++ b/tools/test_multiverse_core.py @@ -0,0 +1,32 @@ +import hashlib +import io +import unittest +import zipfile +from stage_multiverse_core import verify + +class VendorIdentity(unittest.TestCase): + def fixture(self, name="Multiverse-Core"): + out=io.BytesIO() + with zipfile.ZipFile(out,"w") as z: + z.writestr("plugin.yml",f"name: {name}\nversion: 5.8.2\n") + data=out.getvalue() + pin={k:hashlib.new(k,data).hexdigest() for k in ["sha256","sha512"]} + return data,dict(pin,version="5.8.2",scope=["lobby"],optionalModulesInstalled=[]) + + def test_exact_identity(self): + data,pin=self.fixture();verify(data,pin) + + def test_changed_binary_rejected(self): + data,pin=self.fixture() + with self.assertRaises(ValueError):verify(data+b"changed",pin) + + def test_inventory_module_rejected(self): + data,pin=self.fixture("Multiverse-Inventories") + with self.assertRaises(ValueError):verify(data,pin) + + def test_scope_and_optional_modules_rejected(self): + data,pin=self.fixture() + for edit in [dict(scope=["sigma_draconis_iv"]),dict(optionalModulesInstalled=["inventories"])]: + with self.assertRaises(ValueError):verify(data,dict(pin,**edit)) + +if __name__=="__main__":unittest.main()