-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
ScriptEvent.java
779 lines (696 loc) · 34.5 KB
/
ScriptEvent.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
package com.denizenscript.denizencore.events;
import com.denizenscript.denizencore.events.core.*;
import com.denizenscript.denizencore.objects.ArgumentHelper;
import com.denizenscript.denizencore.scripts.containers.core.WorldScriptContainer;
import com.denizenscript.denizencore.scripts.queues.ContextSource;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.ObjectTag;
import com.denizenscript.denizencore.scripts.ScriptEntry;
import com.denizenscript.denizencore.scripts.ScriptEntryData;
import com.denizenscript.denizencore.scripts.ScriptEntrySet;
import com.denizenscript.denizencore.scripts.containers.ScriptContainer;
import com.denizenscript.denizencore.scripts.queues.ScriptQueue;
import com.denizenscript.denizencore.scripts.queues.core.InstantQueue;
import com.denizenscript.denizencore.tags.TagContext;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import com.denizenscript.denizencore.utilities.YamlConfiguration;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import com.denizenscript.denizencore.utilities.scheduling.OneTimeSchedulable;
import com.denizenscript.denizencore.utilities.text.StringHolder;
import com.denizenscript.denizencore.DenizenCore;
import java.util.*;
import java.util.regex.Pattern;
public abstract class ScriptEvent implements ContextSource, Cloneable {
@Override
public ScriptEvent clone() {
try {
return (ScriptEvent) super.clone();
}
catch (CloneNotSupportedException e) {
Debug.echoError("Clone not supported for script events?!");
return this;
}
}
public static void registerCoreEvents() {
registerScriptEvent(new ConsoleOutputScriptEvent());
registerScriptEvent(new DeltaTimeScriptEvent());
registerScriptEvent(new PreScriptReloadScriptEvent());
registerScriptEvent(new ReloadScriptsScriptEvent());
registerScriptEvent(new ScriptGeneratesErrorScriptEvent());
registerScriptEvent(new ServerGeneratesExceptionScriptEvent());
registerScriptEvent(new SystemTimeScriptEvent());
registerScriptEvent(new TickScriptEvent());
}
public static void registerScriptEvent(ScriptEvent event) {
events.add(event);
eventLookup.put(CoreUtilities.toLowerCase(event.getName()), event);
}
public static ArrayList<WorldScriptContainer> worldContainers = new ArrayList<>();
public static ArrayList<ScriptEvent> events = new ArrayList<>();
public static HashMap<String, ScriptEvent> eventLookup = new HashMap<>();
public static class StatData {
public long fires = 0;
public long scriptFires = 0;
public long nanoTimes = 0;
}
public StatData stats = new StatData();
public static class ScriptPath {
public ScriptContainer container;
public String event;
public String eventLower;
public int priority = 0;
public ScriptEntrySet set;
public Boolean switch_cancelled;
public Boolean switch_ignoreCancelled;
public HashMap<String, String> switches = new HashMap<>();
public String[] eventArgs;
public String[] eventArgsLower;
public String[] rawEventArgs;
public List<ScriptEvent> matches = new ArrayList<>();
public TagContext context;
public boolean fireAfter = false;
public List<String> matchFailReasons = null;
public String rawEventArgAt(int index) {
return index < rawEventArgs.length ? rawEventArgs[index] : "";
}
public String eventArgAt(int index) {
return index < eventArgs.length ? eventArgs[index] : "";
}
public String eventArgLowerAt(int index) {
return index < eventArgsLower.length ? eventArgsLower[index] : "";
}
// <--[language]
// @name Script Event Switches
// @group Script Events
// @description
// Modern script events support the concept of 'switches'.
// A switch is a specification of additional requirements in an event line other than what's in the event label it.
//
// A switch consists of a name and a value input, and are can be added anywhere in an event line as "name:<value>".
// For example, "on delta time secondly every:5:" is a valid event, where "delta time secondly" is the event itself, and "every:<#>" is a switch available to the event.
//
// A traditional Denizen event might look like "on <entity> damaged",
// where "<entity>" can be filled with "entity" or any entity type (like "player").
// A switch-using event would instead take the format "on entity damaged" with switch "type:<entity type>"
// meaning you can do "on entity damaged" for any entity, or "on entity damaged type:player:" for players specifically.
// This is both more efficient to process and more explicit in what's going on, however it is less clear/readable to the average user, so it is not often used.
// Some events may have switches for less-often specified data, and use the event line for other options.
//
// There are also some standard switches available to every script event, and some available to an entire category of script events.
//
// One switch available to every event is "server_flagged:<flag name>", which requires that there be a server flag under the given name.
// For example, "on console output server_flagged:recording:" will only run the handler for console output when the "recording" flag is set on the server.
//
// Events that have a player linked have the "flagged" and "permission" switches available.
// Will always fail if the event doesn't have a linked player.
// The "flagged:<flag name>" will limit the event to only fire when the player has the flag with the specified name.
// It can be used like "on player breaks block flagged:nobreak:" (that would be used alongside "- flag player nobreak").
// The "permission:<perm key>" will limit the event to only fire when the player has the specified permission key.
// It can be used like "on player breaks block permission:denizen.my.perm:"
// As with any advanced switch, for multiple flag or permission requirements, just list them separated by '|' pipes, like "flagged:a|b|c".
//
// Events that occur at a specific location have the "in:<area>" and "location_flagged" switches.
// This switches will be ignored (not counted one way or the other) for events that don't have a known location.
// For "in:<area>" switches, 'area' is any area-defining tag type - refer to <@link language Script Event Object Matchables>.
// "location_flagged:<flag name>" works just like "server_flagged" or the player "flagged" switches, but for locations.
//
// All script events have priority switches (see <@link language script event priority>),
// All Bukkit events have bukkit priority switches (see <@link language bukkit event priority>),
// All cancellable script events have cancellation switches (see <@link language script event cancellation>).
//
// See also <@link language advanced script event matching>.
// -->
public boolean checkSwitch(String key, String value) {
String pathValue = switches.get(key);
if (pathValue == null) {
return true;
}
return CoreUtilities.equalsIgnoreCase(pathValue, value);
}
public static HashSet<String> notSwitches = new HashSet<>(Arrays.asList("regex", "item_flagged", "world_flagged", "area_flagged", "inventory_flagged", "player_flagged", "npc_flagged", "entity_flagged", "vanilla_tagged", "raw_exact", "item_enchanted"));
public ScriptPath(ScriptContainer container, String event, String rawEventPath) {
this.event = event;
rawEventArgs = CoreUtilities.split(event, ' ').toArray(new String[0]);
this.container = container;
context = DenizenCore.getImplementation().getTagContext(container);
List<String> eventLabel = new ArrayList<>();
for (String possible : CoreUtilities.split(event, ' ').toArray(new String[0])) {
List<String> split = CoreUtilities.split(possible, ':', 2);
if (split.size() > 1 && !ArgumentHelper.matchesInteger(split.get(0)) && !notSwitches.contains(CoreUtilities.toLowerCase(split.get(0)))) {
switches.put(CoreUtilities.toLowerCase(split.get(0)), split.get(1));
}
else {
eventLabel.add(possible);
}
}
eventLower = CoreUtilities.toLowerCase(String.join(" ", eventLabel));
eventArgs = eventLabel.toArray(new String[0]);
eventArgsLower = CoreUtilities.split(eventLower, ' ').toArray(new String[0]);
switch_cancelled = switches.containsKey("cancelled") ? CoreUtilities.equalsIgnoreCase(switches.get("cancelled"), "true") : null;
switch_ignoreCancelled = switches.containsKey("ignorecancelled") ? CoreUtilities.equalsIgnoreCase(switches.get("ignorecancelled"), "true") : null;
set = container.getSetFor("events." + rawEventPath);
if (set == null || set.entries == null) {
Debug.echoError("Invalid script (formatting error?) in container '" + container.getName() + " at event '" + rawEventPath + "'.");
}
}
@Override
public String toString() {
return container.getName() + ".events.on " + event;
}
}
// <--[language]
// @name Script Event After vs On
// @group Script Events
// @description
// Modern ScriptEvents let you choose between "on" and "after".
// An "on" event looks like "on player breaks block:" while an "after" event looks like "after player breaks block:".
//
// An "on" event fires *before* the event actually happens in the world. This means some relevant data won't be updated
// (for example, "<context.location.material>" would still show the block type that is going to be broken)
// and the result of the event can be changed (eg the event can be cancelled to stop it from actually going through).
//
// An "after" event, as the name implies, fires *after* the event actually happens. This means data will be already updated to the new state
// (so "<context.location.material>" would now show air) but could potentially contain an arbitrary new state from unrelated changes
// (for example "<context.location.material>" might now show a different block type, or the original one, if the event was changed,
// or another thing happened right after the event but before the 'after' event ran).
// This also means you cannot affect the outcome of the event at all (you can't cancel it or anything else - the "determine" command does nothing).
// -->
public static void reload() {
if (Debug.showLoading) {
Debug.log("Reloading script events...");
}
for (ScriptContainer container : worldContainers) {
if (!CoreUtilities.equalsIgnoreCase(container.getContents().getString("enabled", "true"),"true")) {
continue;
}
YamlConfiguration config = container.getConfigurationSection("events");
if (config == null) {
Debug.echoError("Missing or invalid events block for <Y>" + container.getName());
continue;
}
for (StringHolder evt : config.getKeys(false)) {
if (evt == null || evt.str == null) {
Debug.echoError("Missing or invalid events block for <Y>" + container.getName());
}
else if (CoreUtilities.contains(evt.str, '@')) {
Debug.echoError("Script '<Y>" + container.getName() + "<W>' has event '<Y>" + evt.str.replace("@", "<R>@<Y>")
+ "<W>' which contains object notation, which is deprecated for use in world events. Please remove it.");
}
}
}
List<ScriptPath> paths = new ArrayList<>(worldContainers.size() * 3);
for (ScriptContainer container : worldContainers) {
YamlConfiguration config = container.getConfigurationSection("events");
if (config == null) {
continue;
}
for (StringHolder evt1 : config.getKeys(false)) {
String evt;
boolean after = false;
if (evt1.low.startsWith("on ")) {
evt = evt1.str.substring("on ".length());
}
else if (evt1.low.startsWith("after ")) {
evt = evt1.str.substring("after ".length());
after = true;
}
else {
Debug.echoError("Script path '<Y>" + evt1.str + "<W>' is invalid (missing 'on' or 'after').");
continue;
}
evt = evt.replace("&dot", ".").replace("&", "&");
ScriptPath path = new ScriptPath(container, evt, evt1.str);
path.fireAfter = after;
if (path.set == null) {
Debug.echoError("Script path '<Y>" + path + "<W>' is invalid (empty or misconfigured).");
continue;
}
paths.add(path);
}
}
for (ScriptEvent event : events) {
try {
event.destroy();
event.eventPaths.clear();
boolean matched = false;
tryingToBuildEvent = event;
for (ScriptPath path : paths) {
tryingToBuildPath = path;
if (event.couldMatch(path)) {
event.eventPaths.add(path);
path.matches.add(event);
if (Debug.showLoading) {
Debug.log("Event match, <Y>" + event.getName() + "<W> matched for '<Y>" + path + "<W>'!");
}
matched = true;
}
}
if (matched) {
event.sort();
event.init();
}
}
catch (Throwable ex) {
Debug.echoError("Failed to reload event '<Y>" + event.getName() + "<W>':");
Debug.echoError(ex);
}
}
tryingToBuildEvent = null;
tryingToBuildPath = null;
for (ScriptPath path : paths) {
if (path.matches.size() > 1) {
Debug.log("Event <Y>" + path + "<W> is matched to multiple ScriptEvents: <Y>" + CoreUtilities.join("<W>,<Y> ", path.matches));
}
else if (path.matches.isEmpty()) {
Debug.echoError("Event <Y>" + path + "<W> is not matched to any ScriptEvents.");
if (path.matchFailReasons != null) {
for (String reason : path.matchFailReasons) {
Debug.log(reason);
}
}
}
path.matchFailReasons = null;
}
Debug.log("Processed <A>" + paths.size() + "<W> script event paths.");
}
public static ScriptPath tryingToBuildPath = null;
public static ScriptEvent tryingToBuildEvent = null;
public static void addPossibleCouldMatchFailReason(String reason, String example) {
if (tryingToBuildPath == null || tryingToBuildEvent == null) {
return;
}
if (tryingToBuildPath.matchFailReasons == null) {
tryingToBuildPath.matchFailReasons = new ArrayList<>();
}
tryingToBuildPath.matchFailReasons.add("Almost matched: <Y>" + tryingToBuildEvent.getName() + "<W>, but failed because: <Y>" + reason + "<W>: '<LR>" + example + "<W>'");
}
// <--[language]
// @name Script Event Cancellation
// @group Script Events
// @description
// Any modern ScriptEvent can take a "cancelled:<true/false>" argument and a "ignorecancelled:true" argument.
// For example: "on object does something ignorecancelled:true:"
// Or, "on object does something cancelled:true:"
// If you set 'ignorecancelled:true', the event will fire regardless of whether it was cancelled.
// If you set 'cancelled:true', the event will fire /only/ when it was cancelled.
// By default, only non-cancelled events will fire. (Effectively acting as if you had set "cancelled:false").
//
// Any modern script event can take the determinations "cancelled" and "cancelled:false".
// These determinations will set whether the script event is 'cancelled' in the eyes of following script events,
// and, in some cases, can be used to stop the event itself from continuing.
// A script event can at any time check the cancellation state of an event by accessing "<context.cancelled>".
// -->
public static boolean matchesScript(ScriptEvent sEvent, ScriptPath path) {
if (path.switch_cancelled != null) {
if (path.switch_cancelled != sEvent.cancelled) {
return false;
}
}
else if (path.switch_ignoreCancelled != null) {
if (!path.switch_ignoreCancelled && sEvent.cancelled) {
return false;
}
}
else { // No cancelled status switches given
if (sEvent.cancelled) {
return false;
}
}
return sEvent.matches(path);
}
public ArrayList<ScriptPath> eventPaths = new ArrayList<>();
public boolean cancelled = false;
// <--[language]
// @name Script Event Priority
// @group Script Events
// @description
// Any modern ScriptEvent can take a "priority:#" argument.
// For example: "on object does something priority:3:"
// The priority indicates which order the events will fire in.
// Lower numbers fire earlier. EG, -1 fires before 0 fires before 1.
// Any integer number, within reason, is valid. (IE, -1 is fine, 100000 is fine,
// but 200000000000 is not, and 1.5 is not as well)
// The default priority is 0.
// -->
public void sort() {
try {
for (ScriptPath path : eventPaths) {
String gotten = path.switches.get("priority");
path.priority = gotten == null ? 0 : Integer.parseInt(gotten);
}
}
catch (NumberFormatException ex) {
Debug.echoError("Failed to sort events: not-a-number priority value! " + ex.getMessage());
}
eventPaths.sort((scriptPath, t1) -> {
int rel = scriptPath.priority - t1.priority;
return Integer.compare(rel, 0);
});
}
public void init() {
}
public void destroy() {
}
public void cancellationChanged() {
}
@Deprecated
public static boolean isDefaultDetermination(ObjectTag determination) {
Debug.echoError("VERSION MISMATCH, UPDATE ALL DENIZEN-RELATED SUBPROJECTS.");
return false;
}
public boolean applyDetermination(ScriptPath path, ObjectTag determination) {
Debug.echoError("Unknown determination '" + determination + "'");
return false;
}
public boolean handleBaseDetermination(ScriptPath path, ObjectTag determination) {
if (determination instanceof ElementTag) {
String text = determination.toString();
if (text.length() <= "cancelled:false".length()) {
String low = CoreUtilities.toLowerCase(text);
switch (low) {
case "cancelled:true":
case "cancelled":
Debug.echoDebug(path.container, "Event cancelled!");
cancelled = true;
cancellationChanged();
return true;
case "cancelled:false":
Debug.echoDebug(path.container, "Event uncancelled!");
cancelled = false;
cancellationChanged();
return true;
}
}
}
return applyDetermination(path, determination);
}
public ScriptEntryData getScriptEntryData() {
return DenizenCore.getImplementation().getEmptyScriptEntryData();
}
public boolean couldMatch(ScriptPath path) {
throw new UnsupportedOperationException("CouldMatch not implemented for event '" + getName() + "'! Report this error to the Denizen developers!");
}
public boolean matches(ScriptPath path) {
String flagSwitch = path.switches.get("server_flagged");
if (flagSwitch != null) {
for (String flag : CoreUtilities.split(flagSwitch, '|')) {
if (!DenizenCore.getImplementation().getServerFlags().hasFlag(flag)) {
return false;
}
}
}
return true;
}
public abstract String getName();
public ScriptEvent fire() {
ScriptEvent copy = clone();
stats.fires++;
for (ScriptPath path : eventPaths) {
try {
if (matchesScript(copy, path)) {
if (path.fireAfter) {
final ScriptPath finalPath = path;
DenizenCore.schedule(new OneTimeSchedulable(() -> copy.run(finalPath), 0.01f));
}
else {
copy.run(path);
}
}
}
catch (Exception e) {
Debug.echoError("Matching script " + path.container.getName() + " event path:" + path.event + ":::");
Debug.echoError(e);
}
}
return copy;
}
private String currentEvent;
public void run(ScriptPath path) {
try {
stats.scriptFires++;
if (path.container.shouldDebug()) {
Debug.echoDebug(path.container, "<Y>Running script event '<A>" + getName() + "<Y>', event='<A>" + (path.fireAfter ? "after " : "on ") + path.event + "<Y>'"
+ " for script '<A>" + path.container.getName() + "<Y>'");
}
if (path.set == null) {
return;
}
List<ScriptEntry> entries = ScriptContainer.cleanDup(getScriptEntryData(), path.set);
ScriptQueue queue = new InstantQueue(path.container.getName()).addEntries(entries);
currentEvent = path.event;
queue.setContextSource(this);
if (!path.fireAfter) {
queue.determinationTarget = (o) -> handleBaseDetermination(path, o);
}
queue.start();
stats.nanoTimes += System.nanoTime() - queue.startTime;
}
catch (Exception e) {
Debug.echoError("Handling script " + path.container.getName() + " path:" + path.event + ":::");
Debug.echoError(e);
}
}
// <--[language]
// @name Script Event Special Contexts
// @group Script Events
// @description
// Every modern ScriptEvent has some special context tags available.
// The most noteworthy is "context.cancelled", which tracks whether the script event has been cancelled.
// You can also use "context.event_header", which returns the exact event header text that fired (which may be useful for some types of dynamic script).
// That returns, for example, "on player breaks stone".
// You can also use "context.event_name", which returns the internal name of the script event that fired (which may be useful for some debugging techniques).
// That returns, for example, "PlayerBreaksBlock".
// -->
@Override
public ObjectTag getContext(String name) {
switch (name) {
case "cancelled":
return new ElementTag(cancelled);
case "event_header":
return new ElementTag(currentEvent);
case "event_name":
return new ElementTag(getName());
}
return null;
}
@Override
public String toString() {
return getName();
}
// <--[language]
// @name Advanced Script Event Matching
// @group Script Events
// @description
// Script event lines often include specific 'matchable' keywords.
// For example, while you can write "on player breaks block:" as a script event line,
// you can also instead write "on player breaks stone:" to listen to a much more specific event.
// This is general in-line matching.
// This is made available to avoid needing to do things like "- if <context.material.name> == stone"
// just to validate whether an event is even relevant to you.
//
// Of course, there are times when you want to more than one specific thing to be handled by the event, so what do you do?
// The Denizen script event system provides a few 'advanced' options to get more detailed matching.
//
// One option is to use wildcards.
// For example, there are several 'log' materials, such as 'oak_log', 'birch_log', and more for the rest of the tree types.
// So how can you match a player breaking any of these? Use "on player breaks *_log:"
// The asterisk is a generic wildcard, it means any text at all will match. So an asterisk followed by '_log' means
// any material at all that has a name ending with '_log', including 'birch_log' and the rest.
//
// Note that you can also use multiple wildcards at once, like "on player breaks block with:my_*_script_*:"
// That example will work for item scripts named "my_item_script_1" and "my_first_script_of_items" or any similar name.
// Note also that wildcards still match for blanks, so "my_item_script_" would still work for that example.
//
// You can also specify lists. For example, if you want an event to work with certain tool types,
// the 'on player breaks block:' event supports a switch named 'with', like 'on player breaks block with:iron_pickaxe:'
// So lets match multiple tools for our event...
// 'on player breaks block with:iron_pickaxe|gold_pickaxe|diamond_axe|wood_shovel:'
//
// You can also combine wildcards and lists... note that lists are the 'wider' option.
// That is, if you have wildcards and lists together, you will have a list of possible matches, where each entry may contain wildcards, you will not have a wildcard match with a list.
// As a specific example,
// '*_pickaxe|*_axe' will match any pickaxe or any axe.
// '*_pickaxe|stone' will match any pickaxe or specifically stone. It will NOT match other types of stone, as it interprets
// the match to be a list of "*_pickaxe" and "stone", NOT "*" followed by a list of "pickaxe" or "stone".
//
// Additionally, when you're really desperate for a good matcher, you may use 'regex:'
// For example, "on player breaks regex:(?i)\d+_customitem:"
// Note that generally regex should be avoided whenever you can, as it's inherently hard to track exactly what it's doing at-a-glance, and may have unexpected edge case errors.
//
// If you want to match anything *except* a specific value, just prefix the matcher with '!'
// For example, on player breaks !stone:" will fire for a player breaking any block type OTHER THAN stone.
// This can be combined with other match modes, like "on player breaks !*wood|*planks|*log:" will fire for any block break other than any wood variant.
//
// See also <@link language script event object matchables>.
//
// These advanced matchers are also used in some commands and tags.
// -->
public static abstract class MatchHelper {
public abstract boolean doesMatch(String input);
}
public static class AlwaysMatchHelper extends MatchHelper {
@Override
public boolean doesMatch(String input) {
return true;
}
}
public static class ExactMatchHelper extends MatchHelper {
public ExactMatchHelper(String text) {
this.text = CoreUtilities.toLowerCase(text);
}
public String text;
@Override
public boolean doesMatch(String input) {
return CoreUtilities.equalsIgnoreCase(text, input);
}
}
public static class PrefixAsteriskMatchHelper extends MatchHelper {
public PrefixAsteriskMatchHelper(String text) {
this.text = CoreUtilities.toLowerCase(text);
}
public String text;
@Override
public boolean doesMatch(String input) {
return CoreUtilities.toLowerCase(input).endsWith(text);
}
}
public static class PostfixAsteriskMatchHelper extends MatchHelper {
public PostfixAsteriskMatchHelper(String text) {
this.text = CoreUtilities.toLowerCase(text);
}
public String text;
@Override
public boolean doesMatch(String input) {
return CoreUtilities.toLowerCase(input).startsWith(text);
}
}
public static class MultipleAsteriskMatchHelper extends MatchHelper {
public MultipleAsteriskMatchHelper(String[] texts) {
this.texts = texts;
}
public String[] texts;
@Override
public boolean doesMatch(String input) {
int index = 0;
input = CoreUtilities.toLowerCase(input);
if (!input.startsWith(texts[0]) || !input.endsWith(texts[texts.length - 1])) {
return false;
}
for (String text : texts) {
if (text.isEmpty()) {
continue;
}
index = input.indexOf(text, index);
if (index == -1) {
return false;
}
index += text.length();
}
return true;
}
}
public static class RegexMatchHelper extends MatchHelper {
public RegexMatchHelper(String regex) {
this.regex = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
}
public Pattern regex;
@Override
public boolean doesMatch(String input) {
return regex.matcher(input).matches();
}
}
public static class MultipleMatchesHelper extends MatchHelper {
public MultipleMatchesHelper(MatchHelper[] matches) {
this.matches = matches;
}
public MatchHelper[] matches;
@Override
public boolean doesMatch(String input) {
for (MatchHelper match : matches) {
if (match.doesMatch(input)) {
return true;
}
}
return false;
}
}
public static class InverseMatchHelper extends MatchHelper {
public InverseMatchHelper(MatchHelper matcher) {
this.matcher = matcher;
}
public MatchHelper matcher;
@Override
public boolean doesMatch(String input) {
return !matcher.doesMatch(input);
}
}
public static final HashMap<String, MatchHelper> knownMatchers = new HashMap<>();
public static boolean isAdvancedMatchable(String input) {
return input.startsWith("regex:") || CoreUtilities.contains(input, '|') || CoreUtilities.contains(input, '*') || input.startsWith("!");
}
public static MatchHelper createMatcher(String input) {
MatchHelper result = knownMatchers.get(input);
if (result != null) {
return result;
}
int asterisk;
if (input.startsWith("!")) {
result = new InverseMatchHelper(createMatcher(input.substring(1)));
}
else if (input.startsWith("regex:")) {
result = new RegexMatchHelper(input.substring("regex:".length()));
}
else if (CoreUtilities.contains(input, '|')) {
String toSplit = input;
if (toSplit.startsWith("li@")) {
toSplit = toSplit.substring("li@".length());
}
toSplit = CoreUtilities.replace(toSplit, "el@", "");
List<String> split = CoreUtilities.split(toSplit, '|');
MatchHelper[] matchers = new MatchHelper[split.size()];
for (int i = 0; i < split.size(); i++) {
matchers[i] = createMatcher(split.get(i));
}
result = new MultipleMatchesHelper(matchers);
}
else if ((asterisk = input.indexOf('*')) != -1) {
if (input.length() == 1) {
result = new AlwaysMatchHelper();
}
else if (asterisk == 0 && input.indexOf('*', 1) == -1) {
result = new PrefixAsteriskMatchHelper(input.substring(1));
}
else if (asterisk == input.length() - 1) {
result = new PostfixAsteriskMatchHelper(input.substring(0, input.length() - 1));
}
else {
result = new MultipleAsteriskMatchHelper(CoreUtilities.split(CoreUtilities.toLowerCase(input), '*').toArray(new String[0]));
}
}
else {
result = new ExactMatchHelper(input);
}
knownMatchers.put(input, result);
return result;
}
public static boolean runGenericCheck(String matchableValue, String trueValue) {
if (matchableValue == null) {
return false;
}
trueValue = CoreUtilities.toLowerCase(trueValue);
MatchHelper matcher = createMatcher(matchableValue);
return matcher.doesMatch(trueValue);
}
public static boolean runGenericSwitchCheck(ScriptPath path, String switchName, String value) {
String with = path.switches.get(switchName);
if (with == null) {
return true;
}
if (value == null) {
return false;
}
value = CoreUtilities.toLowerCase(value);
MatchHelper matcher = createMatcher(with);
return matcher.doesMatch(value);
}
}