BlueGit

timfa copper-key

Add /keyname and anvil renaming for bound keys.

Custom names use itemName, sync across all copies of a binding, and clear when keys go blank.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-08-22 · 2 months ago

Hash
4974d95ae929fca4d06cb5152f222920df9ddbf5
Parent
7a41f783
7 files changed +273 −30
README.md +1 −0
@@ -31,6 +31,7 @@ The supplied texture is the user's 16x16 key sprite and is selected through the
31 31 - Containers require the matching key somewhere in the player's inventory, including recursively inside Bundles and Shulker Boxes.
32 32 - Locked doors/trapdoors/fence gates may always be closed, but cannot be opened without the matching key. Redstone may close them but may not open them.
33 33 - Locked iron doors and iron trapdoors can be toggled open/closed by right-clicking with the matching key in hand.
34 - Rename a bound key with `/keyname <name>` or an anvil; all copies with the same binding update. Blank keys cannot be named.
34 35 - Hopper transfers, hopper pickup/search and Copper Golem target validation are denied for locked containers.
35 36 - Breaking either half of a double chest or either half of a door breaks the binding.
36 37 - Keys found online are immediately blanked when their bound block is broken. Keys elsewhere are lazily blanked the next time the plugin encounters them.
@@ -31,6 +31,7 @@ The supplied texture is the user's 16x16 key sprite and is selected through the
31- Containers require the matching key somewhere in the player's inventory, including recursively inside Bundles and Shulker Boxes.
31- Containers require the matching key somewhere in the player's inventory, including recursively inside Bundles and Shulker Boxes.
32- Locked doors/trapdoors/fence gates may always be closed, but cannot be opened without the matching key. Redstone may close them but may not open them.
32- Locked doors/trapdoors/fence gates may always be closed, but cannot be opened without the matching key. Redstone may close them but may not open them.
33- Locked iron doors and iron trapdoors can be toggled open/closed by right-clicking with the matching key in hand.
33- Locked iron doors and iron trapdoors can be toggled open/closed by right-clicking with the matching key in hand.
34- Rename a bound key with `/keyname <name>` or an anvil; all copies with the same binding update. Blank keys cannot be named.
34- Hopper transfers, hopper pickup/search and Copper Golem target validation are denied for locked containers.
35- Hopper transfers, hopper pickup/search and Copper Golem target validation are denied for locked containers.
35- Breaking either half of a double chest or either half of a door breaks the binding.
36- Breaking either half of a double chest or either half of a door breaks the binding.
36- Keys found online are immediately blanked when their bound block is broken. Keys elsewhere are lazily blanked the next time the plugin encounters them.
37- Keys found online are immediately blanked when their bound block is broken. Keys elsewhere are lazily blanked the next time the plugin encounters them.
src/main/java/nl/timfalken/copperkeys/CopperKeysPlugin.java +91 −1
@@ -39,9 +39,11 @@ import org.bukkit.event.inventory.InventoryDragEvent;
39 39 import org.bukkit.event.inventory.InventoryMoveItemEvent;
40 40 import org.bukkit.event.inventory.InventoryOpenEvent;
41 41 import org.bukkit.event.inventory.InventoryPickupItemEvent;
42 import org.bukkit.event.inventory.PrepareAnvilEvent;
42 43 import org.bukkit.event.inventory.PrepareItemCraftEvent;
43 44 import org.bukkit.event.player.PlayerInteractEvent;
44 45 import org.bukkit.event.player.PlayerJoinEvent;
46 import org.bukkit.inventory.AnvilInventory;
45 47 import org.bukkit.inventory.CraftingInventory;
46 48 import org.bukkit.inventory.DoubleChestInventory;
47 49 import org.bukkit.inventory.EquipmentSlot;
@@ -85,6 +87,12 @@ public final class CopperKeysPlugin extends JavaPlugin implements Listener {
85 87 registerRecipes();
86 88 registerAdvancement(burglarAdvancementKey, "advancements/burglar.json", "Burglar");
87 89 registerAdvancement(oopsAdvancementKey, "advancements/oops.json", "Oops");
90 var keyNameCommand = getCommand("keyname");
91 if (keyNameCommand != null) {
92 keyNameCommand.setExecutor(new KeyNameCommand(this));
93 } else {
94 getLogger().warning("Command 'keyname' missing from plugin.yml");
95 }
88 96 getServer().getPluginManager().registerEvents(this, this);
89 97 getLogger().info("CopperKeys 1.0.0 enabled with event-driven lock handling.");
90 98 }
@@ -93,6 +101,21 @@ public final class CopperKeysPlugin extends JavaPlugin implements Listener {
93 101 return lockStore;
94 102 }
95 103
104 KeyItems keyItems() {
105 return keyItems;
106 }
107
108 void renameKeyBinding(UUID bindingId, String keyName) {
109 LockRecord updated = lockStore.setKeyName(bindingId, keyName);
110 if (updated == null) {
111 return;
112 }
113 for (Player online : Bukkit.getOnlinePlayers()) {
114 keyItems.applyNameInInventory(online.getInventory(), bindingId);
115 keyItems.applyNameInInventory(online.getEnderChest(), bindingId);
116 }
117 }
118
96 119 private void registerRecipes() {
97 120 Bukkit.removeRecipe(recipeKey);
98 121 Bukkit.removeRecipe(copyRecipeKey);
@@ -199,7 +222,7 @@ public final class CopperKeysPlugin extends JavaPlugin implements Listener {
199 222 }
200 223 }
201 224
202 LockRecord record = new LockRecord(UUID.randomUUID(), displayName(clicked), members);
225 LockRecord record = LockRecord.create(UUID.randomUUID(), displayName(clicked), members);
203 226 lockStore.add(record);
204 227
205 228 Player player = event.getPlayer();
@@ -238,6 +261,10 @@ public final class CopperKeysPlugin extends JavaPlugin implements Listener {
238 261
239 262 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
240 263 public void onInventoryClick(InventoryClickEvent event) {
264 if (event.getInventory() instanceof AnvilInventory anvil && event.getRawSlot() == 2) {
265 handleAnvilResultTake(event, anvil);
266 }
267
241 268 LockRecord lock = lockForInventory(event.getView().getTopInventory());
242 269 if (lock != null) {
243 270 HumanEntity human = event.getWhoClicked();
@@ -255,6 +282,69 @@ public final class CopperKeysPlugin extends JavaPlugin implements Listener {
255 282 }
256 283 }
257 284
285 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
286 public void onPrepareAnvil(PrepareAnvilEvent event) {
287 AnvilInventory anvil = event.getInventory();
288 ItemStack first = anvil.getFirstItem();
289 if (first == null || !keyItems.isKey(first)) {
290 return;
291 }
292 if (keyItems.isBlank(first)) {
293 event.setResult(null);
294 return;
295 }
296
297 String renameText = anvil.getRenameText();
298 if (renameText == null || renameText.isBlank()) {
299 return;
300 }
301 String name = sanitizeKeyName(renameText);
302 if (name == null) {
303 event.setResult(null);
304 return;
305 }
306
307 UUID bindingId = keyItems.getBinding(first);
308 LockRecord lock = bindingId == null ? null : lockStore.get(bindingId);
309 if (lock == null) {
310 event.setResult(null);
311 return;
312 }
313
314 ItemStack result = first.clone();
315 keyItems.applyBoundAppearance(result, lock.withKeyName(name));
316 event.setResult(result);
317 anvil.setRepairCost(1);
318 }
319
320 private void handleAnvilResultTake(InventoryClickEvent event, AnvilInventory anvil) {
321 ItemStack result = event.getCurrentItem();
322 if (result == null || !keyItems.isKey(result) || keyItems.isBlank(result)) {
323 return;
324 }
325 String renameText = anvil.getRenameText();
326 if (renameText == null || renameText.isBlank()) {
327 return;
328 }
329 String name = sanitizeKeyName(renameText);
330 UUID bindingId = keyItems.getBinding(result);
331 if (name == null || bindingId == null || lockStore.get(bindingId) == null) {
332 return;
333 }
334 Bukkit.getScheduler().runTask(this, () -> renameKeyBinding(bindingId, name));
335 }
336
337 private static String sanitizeKeyName(String raw) {
338 String name = raw.trim();
339 if (name.isEmpty()) {
340 return null;
341 }
342 if (name.length() > KeyItems.MAX_KEY_NAME_LENGTH) {
343 return name.substring(0, KeyItems.MAX_KEY_NAME_LENGTH);
344 }
345 return name;
346 }
347
258 348 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
259 349 public void onInventoryDrag(InventoryDragEvent event) {
260 350 LockRecord lock = lockForInventory(event.getView().getTopInventory());
@@ -39,9 +39,11 @@ import org.bukkit.event.inventory.InventoryDragEvent;
39import org.bukkit.event.inventory.InventoryMoveItemEvent;
39import org.bukkit.event.inventory.InventoryMoveItemEvent;
40import org.bukkit.event.inventory.InventoryOpenEvent;
40import org.bukkit.event.inventory.InventoryOpenEvent;
41import org.bukkit.event.inventory.InventoryPickupItemEvent;
41import org.bukkit.event.inventory.InventoryPickupItemEvent;
42import org.bukkit.event.inventory.PrepareAnvilEvent;
42import org.bukkit.event.inventory.PrepareItemCraftEvent;
43import org.bukkit.event.inventory.PrepareItemCraftEvent;
43import org.bukkit.event.player.PlayerInteractEvent;
44import org.bukkit.event.player.PlayerInteractEvent;
44import org.bukkit.event.player.PlayerJoinEvent;
45import org.bukkit.event.player.PlayerJoinEvent;
46import org.bukkit.inventory.AnvilInventory;
45import org.bukkit.inventory.CraftingInventory;
47import org.bukkit.inventory.CraftingInventory;
46import org.bukkit.inventory.DoubleChestInventory;
48import org.bukkit.inventory.DoubleChestInventory;
47import org.bukkit.inventory.EquipmentSlot;
49import org.bukkit.inventory.EquipmentSlot;
@@ -85,6 +87,12 @@ public final class CopperKeysPlugin extends JavaPlugin implements Listener {
85 registerRecipes();
87 registerRecipes();
86 registerAdvancement(burglarAdvancementKey, "advancements/burglar.json", "Burglar");
88 registerAdvancement(burglarAdvancementKey, "advancements/burglar.json", "Burglar");
87 registerAdvancement(oopsAdvancementKey, "advancements/oops.json", "Oops");
89 registerAdvancement(oopsAdvancementKey, "advancements/oops.json", "Oops");
90 var keyNameCommand = getCommand("keyname");
91 if (keyNameCommand != null) {
92 keyNameCommand.setExecutor(new KeyNameCommand(this));
93 } else {
94 getLogger().warning("Command 'keyname' missing from plugin.yml");
95 }
88 getServer().getPluginManager().registerEvents(this, this);
96 getServer().getPluginManager().registerEvents(this, this);
89 getLogger().info("CopperKeys 1.0.0 enabled with event-driven lock handling.");
97 getLogger().info("CopperKeys 1.0.0 enabled with event-driven lock handling.");
90 }
98 }
@@ -93,6 +101,21 @@ public final class CopperKeysPlugin extends JavaPlugin implements Listener {
93 return lockStore;
101 return lockStore;
94 }
102 }
95
103
104 KeyItems keyItems() {
105 return keyItems;
106 }
107
108 void renameKeyBinding(UUID bindingId, String keyName) {
109 LockRecord updated = lockStore.setKeyName(bindingId, keyName);
110 if (updated == null) {
111 return;
112 }
113 for (Player online : Bukkit.getOnlinePlayers()) {
114 keyItems.applyNameInInventory(online.getInventory(), bindingId);
115 keyItems.applyNameInInventory(online.getEnderChest(), bindingId);
116 }
117 }
118
96 private void registerRecipes() {
119 private void registerRecipes() {
97 Bukkit.removeRecipe(recipeKey);
120 Bukkit.removeRecipe(recipeKey);
98 Bukkit.removeRecipe(copyRecipeKey);
121 Bukkit.removeRecipe(copyRecipeKey);
@@ -199,7 +222,7 @@ public final class CopperKeysPlugin extends JavaPlugin implements Listener {
199 }
222 }
200 }
223 }
201
224
202 LockRecord record = new LockRecord(UUID.randomUUID(), displayName(clicked), members);
225 LockRecord record = LockRecord.create(UUID.randomUUID(), displayName(clicked), members);
203 lockStore.add(record);
226 lockStore.add(record);
204
227
205 Player player = event.getPlayer();
228 Player player = event.getPlayer();
@@ -238,6 +261,10 @@ public final class CopperKeysPlugin extends JavaPlugin implements Listener {
238
261
239 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
262 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
240 public void onInventoryClick(InventoryClickEvent event) {
263 public void onInventoryClick(InventoryClickEvent event) {
264 if (event.getInventory() instanceof AnvilInventory anvil && event.getRawSlot() == 2) {
265 handleAnvilResultTake(event, anvil);
266 }
267
241 LockRecord lock = lockForInventory(event.getView().getTopInventory());
268 LockRecord lock = lockForInventory(event.getView().getTopInventory());
242 if (lock != null) {
269 if (lock != null) {
243 HumanEntity human = event.getWhoClicked();
270 HumanEntity human = event.getWhoClicked();
@@ -255,6 +282,69 @@ public final class CopperKeysPlugin extends JavaPlugin implements Listener {
255 }
282 }
256 }
283 }
257
284
285 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
286 public void onPrepareAnvil(PrepareAnvilEvent event) {
287 AnvilInventory anvil = event.getInventory();
288 ItemStack first = anvil.getFirstItem();
289 if (first == null || !keyItems.isKey(first)) {
290 return;
291 }
292 if (keyItems.isBlank(first)) {
293 event.setResult(null);
294 return;
295 }
296
297 String renameText = anvil.getRenameText();
298 if (renameText == null || renameText.isBlank()) {
299 return;
300 }
301 String name = sanitizeKeyName(renameText);
302 if (name == null) {
303 event.setResult(null);
304 return;
305 }
306
307 UUID bindingId = keyItems.getBinding(first);
308 LockRecord lock = bindingId == null ? null : lockStore.get(bindingId);
309 if (lock == null) {
310 event.setResult(null);
311 return;
312 }
313
314 ItemStack result = first.clone();
315 keyItems.applyBoundAppearance(result, lock.withKeyName(name));
316 event.setResult(result);
317 anvil.setRepairCost(1);
318 }
319
320 private void handleAnvilResultTake(InventoryClickEvent event, AnvilInventory anvil) {
321 ItemStack result = event.getCurrentItem();
322 if (result == null || !keyItems.isKey(result) || keyItems.isBlank(result)) {
323 return;
324 }
325 String renameText = anvil.getRenameText();
326 if (renameText == null || renameText.isBlank()) {
327 return;
328 }
329 String name = sanitizeKeyName(renameText);
330 UUID bindingId = keyItems.getBinding(result);
331 if (name == null || bindingId == null || lockStore.get(bindingId) == null) {
332 return;
333 }
334 Bukkit.getScheduler().runTask(this, () -> renameKeyBinding(bindingId, name));
335 }
336
337 private static String sanitizeKeyName(String raw) {
338 String name = raw.trim();
339 if (name.isEmpty()) {
340 return null;
341 }
342 if (name.length() > KeyItems.MAX_KEY_NAME_LENGTH) {
343 return name.substring(0, KeyItems.MAX_KEY_NAME_LENGTH);
344 }
345 return name;
346 }
347
258 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
348 @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
259 public void onInventoryDrag(InventoryDragEvent event) {
349 public void onInventoryDrag(InventoryDragEvent event) {
260 LockRecord lock = lockForInventory(event.getView().getTopInventory());
350 LockRecord lock = lockForInventory(event.getView().getTopInventory());
src/main/java/nl/timfalken/copperkeys/KeyItems.java +77 −27
@@ -3,6 +3,7 @@ package nl.timfalken.copperkeys;
3 3 import net.kyori.adventure.text.Component;
4 4 import net.kyori.adventure.text.format.NamedTextColor;
5 5 import net.kyori.adventure.text.format.TextDecoration;
6 import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
6 7 import org.bukkit.Material;
7 8 import org.bukkit.NamespacedKey;
8 9 import org.bukkit.block.ShulkerBox;
@@ -20,6 +21,7 @@ import java.util.UUID;
20 21
21 22 final class KeyItems {
22 23 private static final int MAX_NESTING_DEPTH = 16;
24 static final int MAX_KEY_NAME_LENGTH = 50;
23 25 /** Bundle occupancy is 1/maxStackSize; keys with the same binding share identical meta and can stack. */
24 26 private static final int KEY_MAX_STACK_SIZE = 64;
25 27
@@ -75,10 +77,15 @@ final class KeyItems {
75 77 }
76 78
77 79 void bind(ItemStack item, LockRecord lock) {
80 applyBoundAppearance(item, lock);
81 }
82
83 void applyBoundAppearance(ItemStack item, LockRecord lock) {
78 84 ItemMeta meta = item.getItemMeta();
79 85 applyCommon(meta);
80 86 meta.getPersistentDataContainer().set(bindingKey, PersistentDataType.STRING, lock.bindingId().toString());
81 meta.itemName(Component.text("Key", NamedTextColor.WHITE));
87 meta.itemName(Component.text(lock.keyName(), NamedTextColor.WHITE));
88 meta.customName(null);
82 89 meta.lore(List.of(
83 90 Component.text("Unlocks " + lock.displayName(), NamedTextColor.GRAY)
84 91 .decoration(TextDecoration.ITALIC, false)
@@ -91,6 +98,7 @@ final class KeyItems {
91 98 applyCommon(meta);
92 99 meta.getPersistentDataContainer().remove(bindingKey);
93 100 meta.itemName(Component.text("Blank Key", NamedTextColor.WHITE));
101 meta.customName(null);
94 102 meta.lore(null);
95 103 item.setItemMeta(meta);
96 104 }
@@ -102,6 +110,45 @@ final class KeyItems {
102 110 meta.setItemModel(itemModel);
103 111 }
104 112
113 private boolean syncKey(ItemStack key) {
114 boolean updated = migrateKeyFormat(key);
115 UUID binding = getBinding(key);
116 if (binding == null) {
117 // Blank keys must never keep a custom name.
118 ItemMeta meta = key.getItemMeta();
119 if (meta != null && meta.hasCustomName()) {
120 meta.customName(null);
121 meta.itemName(Component.text("Blank Key", NamedTextColor.WHITE));
122 key.setItemMeta(meta);
123 return true;
124 }
125 return updated;
126 }
127 LockRecord lock = plugin.lockStore().get(binding);
128 if (lock == null) {
129 makeBlank(key);
130 return true;
131 }
132 if (!matchesBoundAppearance(key, lock)) {
133 applyBoundAppearance(key, lock);
134 return true;
135 }
136 return updated;
137 }
138
139 private boolean matchesBoundAppearance(ItemStack key, LockRecord lock) {
140 ItemMeta meta = key.getItemMeta();
141 if (meta == null || meta.hasCustomName()) {
142 return false;
143 }
144 Component itemName = meta.itemName();
145 if (itemName == null) {
146 return false;
147 }
148 String plain = PlainTextComponentSerializer.plainText().serialize(itemName);
149 return lock.keyName().equals(plain);
150 }
151
105 152 private boolean migrateKeyFormat(ItemStack key) {
106 153 ItemMeta meta = key.getItemMeta();
107 154 if (meta == null) {
@@ -115,21 +162,39 @@ final class KeyItems {
115 162 return true;
116 163 }
117 164
118 boolean inventoryHasBinding(Inventory inventory, UUID bindingId) {
119 boolean[] found = {false};
165 void applyNameInInventory(Inventory inventory, UUID bindingId) {
166 LockRecord lock = plugin.lockStore().get(bindingId);
167 if (lock == null) {
168 return;
169 }
120 170 for (int slot = 0; slot < inventory.getSize(); slot++) {
121 171 ItemStack item = inventory.getItem(slot);
122 172 if (item == null) {
123 173 continue;
124 174 }
125 175 boolean changed = visit(item, 0, key -> {
126 boolean updated = migrateKeyFormat(key);
127 UUID keyBinding = getBinding(key);
128 if (keyBinding != null && !plugin.lockStore().exists(keyBinding)) {
129 makeBlank(key);
176 if (bindingId.equals(getBinding(key))) {
177 applyBoundAppearance(key, lock);
130 178 return true;
131 179 }
132 if (bindingId.equals(keyBinding)) {
180 return false;
181 });
182 if (changed) {
183 inventory.setItem(slot, item);
184 }
185 }
186 }
187
188 boolean inventoryHasBinding(Inventory inventory, UUID bindingId) {
189 boolean[] found = {false};
190 for (int slot = 0; slot < inventory.getSize(); slot++) {
191 ItemStack item = inventory.getItem(slot);
192 if (item == null) {
193 continue;
194 }
195 boolean changed = visit(item, 0, key -> {
196 boolean updated = syncKey(key);
197 if (bindingId.equals(getBinding(key))) {
133 198 found[0] = true;
134 199 }
135 200 return updated;
@@ -150,15 +215,7 @@ final class KeyItems {
150 215 if (item == null) {
151 216 continue;
152 217 }
153 boolean changed = visit(item, 0, key -> {
154 boolean updated = migrateKeyFormat(key);
155 UUID binding = getBinding(key);
156 if (binding != null && !plugin.lockStore().exists(binding)) {
157 makeBlank(key);
158 return true;
159 }
160 return updated;
161 });
218 boolean changed = visit(item, 0, this::syncKey);
162 219 if (changed) {
163 220 inventory.setItem(slot, item);
164 221 }
@@ -189,15 +246,7 @@ final class KeyItems {
189 246 if (item == null) {
190 247 return false;
191 248 }
192 return visit(item, 0, key -> {
193 boolean updated = migrateKeyFormat(key);
194 UUID binding = getBinding(key);
195 if (binding != null && !plugin.lockStore().exists(binding)) {
196 makeBlank(key);
197 return true;
198 }
199 return updated;
200 });
249 return visit(item, 0, this::syncKey);
201 250 }
202 251
203 252 private boolean visit(ItemStack item, int depth, KeyVisitor visitor) {
@@ -225,7 +274,8 @@ final class KeyItems {
225 274 item.setItemMeta(bundleMeta);
226 275 changed = true;
227 276 }
228 } else if (meta instanceof BlockStateMeta blockStateMeta && blockStateMeta.getBlockState() instanceof ShulkerBox shulker) {
277 } else if (meta instanceof BlockStateMeta blockStateMeta
278 && blockStateMeta.getBlockState() instanceof ShulkerBox shulker) {
229 279 Inventory contents = shulker.getInventory();
230 280 boolean nestedChanged = false;
231 281 for (int slot = 0; slot < contents.getSize(); slot++) {
@@ -3,6 +3,7 @@ package nl.timfalken.copperkeys;
3import net.kyori.adventure.text.Component;
3import net.kyori.adventure.text.Component;
4import net.kyori.adventure.text.format.NamedTextColor;
4import net.kyori.adventure.text.format.NamedTextColor;
5import net.kyori.adventure.text.format.TextDecoration;
5import net.kyori.adventure.text.format.TextDecoration;
6import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
6import org.bukkit.Material;
7import org.bukkit.Material;
7import org.bukkit.NamespacedKey;
8import org.bukkit.NamespacedKey;
8import org.bukkit.block.ShulkerBox;
9import org.bukkit.block.ShulkerBox;
@@ -20,6 +21,7 @@ import java.util.UUID;
20
21
21final class KeyItems {
22final class KeyItems {
22 private static final int MAX_NESTING_DEPTH = 16;
23 private static final int MAX_NESTING_DEPTH = 16;
24 static final int MAX_KEY_NAME_LENGTH = 50;
23 /** Bundle occupancy is 1/maxStackSize; keys with the same binding share identical meta and can stack. */
25 /** Bundle occupancy is 1/maxStackSize; keys with the same binding share identical meta and can stack. */
24 private static final int KEY_MAX_STACK_SIZE = 64;
26 private static final int KEY_MAX_STACK_SIZE = 64;
25
27
@@ -75,10 +77,15 @@ final class KeyItems {
75 }
77 }
76
78
77 void bind(ItemStack item, LockRecord lock) {
79 void bind(ItemStack item, LockRecord lock) {
80 applyBoundAppearance(item, lock);
81 }
82
83 void applyBoundAppearance(ItemStack item, LockRecord lock) {
78 ItemMeta meta = item.getItemMeta();
84 ItemMeta meta = item.getItemMeta();
79 applyCommon(meta);
85 applyCommon(meta);
80 meta.getPersistentDataContainer().set(bindingKey, PersistentDataType.STRING, lock.bindingId().toString());
86 meta.getPersistentDataContainer().set(bindingKey, PersistentDataType.STRING, lock.bindingId().toString());
81 meta.itemName(Component.text("Key", NamedTextColor.WHITE));
87 meta.itemName(Component.text(lock.keyName(), NamedTextColor.WHITE));
88 meta.customName(null);
82 meta.lore(List.of(
89 meta.lore(List.of(
83 Component.text("Unlocks " + lock.displayName(), NamedTextColor.GRAY)
90 Component.text("Unlocks " + lock.displayName(), NamedTextColor.GRAY)
84 .decoration(TextDecoration.ITALIC, false)
91 .decoration(TextDecoration.ITALIC, false)
@@ -91,6 +98,7 @@ final class KeyItems {
91 applyCommon(meta);
98 applyCommon(meta);
92 meta.getPersistentDataContainer().remove(bindingKey);
99 meta.getPersistentDataContainer().remove(bindingKey);
93 meta.itemName(Component.text("Blank Key", NamedTextColor.WHITE));
100 meta.itemName(Component.text("Blank Key", NamedTextColor.WHITE));
101 meta.customName(null);
94 meta.lore(null);
102 meta.lore(null);
95 item.setItemMeta(meta);
103 item.setItemMeta(meta);
96 }
104 }
@@ -102,6 +110,45 @@ final class KeyItems {
102 meta.setItemModel(itemModel);
110 meta.setItemModel(itemModel);
103 }
111 }
104
112
113 private boolean syncKey(ItemStack key) {
114 boolean updated = migrateKeyFormat(key);
115 UUID binding = getBinding(key);
116 if (binding == null) {
117 // Blank keys must never keep a custom name.
118 ItemMeta meta = key.getItemMeta();
119 if (meta != null && meta.hasCustomName()) {
120 meta.customName(null);
121 meta.itemName(Component.text("Blank Key", NamedTextColor.WHITE));
122 key.setItemMeta(meta);
123 return true;
124 }
125 return updated;
126 }
127 LockRecord lock = plugin.lockStore().get(binding);
128 if (lock == null) {
129 makeBlank(key);
130 return true;
131 }
132 if (!matchesBoundAppearance(key, lock)) {
133 applyBoundAppearance(key, lock);
134 return true;
135 }
136 return updated;
137 }
138
139 private boolean matchesBoundAppearance(ItemStack key, LockRecord lock) {
140 ItemMeta meta = key.getItemMeta();
141 if (meta == null || meta.hasCustomName()) {
142 return false;
143 }
144 Component itemName = meta.itemName();
145 if (itemName == null) {
146 return false;
147 }
148 String plain = PlainTextComponentSerializer.plainText().serialize(itemName);
149 return lock.keyName().equals(plain);
150 }
151
105 private boolean migrateKeyFormat(ItemStack key) {
152 private boolean migrateKeyFormat(ItemStack key) {
106 ItemMeta meta = key.getItemMeta();
153 ItemMeta meta = key.getItemMeta();
107 if (meta == null) {
154 if (meta == null) {
@@ -115,21 +162,39 @@ final class KeyItems {
115 return true;
162 return true;
116 }
163 }
117
164
118 boolean inventoryHasBinding(Inventory inventory, UUID bindingId) {
165 void applyNameInInventory(Inventory inventory, UUID bindingId) {
119 boolean[] found = {false};
166 LockRecord lock = plugin.lockStore().get(bindingId);
167 if (lock == null) {
168 return;
169 }
120 for (int slot = 0; slot < inventory.getSize(); slot++) {
170 for (int slot = 0; slot < inventory.getSize(); slot++) {
121 ItemStack item = inventory.getItem(slot);
171 ItemStack item = inventory.getItem(slot);
122 if (item == null) {
172 if (item == null) {
123 continue;
173 continue;
124 }
174 }
125 boolean changed = visit(item, 0, key -> {
175 boolean changed = visit(item, 0, key -> {
126 boolean updated = migrateKeyFormat(key);
176 if (bindingId.equals(getBinding(key))) {
127 UUID keyBinding = getBinding(key);
177 applyBoundAppearance(key, lock);
128 if (keyBinding != null && !plugin.lockStore().exists(keyBinding)) {
129 makeBlank(key);
130 return true;
178 return true;
131 }
179 }
132 if (bindingId.equals(keyBinding)) {
180 return false;
181 });
182 if (changed) {
183 inventory.setItem(slot, item);
184 }
185 }
186 }
187
188 boolean inventoryHasBinding(Inventory inventory, UUID bindingId) {
189 boolean[] found = {false};
190 for (int slot = 0; slot < inventory.getSize(); slot++) {
191 ItemStack item = inventory.getItem(slot);
192 if (item == null) {
193 continue;
194 }
195 boolean changed = visit(item, 0, key -> {
196 boolean updated = syncKey(key);
197 if (bindingId.equals(getBinding(key))) {
133 found[0] = true;
198 found[0] = true;
134 }
199 }
135 return updated;
200 return updated;
@@ -150,15 +215,7 @@ final class KeyItems {
150 if (item == null) {
215 if (item == null) {
151 continue;
216 continue;
152 }
217 }
153 boolean changed = visit(item, 0, key -> {
218 boolean changed = visit(item, 0, this::syncKey);
154 boolean updated = migrateKeyFormat(key);
155 UUID binding = getBinding(key);
156 if (binding != null && !plugin.lockStore().exists(binding)) {
157 makeBlank(key);
158 return true;
159 }
160 return updated;
161 });
162 if (changed) {
219 if (changed) {
163 inventory.setItem(slot, item);
220 inventory.setItem(slot, item);
164 }
221 }
@@ -189,15 +246,7 @@ final class KeyItems {
189 if (item == null) {
246 if (item == null) {
190 return false;
247 return false;
191 }
248 }
192 return visit(item, 0, key -> {
249 return visit(item, 0, this::syncKey);
193 boolean updated = migrateKeyFormat(key);
194 UUID binding = getBinding(key);
195 if (binding != null && !plugin.lockStore().exists(binding)) {
196 makeBlank(key);
197 return true;
198 }
199 return updated;
200 });
201 }
250 }
202
251
203 private boolean visit(ItemStack item, int depth, KeyVisitor visitor) {
252 private boolean visit(ItemStack item, int depth, KeyVisitor visitor) {
@@ -225,7 +274,8 @@ final class KeyItems {
225 item.setItemMeta(bundleMeta);
274 item.setItemMeta(bundleMeta);
226 changed = true;
275 changed = true;
227 }
276 }
228 } else if (meta instanceof BlockStateMeta blockStateMeta && blockStateMeta.getBlockState() instanceof ShulkerBox shulker) {
277 } else if (meta instanceof BlockStateMeta blockStateMeta
278 && blockStateMeta.getBlockState() instanceof ShulkerBox shulker) {
229 Inventory contents = shulker.getInventory();
279 Inventory contents = shulker.getInventory();
230 boolean nestedChanged = false;
280 boolean nestedChanged = false;
231 for (int slot = 0; slot < contents.getSize(); slot++) {
281 for (int slot = 0; slot < contents.getSize(); slot++) {
src/main/java/nl/timfalken/copperkeys/KeyNameCommand.java added +64 −0
@@ -0,0 +1,64 @@
1 package nl.timfalken.copperkeys;
2
3 import net.kyori.adventure.text.Component;
4 import net.kyori.adventure.text.format.NamedTextColor;
5 import org.bukkit.command.Command;
6 import org.bukkit.command.CommandExecutor;
7 import org.bukkit.command.CommandSender;
8 import org.bukkit.entity.Player;
9 import org.bukkit.inventory.ItemStack;
10
11 import java.util.UUID;
12
13 final class KeyNameCommand implements CommandExecutor {
14 private final CopperKeysPlugin plugin;
15
16 KeyNameCommand(CopperKeysPlugin plugin) {
17 this.plugin = plugin;
18 }
19
20 @Override
21 public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
22 if (!(sender instanceof Player player)) {
23 sender.sendMessage("Only players can rename keys.");
24 return true;
25 }
26 if (args.length == 0) {
27 player.sendActionBar(Component.text("Usage: /keyname <name>", NamedTextColor.RED));
28 return true;
29 }
30
31 String name = String.join(" ", args).trim();
32 if (name.isEmpty()) {
33 player.sendActionBar(Component.text("Usage: /keyname <name>", NamedTextColor.RED));
34 return true;
35 }
36 if (name.length() > KeyItems.MAX_KEY_NAME_LENGTH) {
37 player.sendActionBar(Component.text(
38 "Name must be at most " + KeyItems.MAX_KEY_NAME_LENGTH + " characters",
39 NamedTextColor.RED
40 ));
41 return true;
42 }
43
44 ItemStack held = player.getInventory().getItemInMainHand();
45 if (!plugin.keyItems().isKey(held)) {
46 player.sendActionBar(Component.text("Hold a bound key to rename it", NamedTextColor.RED));
47 return true;
48 }
49 if (plugin.keyItems().isBlank(held)) {
50 player.sendActionBar(Component.text("Blank keys cannot be renamed", NamedTextColor.RED));
51 return true;
52 }
53
54 UUID bindingId = plugin.keyItems().getBinding(held);
55 if (bindingId == null || plugin.lockStore().get(bindingId) == null) {
56 player.sendActionBar(Component.text("That key is not linked to a lock", NamedTextColor.RED));
57 return true;
58 }
59
60 plugin.renameKeyBinding(bindingId, name);
61 player.sendActionBar(Component.text("Key renamed to " + name, NamedTextColor.GOLD));
62 return true;
63 }
64 }
@@ -0,0 +1,64 @@
1package nl.timfalken.copperkeys;
2
3import net.kyori.adventure.text.Component;
4import net.kyori.adventure.text.format.NamedTextColor;
5import org.bukkit.command.Command;
6import org.bukkit.command.CommandExecutor;
7import org.bukkit.command.CommandSender;
8import org.bukkit.entity.Player;
9import org.bukkit.inventory.ItemStack;
10
11import java.util.UUID;
12
13final class KeyNameCommand implements CommandExecutor {
14 private final CopperKeysPlugin plugin;
15
16 KeyNameCommand(CopperKeysPlugin plugin) {
17 this.plugin = plugin;
18 }
19
20 @Override
21 public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
22 if (!(sender instanceof Player player)) {
23 sender.sendMessage("Only players can rename keys.");
24 return true;
25 }
26 if (args.length == 0) {
27 player.sendActionBar(Component.text("Usage: /keyname <name>", NamedTextColor.RED));
28 return true;
29 }
30
31 String name = String.join(" ", args).trim();
32 if (name.isEmpty()) {
33 player.sendActionBar(Component.text("Usage: /keyname <name>", NamedTextColor.RED));
34 return true;
35 }
36 if (name.length() > KeyItems.MAX_KEY_NAME_LENGTH) {
37 player.sendActionBar(Component.text(
38 "Name must be at most " + KeyItems.MAX_KEY_NAME_LENGTH + " characters",
39 NamedTextColor.RED
40 ));
41 return true;
42 }
43
44 ItemStack held = player.getInventory().getItemInMainHand();
45 if (!plugin.keyItems().isKey(held)) {
46 player.sendActionBar(Component.text("Hold a bound key to rename it", NamedTextColor.RED));
47 return true;
48 }
49 if (plugin.keyItems().isBlank(held)) {
50 player.sendActionBar(Component.text("Blank keys cannot be renamed", NamedTextColor.RED));
51 return true;
52 }
53
54 UUID bindingId = plugin.keyItems().getBinding(held);
55 if (bindingId == null || plugin.lockStore().get(bindingId) == null) {
56 player.sendActionBar(Component.text("That key is not linked to a lock", NamedTextColor.RED));
57 return true;
58 }
59
60 plugin.renameKeyBinding(bindingId, name);
61 player.sendActionBar(Component.text("Key renamed to " + name, NamedTextColor.GOLD));
62 return true;
63 }
64}
src/main/java/nl/timfalken/copperkeys/LockRecord.java +12 −1
@@ -3,8 +3,19 @@ package nl.timfalken.copperkeys;
3 3 import java.util.List;
4 4 import java.util.UUID;
5 5
6 record LockRecord(UUID bindingId, String displayName, List<BlockKey> members) {
6 record LockRecord(UUID bindingId, String displayName, String keyName, List<BlockKey> members) {
7 7 LockRecord {
8 8 members = List.copyOf(members);
9 if (keyName == null || keyName.isBlank()) {
10 keyName = "Key";
11 }
12 }
13
14 static LockRecord create(UUID bindingId, String displayName, List<BlockKey> members) {
15 return new LockRecord(bindingId, displayName, "Key", members);
16 }
17
18 LockRecord withKeyName(String newKeyName) {
19 return new LockRecord(bindingId, displayName, newKeyName, members);
9 20 }
10 21 }
@@ -3,8 +3,19 @@ package nl.timfalken.copperkeys;
3import java.util.List;
3import java.util.List;
4import java.util.UUID;
4import java.util.UUID;
5
5
6record LockRecord(UUID bindingId, String displayName, List<BlockKey> members) {
6record LockRecord(UUID bindingId, String displayName, String keyName, List<BlockKey> members) {
7 LockRecord {
7 LockRecord {
8 members = List.copyOf(members);
8 members = List.copyOf(members);
9 if (keyName == null || keyName.isBlank()) {
10 keyName = "Key";
11 }
12 }
13
14 static LockRecord create(UUID bindingId, String displayName, List<BlockKey> members) {
15 return new LockRecord(bindingId, displayName, "Key", members);
16 }
17
18 LockRecord withKeyName(String newKeyName) {
19 return new LockRecord(bindingId, displayName, newKeyName, members);
9 }
20 }
10}
21}
src/main/java/nl/timfalken/copperkeys/LockStore.java +17 −1
@@ -45,6 +45,7 @@ final class LockStore {
45 45 continue;
46 46 }
47 47 String displayName = section.getString("display-name", "Block");
48 String keyName = section.getString("key-name", "Key");
48 49 List<BlockKey> members = new ArrayList<>();
49 50 for (String encoded : section.getStringList("members")) {
50 51 members.add(BlockKey.decode(encoded));
@@ -52,7 +53,7 @@ final class LockStore {
52 53 if (members.isEmpty()) {
53 54 continue;
54 55 }
55 LockRecord record = new LockRecord(id, displayName, members);
56 LockRecord record = new LockRecord(id, displayName, keyName, members);
56 57 byBinding.put(id, record);
57 58 for (BlockKey member : members) {
58 59 byBlock.put(member, record);
@@ -103,6 +104,20 @@ final class LockStore {
103 104 return record;
104 105 }
105 106
107 LockRecord setKeyName(UUID bindingId, String keyName) {
108 LockRecord current = byBinding.get(bindingId);
109 if (current == null) {
110 return null;
111 }
112 LockRecord updated = current.withKeyName(keyName);
113 byBinding.put(bindingId, updated);
114 for (BlockKey member : updated.members()) {
115 byBlock.put(member, updated);
116 }
117 save();
118 return updated;
119 }
120
106 121 private void save() {
107 122 if (!plugin.getDataFolder().isDirectory() && !plugin.getDataFolder().mkdirs()) {
108 123 plugin.getLogger().warning("Could not create plugin data directory; locks are only in memory.");
@@ -113,6 +128,7 @@ final class LockStore {
113 128 for (LockRecord record : byBinding.values()) {
114 129 String base = "locks." + record.bindingId();
115 130 yaml.set(base + ".display-name", record.displayName());
131 yaml.set(base + ".key-name", record.keyName());
116 132 yaml.set(base + ".members", record.members().stream().map(BlockKey::encode).toList());
117 133 }
118 134 try {
@@ -45,6 +45,7 @@ final class LockStore {
45 continue;
45 continue;
46 }
46 }
47 String displayName = section.getString("display-name", "Block");
47 String displayName = section.getString("display-name", "Block");
48 String keyName = section.getString("key-name", "Key");
48 List<BlockKey> members = new ArrayList<>();
49 List<BlockKey> members = new ArrayList<>();
49 for (String encoded : section.getStringList("members")) {
50 for (String encoded : section.getStringList("members")) {
50 members.add(BlockKey.decode(encoded));
51 members.add(BlockKey.decode(encoded));
@@ -52,7 +53,7 @@ final class LockStore {
52 if (members.isEmpty()) {
53 if (members.isEmpty()) {
53 continue;
54 continue;
54 }
55 }
55 LockRecord record = new LockRecord(id, displayName, members);
56 LockRecord record = new LockRecord(id, displayName, keyName, members);
56 byBinding.put(id, record);
57 byBinding.put(id, record);
57 for (BlockKey member : members) {
58 for (BlockKey member : members) {
58 byBlock.put(member, record);
59 byBlock.put(member, record);
@@ -103,6 +104,20 @@ final class LockStore {
103 return record;
104 return record;
104 }
105 }
105
106
107 LockRecord setKeyName(UUID bindingId, String keyName) {
108 LockRecord current = byBinding.get(bindingId);
109 if (current == null) {
110 return null;
111 }
112 LockRecord updated = current.withKeyName(keyName);
113 byBinding.put(bindingId, updated);
114 for (BlockKey member : updated.members()) {
115 byBlock.put(member, updated);
116 }
117 save();
118 return updated;
119 }
120
106 private void save() {
121 private void save() {
107 if (!plugin.getDataFolder().isDirectory() && !plugin.getDataFolder().mkdirs()) {
122 if (!plugin.getDataFolder().isDirectory() && !plugin.getDataFolder().mkdirs()) {
108 plugin.getLogger().warning("Could not create plugin data directory; locks are only in memory.");
123 plugin.getLogger().warning("Could not create plugin data directory; locks are only in memory.");
@@ -113,6 +128,7 @@ final class LockStore {
113 for (LockRecord record : byBinding.values()) {
128 for (LockRecord record : byBinding.values()) {
114 String base = "locks." + record.bindingId();
129 String base = "locks." + record.bindingId();
115 yaml.set(base + ".display-name", record.displayName());
130 yaml.set(base + ".display-name", record.displayName());
131 yaml.set(base + ".key-name", record.keyName());
116 yaml.set(base + ".members", record.members().stream().map(BlockKey::encode).toList());
132 yaml.set(base + ".members", record.members().stream().map(BlockKey::encode).toList());
117 }
133 }
118 try {
134 try {
src/main/resources/plugin.yml +11 −0
@@ -4,3 +4,14 @@ main: nl.timfalken.copperkeys.CopperKeysPlugin
4 4 api-version: '26.2'
5 5 author: Tim Falken
6 6 description: Event-driven keys for locking containers and openable blocks.
7
8 commands:
9 keyname:
10 description: Rename the bound key you are holding and all copies with the same binding.
11 usage: /keyname <name>
12 permission: copperkeys.keyname
13
14 permissions:
15 copperkeys.keyname:
16 description: Allows renaming bound keys with /keyname
17 default: true
@@ -4,3 +4,14 @@ main: nl.timfalken.copperkeys.CopperKeysPlugin
4api-version: '26.2'
4api-version: '26.2'
5author: Tim Falken
5author: Tim Falken
6description: Event-driven keys for locking containers and openable blocks.
6description: Event-driven keys for locking containers and openable blocks.
7
8commands:
9 keyname:
10 description: Rename the bound key you are holding and all copies with the same binding.
11 usage: /keyname <name>
12 permission: copperkeys.keyname
13
14permissions:
15 copperkeys.keyname:
16 description: Allows renaming bound keys with /keyname
17 default: true