fix: preserve order of saved items to keep, close #186

feat/data-edit-commands
William 10 months ago
parent c2ae9bd20a
commit c6fb7fb10f
No known key found for this signature in database

@ -19,14 +19,17 @@
package net.william278.husksync.listener; package net.william278.husksync.listener;
import com.google.common.collect.Lists;
import net.william278.husksync.BukkitHuskSync; import net.william278.husksync.BukkitHuskSync;
import net.william278.husksync.data.BukkitData; import net.william278.husksync.data.BukkitData;
import net.william278.husksync.user.BukkitUser; import net.william278.husksync.user.BukkitUser;
import net.william278.husksync.user.OnlineUser; import net.william278.husksync.user.OnlineUser;
import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.Iterator;
import java.util.List; import java.util.List;
import static net.william278.husksync.config.Settings.SynchronizationSettings.SaveOnDeathSettings; import static net.william278.husksync.config.Settings.SynchronizationSettings.SaveOnDeathSettings;
@ -57,7 +60,7 @@ public class PaperEventListener extends BukkitEventListener {
final int maxInventorySize = BukkitData.Items.Inventory.INVENTORY_SLOT_COUNT; final int maxInventorySize = BukkitData.Items.Inventory.INVENTORY_SLOT_COUNT;
final List<ItemStack> itemsToSave = switch (settings.getItemsToSave()) { final List<ItemStack> itemsToSave = switch (settings.getItemsToSave()) {
case DROPS -> event.getDrops(); case DROPS -> event.getDrops();
case ITEMS_TO_KEEP -> event.getItemsToKeep(); case ITEMS_TO_KEEP -> preserveOrder(event.getEntity().getInventory(), event.getItemsToKeep());
}; };
if (itemsToSave.size() > maxInventorySize) { if (itemsToSave.size() > maxInventorySize) {
itemsToSave.subList(maxInventorySize, itemsToSave.size()).clear(); itemsToSave.subList(maxInventorySize, itemsToSave.size()).clear();
@ -65,4 +68,22 @@ public class PaperEventListener extends BukkitEventListener {
super.saveOnPlayerDeath(user, BukkitData.Items.ItemArray.adapt(itemsToSave)); super.saveOnPlayerDeath(user, BukkitData.Items.ItemArray.adapt(itemsToSave));
} }
@NotNull
private List<ItemStack> preserveOrder(@NotNull PlayerInventory inventory, @NotNull List<ItemStack> toKeep) {
final List<ItemStack> preserved = Lists.newArrayList();
final List<ItemStack> items = Lists.newArrayList(inventory.getContents());
for (ItemStack item : toKeep) {
final Iterator<ItemStack> iterator = items.iterator();
while (iterator.hasNext()) {
final ItemStack originalItem = iterator.next();
if (originalItem != null && originalItem.equals(item)) {
preserved.add(originalItem);
iterator.remove();
break;
}
}
}
return preserved;
}
} }

Loading…
Cancel
Save