-
-
Notifications
You must be signed in to change notification settings - Fork 104
/
InventoryTag.java
2578 lines (2426 loc) · 106 KB
/
InventoryTag.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.denizenscript.denizen.objects;
import com.denizenscript.denizen.events.BukkitScriptEvent;
import com.denizenscript.denizen.scripts.containers.core.InventoryScriptContainer;
import com.denizenscript.denizen.scripts.containers.core.InventoryScriptHelper;
import com.denizenscript.denizen.scripts.containers.core.ItemScriptHelper;
import com.denizenscript.denizen.utilities.PaperAPITools;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import com.denizenscript.denizen.utilities.depends.Depends;
import com.denizenscript.denizen.utilities.inventory.InventoryTrackerSystem;
import com.denizenscript.denizen.utilities.inventory.RecipeHelper;
import com.denizenscript.denizen.utilities.inventory.SlotHelper;
import com.denizenscript.denizen.utilities.nbt.CustomNBT;
import com.denizenscript.denizencore.events.ScriptEvent;
import com.denizenscript.denizencore.flags.AbstractFlagTracker;
import com.denizenscript.denizencore.flags.FlaggableObject;
import com.denizenscript.denizencore.flags.SavableMapFlagTracker;
import com.denizenscript.denizencore.objects.*;
import com.denizenscript.denizen.nms.NMSHandler;
import com.denizenscript.denizen.nms.abstracts.ImprovedOfflinePlayer;
import com.denizenscript.denizen.tags.BukkitTagContext;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.core.ListTag;
import com.denizenscript.denizencore.objects.core.MapTag;
import com.denizenscript.denizencore.objects.core.ScriptTag;
import com.denizenscript.denizencore.objects.notable.Notable;
import com.denizenscript.denizencore.objects.notable.Note;
import com.denizenscript.denizencore.objects.notable.NoteManager;
import com.denizenscript.denizencore.objects.properties.PropertyParser;
import com.denizenscript.denizencore.scripts.ScriptRegistry;
import com.denizenscript.denizencore.tags.Attribute;
import com.denizenscript.denizencore.tags.ObjectTagProcessor;
import com.denizenscript.denizencore.tags.TagContext;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import com.denizenscript.denizen.utilities.BukkitImplDeprecations;
import com.denizenscript.denizencore.utilities.YamlConfiguration;
import net.citizensnpcs.api.CitizensAPI;
import org.bukkit.Bukkit;
import org.bukkit.Keyed;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.block.DoubleChest;
import org.bukkit.entity.Entity;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.*;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.*;
public class InventoryTag implements ObjectTag, Notable, Adjustable, FlaggableObject {
// <--[ObjectType]
// @name InventoryTag
// @prefix in
// @base ElementTag
// @implements FlaggableObject, PropertyHolderObject
// @ExampleTagBase player.inventory
// @ExampleValues <player.inventory>
// @ExampleForReturns
// - note %VALUE% as:my_new_inventory
// @ExampleForReturns
// - inventory set o:%VALUE% d:stick slot:5
// @format
// The identity format for inventories is a the classification type of inventory to use. All other data is specified through properties.
//
// @description
// An InventoryTag represents an inventory, generically or attached to some in-the-world object.
//
// Inventories can be generically designed using inventory script containers,
// and can be modified using the inventory command.
//
// Valid inventory type classifications:
// "npc", "player", "crafting", "enderchest", "workbench", "entity", "location", "generic"
//
// This object type can be noted.
//
// This object type is flaggable when it is noted.
// Flags on this object type will be stored in the notables.yml file.
//
// @Matchable
// InventoryTag matchers, sometimes identified as "<inventory>":
// "inventory" plaintext: always matches.
// "note" plaintext: matches if the inventory is noted.
// Inventory script name: matches if the inventory comes from an inventory script of the given name, using advanced matchers.
// Inventory note name: matches if the inventory is noted with the given name, using advanced matchers.
// Inventory type: matches if the inventory is of a given type, using advanced matchers.
// "inventory_flagged:<flag>": a Flag Matchable for InventoryTag flags.
//
// -->
public static void trackTemporaryInventory(InventoryTag tagForm) {
if (tagForm == null) {
return;
}
InventoryTrackerSystem.trackTemporaryInventory(tagForm.inventory, tagForm);
}
public static void setupInventoryTracker() {
InventoryTrackerSystem.setup();
}
public static InventoryTag mirrorBukkitInventory(Inventory inventory) {
if (inventory == null) {
return null;
}
InventoryTag result = InventoryTrackerSystem.getTagFormFor(inventory);
if (result != null) {
return result;
}
// Use the map to get noted inventories
result = InventoryScriptHelper.notedInventories.get(inventory);
if (result != null) {
return result;
}
// Iterate through offline player inventories
for (Map.Entry<UUID, PlayerInventory> inv : ImprovedOfflinePlayer.offlineInventories.entrySet()) {
if (inv.getValue().equals(inventory)) {
return new InventoryTag(NMSHandler.playerHelper.getOfflineData(inv.getKey()));
}
}
// Iterate through offline player enderchests
for (Map.Entry<UUID, Inventory> inv : ImprovedOfflinePlayer.offlineEnderChests.entrySet()) {
if (inv.getValue().equals(inventory)) {
return new InventoryTag(NMSHandler.playerHelper.getOfflineData(inv.getKey()), true);
}
}
return new InventoryTag(inventory);
}
/////////////////////
// STATIC FIELDS
/////////////////
// The maximum number of slots a Bukkit inventory can have
public final static int maxSlots = 54;
// All of the inventory id types we use
public final static String[] idTypes = {"npc", "player", "crafting", "enderchest", "workbench", "entity", "location", "generic"};
/////////////////////
// NOTABLE METHODS
/////////////////
@Override
public boolean isUnique() {
return noteName != null;
}
public boolean isSaving = false;
public AbstractFlagTracker flagTracker = null;
@Note("Inventories")
public Object getSaveObject() {
isSaving = true;
try {
YamlConfiguration section = new YamlConfiguration();
section.set("object", "in@" + idType + PropertyParser.getPropertiesString(this));
section.set("flags", flagTracker.toString());
return section;
}
finally {
isSaving = false;
}
}
public void setInventory(Inventory inventory) {
if (isUnique()) {
InventoryScriptHelper.notedInventories.remove(this.inventory);
InventoryScriptHelper.notedInventories.put(inventory, this);
}
this.inventory = inventory;
}
public String noteName = null, priorNoteName = null;
public void makeUnique(String id) {
InventoryTag toNote = new InventoryTag(inventory, idType, idHolder);
toNote.uniquifier = null;
String title = PaperAPITools.instance.getTitle(inventory);
if (title == null || title.startsWith("container.")) {
title = toNote.inventory.getType().getDefaultTitle();
}
ItemStack[] contents = toNote.inventory.getContents();
if (getInventoryType() == InventoryType.CHEST) {
toNote.inventory = PaperAPITools.instance.createInventory(null, toNote.inventory.getSize(), title);
}
else {
toNote.inventory = PaperAPITools.instance.createInventory(null, toNote.inventory.getType(), title);
}
toNote.inventory.setContents(contents);
InventoryScriptHelper.notedInventories.put(toNote.inventory, toNote);
if (!idType.equals("generic") && !idType.equals("script")) {
toNote.idType = "generic";
toNote.idHolder = new ElementTag(CoreUtilities.toLowerCase(getInventoryType().name()));
}
toNote.flagTracker = new SavableMapFlagTracker();
NoteManager.saveAs(toNote, id);
toNote.noteName = id;
}
@Override
public void forget() {
if (noteName == null) {
return;
}
priorNoteName = noteName;
NoteManager.remove(this);
InventoryScriptHelper.notedInventories.remove(inventory);
flagTracker = null;
noteName = null;
}
@Override
public InventoryTag refreshState() {
if (noteName == null && priorNoteName != null) {
Notable note = NoteManager.getSavedObject(priorNoteName);
if (note instanceof InventoryTag) {
return (InventoryTag) note;
}
priorNoteName = null;
}
trackTemporaryInventory(this);
return this;
}
@Override
public AbstractFlagTracker getFlagTracker() {
return flagTracker;
}
@Override
public void reapplyTracker(AbstractFlagTracker tracker) {
if (noteName != null) {
this.flagTracker = tracker;
}
}
@Override
public String getReasonNotFlaggable() {
if (noteName == null) {
return "the inventory is not noted - only noted inventories can hold flags";
}
return "unknown reason - something went wrong";
}
public static InventoryTag valueOf(String string, PlayerTag player, NPCTag npc, boolean silent) {
return valueOf(string, new BukkitTagContext(player, npc, null, !silent, null));
}
public static InventoryTag valueOf(String string, PlayerTag player, NPCTag npc) {
return valueOf(string, player, npc, false);
}
public static InventoryTag internalGetInventoryFor(TagContext context, List<String> properties) {
String typeName = properties.get(0);
String holder = null;
int size = -1;
for (String property : properties) {
if (property.startsWith("holder=")) {
holder = ObjectFetcher.unescapeProperty(property.substring("holder=".length()));
}
else if (property.startsWith("script_name=")) {
holder = ObjectFetcher.unescapeProperty(property.substring("script_name=".length()));
typeName = "script";
}
else if (property.startsWith("uniquifier=")) {
String idText = property.substring("uniquifier=".length());
if (!ArgumentHelper.matchesInteger(idText)) {
return null;
}
long id = Long.parseLong(idText);
InventoryTag fixedResult = InventoryTrackerSystem.idTrackedInventories.get(id);
if (fixedResult != null) {
trackTemporaryInventory(fixedResult);
return fixedResult;
}
}
else if (property.startsWith("size=")) {
String sizeText = property.substring("size=".length());
if (!ArgumentHelper.matchesInteger(sizeText)) {
return null;
}
size = Integer.parseInt(sizeText);
}
}
if (holder != null) {
switch (typeName) {
case "player":
case "enderchest":
case "workbench":
case "crafting":
PlayerTag player = PlayerTag.valueOf(holder, context);
if (player == null) {
if (context == null || context.showErrors()) {
Debug.echoError("Invalid inventory player '" + holder + "'");
}
return null;
}
switch (typeName) {
case "player":
return player.getInventory();
case "enderchest":
return player.getEnderChest();
case "workbench":
return player.getWorkbench();
case "crafting":
Inventory opened = player.getPlayerEntity().getOpenInventory().getTopInventory();
if (opened instanceof CraftingInventory) {
return new InventoryTag(opened, player.getPlayerEntity());
}
else {
return player.getInventory();
}
}
break;
case "npc":
NPCTag npc = NPCTag.valueOf(holder, context);
if (npc == null) {
if (context == null || context.showErrors()) {
Debug.echoError("Invalid inventory npc '" + holder + "'");
}
return null;
}
return npc.getDenizenInventory();
case "entity":
EntityTag entity = EntityTag.valueOf(holder, context);
if (entity == null) {
if (context == null || context.showErrors()) {
Debug.echoError("Invalid inventory entity '" + holder + "'");
}
return null;
}
return entity.getInventory();
case "location":
LocationTag location = LocationTag.valueOf(holder, context);
if (location == null) {
if (context == null || context.showErrors()) {
Debug.echoError("Invalid inventory location '" + holder + "'");
}
return null;
}
return location.getInventory();
}
}
InventoryTag result = null;
if (typeName.equals("generic")) {
if (holder != null && !new ElementTag(holder).matchesEnum(InventoryType.class)) {
if (context == null || context.showErrors()) {
Debug.echoError("Unknown inventory type '" + holder + "'");
}
return null;
}
InventoryType type = holder == null ? InventoryType.CHEST : InventoryType.valueOf(holder.toUpperCase());
if (size == -1 || type != InventoryType.CHEST) {
result = new InventoryTag(type);
}
else {
result = new InventoryTag(size);
}
}
else if (typeName.equals("script") && holder != null) {
ScriptTag script = ScriptTag.valueOf(holder, context);
if (script == null || !(script.getContainer() instanceof InventoryScriptContainer)) {
if (context == null || context.showErrors()) {
Debug.echoError("Unknown inventory script '" + holder + "'");
}
return null;
}
result = ((InventoryScriptContainer) script.getContainer()).getInventoryFrom(context);
if (size != -1) {
result.setSize(size);
}
}
if (result == null && holder != null) {
ScriptTag script = ScriptTag.valueOf(holder, context);
if (script != null && (script.getContainer() instanceof InventoryScriptContainer)) {
result = ((InventoryScriptContainer) script.getContainer()).getInventoryFrom(context);
}
}
if (result == null && new ElementTag(typeName).matchesEnum(InventoryType.class)) {
InventoryType type = InventoryType.valueOf(typeName.toUpperCase());
if (size == -1 || type != InventoryType.CHEST) {
result = new InventoryTag(type);
}
else {
result = new InventoryTag(size);
}
}
if (result == null) {
if (context == null || context.showErrors()) {
Debug.echoError("Unknown inventory idType '" + typeName + "'");
}
return null;
}
internalApplyPropertySet(result, context, properties);
return result;
}
public static void internalApplyPropertySet(InventoryTag result, TagContext context, List<String> properties) {
for (int i = 1; i < properties.size(); i++) {
List<String> data = CoreUtilities.split(properties.get(i), '=', 2);
if (data.size() != 2) {
if (context == null || context.showErrors()) {
Debug.echoError("Invalid property string '" + properties.get(i) + "'!");
}
continue;
}
String name = CoreUtilities.toLowerCase(data.get(0));
String description = ObjectFetcher.unescapeProperty(data.get(1));
ElementTag descriptionElement = new ElementTag(description);
Mechanism mechanism = new Mechanism(data.get(0), descriptionElement, context);
if (!name.equals("holder") && !name.equals("uniquifier") && !name.equals("size") && !name.equals("script_name")) {
result.safeAdjust(mechanism);
}
}
}
@Fetchable("in")
public static InventoryTag valueOf(String string, TagContext context) {
if (string == null) {
return null;
}
if (string.startsWith("in@")) {
string = string.substring("in@".length());
}
List<String> properties = ObjectFetcher.separateProperties(string);
if (properties != null && properties.size() > 1) {
InventoryTag result = internalGetInventoryFor(context, properties);
if (result == null) {
if (context == null || context.showErrors()) {
Debug.echoError("Value of InventoryTag returning null. Invalid InventoryTag-with-properties specified: " + string);
}
return null;
}
trackTemporaryInventory(result);
return result;
}
Notable noted = NoteManager.getSavedObject(string);
if (noted instanceof InventoryTag) {
return (InventoryTag) noted;
}
if (ScriptRegistry.containsScript(string, InventoryScriptContainer.class)) {
return ScriptRegistry.getScriptContainerAs(string, InventoryScriptContainer.class).getInventoryFrom(context);
}
if (new ElementTag(string).matchesEnum(InventoryType.class)) {
InventoryType type = InventoryType.valueOf(string.toUpperCase());
return new InventoryTag(type);
}
if (context == null || context.showErrors()) {
Debug.echoError("Value of InventoryTag returning null. Invalid InventoryTag specified: " + string);
}
return null;
}
public static boolean matches(String arg) {
if (CoreUtilities.toLowerCase(arg).startsWith("in@")) {
return true;
}
String tid = arg;
if (arg.contains("[")) {
tid = arg.substring(0, arg.indexOf('['));
}
if (new ElementTag(tid).matchesEnum(InventoryType.class)) {
return true;
}
if (ScriptRegistry.containsScript(tid, InventoryScriptContainer.class)) {
return true;
}
if (NoteManager.getSavedObject(tid) instanceof InventoryTag) {
return true;
}
for (String idType : idTypes) {
if (tid.equalsIgnoreCase(idType)) {
return true;
}
}
return false;
}
public boolean isGeneric() {
return idType.equals("generic") || idType.equals("script") && !isUnique();
}
public static final ElementTag defaultIdHolder = new ElementTag("unknown");
public String idType = null;
public ObjectTag idHolder = defaultIdHolder;
public Long uniquifier = null;
public Inventory inventory = null;
public String customTitle = null;
public String prefix = "Inventory";
private InventoryTag(Inventory inventory) {
this.inventory = inventory;
loadIdentifiers(inventory.getHolder());
}
public InventoryTag(Inventory inventory, InventoryHolder holder) {
this.inventory = inventory;
loadIdentifiers(holder);
}
public InventoryTag(Inventory inventory, String type, ObjectTag holder) {
this.inventory = inventory;
this.idType = type;
this.idHolder = holder;
}
public InventoryTag(ItemStack[] items) {
inventory = Bukkit.getServer().createInventory(null, (int) Math.ceil(items.length / 9.0) * 9);
idType = "generic";
idHolder = new ElementTag("chest");
setContents(items);
}
public InventoryTag(ImprovedOfflinePlayer offlinePlayer) {
this(offlinePlayer, false);
}
public InventoryTag(ImprovedOfflinePlayer offlinePlayer, boolean isEnderChest) {
inventory = isEnderChest ? offlinePlayer.getEnderChest() : offlinePlayer.getInventory();
idType = isEnderChest ? "enderchest" : "player";
idHolder = new PlayerTag(offlinePlayer.getUniqueId());
}
public InventoryTag(int size, String title) {
if (size <= 0 || size % 9 != 0) {
Debug.echoError("InventorySize must be multiple of 9, and greater than 0.");
return;
}
inventory = PaperAPITools.instance.createInventory(null, size, title);
idType = "generic";
idHolder = new ElementTag("chest");
}
public InventoryTag(InventoryType type) {
inventory = Bukkit.getServer().createInventory(null, type);
idType = "generic";
idHolder = new ElementTag(CoreUtilities.toLowerCase(type.name()));
}
public InventoryTag(InventoryType type, String title) {
inventory = PaperAPITools.instance.createInventory(null, type, title);
idType = "generic";
idHolder = new ElementTag(CoreUtilities.toLowerCase(type.name()));
}
public InventoryTag(int size) {
this(size, "Chest");
}
public Inventory getInventory() {
return inventory;
}
public boolean containsItem(ItemTag item, int amount) {
if (item == null) {
return false;
}
item = new ItemTag(item.getItemStack().clone());
item.setAmount(1);
String myItem = CoreUtilities.toLowerCase(item.identify());
for (int i = 0; i < inventory.getSize(); i++) {
ItemStack is = inventory.getItem(i);
if (is == null || item.getMaterial().getMaterial() != is.getType()) {
continue;
}
is = is.clone();
int count = is.getAmount();
is.setAmount(1);
String newItem = CoreUtilities.toLowerCase(new ItemTag(is).identify());
if (myItem.equals(newItem)) {
if (count <= amount) {
amount -= count;
if (amount == 0) {
return true;
}
}
else if (count > amount) {
return true;
}
}
}
return false;
}
public void setSize(int size) {
if (!getIdType().equals("generic") && !getIdType().equals("script")) {
return;
}
else if (size <= 0 || size % 9 != 0) {
Debug.echoError("InventorySize must be multiple of 9, and greater than 0.");
return;
}
else if (inventory == null) {
uniquifier = null;
inventory = Bukkit.getServer().createInventory(null, size, "Chest");
trackTemporaryInventory(this);
return;
}
int oldSize = inventory.getSize();
if (oldSize == size) {
return;
}
uniquifier = null;
ItemStack[] oldContents = inventory.getContents();
ItemStack[] newContents = new ItemStack[size];
if (oldSize > size) {
// TODO: Why is this a manual copy?
System.arraycopy(oldContents, 0, newContents, 0, size);
}
else {
newContents = oldContents;
}
String title = PaperAPITools.instance.getTitle(inventory);
if (title == null) {
setInventory(Bukkit.getServer().createInventory(null, size));
}
else {
setInventory(PaperAPITools.instance.createInventory(null, size, title));
}
inventory.setContents(newContents);
trackTemporaryInventory(this);
}
private void loadIdentifiers(final InventoryHolder holder) {
if (inventory == null) {
return;
}
InventoryTag realInv = InventoryTrackerSystem.getTagFormFor(inventory);
if (realInv != null) {
Debug.echoError("Tried to load already-tracked inventory as new inventory?");
return;
}
trackTemporaryInventory(this);
if (holder != null) {
if (holder instanceof NPCTag) {
idType = "npc";
idHolder = ((NPCTag) holder);
return;
}
else if (holder instanceof Player) {
if (Depends.citizens != null && CitizensAPI.getNPCRegistry().isNPC((Player) holder)) {
idType = "npc";
idHolder = (NPCTag.fromEntity((Player) holder));
return;
}
if (inventory.getType() == InventoryType.CRAFTING) {
idType = "crafting";
}
if (inventory.getType() == InventoryType.ENDER_CHEST) {
idType = "enderchest";
}
else if (inventory.getType() == InventoryType.WORKBENCH) {
idType = "workbench";
}
else {
idType = "player";
}
idHolder = new PlayerTag((Player) holder);
return;
}
else if (holder instanceof Entity) {
idType = "entity";
idHolder = new EntityTag((Entity) holder);
return;
}
else {
idType = "location";
idHolder = getLocation(holder);
if (idHolder != null) {
return;
}
}
}
else if (inventory instanceof AnvilInventory && inventory.getLocation() != null) {
idType = "location";
idHolder = new LocationTag(inventory.getLocation());
}
else if (getIdType().equals("player")) {
if (idHolder instanceof PlayerTag) {
return;
}
// Iterate through offline player inventories
for (Map.Entry<UUID, PlayerInventory> inv : ImprovedOfflinePlayer.offlineInventories.entrySet()) { // TODO: Less weird lookup?
if (inv.getValue().equals(inventory)) {
idHolder = new PlayerTag(inv.getKey());
return;
}
}
}
else if (getIdType().equals("enderchest")) {
if (idHolder instanceof PlayerTag) {
return;
}
// Iterate through offline player enderchests
for (Map.Entry<UUID, Inventory> inv : ImprovedOfflinePlayer.offlineEnderChests.entrySet()) { // TODO: Less weird lookup?
if (inv.getValue().equals(inventory)) {
idHolder = new PlayerTag(inv.getKey());
return;
}
}
}
else if (getIdType().equals("script")) {
if (idHolder instanceof ScriptTag) {
return;
}
InventoryTag tracked = InventoryTrackerSystem.retainedInventoryLinks.get(inventory);
if (tracked != null) {
idHolder = tracked.idHolder;
return;
}
}
idType = "generic";
idHolder = new ElementTag(CoreUtilities.toLowerCase(getInventory().getType().name()));
}
public String getIdType() {
return idType == null ? "" : idType;
}
public ObjectTag getIdHolder() {
return idHolder;
}
public LocationTag getLocation() {
return getLocation(inventory.getHolder());
}
public LocationTag getLocation(InventoryHolder holder) {
if (inventory != null && holder != null) {
if (holder instanceof BlockState) {
return new LocationTag(((BlockState) holder).getLocation());
}
else if (holder instanceof DoubleChest) {
return new LocationTag(((DoubleChest) holder).getLocation());
}
else if (holder instanceof Entity) {
return new LocationTag(((Entity) holder).getLocation());
}
else if (holder instanceof NPCTag) {
NPCTag npc = (NPCTag) holder;
if (npc.getLocation() == null) {
return new LocationTag(((NPCTag) holder).getCitizen().getStoredLocation());
}
return npc.getLocation();
}
}
return null;
}
public ItemStack[] getContents() {
if (inventory != null) {
return inventory.getContents();
}
else {
return new ItemStack[0];
}
}
public ItemStack[] getStorageContents() {
if (inventory != null) {
return inventory.getStorageContents();
}
else {
return new ItemStack[0];
}
}
public static void addToMapIfNonAir(MapTag map, String name, ItemStack item) {
if (item == null || item.getType() == Material.AIR) {
return;
}
map.putObject(name, new ItemTag(item));
}
public MapTag getEquipmentMap() {
MapTag output = new MapTag();
if (inventory instanceof PlayerInventory) {
ItemStack[] equipment = ((PlayerInventory) inventory).getArmorContents();
addToMapIfNonAir(output, "boots", equipment[0]);
addToMapIfNonAir(output, "leggings", equipment[1]);
addToMapIfNonAir(output, "chestplate", equipment[2]);
addToMapIfNonAir(output, "helmet", equipment[3]);
}
else if (inventory instanceof HorseInventory) {
addToMapIfNonAir(output, "saddle", ((HorseInventory) inventory).getSaddle());
addToMapIfNonAir(output, "armor", ((HorseInventory) inventory).getArmor());
}
else {
return null;
}
return output;
}
public ListTag getEquipment() {
ItemStack[] equipment = null;
if (inventory instanceof PlayerInventory) {
equipment = ((PlayerInventory) inventory).getArmorContents();
}
else if (inventory instanceof HorseInventory) {
equipment = new ItemStack[] {((HorseInventory) inventory).getSaddle(), ((HorseInventory) inventory).getArmor()};
}
if (equipment == null) {
return null;
}
ListTag equipmentList = new ListTag();
for (ItemStack item : equipment) {
equipmentList.addObject(new ItemTag(item));
}
return equipmentList;
}
public InventoryType getInventoryType() {
return inventory.getType();
}
public int getSize() {
return inventory.getSize();
}
public void setContents(ItemStack[] contents) {
inventory.setContents(contents);
}
public void setContents(ListTag list, TagContext context) {
int size;
if (inventory == null) {
size = (int) Math.ceil(list.size() / 9.0) * 9;
if (size == 0) {
size = 9;
}
inventory = Bukkit.getServer().createInventory(null, size);
idType = "generic";
idHolder = new ElementTag("chest");
}
else {
size = inventory.getSize();
}
ItemStack[] contents = new ItemStack[size];
int filled = 0;
for (ItemTag item : list.filter(ItemTag.class, context)) {
if (filled >= contents.length) {
Debug.echoError("Cannot set contents of inventory to " + list.size() + " items, as the inventory size is only " + size + "!");
break;
}
contents[filled] = item.getItemStack();
filled++;
}
while (filled < size) {
contents[filled] = new ItemStack(Material.AIR);
filled++;
}
inventory.setContents(contents);
if (Depends.citizens != null && idHolder instanceof NPCTag) {
((NPCTag) idHolder).getInventoryTrait().setContents(contents);
}
}
public int firstPartial(int startSlot, ItemStack item) {
ItemStack[] inventory = getContents();
if (item == null) {
return -1;
}
for (int i = startSlot; i < inventory.length; i++) {
ItemStack item1 = inventory[i];
if (item1 != null && item1.getAmount() < item.getMaxStackSize() && item1.isSimilar(item)) {
return i;
}
}
return -1;
}
public int firstEmpty(int startSlot) {
ItemStack[] inventory = getStorageContents();
for (int i = startSlot; i < inventory.length; i++) {
if (inventory[i] == null) {
return i;
}
}
return -1;
}
// Somewhat simplified version of CraftBukkit's code
public InventoryTag add(int slot, ItemStack... items) {
if (inventory == null || items == null) {
return this;
}
for (int i = 0; i < items.length; i++) {
ItemStack item = items[i];
if (item == null || item.getType().isAir()) {
continue;
}
int amount = item.getAmount();
int max = item.getMaxStackSize();
while (true) {
// Do we already have a stack of it?
int firstPartial = firstPartial(slot, item);
// Drat! no partial stack
if (firstPartial == -1) {
// Find a free spot!
int firstFree = firstEmpty(slot);
if (firstFree == -1) {
// No space at all!
break;
}
else {
// More than a single stack!
if (amount > max) {
ItemStack clone = item.clone();
clone.setAmount(max);
NMSHandler.itemHelper.setInventoryItem(inventory, clone, firstFree);
item.setAmount(amount -= max);
}
else {
// Just store it
NMSHandler.itemHelper.setInventoryItem(inventory, item, firstFree);
break;
}
}
}
else {
// So, apparently it might only partially fit, well lets do just that
ItemStack partialItem = inventory.getItem(firstPartial);
int partialAmount = partialItem.getAmount();
int total = amount + partialAmount;
// Check if it fully fits
if (total <= max) {
partialItem.setAmount(total);
break;
}
// It fits partially
partialItem.setAmount(max);
item.setAmount(amount = total - max);
}
}
}
return this;
}
public List<ItemStack> addWithLeftovers(int slot, boolean keepMaxStackSize, ItemStack... items) {
if (inventory == null || items == null) {
return null;
}
List<ItemStack> leftovers = new ArrayList<>();
for (int i = 0; i < items.length; i++) {
ItemStack item = items[i];
if (item == null || item.getType().isAir()) {
continue;
}
int amount = item.getAmount();
int max;
if (keepMaxStackSize) {
max = item.getMaxStackSize();
}
else {
max = 64;
}
while (true) {
// Do we already have a stack of it?
int firstPartial = firstPartial(slot, item);
// Drat! no partial stack
if (firstPartial == -1) {
// Find a free spot!
int firstFree = firstEmpty(slot);
if (firstFree == -1) {
// No space at all!
leftovers.add(item);
break;
}
else {
// More than a single stack!
if (amount > max) {
ItemStack clone = item.clone();
clone.setAmount(max);
NMSHandler.itemHelper.setInventoryItem(inventory, clone, firstFree);
item.setAmount(amount -= max);
}
else {
// Just store it
NMSHandler.itemHelper.setInventoryItem(inventory, item, firstFree);
break;
}
}
}
else {
// So, apparently it might only partially fit, well lets do just that
ItemStack partialItem = inventory.getItem(firstPartial);