/
WorldEdit.java
748 lines (650 loc) · 25 KB
/
WorldEdit.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
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.sk89q.worldedit.blocks.BaseItem;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.platform.BlockInteractEvent;
import com.sk89q.worldedit.event.platform.InputType;
import com.sk89q.worldedit.event.platform.PlayerInputEvent;
import com.sk89q.worldedit.extension.factory.BlockFactory;
import com.sk89q.worldedit.extension.factory.ItemFactory;
import com.sk89q.worldedit.extension.factory.MaskFactory;
import com.sk89q.worldedit.extension.factory.PatternFactory;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extension.platform.PlatformManager;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.scripting.CraftScriptContext;
import com.sk89q.worldedit.scripting.CraftScriptEngine;
import com.sk89q.worldedit.scripting.RhinoCraftScriptEngine;
import com.sk89q.worldedit.session.SessionManager;
import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.concurrency.EvenMoreExecutors;
import com.sk89q.worldedit.util.eventbus.EventBus;
import com.sk89q.worldedit.util.io.file.FileSelectionAbortedException;
import com.sk89q.worldedit.util.io.file.FilenameException;
import com.sk89q.worldedit.util.io.file.FilenameResolutionException;
import com.sk89q.worldedit.util.io.file.InvalidFilenameException;
import com.sk89q.worldedit.util.task.SimpleSupervisor;
import com.sk89q.worldedit.util.task.Supervisor;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.registry.BundledBlockData;
import com.sk89q.worldedit.world.registry.BundledItemData;
import com.sk89q.worldedit.world.registry.LegacyMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.script.ScriptException;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.sk89q.worldedit.event.platform.Interaction.HIT;
import static com.sk89q.worldedit.event.platform.Interaction.OPEN;
/**
* The entry point and container for a working implementation of WorldEdit.
*
* <p>An instance handles event handling; block, mask, pattern, etc. registration;
* the management of sessions; the creation of {@link EditSession}s; and more.
* In order to use WorldEdit, at least one {@link Platform} must be registered
* with WorldEdit using {@link PlatformManager#register(Platform)} on the
* manager retrieved using {@link WorldEdit#getPlatformManager()}.</p>
*
* <p>An instance of WorldEdit can be retrieved using the static
* method {@link WorldEdit#getInstance()}, which is shared among all
* platforms within the same classloader hierarchy.</p>
*/
public final class WorldEdit {
public static final Logger logger = LoggerFactory.getLogger(WorldEdit.class);
private static final WorldEdit instance = new WorldEdit();
private static String version;
private final EventBus eventBus = new EventBus();
private final PlatformManager platformManager = new PlatformManager(this);
private final EditSessionFactory editSessionFactory = new EditSessionFactory.EditSessionFactoryImpl(eventBus);
private final SessionManager sessions = new SessionManager(this);
private final ListeningExecutorService executorService = MoreExecutors.listeningDecorator(
EvenMoreExecutors.newBoundedCachedThreadPool(0, 1, 20, "WorldEdit Task Executor - %s"));
private final Supervisor supervisor = new SimpleSupervisor();
private final BlockFactory blockFactory = new BlockFactory(this);
private final ItemFactory itemFactory = new ItemFactory(this);
private final MaskFactory maskFactory = new MaskFactory(this);
private final PatternFactory patternFactory = new PatternFactory(this);
static {
getVersion();
}
private WorldEdit() {
}
/**
* Gets the current instance of this class.
*
* <p>An instance will always be available, but no platform may yet be
* registered with WorldEdit, meaning that a number of operations
* may fail. However, event handlers can be registered.</p>
*
* @return an instance of WorldEdit.
*/
public static WorldEdit getInstance() {
return instance;
}
/**
* Get the platform manager, where platforms (that implement WorldEdit)
* can be registered and information about registered platforms can
* be queried.
*
* @return the platform manager
*/
public PlatformManager getPlatformManager() {
return platformManager;
}
/**
* Get the event bus for WorldEdit.
*
* <p>Event handlers can be registered on the event bus.</p>
*
* @return the event bus
*/
public EventBus getEventBus() {
return eventBus;
}
/**
* Get the supervisor. Internal, not for API use.
*
* @return the supervisor
*/
public Supervisor getSupervisor() {
return supervisor;
}
/**
* Get the executor service. Internal, not for API use.
*
* @return the executor service
*/
public ListeningExecutorService getExecutorService() {
return executorService;
}
/**
* Get the block factory from which new {@link BlockStateHolder}s can be
* constructed.
*
* @return the block factory
*/
public BlockFactory getBlockFactory() {
return blockFactory;
}
/**
* Get the item factory from which new {@link BaseItem}s can be
* constructed.
*
* @return the item factory
*/
public ItemFactory getItemFactory() {
return itemFactory;
}
/**
* Get the mask factory from which new {@link Mask}s
* can be constructed.
*
* @return the mask factory
*/
public MaskFactory getMaskFactory() {
return maskFactory;
}
/**
* Get the pattern factory from which new {@link Pattern}s
* can be constructed.
*
* @return the pattern factory
*/
public PatternFactory getPatternFactory() {
return patternFactory;
}
/**
* Return the session manager.
*
* @return the session manager
*/
public SessionManager getSessionManager() {
return sessions;
}
/**
* Gets the path to a file. This method will check to see if the filename
* has valid characters and has an extension. It also prevents directory
* traversal exploits by checking the root directory and the file directory.
* On success, a {@code java.io.File} object will be returned.
*
* @param actor the actor
* @param dir sub-directory to look in
* @param filename filename (user-submitted)
* @param defaultExt append an extension if missing one, null to not use
* @param extensions list of extensions, null for any
* @return a file
* @throws FilenameException thrown if the filename is invalid
*/
public File getSafeSaveFile(Actor actor, File dir, String filename, String defaultExt, String... extensions) throws FilenameException {
return getSafeFile(actor, dir, filename, defaultExt, extensions, true);
}
/**
* Gets the path to a file. This method will check to see if the filename
* has valid characters and has an extension. It also prevents directory
* traversal exploits by checking the root directory and the file directory.
* On success, a {@code java.io.File} object will be returned.
*
* @param actor the actor
* @param dir sub-directory to look in
* @param filename filename (user-submitted)
* @param defaultExt append an extension if missing one, null to not use
* @param extensions list of extensions, null for any
* @return a file
* @throws FilenameException thrown if the filename is invalid
*/
public File getSafeOpenFile(Actor actor, File dir, String filename, String defaultExt, String... extensions) throws FilenameException {
return getSafeFile(actor, dir, filename, defaultExt, extensions, false);
}
/**
* Get a safe path to a file.
*
* @param actor the actor
* @param dir sub-directory to look in
* @param filename filename (user-submitted)
* @param defaultExt append an extension if missing one, null to not use
* @param extensions list of extensions, null for any
* @param isSave true if the purpose is for saving
* @return a file
* @throws FilenameException thrown if the filename is invalid
*/
private File getSafeFile(@Nullable Actor actor, File dir, String filename, String defaultExt, String[] extensions, boolean isSave) throws FilenameException {
if (extensions != null && (extensions.length == 1 && extensions[0] == null)) extensions = null;
File f;
if (filename.equals("#") && actor != null) {
if (isSave) {
f = actor.openFileSaveDialog(extensions);
} else {
f = actor.openFileOpenDialog(extensions);
}
if (f == null) {
throw new FileSelectionAbortedException("No file selected");
}
} else {
List<String> exts = extensions == null ? ImmutableList.of(defaultExt) : Lists.asList(defaultExt, extensions);
f = getSafeFileWithExtensions(dir, filename, exts, isSave);
}
try {
Path filePath = Paths.get(f.toURI()).normalize();
Path dirPath = Paths.get(dir.toURI()).normalize();
boolean inDir = filePath.startsWith(dirPath);
Path existingParent = filePath;
do {
existingParent = existingParent.getParent();
} while (existingParent != null && !existingParent.toFile().exists());
boolean isSym = existingParent != null && !existingParent.toRealPath().equals(existingParent);
if (!inDir || (!getConfiguration().allowSymlinks && isSym)) {
throw new FilenameResolutionException(filename, "Path is outside allowable root");
}
return filePath.toFile();
} catch (IOException e) {
throw new FilenameResolutionException(filename, "Failed to resolve path");
}
}
private File getSafeFileWithExtensions(File dir, String filename, List<String> exts, boolean isSave) throws InvalidFilenameException {
if (isSave) {
// First is default, only use that.
if (exts.size() != 1) {
exts = exts.subList(0, 1);
}
} else {
int dot = filename.lastIndexOf('.');
if (dot < 0 || dot == filename.length() - 1) {
String currentExt = filename.substring(dot + 1);
if (exts.contains(currentExt) && checkFilename(filename)) {
File f = new File(dir, filename);
if (f.exists()) {
return f;
}
}
}
}
File result = null;
for (Iterator<String> iter = exts.iterator(); iter.hasNext() && (result == null || (!isSave && !result.exists()));) {
result = getSafeFileWithExtension(dir, filename, iter.next());
}
if (result == null) {
throw new InvalidFilenameException(filename, "Invalid characters or extension missing");
}
return result;
}
private File getSafeFileWithExtension(File dir, String filename, String extension) {
if (extension != null) {
int dot = filename.lastIndexOf('.');
if (dot < 0 || dot == filename.length() - 1 || !filename.substring(dot + 1).equalsIgnoreCase(extension)) {
filename += "." + extension;
}
}
if (!checkFilename(filename)) {
return null;
}
return new File(dir, filename);
}
private boolean checkFilename(String filename) {
return filename.matches("^[A-Za-z0-9_\\- \\./\\\\'\\$@~!%\\^\\*\\(\\)\\[\\]\\+\\{\\},\\?]+\\.[A-Za-z0-9]+$");
}
/**
* Load the bundled mappings.
*/
public void loadMappings() {
BundledBlockData.getInstance(); // Load block registry
BundledItemData.getInstance(); // Load item registry
LegacyMapper.getInstance(); // Load item registry
}
/**
* Checks to see if the specified radius is within bounds.
*
* @param radius the radius
* @throws MaxRadiusException
*/
public void checkMaxRadius(double radius) throws MaxRadiusException {
if (getConfiguration().maxRadius > 0 && radius > getConfiguration().maxRadius) {
throw new MaxRadiusException();
}
}
/**
* Checks to see if the specified brush radius is within bounds.
*
* @param radius the radius
* @throws MaxBrushRadiusException
*/
public void checkMaxBrushRadius(double radius) throws MaxBrushRadiusException {
if (getConfiguration().maxBrushRadius > 0 && radius > getConfiguration().maxBrushRadius) {
throw new MaxBrushRadiusException();
}
}
/**
* Get a file relative to the defined working directory. If the specified
* path is absolute, then the working directory is not used.
*
* @param path the subpath under the working directory
* @return a working directory
*/
public File getWorkingDirectoryFile(String path) {
File f = new File(path);
if (f.isAbsolute()) {
return f;
}
return new File(getConfiguration().getWorkingDirectory(), path);
}
/**
* Get the direction vector for a player's direction.
*
* @param player the player
* @param dirStr the direction string
* @return a direction vector
* @throws UnknownDirectionException thrown if the direction is not known, or a relative direction is used with null player
*/
public BlockVector3 getDirection(@Nullable Player player, String dirStr) throws UnknownDirectionException {
dirStr = dirStr.toLowerCase(Locale.ROOT);
final Direction dir = getPlayerDirection(player, dirStr);
if (dir.isUpright() || dir.isCardinal()) {
return dir.toBlockVector();
} else {
throw new UnknownDirectionException(dir.name());
}
}
/**
* Get the direction vector for a player's direction.
*
* @param player the player
* @param dirStr the direction string
* @return a direction vector
* @throws UnknownDirectionException thrown if the direction is not known, or a relative direction is used with null player
*/
public BlockVector3 getDiagonalDirection(@Nullable Player player, String dirStr) throws UnknownDirectionException {
dirStr = dirStr.toLowerCase(Locale.ROOT);
final Direction dir = getPlayerDirection(player, dirStr);
if (dir.isCardinal() || dir.isOrdinal() || dir.isUpright()) {
return dir.toBlockVector();
}
throw new UnknownDirectionException(dir.name());
}
/**
* Get the direction vector for a player's direction.
*
* @param player the player
* @param dirStr the direction string
* @return a direction enum value
* @throws UnknownDirectionException thrown if the direction is not known, or a relative direction is used with null player
*/
private Direction getPlayerDirection(@Nullable Player player, String dirStr) throws UnknownDirectionException {
final Direction dir;
switch (dirStr.charAt(0)) {
case 'w':
dir = Direction.WEST;
break;
case 'e':
dir = Direction.EAST;
break;
case 's':
if (dirStr.indexOf('w') > 0) {
return Direction.SOUTHWEST;
}
if (dirStr.indexOf('e') > 0) {
return Direction.SOUTHEAST;
}
dir = Direction.SOUTH;
break;
case 'n':
if (dirStr.indexOf('w') > 0) {
return Direction.NORTHWEST;
}
if (dirStr.indexOf('e') > 0) {
return Direction.NORTHEAST;
}
dir = Direction.NORTH;
break;
case 'u':
dir = Direction.UP;
break;
case 'd':
dir = Direction.DOWN;
break;
case 'm': // me
case 'f': // forward
dir = getDirectionRelative(player, 0);
break;
case 'b': // back
dir = getDirectionRelative(player, 180);
break;
case 'l': // left
dir = getDirectionRelative(player, -90);
break;
case 'r': // right
dir = getDirectionRelative(player, 90);
break;
default:
throw new UnknownDirectionException(dirStr);
}
return dir;
}
private Direction getDirectionRelative(Player player, int yawOffset) throws UnknownDirectionException {
if (player != null) {
return player.getCardinalDirection(yawOffset);
}
throw new UnknownDirectionException("Only a player can use relative directions");
}
/**
* Flush a block bag's changes to a player.
*
* @param actor the actor
* @param editSession the edit session
*/
public void flushBlockBag(Actor actor, EditSession editSession) {
BlockBag blockBag = editSession.getBlockBag();
if (blockBag != null) {
blockBag.flushChanges();
}
Map<BlockType, Integer> missingBlocks = editSession.popMissingBlocks();
if (!missingBlocks.isEmpty()) {
StringBuilder str = new StringBuilder();
str.append("Missing these blocks: ");
int size = missingBlocks.size();
int i = 0;
for (Map.Entry<BlockType, Integer> blockTypeIntegerEntry : missingBlocks.entrySet()) {
str.append((blockTypeIntegerEntry.getKey()).getName());
str.append(" [Amt: ").append(blockTypeIntegerEntry.getValue()).append("]");
++i;
if (i != size) {
str.append(", ");
}
}
actor.printError(str.toString());
}
}
/**
* Called on arm swing.
*
* @param player the player
* @return true if the swing was handled
*/
public boolean handleArmSwing(Player player) {
PlayerInputEvent event = new PlayerInputEvent(player, InputType.PRIMARY);
getEventBus().post(event);
return event.isCancelled();
}
/**
* Called on right click (not on a block).
*
* @param player the player
* @return true if the right click was handled
*/
public boolean handleRightClick(Player player) {
PlayerInputEvent event = new PlayerInputEvent(player, InputType.SECONDARY);
getEventBus().post(event);
return event.isCancelled();
}
/**
* Called on right click.
*
* @param player the player
* @param clicked the clicked block
* @return false if you want the action to go through
*/
public boolean handleBlockRightClick(Player player, Location clicked) {
BlockInteractEvent event = new BlockInteractEvent(player, clicked, OPEN);
getEventBus().post(event);
return event.isCancelled();
}
/**
* Called on left click.
*
* @param player the player
* @param clicked the clicked block
* @return false if you want the action to go through
*/
public boolean handleBlockLeftClick(Player player, Location clicked) {
BlockInteractEvent event = new BlockInteractEvent(player, clicked, HIT);
getEventBus().post(event);
return event.isCancelled();
}
/**
* Executes a WorldEdit script.
*
* @param player the player
* @param f the script file to execute
* @param args arguments for the script
* @throws WorldEditException
*/
public void runScript(Player player, File f, String[] args) throws WorldEditException {
String filename = f.getPath();
int index = filename.lastIndexOf('.');
String ext = filename.substring(index + 1);
if (!ext.equalsIgnoreCase("js")) {
player.printError("Only .js scripts are currently supported");
return;
}
String script;
try {
InputStream file;
if (!f.exists()) {
file = WorldEdit.class.getResourceAsStream("craftscripts/" + filename);
if (file == null) {
player.printError("Script does not exist: " + filename);
return;
}
} else {
file = new FileInputStream(f);
}
DataInputStream in = new DataInputStream(file);
byte[] data = new byte[in.available()];
in.readFully(data);
in.close();
script = new String(data, 0, data.length, StandardCharsets.UTF_8);
} catch (IOException e) {
player.printError("Script read error: " + e.getMessage());
return;
}
LocalSession session = getSessionManager().get(player);
CraftScriptContext scriptContext = new CraftScriptContext(this, getPlatformManager().queryCapability(Capability.USER_COMMANDS),
getConfiguration(), session, player, args);
CraftScriptEngine engine;
try {
engine = new RhinoCraftScriptEngine();
} catch (NoClassDefFoundError ignored) {
player.printError("Failed to find an installed script engine.");
player.printError("Please see https://worldedit.readthedocs.io/en/latest/usage/other/craftscripts/");
return;
}
engine.setTimeLimit(getConfiguration().scriptTimeout);
Map<String, Object> vars = new HashMap<>();
vars.put("argv", args);
vars.put("context", scriptContext);
vars.put("player", player);
try {
engine.evaluate(script, filename, vars);
} catch (ScriptException e) {
player.printError("Failed to execute:");
player.printRaw(e.getMessage());
logger.warn("Failed to execute script", e);
} catch (NumberFormatException | WorldEditException e) {
throw e;
} catch (Throwable e) {
player.printError("Failed to execute (see console):");
player.printRaw(e.getClass().getCanonicalName());
logger.warn("Failed to execute script", e);
} finally {
for (EditSession editSession : scriptContext.getEditSessions()) {
editSession.flushSession();
session.remember(editSession);
}
}
}
/**
* Get Worldedit's configuration.
*
* @return a configuration
*/
public LocalConfiguration getConfiguration() {
return getPlatformManager().getConfiguration();
}
/**
* Get a factory for {@link EditSession}s.
*/
public EditSessionFactory getEditSessionFactory() {
return editSessionFactory;
}
/**
* Get the version.
*
* @return the version of WorldEdit
*/
public static String getVersion() {
if (version != null) {
return version;
}
Package p = WorldEdit.class.getPackage();
if (p == null) {
p = Package.getPackage("com.sk89q.worldedit");
}
if (p == null) {
version = "(unknown)";
} else {
version = p.getImplementationVersion();
if (version == null) {
version = "(unknown)";
}
}
return version;
}
}