From 26106815ce99461a8215c72d6cecc77e7bf22992 Mon Sep 17 00:00:00 2001 From: unimatrixgit <95320811+unimatrixgit@users.noreply.github.com> Date: Sun, 6 Dec 2026 11:14:19 +0100 Subject: [PATCH] Keep unnamed goods visible in Exchange listing cards --- .forgejo/workflows/exchange-listing-cards.yml | 42 +++++++++++++++ .../com/dunerealms/gui/ExchangeMenus.java | 6 ++- .../gui/ExchangeBrowseSafetyTest.java | 8 +++ tools/ExchangeListingMerge.java | 51 +++++++++++++++++++ tools/plugin_exchange_listings.py | 49 ++++++++++++++++++ 5 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 .forgejo/workflows/exchange-listing-cards.yml create mode 100644 tools/ExchangeListingMerge.java create mode 100644 tools/plugin_exchange_listings.py diff --git a/.forgejo/workflows/exchange-listing-cards.yml b/.forgejo/workflows/exchange-listing-cards.yml new file mode 100644 index 00000000..0e05a50d --- /dev/null +++ b/.forgejo/workflows/exchange-listing-cards.yml @@ -0,0 +1,42 @@ +name: Exchange Listing Cards Build +on: + workflow_dispatch: + push: + branches: ['fix/exchange-listing-cards-*'] + +jobs: + exchange-listing-cards: + 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: Build Exchange listing class donor + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneRealmsGUI test jar + + mkdir exchange-listing-cards-artifacts + python3 tools/plugin_exchange_listings.py DuneRealmsGUI/build/libs/DunerealmsGUI.jar exchange-listing-cards-artifacts/exchange-listing-cards-classes.zip + cp tools/plugin_exchange_listings.py tools/ExchangeListingMerge.java exchange-listing-cards-artifacts/ + printf '%s\n' "$(git rev-parse HEAD)" > exchange-listing-cards-artifacts/SOURCE_COMMIT + (cd exchange-listing-cards-artifacts && sha256sum -- exchange-listing-cards-classes.zip *.py SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Exchange-Listing-Cards + path: exchange-listing-cards-artifacts/ + if-no-files-found: error diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/ExchangeMenus.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/ExchangeMenus.java index 10f815f7..389149c9 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/ExchangeMenus.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/ExchangeMenus.java @@ -41,7 +41,11 @@ final class ExchangeMenus implements Listener,AutoCloseable { } private void request(Player p,JsonObject input,Consumer done){request(p,input,done,p::sendMessage);} private JsonObject action(String action){var q=new JsonObject();q.addProperty("action",action);return q;} - private void list(Player p,boolean mine,int page){var q=action("read");q.addProperty("mine",mine);q.addProperty("page",page);request(p,q,data->{var s=panel(p,mine?"Exchange · Your listings":"Exchange · Buy");button(s,1,Material.EMERALD,"Buy","Browse all available items",()->list(p,false,0));button(s,4,Material.NETHERITE_CHESTPLATE,"Kits","Published organisation stillsuit kits",()->kits(p,0));button(s,7,Material.CHEST,"My listings","Manage your existing listings",()->list(p,true,0));int index=0;for(var value:data.getAsJsonArray("listings")){var row=value.getAsJsonObject();int slot=10+(index/6)*9+index%6;index++;try{var item=bridge.exchangeIcon(row);var meta=item.getItemMeta();List lore=new ArrayList<>(meta.hasLore()?meta.lore():List.of());lore.add(Component.text(" "));lore.add(Component.text("Seller: "+row.get("seller").getAsString(),NamedTextColor.GRAY));lore.add(Component.text(row.get("quantity").getAsInt()+" available · "+money(row.get("priceMinor").getAsLong())+" each",NamedTextColor.GOLD));meta.lore(lore);item.setItemMeta(meta);s.inventory.setItem(slot,item);Runnable pick=()->{if(row.get("sellerUuid").getAsString().equals(p.getUniqueId().toString()))withdraw(p,row);else purchase(p,new Purchase(row,1,UUID.randomUUID()));};s.actions.put(slot,pick);s.choices.add(new BedrockForms.Choice(row.get("title").getAsString(),money(row.get("priceMinor").getAsLong())+" · "+row.get("quantity").getAsInt()+" available",pick));}catch(Exception unsupported){s.inventory.setItem(slot,icon(Material.BARRIER,"Unsupported item","This version cannot display the stored item."));}} + static Component listingName(Component original,String title,boolean own){ + if(original!=null&&!net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(original).isBlank())return original; + return Component.text(own?"Yours · "+title:title); + } + private void list(Player p,boolean mine,int page){var q=action("read");q.addProperty("mine",mine);q.addProperty("page",page);request(p,q,data->{var s=panel(p,mine?"Exchange · Your listings":"Exchange · Buy");button(s,1,Material.EMERALD,"Buy","Browse all available items",()->list(p,false,0));button(s,4,Material.NETHERITE_CHESTPLATE,"Kits","Published organisation stillsuit kits",()->kits(p,0));button(s,7,Material.CHEST,"My listings","Manage your existing listings",()->list(p,true,0));int index=0;for(var value:data.getAsJsonArray("listings")){var row=value.getAsJsonObject();int slot=10+(index/6)*9+index%6;index++;try{var item=bridge.exchangeIcon(row);var meta=item.getItemMeta();String title=row.get("title").getAsString();boolean own=row.get("sellerUuid").getAsString().equalsIgnoreCase(p.getUniqueId().toString());meta.displayName(listingName(meta.displayName(),title,own));List lore=new ArrayList<>(meta.hasLore()?meta.lore():List.of());lore.add(Component.text(" "));lore.add(Component.text(own?"Your listing · Select to withdraw":"Seller: "+row.get("seller").getAsString(),NamedTextColor.GRAY));lore.add(Component.text(row.get("quantity").getAsInt()+" available · "+money(row.get("priceMinor").getAsLong())+" each",NamedTextColor.GOLD));meta.lore(lore);item.setItemMeta(meta);s.inventory.setItem(slot,item);Runnable pick=()->{if(row.get("sellerUuid").getAsString().equals(p.getUniqueId().toString()))withdraw(p,row);else purchase(p,new Purchase(row,1,UUID.randomUUID()));};s.actions.put(slot,pick);s.choices.add(new BedrockForms.Choice(own?"Yours · "+title:title,money(row.get("priceMinor").getAsLong())+" · "+row.get("quantity").getAsInt()+" available",pick));}catch(Exception unsupported){String title=row.get("title").getAsString();String details=money(row.get("priceMinor").getAsLong())+" each · "+row.get("quantity").getAsInt()+" available";s.inventory.setItem(slot,icon(Material.BARRIER,title,details,"Item preview unavailable."));s.description+="\n"+title+" · "+details+" · Item preview unavailable.";}} if(index==0)s.inventory.setItem(22,icon(Material.PAPER,"No listings",mine?"No own listings. Hold an item and choose Sell item.":"Check again after players publish goods.")); if(page>0)button(s,45,Material.ARROW,"Previous","Page "+page,()->list(p,mine,page-1));if(data.get("hasNext").getAsBoolean())button(s,53,Material.ARROW,"Next","More listings",()->list(p,mine,page+1));button(s,48,Material.BOOK,"Imperial Codex","Return to your services",()->back.accept(p));button(s,49,Material.HOPPER,"Sell item","List the item in your main hand",()->draft(p));button(s,50,Material.CHEST_MINECART,"Collect purchases","Deliver paid items waiting for inventory space",()->{deliver(p,true);list(p,mine,page);});resumeButton(p,s);show(p,s); });} diff --git a/DuneRealmsGUI/src/test/java/com/dunerealms/gui/ExchangeBrowseSafetyTest.java b/DuneRealmsGUI/src/test/java/com/dunerealms/gui/ExchangeBrowseSafetyTest.java index a078c601..7e77a0bf 100644 --- a/DuneRealmsGUI/src/test/java/com/dunerealms/gui/ExchangeBrowseSafetyTest.java +++ b/DuneRealmsGUI/src/test/java/com/dunerealms/gui/ExchangeBrowseSafetyTest.java @@ -3,4 +3,12 @@ import com.google.gson.JsonObject;import java.util.*;import org.junit.jupiter.ap class ExchangeBrowseSafetyTest { @Test void unresolvedAttemptKeepsOriginalReferenceQuantityAndListing(){var old=new JsonObject();old.addProperty("id","9");var pending=new ExchangeMenus.Purchase(old,1,UUID.randomUUID());var candidate=new ExchangeMenus.Purchase(new JsonObject(),64,UUID.randomUUID());var result=ExchangeMenus.resume(candidate,pending);assertSame(pending,result);assertEquals(pending.request(),result.request());assertEquals(1,result.amount());assertEquals("9",result.row().get("id").getAsString());assertSame(candidate,ExchangeMenus.resume(candidate,null));} @Test void quantityPresetsCannotAdvertiseUnavailableAmounts(){assertEquals(List.of(),ExchangeQuantity.presets(1));assertEquals(List.of(16),ExchangeQuantity.presets(24));assertEquals(List.of(16,32),ExchangeQuantity.presets(32));assertEquals(List.of(16,32,64),ExchangeQuantity.presets(64));} + @Test void listingNamesKeepVanillaGoodsVisibleAndIdentifyOwnGoods(){ + var serializer=net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText(); + var custom=net.kyori.adventure.text.Component.text("Dune blade",net.kyori.adventure.text.format.NamedTextColor.RED); + assertEquals("Carrot",serializer.serialize(ExchangeMenus.listingName(null,"Carrot",false))); + assertEquals("Yours · Spruce Log",serializer.serialize(ExchangeMenus.listingName(net.kyori.adventure.text.Component.empty(),"Spruce Log",true))); + assertSame(custom,ExchangeMenus.listingName(custom,"A different title",false)); + assertSame(custom,ExchangeMenus.listingName(custom,"A different title",true)); + } } diff --git a/tools/ExchangeListingMerge.java b/tools/ExchangeListingMerge.java new file mode 100644 index 00000000..dce70480 --- /dev/null +++ b/tools/ExchangeListingMerge.java @@ -0,0 +1,51 @@ +import java.nio.file.Files; +import java.nio.file.Path; +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 ExchangeListingMerge { + private static final String CLASS = "com/dunerealms/gui/ExchangeMenus"; + private static final String LIST_BODY = "lambda$list$13"; + private static final String LIST_DESC = "(Lorg/bukkit/entity/Player;ZILcom/google/gson/JsonObject;)V"; + private static final String NAME_DESC = "(Lnet/kyori/adventure/text/Component;Ljava/lang/String;Z)Lnet/kyori/adventure/text/Component;"; + + 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]))); + ClassNode retained = parse(retainedReader); + ClassNode donor = parse(new ClassReader(Files.readAllBytes(Path.of(args[1])))); + if (!CLASS.equals(retained.name) || !CLASS.equals(donor.name)) throw new IllegalArgumentException("Wrong class"); + MethodNode old = method(retained,LIST_BODY,LIST_DESC); + MethodNode next = method(donor,LIST_BODY,LIST_DESC); + for (var instruction : next.instructions) { + if (instruction instanceof InvokeDynamicInsnNode dynamic) { + for (Object argument : dynamic.bsmArgs) { + if (argument instanceof Handle target && CLASS.equals(target.getOwner())) { + method(retained,target.getName(),target.getDesc()); + } + } + } + } + if (retained.methods.stream().anyMatch(m -> m.name.equals("listingName"))) throw new IllegalArgumentException("Preview helper already exists"); + retained.methods.set(retained.methods.indexOf(old),next); + retained.methods.add(method(donor,"listingName",NAME_DESC)); + var writer = new ClassWriter(retainedReader,0); + retained.accept(writer); + Files.write(Path.of(args[2]),writer.toByteArray()); + } + + private static MethodNode method(ClassNode cls,String name,String desc) { + return cls.methods.stream().filter(m -> m.name.equals(name) && m.desc.equals(desc)).findFirst() + .orElseThrow(() -> new IllegalArgumentException("Missing exact method " + name + desc)); + } + + private static ClassNode parse(ClassReader reader) { + var node = new ClassNode(); + reader.accept(node,0); + return node; + } +} diff --git a/tools/plugin_exchange_listings.py b/tools/plugin_exchange_listings.py new file mode 100644 index 00000000..abbee773 --- /dev/null +++ b/tools/plugin_exchange_listings.py @@ -0,0 +1,49 @@ +"""Build the scoped Exchange listing preview overlay.""" +import argparse +from hashlib import sha256 +from pathlib import Path +import subprocess +from tempfile import TemporaryDirectory +from zipfile import ZipFile + +CLASS = "com/dunerealms/gui/ExchangeMenus.class" +BASELINES = { + "8bdd90dbb5e0fb0d0da0d15008a82cdfaefebecc0864f4ee443e6cd9442fd4db", + "c252f79f2735e92b1be3660a6c5d9d09f7aa8e57e81f05582fb9bca1c8bc04eb", +} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("input", type=Path) + parser.add_argument("output", type=Path) + parser.add_argument("--baseline", type=Path) + parser.add_argument("--classpath") + args = parser.parse_args() + with ZipFile(args.input) as donor: + if not args.baseline: + with ZipFile(args.output, "x") as capsule: + capsule.writestr(CLASS, donor.read(CLASS)) + return + if donor.namelist() != [CLASS] or not args.classpath: + raise ValueError("Expected the single-class donor and ASM classpath") + if sha256(args.baseline.read_bytes()).hexdigest() not in BASELINES: + raise ValueError("Unexpected retained GUI") + with TemporaryDirectory() as temp, ZipFile(args.baseline) as retained: + work = Path(temp) + before, new, result = (work / name for name in ("before.class", "donor.class", "patched.class")) + before.write_bytes(retained.read(CLASS)) + new.write_bytes(donor.read(CLASS)) + subprocess.run( + ["java", "--class-path", args.classpath, str(Path(__file__).with_name("ExchangeListingMerge.java")), str(before), str(new), str(result)], + check=True, + ) + if len(set(retained.namelist())) != len(retained.namelist()): + raise ValueError("Duplicate baseline entries") + with ZipFile(args.output, "x") as output: + for entry in retained.infolist(): + output.writestr(entry, result.read_bytes() if entry.filename == CLASS else retained.read(entry)) + + +if __name__ == "__main__": + main()