diff --git a/.forgejo/workflows/exchange-market.yml b/.forgejo/workflows/exchange-market.yml new file mode 100644 index 00000000..bdfa49ab --- /dev/null +++ b/.forgejo/workflows/exchange-market.yml @@ -0,0 +1,42 @@ +name: Exchange Market Build +on: + workflow_dispatch: + push: + branches: ['feat/exchange-market-order-*'] + +jobs: + exchange-market: + 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 class donors + shell: bash + run: | + set -euo pipefail + gradle --no-daemon -p DuneRealmsGUI test jar + gradle --no-daemon -p DuneMenus test jar + mkdir exchange-market-artifacts + python3 tools/plugin_exchange_market.py package DuneRealmsGUI/build/libs/DunerealmsGUI.jar DuneMenus/build/libs/DuneMenus.jar exchange-market-artifacts/exchange-market-classes.zip + cp tools/plugin_exchange_market.py tools/ExchangeMarketToolbarMerge.java exchange-market-artifacts/ + git rev-parse HEAD > exchange-market-artifacts/SOURCE_COMMIT + (cd exchange-market-artifacts && sha256sum -- exchange-market-classes.zip *.py *.java SOURCE_COMMIT > SHA256SUMS) + - uses: actions/upload-artifact@v3 + with: + name: DuneRealms-Exchange-Market + path: exchange-market-artifacts/ + if-no-files-found: error diff --git a/DuneMenus/src/main/java/com/dunerealms/menus/SuppliedDocument.java b/DuneMenus/src/main/java/com/dunerealms/menus/SuppliedDocument.java index 78a83488..b5d4bf72 100644 --- a/DuneMenus/src/main/java/com/dunerealms/menus/SuppliedDocument.java +++ b/DuneMenus/src/main/java/com/dunerealms/menus/SuppliedDocument.java @@ -9,7 +9,7 @@ final class SuppliedDocument { static List lines(String text,int width){List out=new ArrayList<>();String rest=clean(text);while(rest.length()>width){int split=rest.lastIndexOf(' ',width);if(split summary(Card card){List ordered=new ArrayList<>();for(String pattern:List.of("(?i).*\\bDM\\b.*","(?i).*(available|in stock).*","(?i).*seller:.*"))for(String line:card.lore())if(clean(line).matches(pattern)&&!ordered.contains(line))ordered.add(line);for(String line:card.lore())if(!ordered.contains(line))ordered.add(line);List out=new ArrayList<>();for(String line:ordered)out.addAll(lines(line,24));return out;} static String image(Card c,Map images){String image=images.getOrDefault(c.slot(),"");return image.matches("pack/assets/[a-z0-9_/.-]+\\.png")&&!image.contains("..")?"":symbol(c);} - static boolean marketTool(Card c){return Set.of(1,4,7,45,46,48,49,50,53).contains(c.slot())&&Set.of("Buy","Buy items","Kits","My listings","Sell item","Imperial Codex","Collect purchases","Resume pending purchase","Previous","Next","Back").contains(clean(c.title()));} + static boolean marketTool(Card c){return Set.of(1,4,7,45,46,47,48,49,50,52,53).contains(c.slot())&&Set.of("Buy","Buy items","Kits","My listings","Sort listings","Categories","Sell item","Imperial Codex","Collect purchases","Resume pending purchase","Previous","Next","Back").contains(clean(c.title()));} static String kind(Card c){if(!c.material().equals("arrow"))return "card";String t=clean(c.title()).toLowerCase(Locale.ROOT);return t.contains("back")?"back":t.contains("previous")||t.contains("next")?"pager":"card";} static String html(String id,String title,String subtitle,List cards,List info){return html(id,title,subtitle,cards,info,Map.of());} static String html(String id,String title,String subtitle,List cards,List info,Map images){return html(id,title,subtitle,cards,info,images,-1);} diff --git a/DuneMenus/src/rendererTest/java/com/dunerealms/menus/RendererVerification.java b/DuneMenus/src/rendererTest/java/com/dunerealms/menus/RendererVerification.java index 356ca93f..a0b0e783 100644 --- a/DuneMenus/src/rendererTest/java/com/dunerealms/menus/RendererVerification.java +++ b/DuneMenus/src/rendererTest/java/com/dunerealms/menus/RendererVerification.java @@ -71,7 +71,7 @@ public class RendererVerification { 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); for(String name:List.of("item/iron_sword","block/cobblestone")){Path target=dir.resolve("pack/assets/minecraft/textures/"+name+".png");Files.createDirectories(target.getParent());Files.copy(Path.of("../network/resource-pack/vanilla-art/overlay/assets/minecraft/textures/"+name+".png"),target,StandardCopyOption.REPLACE_EXISTING);} var listing=new Card(13,"\uE400§6Paul's chopper",List.of("LEGENDARY | MK XIV","Used by Paul himself.","Efficiency VIII","Fortune IV","Mending I","Unbreaking IV","Seller: J.A.R.V.I.S. HQ","1 available · 500.00 DM each"),"netherite_axe"); - String listingHtml=SuppliedDocument.html("exchange","Exchange · Buy","Authoritative item artwork",List.of(new Card(1,"Buy",List.of("Browse available items"),"emerald"),new Card(4,"Kits",List.of(),"netherite_chestplate"),new Card(7,"My listings",List.of(),"chest"),new Card(49,"Sell item",List.of(),"hopper"),new Card(50,"Collect purchases",List.of(),"chest_minecart"),listing,new Card(14,"Cobblestone",List.of("64 available · 1.00 DM each"),"cobblestone"),new Card(15,"Iron sword",List.of("1 available · 10.00 DM each"),"iron_sword")),List.of(),Map.of(13,"pack/assets/dunerealms/textures/item/equipment/legendary_mk14_axe.png",14,"pack/assets/minecraft/textures/block/cobblestone.png",15,"pack/assets/minecraft/textures/item/iron_sword.png"),13); + String listingHtml=SuppliedDocument.html("exchange","Exchange · Buy","Authoritative item artwork",List.of(new Card(1,"Buy",List.of("Browse available items"),"emerald"),new Card(4,"Kits",List.of(),"netherite_chestplate"),new Card(7,"My listings",List.of(),"chest"),new Card(47,"Sort listings",List.of(),"compass"),new Card(52,"Categories",List.of(),"bookshelf"),new Card(49,"Sell item",List.of(),"hopper"),new Card(50,"Collect purchases",List.of(),"chest_minecart"),listing,new Card(14,"Cobblestone",List.of("64 available · 1.00 DM each"),"cobblestone"),new Card(15,"Iron sword",List.of("1 available · 10.00 DM each"),"iron_sword")),List.of(),Map.of(13,"pack/assets/dunerealms/textures/item/equipment/legendary_mk14_axe.png",14,"pack/assets/minecraft/textures/block/cobblestone.png",15,"pack/assets/minecraft/textures/item/iron_sword.png"),13); var listingPage=Page.of(listingHtml,dir.resolve("exchange-item.html"),loader);var listingFrame=HtmlRenderer.render(listingPage,1536,896,1.5,0,Selector.State.NONE);if(!listingPage.problems.isEmpty())throw new AssertionError(listingPage.problems.toString());ImageIO.write(listingFrame.image(),"png",dir.resolve("exchange-item-engine.png").toFile()); for(var element:listingPage.document.select(".market-tool,[data-slot='1013']")){var bounds=listingFrame.boundsOf(element);var at=listingFrame.elementAt(bounds.getCenterX(),bounds.getCenterY());if(at==null||!at.closest("[data-slot]").attr("data-slot").equals(element.attr("data-slot")))throw new AssertionError("Detail control hitbox");} System.out.println("PASS: "+checked+" direct action hitboxes across15 menu families."); diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/ExchangeMenus.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/ExchangeMenus.java index 389149c9..73b875c1 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/ExchangeMenus.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/ExchangeMenus.java @@ -18,8 +18,29 @@ final class ExchangeMenus implements Listener,AutoCloseable { private final JavaPlugin plugin;private final HouseBridge bridge;private final Consumer back;private final Predicate artwork; private final Map pending=new HashMap<>();private final Set delivering=new HashSet<>(); private final Map retries=new HashMap<>(); + private final Map listingSorts=new HashMap<>(); + private final Map listingCategories=new HashMap<>(); + private enum ListingCategory { + ALL("all","All categories"), EQUIPMENT("equipment","Equipment"), BUILDING("building","Building"), + ORES("ores","Ores"), FARMING("farming","Farming"), FOOD("food","Food"), + DRINKS("drinks","Drinks"), SPICE("spice","Spice"), MISC("misc","Miscellaneous"); + final String token,label; + ListingCategory(String token,String label){this.token=token;this.label=label;} + } + private enum ListingSort { + NEWEST("newest","Newest"), OLDEST("oldest","Oldest"), + MARK_ASC("mk_asc","Mark · Lowest first"), MARK_DESC("mk_desc","Mark · Highest first"), + RARITY_ASC("rarity_asc","Rarity · Lowest first"), RARITY_DESC("rarity_desc","Rarity · Highest first"), + PRICE_ASC("price_asc","Unit price · Lowest first"), PRICE_DESC("price_desc","Unit price · Highest first"); + final String token,label; + ListingSort(String token,String label){this.token=token;this.label=label;} + } private record Draft(ItemStack item,int slot,int amount,long price){Draft quantity(int n){return new Draft(item,slot,n,price);}Draft price(long n){return new Draft(item,slot,amount,n);}} - record Purchase(JsonObject row,int amount,UUID request){Purchase quantity(int n){return new Purchase(row,n,UUID.randomUUID());}} + record Purchase(JsonObject row,int amount,UUID request,long resalePrice){ + Purchase(JsonObject row,int amount,UUID request){this(row,amount,request,0);} + Purchase quantity(int n){return new Purchase(row,n,UUID.randomUUID());} + Purchase resale(long price){return new Purchase(row,amount,request,price);} + } private static final class Panel implements InventoryHolder { final UUID owner,world;final GuiSession gate;final Map actions=new HashMap<>();final List choices=new ArrayList<>();final Inventory inventory;final String title;final boolean artwork;String description="Central bank · J.A.R.V.I.S. Exchange"; Panel(Player p,String title,boolean artwork,int screen){owner=p.getUniqueId();world=p.getWorld().getUID();gate=new GuiSession(owner);this.title=title;this.artwork=artwork;inventory=Bukkit.createInventory(this,54,artwork?Component.text(ExchangeArtwork.background(screen),NamedTextColor.WHITE).font(net.kyori.adventure.key.Key.key("dunerealms:exchange")):Component.text(title,NamedTextColor.GOLD));} @@ -37,7 +58,7 @@ final class ExchangeMenus implements Listener,AutoCloseable { private void show(Player p,Panel s){if(BedrockForms.isBedrock(p)){s.gate.expire();BedrockForms.show(plugin,p,s.title,s.description,s.choices);}else{if(MCGUIMenus.show(p,s.title,s.description,s.inventory,s.actions,s.gate))return;p.openInventory(s.inventory);Bukkit.getScheduler().runTaskLater(plugin,s.gate::expire,2400L);}} private void request(Player p,JsonObject input,Consumer success,Consumer failure){ UUID id=p.getUniqueId(),world=p.getWorld().getUID();if(pending.containsKey(id)){p.sendMessage("J.A.R.V.I.S. is processing your Exchange action.");return;}UUID token=UUID.randomUUID();pending.put(id,token);p.closeInventory(); - Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject result=null;String error=null;try{result=bridge.exchange(id,input);}catch(Exception e){error=e.getMessage();}var response=result;String message=error;if(!plugin.isEnabled())return;Bukkit.getScheduler().runTask(plugin,()->{if(!token.equals(pending.get(id)))return;pending.remove(id);if(!p.isOnline()||!world.equals(p.getWorld().getUID()))return;if(response==null){failure.accept(message==null?"The Exchange is temporarily unavailable.":message);return;}if(response.has("rejectedStatus")){if(Set.of("buy","buy_kit").contains(input.get("action").getAsString()))retries.remove(id);failure.accept(response.has("message")?response.get("message").getAsString():"The Exchange rejected this action.");return;}success.accept(response);});}); + Bukkit.getScheduler().runTaskAsynchronously(plugin,()->{JsonObject result=null;String error=null;try{result=bridge.exchange(id,input);}catch(Exception e){error=e.getMessage();}var response=result;String message=error;if(!plugin.isEnabled())return;Bukkit.getScheduler().runTask(plugin,()->{if(!token.equals(pending.get(id)))return;pending.remove(id);if(!p.isOnline()||!world.equals(p.getWorld().getUID()))return;if(response==null){failure.accept(message==null?"The Exchange is temporarily unavailable.":message);return;}if(response.has("rejectedStatus")){String operation=input.get("action").getAsString();int status=response.get("rejectedStatus").getAsInt();if(Set.of("buy","buy_kit").contains(operation)||"buy_resell".equals(operation)&&Set.of(400,403,409).contains(status))retries.remove(id);failure.accept(response.has("message")?response.get("message").getAsString():"The Exchange rejected this action.");return;}success.accept(response);});}); } 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;} @@ -45,9 +66,39 @@ final class ExchangeMenus implements Listener,AutoCloseable { 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); + private void filterListings(Player player,boolean mine,int page){ + var panel=panel(player,"Exchange · Categories"); + var current=listingCategories.getOrDefault(player.getUniqueId(),ListingCategory.ALL); + panel.description="Current category: "+current.label; + int slot=10; + for(var category:ListingCategory.values()){ + button(panel,slot++,category==current?Material.LIME_DYE:Material.PAPER,category.label, + category==current?"Current category":"Show listings in this category",()->{ + listingCategories.put(player.getUniqueId(),category); + list(player,mine,0); + }); + } + button(panel,45,Material.ARROW,"Back","Keep the current category",()->list(player,mine,page)); + show(player,panel); + } + private void sortListings(Player player,boolean mine,int page){ + var panel=panel(player,"Exchange · Sort listings"); + var current=listingSorts.getOrDefault(player.getUniqueId(),ListingSort.NEWEST); + panel.description="Current order: "+current.label; + int slot=10; + for(var order:ListingSort.values()){ + button(panel,slot++,order==current?Material.LIME_DYE:Material.PAPER,order.label, + order==current?"Current order":"Apply to all listings",()->{ + listingSorts.put(player.getUniqueId(),order); + list(player,mine,0); + }); + } + button(panel,45,Material.ARROW,"Back","Keep the current order",()->list(player,mine,page)); + show(player,panel); + } + private void list(Player p,boolean mine,int page){var order=listingSorts.getOrDefault(p.getUniqueId(),ListingSort.NEWEST);var category=listingCategories.getOrDefault(p.getUniqueId(),ListingCategory.ALL);var q=action("read");q.addProperty("mine",mine);q.addProperty("page",page);q.addProperty("sort",order.token);q.addProperty("category",category.token);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",category!=ListingCategory.ALL?"No listings in "+category.label+".":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,52,Material.BOOKSHELF,"Categories",category.label,()->filterListings(p,mine,page));button(s,47,Material.COMPASS,"Sort listings",order.label,()->sortListings(p,mine,page));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); });} private void draft(Player p){var item=p.getInventory().getItemInMainHand();if(item.isEmpty()){p.sendMessage("Hold the item you want to sell first.");return;}sell(p,new Draft(item.clone(),p.getInventory().getHeldItemSlot(),Math.min(64,item.getAmount()),100));} private void sell(Player p,Draft draft){var s=panel(p,"Exchange · Add item");s.description=draft.item.getType().name()+" · "+draft.amount+" items\n"+money(draft.price)+" per item\nTotal: "+money(draft.price*draft.amount);s.inventory.setItem(13,draft.item.clone());quantityPresets(s,Math.min(64,draft.item.getAmount()),amount->sell(p,draft.quantity(amount)));button(s,30,Material.RED_DYE,"− Quantity","Sell "+draft.amount+" items",()->sell(p,draft.quantity(Math.max(1,draft.amount-1))));button(s,31,Material.PAPER,"Quantity: "+draft.amount,"Maximum "+Math.min(64,draft.item.getAmount()),()->sell(p,draft));button(s,32,Material.LIME_DYE,"+ Quantity","Add one item",()->sell(p,draft.quantity(Math.min(Math.min(64,draft.item.getAmount()),draft.amount+1))));button(s,40,Material.GOLD_INGOT,"Price: "+money(draft.price),"Price per item · total "+money(draft.price*draft.amount),()->editPrice(p,draft));button(s,45,Material.ARROW,"Back","Return to your listings",()->list(p,true,0));button(s,49,Material.EMERALD,"Confirm listing","Move "+draft.amount+" items into the Exchange",()->{UUID id=UUID.randomUUID();var q=action("prepare_sale");q.addProperty("requestId",id.toString());q.addProperty("amount",draft.amount);q.addProperty("priceMinor",draft.price);request(p,q,permit->{try{bridge.exchangePublish(p,permit,id,draft.item,draft.slot,draft.amount,draft.price);p.sendMessage("Listing published. Items are held by the Exchange until sold or withdrawn.");list(p,true,0);}catch(Exception e){p.sendMessage(e.getMessage()==null?"The listing was not confirmed.":e.getMessage());}});});show(p,s);} @@ -58,7 +109,19 @@ final class ExchangeMenus implements Listener,AutoCloseable { } private void quantityPresets(Panel s,int available,IntConsumer choose){int slot=21;for(int amount:ExchangeQuantity.presets(available))button(s,slot++,Material.CHEST,String.valueOf(amount),"Set quantity · maximum "+available,()->choose.accept(amount));} private void typePrice(Player p,Draft draft){ - if(BedrockForms.isBedrock(p)){BedrockForms.input(plugin,p,"Listing price","Dunemarks per item",BigDecimal.valueOf(draft.price,2).toPlainString(),text->{try{sell(p,draft.price(price(text.trim())));}catch(IllegalArgumentException e){p.sendMessage(e.getMessage());sell(p,draft);}});return;} + typePrice(p,"Listing price",BigDecimal.valueOf(draft.price,2).toPlainString(), + amount->sell(p,draft.price(amount)),()->sell(p,draft)); + } + private void typePrice(Player p,String title,String initial,LongConsumer onPrice,Runnable onCancel){ + if(BedrockForms.isBedrock(p)){ + BedrockForms.input(plugin,p,title,"Dunemarks per item",initial,text->{ + long amount; + try{amount=price(text.trim());} + catch(IllegalArgumentException invalid){p.sendMessage(invalid.getMessage());onCancel.run();return;} + onPrice.accept(amount); + }); + return; + } if(p.isConversing()){p.sendMessage("Finish your current text entry first, or type cancel.");return;} UUID owner=p.getUniqueId(),world=p.getWorld().getUID();p.closeInventory(); var prompt=new org.bukkit.conversations.ValidatingPrompt(){ @@ -70,13 +133,81 @@ final class ExchangeMenus implements Listener,AutoCloseable { var conversation=new org.bukkit.conversations.ConversationFactory(plugin).withModality(true).withLocalEcho(false).withTimeout(120).withEscapeSequence("cancel").withFirstPrompt(prompt).addConversationAbandonedListener(event->{ priceInputs.computeIfPresent(owner,(id,current)->current.getContext()==event.getContext()?null:current); Object value=event.getContext().getSessionData("priceMinor");if(!plugin.isEnabled())return; - Bukkit.getScheduler().runTask(plugin,()->{if(!p.isOnline()||!world.equals(p.getWorld().getUID()))return;if(event.gracefulExit()&&value instanceof Long amount){sell(p,draft.price(amount));}else{p.sendMessage("Price entry cancelled. Your listing has not been published.");sell(p,draft);}}); + Bukkit.getScheduler().runTask(plugin,()->{if(!p.isOnline()||!world.equals(p.getWorld().getUID()))return;if(event.gracefulExit()&&value instanceof Long amount){onPrice.accept(amount);}else{p.sendMessage("Price entry cancelled.");onCancel.run();}}); }).buildConversation(p); priceInputs.put(owner,conversation);conversation.begin(); } static Purchase resume(Purchase requested,Purchase unresolved){return unresolved==null?requested:unresolved;} private void resumeButton(Player p,Panel panel){var retry=retries.get(p.getUniqueId());if(retry!=null)button(panel,46,Material.CLOCK,"Resume pending purchase","Retry the original purchase reference; no new order",()->purchase(p,retry));} - private void purchase(Player p,Purchase purchase){var existing=resume(purchase,retries.get(p.getUniqueId()));if(existing!=purchase){purchase(p,existing);return;}if(purchase.row.has("kitsetId")){kitPurchase(p,purchase);return;}var row=purchase.row;var s=panel(p,"Exchange · Confirm purchase");s.description=row.get("title").getAsString()+"\nSeller: "+row.get("seller").getAsString()+"\nQuantity: "+purchase.amount+" · Total: "+money(row.get("priceMinor").getAsLong()*purchase.amount);try{s.inventory.setItem(13,bridge.exchangeIcon(row));}catch(Exception bad){p.sendMessage("This item cannot be delivered by your current version.");return;}quantityPresets(s,Math.min(64,row.get("quantity").getAsInt()),amount->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(amount)));button(s,30,Material.RED_DYE,"− Quantity","Buy "+purchase.amount,()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.max(1,purchase.amount-1))));button(s,31,Material.PAPER,"Quantity: "+purchase.amount,money(row.get("priceMinor").getAsLong())+" per item",()->purchase(p,purchase));button(s,32,Material.LIME_DYE,"+ Quantity","Maximum "+Math.min(64,row.get("quantity").getAsInt()),()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.min(Math.min(64,row.get("quantity").getAsInt()),purchase.amount+1))));button(s,45,Material.ARROW,"Back","Return to the Exchange",()->list(p,false,0));button(s,49,Material.EMERALD,(retries.containsKey(p.getUniqueId())?"Retry purchase · ":"Buy · ")+money(row.get("priceMinor").getAsLong()*purchase.amount),"Pay from your central personal bank account",()->{retries.put(p.getUniqueId(),purchase);var q=action("buy");q.addProperty("requestId",purchase.request.toString());q.addProperty("listingId",row.get("id").getAsString());q.addProperty("amount",purchase.amount);q.addProperty("priceMinor",row.get("priceMinor").getAsLong());q.addProperty("confirmed",true);request(p,q,receipt->{retries.remove(p.getUniqueId());p.sendMessage("Purchase confirmed: "+money(receipt.get("totalMinor").getAsLong())+". Your items are ready for delivery.");if(receipt.has("rebateMinor")&&receipt.get("rebateMinor").getAsLong()>0)p.sendMessage("Ordos trade incentive credited: "+money(receipt.get("rebateMinor").getAsLong())+".");deliver(p,true);list(p,false,0);},error->{p.sendMessage(error+" Retry this confirmation with the same purchase reference.");purchase(p,purchase);});});show(p,s);} + private void purchase(Player p,Purchase purchase){var existing=resume(purchase,retries.get(p.getUniqueId()));if(existing!=purchase){purchase(p,existing);return;}if(purchase.resalePrice>0){confirmResale(p,purchase);return;}if(purchase.row.has("kitsetId")){kitPurchase(p,purchase);return;}var row=purchase.row;var s=panel(p,"Exchange · Confirm purchase");s.description=row.get("title").getAsString()+"\nSeller: "+row.get("seller").getAsString()+"\nQuantity: "+purchase.amount+" · Total: "+money(row.get("priceMinor").getAsLong()*purchase.amount);try{s.inventory.setItem(13,bridge.exchangeIcon(row));}catch(Exception bad){p.sendMessage("This item cannot be delivered by your current version.");return;}quantityPresets(s,Math.min(64,row.get("quantity").getAsInt()),amount->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(amount)));button(s,30,Material.RED_DYE,"− Quantity","Buy "+purchase.amount,()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.max(1,purchase.amount-1))));button(s,31,Material.PAPER,"Quantity: "+purchase.amount,money(row.get("priceMinor").getAsLong())+" per item",()->purchase(p,purchase));button(s,32,Material.LIME_DYE,"+ Quantity","Maximum "+Math.min(64,row.get("quantity").getAsInt()),()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.min(Math.min(64,row.get("quantity").getAsInt()),purchase.amount+1))));button(s,45,Material.ARROW,"Back","Return to the Exchange",()->list(p,false,0));if(!retries.containsKey(p.getUniqueId())&&row.get("priceMinor").getAsLong()<100000000)button(s,53,Material.GOLD_INGOT,"Buy and relist","Enter a higher unit price before confirming",()->enterResalePrice(p,purchase));button(s,49,Material.EMERALD,(retries.containsKey(p.getUniqueId())?"Retry purchase · ":"Buy · ")+money(row.get("priceMinor").getAsLong()*purchase.amount),"Pay from your central personal bank account",()->{retries.put(p.getUniqueId(),purchase);var q=action("buy");q.addProperty("requestId",purchase.request.toString());q.addProperty("listingId",row.get("id").getAsString());q.addProperty("amount",purchase.amount);q.addProperty("priceMinor",row.get("priceMinor").getAsLong());q.addProperty("confirmed",true);request(p,q,receipt->{retries.remove(p.getUniqueId());p.sendMessage("Purchase confirmed: "+money(receipt.get("totalMinor").getAsLong())+". Your items are ready for delivery.");if(receipt.has("rebateMinor")&&receipt.get("rebateMinor").getAsLong()>0)p.sendMessage("Ordos trade incentive credited: "+money(receipt.get("rebateMinor").getAsLong())+".");deliver(p,true);list(p,false,0);},error->{p.sendMessage(error+" Retry this confirmation with the same purchase reference.");purchase(p,purchase);});});show(p,s);} + private void enterResalePrice(Player player,Purchase purchase){ + typePrice(player,"Resale unit price","",amount->{ + if(amount<=purchase.row.get("priceMinor").getAsLong()){ + player.sendMessage("Enter a resale price above the purchase price per item."); + purchase(player,purchase); + return; + } + purchase(player,purchase.resale(amount)); + },()->purchase(player,purchase)); + } + private void confirmResale(Player player,Purchase purchase){ + var row=purchase.row; + long price=row.get("priceMinor").getAsLong(); + long cost=price*purchase.amount; + long gross=purchase.resalePrice*purchase.amount; + var panel=panel(player,"Exchange · Confirm resale"); + panel.description=row.get("title").getAsString()+" · "+purchase.amount+" items" + +"\nPay now: "+money(cost)+" · "+money(price)+" each" + +"\nRelist for "+money(purchase.resalePrice)+" each · "+money(gross)+" gross if all sell"; + panel.inventory.setItem(13,icon(Material.PAPER,row.get("title").getAsString(), + purchase.amount+" items", "Purchase total: "+money(cost), + "Resale per item: "+money(purchase.resalePrice), "Gross if sold: "+money(gross))); + boolean retry=retries.containsKey(player.getUniqueId()); + if(!retry){ + button(panel,40,Material.GOLD_INGOT,"Change resale price","Enter a different price",()->enterResalePrice(player,purchase)); + button(panel,45,Material.ARROW,"Back","Return to the purchase without paying",()->purchase(player,purchase.resale(0))); + } + button(panel,49,Material.EMERALD,(retry?"Retry resale · ":"Pay and relist · ")+money(cost), + "Place the purchased items straight into your listings",()->{ + retries.put(player.getUniqueId(),purchase); + var request=action("buy_resell"); + request.addProperty("requestId",purchase.request.toString()); + request.addProperty("listingId",row.get("id").getAsString()); + request.addProperty("amount",purchase.amount); + request.addProperty("priceMinor",price); + request.addProperty("resalePriceMinor",purchase.resalePrice); + request.addProperty("confirmed",true); + request(player,request,receipt->{ + if(!resaleConfirmed(receipt,purchase)){ + player.sendMessage("The resale receipt could not be verified. Retry with the same reference."); + confirmResale(player,purchase); + return; + } + retries.remove(player.getUniqueId()); + player.sendMessage("Purchase paid and items relisted at "+money(purchase.resalePrice)+" each."); + list(player,true,0); + },error->{ + player.sendMessage(error); + if(retries.containsKey(player.getUniqueId()))confirmResale(player,purchase); + else list(player,false,0); + }); + }); + show(player,panel); + } + static boolean resaleConfirmed(JsonObject receipt,Purchase purchase){ + try{ + return "buy_resell".equals(receipt.get("action").getAsString()) + && "relisted".equals(receipt.get("state").getAsString()) + && purchase.request.toString().equals(receipt.get("id").getAsString()) + && Long.parseLong(receipt.get("resaleListingId").getAsString())>0 + && Long.parseLong(receipt.get("resalePriceMinor").getAsString())==purchase.resalePrice + && Integer.parseInt(receipt.get("quantity").getAsString())==purchase.amount + && Long.parseLong(receipt.get("totalMinor").getAsString()) + ==purchase.row.get("priceMinor").getAsLong()*purchase.amount; + }catch(NullPointerException|IllegalStateException|UnsupportedOperationException|NumberFormatException invalid){ + return false; + } + } private void kits(Player p,int page){var q=action("read_kits");q.addProperty("page",page);request(p,q,data->{var s=panel(p,"Exchange · Kits");button(s,1,Material.EMERALD,"Buy items","Browse loose goods",()->list(p,false,0));button(s,4,Material.NETHERITE_CHESTPLATE,"Kits","Published organisation designs",()->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++;String title=row.get("title").getAsString(),description=row.get("seller").getAsString()+" · "+row.get("items").getAsInt()+" items · "+money(row.get("priceMinor").getAsLong());if(row.get("purchaseAvailable").getAsBoolean())button(s,slot,Material.NETHERITE_CHESTPLATE,title,description,()->kitPurchase(p,new Purchase(row.deepCopy(),1,UUID.randomUUID())));else{s.inventory.setItem(slot,icon(Material.GRAY_DYE,title,description,"Organisation banking is unavailable"));s.description+="\n"+title+" · unavailable";}}resumeButton(p,s);if(page>0)button(s,45,Material.ARROW,"Previous","Previous kits",()->kits(p,page-1));button(s,49,Material.ARROW,"Back","Imperial Codex",()->back.accept(p));if(data.get("hasNext").getAsBoolean())button(s,53,Material.ARROW,"Next","More kits",()->kits(p,page+1));show(p,s);});} private void kitPurchase(Player p,Purchase purchase){var existing=resume(purchase,retries.get(p.getUniqueId()));if(existing!=purchase){purchase(p,existing);return;}var row=purchase.row;var s=panel(p,"Exchange · Confirm purchase");s.description=row.get("title").getAsString()+"\nOrganisation: "+row.get("seller").getAsString()+"\n"+row.get("items").getAsInt()+" items · "+money(row.get("priceMinor").getAsLong());s.inventory.setItem(13,icon(Material.NETHERITE_CHESTPLATE,row.get("title").getAsString(),row.get("seller").getAsString(),row.get("items").getAsInt()+" items"));button(s,45,Material.ARROW,"Back","Kit catalogue",()->kits(p,0));button(s,49,Material.EMERALD,(retries.containsKey(p.getUniqueId())?"Retry kit · ":"Buy kit · ")+money(row.get("priceMinor").getAsLong()),"Pay personally; proceeds go to the organisation",()->{retries.put(p.getUniqueId(),purchase);var q=action("buy_kit");q.addProperty("requestId",purchase.request.toString());q.addProperty("kitsetId",row.get("kitsetId").getAsString());q.add("listingVersion",row.get("listingVersion"));q.add("priceMinor",row.get("priceMinor"));q.addProperty("confirmed",true);request(p,q,receipt->{retries.remove(p.getUniqueId());p.sendMessage("Kit purchased: "+money(receipt.get("totalMinor").getAsLong())+". Delivery follows automatically; make room for the complete kit.");try{bridge.refreshKits(p);}catch(Exception unavailable){p.sendMessage("Your kit remains owed until the next inventory sync.");}kits(p,0);},error->{p.sendMessage(error+" Retry this confirmation with the same reference.");kitPurchase(p,purchase);});});show(p,s);} private void withdraw(Player p,JsonObject row){var s=panel(p,"Exchange · Withdraw listing");try{s.inventory.setItem(13,bridge.exchangeIcon(row));}catch(Exception bad){p.sendMessage("This stored item cannot be decoded.");return;}button(s,45,Material.ARROW,"Back","Your listings",()->list(p,true,0));button(s,49,Material.CHEST,"Withdraw "+row.get("quantity").getAsInt()+" items","Return all unsold stock to your inventory",()->{UUID id=UUID.randomUUID();var q=action("prepare_cancel");q.addProperty("requestId",id.toString());request(p,q,permit->{try{int quantity=bridge.exchangeCancel(p,permit,id,Long.parseLong(row.get("id").getAsString()));p.sendMessage("Listing withdrawn. Returned "+quantity+" items.");list(p,true,0);}catch(Exception e){p.sendMessage(e.getMessage()==null?"The listing was not withdrawn.":e.getMessage());}});});show(p,s);} @@ -85,6 +216,6 @@ final class ExchangeMenus implements Listener,AutoCloseable { @EventHandler(priority=EventPriority.HIGHEST) public void click(InventoryClickEvent e){var holder=e.getView().getTopInventory().getHolder();if(!(holder instanceof Panel s))return;e.setCancelled(true);if(!(e.getWhoClicked() instanceof Player p)||!Set.of(ClickType.LEFT,ClickType.RIGHT).contains(e.getClick())||!s.owner.equals(p.getUniqueId())||!s.world.equals(p.getWorld().getUID())||!s.actions.containsKey(e.getRawSlot())||!s.gate.claim(p.getUniqueId()))return;Bukkit.getScheduler().runTask(plugin,s.actions.get(e.getRawSlot()));} @EventHandler(priority=EventPriority.HIGHEST) public void drag(InventoryDragEvent e){if(e.getView().getTopInventory().getHolder() instanceof Panel)e.setCancelled(true);} @EventHandler public void changeWorld(PlayerChangedWorldEvent e){var conversation=priceInputs.remove(e.getPlayer().getUniqueId());if(conversation!=null)conversation.abandon();} - @EventHandler public void quit(PlayerQuitEvent e){var conversation=priceInputs.remove(e.getPlayer().getUniqueId());if(conversation!=null)conversation.abandon();pending.remove(e.getPlayer().getUniqueId());delivering.remove(e.getPlayer().getUniqueId());} - @Override public void close(){for(var conversation:List.copyOf(priceInputs.values()))conversation.abandon();priceInputs.clear();pending.clear();delivering.clear();retries.clear();for(Player p:Bukkit.getOnlinePlayers())if(p.getOpenInventory().getTopInventory().getHolder() instanceof Panel)p.closeInventory();} + @EventHandler public void quit(PlayerQuitEvent e){var conversation=priceInputs.remove(e.getPlayer().getUniqueId());if(conversation!=null)conversation.abandon();pending.remove(e.getPlayer().getUniqueId());delivering.remove(e.getPlayer().getUniqueId());listingSorts.remove(e.getPlayer().getUniqueId());listingCategories.remove(e.getPlayer().getUniqueId());} + @Override public void close(){for(var conversation:List.copyOf(priceInputs.values()))conversation.abandon();priceInputs.clear();pending.clear();delivering.clear();retries.clear();listingSorts.clear();listingCategories.clear();for(Player p:Bukkit.getOnlinePlayers())if(p.getOpenInventory().getTopInventory().getHolder() instanceof Panel)p.closeInventory();} } diff --git a/DuneRealmsGUI/src/test/java/com/dunerealms/gui/ExchangeBrowseSafetyTest.java b/DuneRealmsGUI/src/test/java/com/dunerealms/gui/ExchangeBrowseSafetyTest.java index 7e77a0bf..c6f2b062 100644 --- a/DuneRealmsGUI/src/test/java/com/dunerealms/gui/ExchangeBrowseSafetyTest.java +++ b/DuneRealmsGUI/src/test/java/com/dunerealms/gui/ExchangeBrowseSafetyTest.java @@ -11,4 +11,26 @@ class ExchangeBrowseSafetyTest { assertSame(custom,ExchangeMenus.listingName(custom,"A different title",false)); assertSame(custom,ExchangeMenus.listingName(custom,"A different title",true)); } + @Test void onlyExactRelistReceiptConfirmsAndRetryKeepsOriginalTerms(){ + var row=new JsonObject(); + row.addProperty("priceMinor",120); + var purchase=new ExchangeMenus.Purchase(row,3,UUID.randomUUID()).resale(150); + assertSame(purchase,ExchangeMenus.resume(purchase.resale(180),purchase)); + var receipt=new JsonObject(); + receipt.addProperty("action","buy_resell"); + receipt.addProperty("state","relisted"); + receipt.addProperty("id",purchase.request().toString()); + receipt.addProperty("resaleListingId","720"); + receipt.addProperty("resalePriceMinor",150); + receipt.addProperty("quantity",3); + receipt.addProperty("totalMinor",360); + assertTrue(ExchangeMenus.resaleConfirmed(receipt,purchase)); + receipt.addProperty("resalePriceMinor",180); + assertFalse(ExchangeMenus.resaleConfirmed(receipt,purchase)); + receipt.addProperty("resalePriceMinor",150); + receipt.addProperty("state","delivery_pending"); + assertFalse(ExchangeMenus.resaleConfirmed(receipt,purchase)); + receipt.remove("resaleListingId"); + assertFalse(ExchangeMenus.resaleConfirmed(receipt,purchase)); + } } diff --git a/tools/ExchangeMarketToolbarMerge.java b/tools/ExchangeMarketToolbarMerge.java new file mode 100644 index 00000000..259af0f9 --- /dev/null +++ b/tools/ExchangeMarketToolbarMerge.java @@ -0,0 +1,36 @@ +import java.nio.file.Files; +import java.nio.file.Path; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; + +class ExchangeMarketToolbarMerge { + private static final String CLASS = "com/dunerealms/menus/SuppliedDocument"; + private static final String DESCRIPTOR = "(Lcom/dunerealms/menus/Card;)Z"; + + 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("Unexpected toolbar class"); + } + retained.methods.set(retained.methods.indexOf(toolbar(retained)), toolbar(donor)); + var writer = new ClassWriter(retainedReader, 0); + retained.accept(writer); + Files.write(Path.of(args[2]), writer.toByteArray()); + } + + private static MethodNode toolbar(ClassNode node) { + return node.methods.stream().filter(m -> m.name.equals("marketTool") && m.desc.equals(DESCRIPTOR)) + .findFirst().orElseThrow(() -> new IllegalArgumentException("Missing exact market toolbar method")); + } + + private static ClassNode parse(ClassReader reader) { + var node = new ClassNode(); + reader.accept(node, 0); + return node; + } +} diff --git a/tools/plugin_exchange_market.py b/tools/plugin_exchange_market.py new file mode 100644 index 00000000..3ad67391 --- /dev/null +++ b/tools/plugin_exchange_market.py @@ -0,0 +1,91 @@ +"""Package scoped Exchange browsing and resale classes or assemble pinned retained JARs.""" +import argparse +from hashlib import sha256 +from pathlib import Path +import subprocess +from tempfile import TemporaryDirectory +from zipfile import ZipFile + +EXCHANGE = "com/dunerealms/gui/ExchangeMenus" +GUI_REPLACE = {f"{EXCHANGE}.class", f"{EXCHANGE}$Purchase.class"} +GUI_ADD = {f"{EXCHANGE}$ListingCategory.class", f"{EXCHANGE}$ListingSort.class"} +TOOLBAR = "com/dunerealms/menus/SuppliedDocument.class" +GUI_BASELINES = { + "cc297181ebc26b1750a0cb1abc96f02c58c02d5b56ac5a016229933f84093475", + "54e32d06818cacf70437cc6bed99bee92eea7826ec95903018f4909fc0cb338d", +} +MENU_BASELINES = { + "cd5de929f70ee40c12b34a355f2f8c9f23c4cf0829d80713feef431a405c126d", + "70417e9b62cf3151c511b7cba7f78b173aea6c73e618b842860536462301ae93", +} + + +def entries(archive): + names = archive.namelist() + if len(names) != len(set(names)): + raise ValueError("Duplicate archive entry") + return set(names) + + +def package(gui, menus, output): + with ZipFile(gui) as a, ZipFile(menus) as b: + if not (GUI_ADD | GUI_REPLACE) <= entries(a) or TOOLBAR not in entries(b): + raise ValueError("Expected Exchange donor classes are missing") + with ZipFile(output, "x") as capsule: + for name in sorted(GUI_ADD | GUI_REPLACE): + capsule.writestr(name, a.read(name)) + capsule.writestr(TOOLBAR, b.read(TOOLBAR)) + + +def toolbar(retained, donor, classpath): + if not classpath: + raise ValueError("An ASM classpath is required") + with TemporaryDirectory() as temp: + before, new, result = (Path(temp) / name for name in ("before.class", "donor.class", "result.class")) + before.write_bytes(retained) + new.write_bytes(donor) + subprocess.run(["java", "--class-path", classpath, + str(Path(__file__).with_name("ExchangeMarketToolbarMerge.java")), + str(before), str(new), str(result)], check=True) + return result.read_bytes() + + +def assemble(capsule, baseline, output, classpath): + baseline_hash = sha256(baseline.read_bytes()).hexdigest() + with ZipFile(capsule) as donor, ZipFile(baseline) as retained: + names = entries(retained) + if entries(donor) != GUI_ADD | GUI_REPLACE | {TOOLBAR}: + raise ValueError("Unexpected Exchange capsule scope") + if baseline_hash in GUI_BASELINES and GUI_REPLACE <= names and not GUI_ADD & names: + replacements = {name: donor.read(name) for name in GUI_REPLACE | GUI_ADD} + elif baseline_hash in MENU_BASELINES and TOOLBAR in names: + replacements = {TOOLBAR: toolbar(retained.read(TOOLBAR), donor.read(TOOLBAR), classpath)} + else: + raise ValueError("Unexpected retained JAR") + with ZipFile(output, "x") as result: + for entry in retained.infolist(): + data = replacements[entry.filename] if entry.filename in replacements else retained.read(entry) + result.writestr(entry, data) + for name in sorted(replacements.keys() - names): + result.writestr(name, replacements[name]) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + pack = commands.add_parser("package") + for field in ("gui", "menus", "output"): + pack.add_argument(field, type=Path) + install = commands.add_parser("assemble") + for field in ("capsule", "baseline", "output"): + install.add_argument(field, type=Path) + install.add_argument("--classpath") + args = parser.parse_args() + if args.command == "package": + package(args.gui, args.menus, args.output) + else: + assemble(args.capsule, args.baseline, args.output, args.classpath) + + +if __name__ == "__main__": + main()